PackageManagerService.java revision f09f0699369c02a6a46fbff68c02b00a7c703697
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.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.INetworkPolicyManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.security.KeyStore; 201import android.security.SystemKeyStore; 202import android.system.ErrnoException; 203import android.system.Os; 204import android.text.TextUtils; 205import android.text.format.DateUtils; 206import android.util.ArrayMap; 207import android.util.ArraySet; 208import android.util.AtomicFile; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.EventLogTags; 243import com.android.server.FgThread; 244import com.android.server.IntentResolver; 245import com.android.server.LocalServices; 246import com.android.server.ServiceThread; 247import com.android.server.SystemConfig; 248import com.android.server.Watchdog; 249import com.android.server.net.NetworkPolicyManagerInternal; 250import com.android.server.pm.PermissionsState.PermissionState; 251import com.android.server.pm.Settings.DatabaseVersion; 252import com.android.server.pm.Settings.VersionInfo; 253import com.android.server.storage.DeviceStorageMonitorInternal; 254 255import dalvik.system.CloseGuard; 256import dalvik.system.DexFile; 257import dalvik.system.VMRuntime; 258 259import libcore.io.IoUtils; 260import libcore.util.EmptyArray; 261 262import org.xmlpull.v1.XmlPullParser; 263import org.xmlpull.v1.XmlPullParserException; 264import org.xmlpull.v1.XmlSerializer; 265 266import java.io.BufferedInputStream; 267import java.io.BufferedOutputStream; 268import java.io.BufferedReader; 269import java.io.ByteArrayInputStream; 270import java.io.ByteArrayOutputStream; 271import java.io.File; 272import java.io.FileDescriptor; 273import java.io.FileInputStream; 274import java.io.FileNotFoundException; 275import java.io.FileOutputStream; 276import java.io.FileReader; 277import java.io.FilenameFilter; 278import java.io.IOException; 279import java.io.InputStream; 280import java.io.PrintWriter; 281import java.nio.charset.StandardCharsets; 282import java.security.DigestInputStream; 283import java.security.MessageDigest; 284import java.security.NoSuchAlgorithmException; 285import java.security.PublicKey; 286import java.security.cert.Certificate; 287import java.security.cert.CertificateEncodingException; 288import java.security.cert.CertificateException; 289import java.text.SimpleDateFormat; 290import java.util.ArrayList; 291import java.util.Arrays; 292import java.util.Collection; 293import java.util.Collections; 294import java.util.Comparator; 295import java.util.Date; 296import java.util.HashSet; 297import java.util.Iterator; 298import java.util.List; 299import java.util.Map; 300import java.util.Objects; 301import java.util.Set; 302import java.util.concurrent.CountDownLatch; 303import java.util.concurrent.TimeUnit; 304import java.util.concurrent.atomic.AtomicBoolean; 305import java.util.concurrent.atomic.AtomicInteger; 306import java.util.concurrent.atomic.AtomicLong; 307 308/** 309 * Keep track of all those APKs everywhere. 310 * <p> 311 * Internally there are two important locks: 312 * <ul> 313 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 314 * and other related state. It is a fine-grained lock that should only be held 315 * momentarily, as it's one of the most contended locks in the system. 316 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 317 * operations typically involve heavy lifting of application data on disk. Since 318 * {@code installd} is single-threaded, and it's operations can often be slow, 319 * this lock should never be acquired while already holding {@link #mPackages}. 320 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 321 * holding {@link #mInstallLock}. 322 * </ul> 323 * Many internal methods rely on the caller to hold the appropriate locks, and 324 * this contract is expressed through method name suffixes: 325 * <ul> 326 * <li>fooLI(): the caller must hold {@link #mInstallLock} 327 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 328 * being modified must be frozen 329 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 330 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 331 * </ul> 332 * <p> 333 * Because this class is very central to the platform's security; please run all 334 * CTS and unit tests whenever making modifications: 335 * 336 * <pre> 337 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 338 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 339 * </pre> 340 */ 341public class PackageManagerService extends IPackageManager.Stub { 342 static final String TAG = "PackageManager"; 343 static final boolean DEBUG_SETTINGS = false; 344 static final boolean DEBUG_PREFERRED = false; 345 static final boolean DEBUG_UPGRADE = false; 346 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 347 private static final boolean DEBUG_BACKUP = false; 348 private static final boolean DEBUG_INSTALL = false; 349 private static final boolean DEBUG_REMOVE = false; 350 private static final boolean DEBUG_BROADCASTS = false; 351 private static final boolean DEBUG_SHOW_INFO = false; 352 private static final boolean DEBUG_PACKAGE_INFO = false; 353 private static final boolean DEBUG_INTENT_MATCHING = false; 354 private static final boolean DEBUG_PACKAGE_SCANNING = false; 355 private static final boolean DEBUG_VERIFY = false; 356 private static final boolean DEBUG_FILTERS = false; 357 358 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 359 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 360 // user, but by default initialize to this. 361 static final boolean DEBUG_DEXOPT = false; 362 363 private static final boolean DEBUG_ABI_SELECTION = false; 364 private static final boolean DEBUG_EPHEMERAL = false; 365 private static final boolean DEBUG_TRIAGED_MISSING = false; 366 private static final boolean DEBUG_APP_DATA = false; 367 368 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 369 370 private static final boolean DISABLE_EPHEMERAL_APPS = true; 371 372 private static final int RADIO_UID = Process.PHONE_UID; 373 private static final int LOG_UID = Process.LOG_UID; 374 private static final int NFC_UID = Process.NFC_UID; 375 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 376 private static final int SHELL_UID = Process.SHELL_UID; 377 378 // Cap the size of permission trees that 3rd party apps can define 379 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 380 381 // Suffix used during package installation when copying/moving 382 // package apks to install directory. 383 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 384 385 static final int SCAN_NO_DEX = 1<<1; 386 static final int SCAN_FORCE_DEX = 1<<2; 387 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 388 static final int SCAN_NEW_INSTALL = 1<<4; 389 static final int SCAN_NO_PATHS = 1<<5; 390 static final int SCAN_UPDATE_TIME = 1<<6; 391 static final int SCAN_DEFER_DEX = 1<<7; 392 static final int SCAN_BOOTING = 1<<8; 393 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 394 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 395 static final int SCAN_REPLACING = 1<<11; 396 static final int SCAN_REQUIRE_KNOWN = 1<<12; 397 static final int SCAN_MOVE = 1<<13; 398 static final int SCAN_INITIAL = 1<<14; 399 static final int SCAN_CHECK_ONLY = 1<<15; 400 static final int SCAN_DONT_KILL_APP = 1<<17; 401 static final int SCAN_IGNORE_FROZEN = 1<<18; 402 403 static final int REMOVE_CHATTY = 1<<16; 404 405 private static final int[] EMPTY_INT_ARRAY = new int[0]; 406 407 /** 408 * Timeout (in milliseconds) after which the watchdog should declare that 409 * our handler thread is wedged. The usual default for such things is one 410 * minute but we sometimes do very lengthy I/O operations on this thread, 411 * such as installing multi-gigabyte applications, so ours needs to be longer. 412 */ 413 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 414 415 /** 416 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 417 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 418 * settings entry if available, otherwise we use the hardcoded default. If it's been 419 * more than this long since the last fstrim, we force one during the boot sequence. 420 * 421 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 422 * one gets run at the next available charging+idle time. This final mandatory 423 * no-fstrim check kicks in only of the other scheduling criteria is never met. 424 */ 425 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 426 427 /** 428 * Whether verification is enabled by default. 429 */ 430 private static final boolean DEFAULT_VERIFY_ENABLE = true; 431 432 /** 433 * The default maximum time to wait for the verification agent to return in 434 * milliseconds. 435 */ 436 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 437 438 /** 439 * The default response for package verification timeout. 440 * 441 * This can be either PackageManager.VERIFICATION_ALLOW or 442 * PackageManager.VERIFICATION_REJECT. 443 */ 444 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 445 446 static final String PLATFORM_PACKAGE_NAME = "android"; 447 448 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 449 450 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 451 DEFAULT_CONTAINER_PACKAGE, 452 "com.android.defcontainer.DefaultContainerService"); 453 454 private static final String KILL_APP_REASON_GIDS_CHANGED = 455 "permission grant or revoke changed gids"; 456 457 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 458 "permissions revoked"; 459 460 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 461 462 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 463 464 /** Permission grant: not grant the permission. */ 465 private static final int GRANT_DENIED = 1; 466 467 /** Permission grant: grant the permission as an install permission. */ 468 private static final int GRANT_INSTALL = 2; 469 470 /** Permission grant: grant the permission as a runtime one. */ 471 private static final int GRANT_RUNTIME = 3; 472 473 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 474 private static final int GRANT_UPGRADE = 4; 475 476 /** Canonical intent used to identify what counts as a "web browser" app */ 477 private static final Intent sBrowserIntent; 478 static { 479 sBrowserIntent = new Intent(); 480 sBrowserIntent.setAction(Intent.ACTION_VIEW); 481 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 482 sBrowserIntent.setData(Uri.parse("http:")); 483 } 484 485 /** 486 * The set of all protected actions [i.e. those actions for which a high priority 487 * intent filter is disallowed]. 488 */ 489 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 490 static { 491 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 492 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 494 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 495 } 496 497 // Compilation reasons. 498 public static final int REASON_FIRST_BOOT = 0; 499 public static final int REASON_BOOT = 1; 500 public static final int REASON_INSTALL = 2; 501 public static final int REASON_BACKGROUND_DEXOPT = 3; 502 public static final int REASON_AB_OTA = 4; 503 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 504 public static final int REASON_SHARED_APK = 6; 505 public static final int REASON_FORCED_DEXOPT = 7; 506 507 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 508 509 /** Special library name that skips shared libraries check during compilation. */ 510 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 511 512 final ServiceThread mHandlerThread; 513 514 final PackageHandler mHandler; 515 516 private final ProcessLoggingHandler mProcessLoggingHandler; 517 518 /** 519 * Messages for {@link #mHandler} that need to wait for system ready before 520 * being dispatched. 521 */ 522 private ArrayList<Message> mPostSystemReadyMessages; 523 524 final int mSdkVersion = Build.VERSION.SDK_INT; 525 526 final Context mContext; 527 final boolean mFactoryTest; 528 final boolean mOnlyCore; 529 final DisplayMetrics mMetrics; 530 final int mDefParseFlags; 531 final String[] mSeparateProcesses; 532 final boolean mIsUpgrade; 533 final boolean mIsPreNUpgrade; 534 535 /** The location for ASEC container files on internal storage. */ 536 final String mAsecInternalPath; 537 538 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 539 // LOCK HELD. Can be called with mInstallLock held. 540 @GuardedBy("mInstallLock") 541 final Installer mInstaller; 542 543 /** Directory where installed third-party apps stored */ 544 final File mAppInstallDir; 545 final File mEphemeralInstallDir; 546 547 /** 548 * Directory to which applications installed internally have their 549 * 32 bit native libraries copied. 550 */ 551 private File mAppLib32InstallDir; 552 553 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 554 // apps. 555 final File mDrmAppPrivateInstallDir; 556 557 // ---------------------------------------------------------------- 558 559 // Lock for state used when installing and doing other long running 560 // operations. Methods that must be called with this lock held have 561 // the suffix "LI". 562 final Object mInstallLock = new Object(); 563 564 // ---------------------------------------------------------------- 565 566 // Keys are String (package name), values are Package. This also serves 567 // as the lock for the global state. Methods that must be called with 568 // this lock held have the prefix "LP". 569 @GuardedBy("mPackages") 570 final ArrayMap<String, PackageParser.Package> mPackages = 571 new ArrayMap<String, PackageParser.Package>(); 572 573 final ArrayMap<String, Set<String>> mKnownCodebase = 574 new ArrayMap<String, Set<String>>(); 575 576 // Tracks available target package names -> overlay package paths. 577 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 578 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 579 580 /** 581 * Tracks new system packages [received in an OTA] that we expect to 582 * find updated user-installed versions. Keys are package name, values 583 * are package location. 584 */ 585 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 586 /** 587 * Tracks high priority intent filters for protected actions. During boot, certain 588 * filter actions are protected and should never be allowed to have a high priority 589 * intent filter for them. However, there is one, and only one exception -- the 590 * setup wizard. It must be able to define a high priority intent filter for these 591 * actions to ensure there are no escapes from the wizard. We need to delay processing 592 * of these during boot as we need to look at all of the system packages in order 593 * to know which component is the setup wizard. 594 */ 595 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 596 /** 597 * Whether or not processing protected filters should be deferred. 598 */ 599 private boolean mDeferProtectedFilters = true; 600 601 /** 602 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 603 */ 604 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 605 /** 606 * Whether or not system app permissions should be promoted from install to runtime. 607 */ 608 boolean mPromoteSystemApps; 609 610 @GuardedBy("mPackages") 611 final Settings mSettings; 612 613 /** 614 * Set of package names that are currently "frozen", which means active 615 * surgery is being done on the code/data for that package. The platform 616 * will refuse to launch frozen packages to avoid race conditions. 617 * 618 * @see PackageFreezer 619 */ 620 @GuardedBy("mPackages") 621 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 622 623 boolean mRestoredSettings; 624 625 // System configuration read by SystemConfig. 626 final int[] mGlobalGids; 627 final SparseArray<ArraySet<String>> mSystemPermissions; 628 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 629 630 // If mac_permissions.xml was found for seinfo labeling. 631 boolean mFoundPolicyFile; 632 633 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 634 635 public static final class SharedLibraryEntry { 636 public final String path; 637 public final String apk; 638 639 SharedLibraryEntry(String _path, String _apk) { 640 path = _path; 641 apk = _apk; 642 } 643 } 644 645 // Currently known shared libraries. 646 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 647 new ArrayMap<String, SharedLibraryEntry>(); 648 649 // All available activities, for your resolving pleasure. 650 final ActivityIntentResolver mActivities = 651 new ActivityIntentResolver(); 652 653 // All available receivers, for your resolving pleasure. 654 final ActivityIntentResolver mReceivers = 655 new ActivityIntentResolver(); 656 657 // All available services, for your resolving pleasure. 658 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 659 660 // All available providers, for your resolving pleasure. 661 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 662 663 // Mapping from provider base names (first directory in content URI codePath) 664 // to the provider information. 665 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 666 new ArrayMap<String, PackageParser.Provider>(); 667 668 // Mapping from instrumentation class names to info about them. 669 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 670 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 671 672 // Mapping from permission names to info about them. 673 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 674 new ArrayMap<String, PackageParser.PermissionGroup>(); 675 676 // Packages whose data we have transfered into another package, thus 677 // should no longer exist. 678 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 679 680 // Broadcast actions that are only available to the system. 681 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 682 683 /** List of packages waiting for verification. */ 684 final SparseArray<PackageVerificationState> mPendingVerification 685 = new SparseArray<PackageVerificationState>(); 686 687 /** Set of packages associated with each app op permission. */ 688 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 689 690 final PackageInstallerService mInstallerService; 691 692 private final PackageDexOptimizer mPackageDexOptimizer; 693 694 private AtomicInteger mNextMoveId = new AtomicInteger(); 695 private final MoveCallbacks mMoveCallbacks; 696 697 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 698 699 // Cache of users who need badging. 700 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 701 702 /** Token for keys in mPendingVerification. */ 703 private int mPendingVerificationToken = 0; 704 705 volatile boolean mSystemReady; 706 volatile boolean mSafeMode; 707 volatile boolean mHasSystemUidErrors; 708 709 ApplicationInfo mAndroidApplication; 710 final ActivityInfo mResolveActivity = new ActivityInfo(); 711 final ResolveInfo mResolveInfo = new ResolveInfo(); 712 ComponentName mResolveComponentName; 713 PackageParser.Package mPlatformPackage; 714 ComponentName mCustomResolverComponentName; 715 716 boolean mResolverReplaced = false; 717 718 private final @Nullable ComponentName mIntentFilterVerifierComponent; 719 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 720 721 private int mIntentFilterVerificationToken = 0; 722 723 /** Component that knows whether or not an ephemeral application exists */ 724 final ComponentName mEphemeralResolverComponent; 725 /** The service connection to the ephemeral resolver */ 726 final EphemeralResolverConnection mEphemeralResolverConnection; 727 728 /** Component used to install ephemeral applications */ 729 final ComponentName mEphemeralInstallerComponent; 730 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 731 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 732 733 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 734 = new SparseArray<IntentFilterVerificationState>(); 735 736 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 737 new DefaultPermissionGrantPolicy(this); 738 739 // List of packages names to keep cached, even if they are uninstalled for all users 740 private List<String> mKeepUninstalledPackages; 741 742 private UserManagerInternal mUserManagerInternal; 743 744 private static class IFVerificationParams { 745 PackageParser.Package pkg; 746 boolean replacing; 747 int userId; 748 int verifierUid; 749 750 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 751 int _userId, int _verifierUid) { 752 pkg = _pkg; 753 replacing = _replacing; 754 userId = _userId; 755 replacing = _replacing; 756 verifierUid = _verifierUid; 757 } 758 } 759 760 private interface IntentFilterVerifier<T extends IntentFilter> { 761 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 762 T filter, String packageName); 763 void startVerifications(int userId); 764 void receiveVerificationResponse(int verificationId); 765 } 766 767 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 768 private Context mContext; 769 private ComponentName mIntentFilterVerifierComponent; 770 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 771 772 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 773 mContext = context; 774 mIntentFilterVerifierComponent = verifierComponent; 775 } 776 777 private String getDefaultScheme() { 778 return IntentFilter.SCHEME_HTTPS; 779 } 780 781 @Override 782 public void startVerifications(int userId) { 783 // Launch verifications requests 784 int count = mCurrentIntentFilterVerifications.size(); 785 for (int n=0; n<count; n++) { 786 int verificationId = mCurrentIntentFilterVerifications.get(n); 787 final IntentFilterVerificationState ivs = 788 mIntentFilterVerificationStates.get(verificationId); 789 790 String packageName = ivs.getPackageName(); 791 792 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 793 final int filterCount = filters.size(); 794 ArraySet<String> domainsSet = new ArraySet<>(); 795 for (int m=0; m<filterCount; m++) { 796 PackageParser.ActivityIntentInfo filter = filters.get(m); 797 domainsSet.addAll(filter.getHostsList()); 798 } 799 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 800 synchronized (mPackages) { 801 if (mSettings.createIntentFilterVerificationIfNeededLPw( 802 packageName, domainsList) != null) { 803 scheduleWriteSettingsLocked(); 804 } 805 } 806 sendVerificationRequest(userId, verificationId, ivs); 807 } 808 mCurrentIntentFilterVerifications.clear(); 809 } 810 811 private void sendVerificationRequest(int userId, int verificationId, 812 IntentFilterVerificationState ivs) { 813 814 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 815 verificationIntent.putExtra( 816 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 817 verificationId); 818 verificationIntent.putExtra( 819 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 820 getDefaultScheme()); 821 verificationIntent.putExtra( 822 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 823 ivs.getHostsString()); 824 verificationIntent.putExtra( 825 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 826 ivs.getPackageName()); 827 verificationIntent.setComponent(mIntentFilterVerifierComponent); 828 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 829 830 UserHandle user = new UserHandle(userId); 831 mContext.sendBroadcastAsUser(verificationIntent, user); 832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 833 "Sending IntentFilter verification broadcast"); 834 } 835 836 public void receiveVerificationResponse(int verificationId) { 837 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 838 839 final boolean verified = ivs.isVerified(); 840 841 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 842 final int count = filters.size(); 843 if (DEBUG_DOMAIN_VERIFICATION) { 844 Slog.i(TAG, "Received verification response " + verificationId 845 + " for " + count + " filters, verified=" + verified); 846 } 847 for (int n=0; n<count; n++) { 848 PackageParser.ActivityIntentInfo filter = filters.get(n); 849 filter.setVerified(verified); 850 851 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 852 + " verified with result:" + verified + " and hosts:" 853 + ivs.getHostsString()); 854 } 855 856 mIntentFilterVerificationStates.remove(verificationId); 857 858 final String packageName = ivs.getPackageName(); 859 IntentFilterVerificationInfo ivi = null; 860 861 synchronized (mPackages) { 862 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 863 } 864 if (ivi == null) { 865 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 866 + verificationId + " packageName:" + packageName); 867 return; 868 } 869 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 870 "Updating IntentFilterVerificationInfo for package " + packageName 871 +" verificationId:" + verificationId); 872 873 synchronized (mPackages) { 874 if (verified) { 875 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 876 } else { 877 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 878 } 879 scheduleWriteSettingsLocked(); 880 881 final int userId = ivs.getUserId(); 882 if (userId != UserHandle.USER_ALL) { 883 final int userStatus = 884 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 885 886 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 887 boolean needUpdate = false; 888 889 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 890 // already been set by the User thru the Disambiguation dialog 891 switch (userStatus) { 892 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 893 if (verified) { 894 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 895 } else { 896 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 897 } 898 needUpdate = true; 899 break; 900 901 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 902 if (verified) { 903 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 904 needUpdate = true; 905 } 906 break; 907 908 default: 909 // Nothing to do 910 } 911 912 if (needUpdate) { 913 mSettings.updateIntentFilterVerificationStatusLPw( 914 packageName, updatedStatus, userId); 915 scheduleWritePackageRestrictionsLocked(userId); 916 } 917 } 918 } 919 } 920 921 @Override 922 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 923 ActivityIntentInfo filter, String packageName) { 924 if (!hasValidDomains(filter)) { 925 return false; 926 } 927 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 928 if (ivs == null) { 929 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 930 packageName); 931 } 932 if (DEBUG_DOMAIN_VERIFICATION) { 933 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 934 } 935 ivs.addFilter(filter); 936 return true; 937 } 938 939 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 940 int userId, int verificationId, String packageName) { 941 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 942 verifierUid, userId, packageName); 943 ivs.setPendingState(); 944 synchronized (mPackages) { 945 mIntentFilterVerificationStates.append(verificationId, ivs); 946 mCurrentIntentFilterVerifications.add(verificationId); 947 } 948 return ivs; 949 } 950 } 951 952 private static boolean hasValidDomains(ActivityIntentInfo filter) { 953 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 954 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 955 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 956 } 957 958 // Set of pending broadcasts for aggregating enable/disable of components. 959 static class PendingPackageBroadcasts { 960 // for each user id, a map of <package name -> components within that package> 961 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 962 963 public PendingPackageBroadcasts() { 964 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 965 } 966 967 public ArrayList<String> get(int userId, String packageName) { 968 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 969 return packages.get(packageName); 970 } 971 972 public void put(int userId, String packageName, ArrayList<String> components) { 973 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 974 packages.put(packageName, components); 975 } 976 977 public void remove(int userId, String packageName) { 978 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 979 if (packages != null) { 980 packages.remove(packageName); 981 } 982 } 983 984 public void remove(int userId) { 985 mUidMap.remove(userId); 986 } 987 988 public int userIdCount() { 989 return mUidMap.size(); 990 } 991 992 public int userIdAt(int n) { 993 return mUidMap.keyAt(n); 994 } 995 996 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 997 return mUidMap.get(userId); 998 } 999 1000 public int size() { 1001 // total number of pending broadcast entries across all userIds 1002 int num = 0; 1003 for (int i = 0; i< mUidMap.size(); i++) { 1004 num += mUidMap.valueAt(i).size(); 1005 } 1006 return num; 1007 } 1008 1009 public void clear() { 1010 mUidMap.clear(); 1011 } 1012 1013 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1014 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1015 if (map == null) { 1016 map = new ArrayMap<String, ArrayList<String>>(); 1017 mUidMap.put(userId, map); 1018 } 1019 return map; 1020 } 1021 } 1022 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1023 1024 // Service Connection to remote media container service to copy 1025 // package uri's from external media onto secure containers 1026 // or internal storage. 1027 private IMediaContainerService mContainerService = null; 1028 1029 static final int SEND_PENDING_BROADCAST = 1; 1030 static final int MCS_BOUND = 3; 1031 static final int END_COPY = 4; 1032 static final int INIT_COPY = 5; 1033 static final int MCS_UNBIND = 6; 1034 static final int START_CLEANING_PACKAGE = 7; 1035 static final int FIND_INSTALL_LOC = 8; 1036 static final int POST_INSTALL = 9; 1037 static final int MCS_RECONNECT = 10; 1038 static final int MCS_GIVE_UP = 11; 1039 static final int UPDATED_MEDIA_STATUS = 12; 1040 static final int WRITE_SETTINGS = 13; 1041 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1042 static final int PACKAGE_VERIFIED = 15; 1043 static final int CHECK_PENDING_VERIFICATION = 16; 1044 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1045 static final int INTENT_FILTER_VERIFIED = 18; 1046 1047 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1048 1049 // Delay time in millisecs 1050 static final int BROADCAST_DELAY = 10 * 1000; 1051 1052 static UserManagerService sUserManager; 1053 1054 // Stores a list of users whose package restrictions file needs to be updated 1055 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1056 1057 final private DefaultContainerConnection mDefContainerConn = 1058 new DefaultContainerConnection(); 1059 class DefaultContainerConnection implements ServiceConnection { 1060 public void onServiceConnected(ComponentName name, IBinder service) { 1061 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1062 IMediaContainerService imcs = 1063 IMediaContainerService.Stub.asInterface(service); 1064 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1065 } 1066 1067 public void onServiceDisconnected(ComponentName name) { 1068 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1069 } 1070 } 1071 1072 // Recordkeeping of restore-after-install operations that are currently in flight 1073 // between the Package Manager and the Backup Manager 1074 static class PostInstallData { 1075 public InstallArgs args; 1076 public PackageInstalledInfo res; 1077 1078 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1079 args = _a; 1080 res = _r; 1081 } 1082 } 1083 1084 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1085 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1086 1087 // XML tags for backup/restore of various bits of state 1088 private static final String TAG_PREFERRED_BACKUP = "pa"; 1089 private static final String TAG_DEFAULT_APPS = "da"; 1090 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1091 1092 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1093 private static final String TAG_ALL_GRANTS = "rt-grants"; 1094 private static final String TAG_GRANT = "grant"; 1095 private static final String ATTR_PACKAGE_NAME = "pkg"; 1096 1097 private static final String TAG_PERMISSION = "perm"; 1098 private static final String ATTR_PERMISSION_NAME = "name"; 1099 private static final String ATTR_IS_GRANTED = "g"; 1100 private static final String ATTR_USER_SET = "set"; 1101 private static final String ATTR_USER_FIXED = "fixed"; 1102 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1103 1104 // System/policy permission grants are not backed up 1105 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1106 FLAG_PERMISSION_POLICY_FIXED 1107 | FLAG_PERMISSION_SYSTEM_FIXED 1108 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1109 1110 // And we back up these user-adjusted states 1111 private static final int USER_RUNTIME_GRANT_MASK = 1112 FLAG_PERMISSION_USER_SET 1113 | FLAG_PERMISSION_USER_FIXED 1114 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1115 1116 final @Nullable String mRequiredVerifierPackage; 1117 final @NonNull String mRequiredInstallerPackage; 1118 final @Nullable String mSetupWizardPackage; 1119 final @NonNull String mServicesSystemSharedLibraryPackageName; 1120 final @NonNull String mSharedSystemSharedLibraryPackageName; 1121 1122 private final PackageUsage mPackageUsage = new PackageUsage(); 1123 1124 private class PackageUsage { 1125 private static final int WRITE_INTERVAL 1126 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1127 1128 private final Object mFileLock = new Object(); 1129 private final AtomicLong mLastWritten = new AtomicLong(0); 1130 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1131 1132 private boolean mIsHistoricalPackageUsageAvailable = true; 1133 1134 boolean isHistoricalPackageUsageAvailable() { 1135 return mIsHistoricalPackageUsageAvailable; 1136 } 1137 1138 void write(boolean force) { 1139 if (force) { 1140 writeInternal(); 1141 return; 1142 } 1143 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1144 && !DEBUG_DEXOPT) { 1145 return; 1146 } 1147 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1148 new Thread("PackageUsage_DiskWriter") { 1149 @Override 1150 public void run() { 1151 try { 1152 writeInternal(); 1153 } finally { 1154 mBackgroundWriteRunning.set(false); 1155 } 1156 } 1157 }.start(); 1158 } 1159 } 1160 1161 private void writeInternal() { 1162 synchronized (mPackages) { 1163 synchronized (mFileLock) { 1164 AtomicFile file = getFile(); 1165 FileOutputStream f = null; 1166 try { 1167 f = file.startWrite(); 1168 BufferedOutputStream out = new BufferedOutputStream(f); 1169 FileUtils.setPermissions(file.getBaseFile().getPath(), 1170 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1171 StringBuilder sb = new StringBuilder(); 1172 1173 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1174 sb.append('\n'); 1175 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1176 1177 for (PackageParser.Package pkg : mPackages.values()) { 1178 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1179 continue; 1180 } 1181 sb.setLength(0); 1182 sb.append(pkg.packageName); 1183 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1184 sb.append(' '); 1185 sb.append(usageTimeInMillis); 1186 } 1187 sb.append('\n'); 1188 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1189 } 1190 out.flush(); 1191 file.finishWrite(f); 1192 } catch (IOException e) { 1193 if (f != null) { 1194 file.failWrite(f); 1195 } 1196 Log.e(TAG, "Failed to write package usage times", e); 1197 } 1198 } 1199 } 1200 mLastWritten.set(SystemClock.elapsedRealtime()); 1201 } 1202 1203 void readLP() { 1204 synchronized (mFileLock) { 1205 AtomicFile file = getFile(); 1206 BufferedInputStream in = null; 1207 try { 1208 in = new BufferedInputStream(file.openRead()); 1209 StringBuffer sb = new StringBuffer(); 1210 1211 String firstLine = readLine(in, sb); 1212 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1213 readVersion1LP(in, sb); 1214 } else { 1215 readVersion0LP(in, sb, firstLine); 1216 } 1217 } catch (FileNotFoundException expected) { 1218 mIsHistoricalPackageUsageAvailable = false; 1219 } catch (IOException e) { 1220 Log.w(TAG, "Failed to read package usage times", e); 1221 } finally { 1222 IoUtils.closeQuietly(in); 1223 } 1224 } 1225 mLastWritten.set(SystemClock.elapsedRealtime()); 1226 } 1227 1228 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1229 throws IOException { 1230 // Initial version of the file had no version number and stored one 1231 // package-timestamp pair per line. 1232 // Note that the first line has already been read from the InputStream. 1233 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1234 String[] tokens = line.split(" "); 1235 if (tokens.length != 2) { 1236 throw new IOException("Failed to parse " + line + 1237 " as package-timestamp pair."); 1238 } 1239 1240 String packageName = tokens[0]; 1241 PackageParser.Package pkg = mPackages.get(packageName); 1242 if (pkg == null) { 1243 continue; 1244 } 1245 1246 long timestamp = parseAsLong(tokens[1]); 1247 for (int reason = 0; 1248 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1249 reason++) { 1250 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1251 } 1252 } 1253 } 1254 1255 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1256 // Version 1 of the file started with the corresponding version 1257 // number and then stored a package name and eight timestamps per line. 1258 String line; 1259 while ((line = readLine(in, sb)) != null) { 1260 String[] tokens = line.split(" "); 1261 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1262 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1263 } 1264 1265 String packageName = tokens[0]; 1266 PackageParser.Package pkg = mPackages.get(packageName); 1267 if (pkg == null) { 1268 continue; 1269 } 1270 1271 for (int reason = 0; 1272 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1273 reason++) { 1274 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1275 } 1276 } 1277 } 1278 1279 private long parseAsLong(String token) throws IOException { 1280 try { 1281 return Long.parseLong(token); 1282 } catch (NumberFormatException e) { 1283 throw new IOException("Failed to parse " + token + " as a long.", e); 1284 } 1285 } 1286 1287 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1288 return readToken(in, sb, '\n'); 1289 } 1290 1291 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1292 throws IOException { 1293 sb.setLength(0); 1294 while (true) { 1295 int ch = in.read(); 1296 if (ch == -1) { 1297 if (sb.length() == 0) { 1298 return null; 1299 } 1300 throw new IOException("Unexpected EOF"); 1301 } 1302 if (ch == endOfToken) { 1303 return sb.toString(); 1304 } 1305 sb.append((char)ch); 1306 } 1307 } 1308 1309 private AtomicFile getFile() { 1310 File dataDir = Environment.getDataDirectory(); 1311 File systemDir = new File(dataDir, "system"); 1312 File fname = new File(systemDir, "package-usage.list"); 1313 return new AtomicFile(fname); 1314 } 1315 1316 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1317 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1318 } 1319 1320 class PackageHandler extends Handler { 1321 private boolean mBound = false; 1322 final ArrayList<HandlerParams> mPendingInstalls = 1323 new ArrayList<HandlerParams>(); 1324 1325 private boolean connectToService() { 1326 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1327 " DefaultContainerService"); 1328 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1330 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1331 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1333 mBound = true; 1334 return true; 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 return false; 1338 } 1339 1340 private void disconnectService() { 1341 mContainerService = null; 1342 mBound = false; 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1344 mContext.unbindService(mDefContainerConn); 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 } 1347 1348 PackageHandler(Looper looper) { 1349 super(looper); 1350 } 1351 1352 public void handleMessage(Message msg) { 1353 try { 1354 doHandleMessage(msg); 1355 } finally { 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 } 1358 } 1359 1360 void doHandleMessage(Message msg) { 1361 switch (msg.what) { 1362 case INIT_COPY: { 1363 HandlerParams params = (HandlerParams) msg.obj; 1364 int idx = mPendingInstalls.size(); 1365 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1366 // If a bind was already initiated we dont really 1367 // need to do anything. The pending install 1368 // will be processed later on. 1369 if (!mBound) { 1370 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1371 System.identityHashCode(mHandler)); 1372 // If this is the only one pending we might 1373 // have to bind to the service again. 1374 if (!connectToService()) { 1375 Slog.e(TAG, "Failed to bind to media container service"); 1376 params.serviceError(); 1377 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1378 System.identityHashCode(mHandler)); 1379 if (params.traceMethod != null) { 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1381 params.traceCookie); 1382 } 1383 return; 1384 } else { 1385 // Once we bind to the service, the first 1386 // pending request will be processed. 1387 mPendingInstalls.add(idx, params); 1388 } 1389 } else { 1390 mPendingInstalls.add(idx, params); 1391 // Already bound to the service. Just make 1392 // sure we trigger off processing the first request. 1393 if (idx == 0) { 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 } 1397 break; 1398 } 1399 case MCS_BOUND: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1401 if (msg.obj != null) { 1402 mContainerService = (IMediaContainerService) msg.obj; 1403 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1404 System.identityHashCode(mHandler)); 1405 } 1406 if (mContainerService == null) { 1407 if (!mBound) { 1408 // Something seriously wrong since we are not bound and we are not 1409 // waiting for connection. Bail out. 1410 Slog.e(TAG, "Cannot bind to media container service"); 1411 for (HandlerParams params : mPendingInstalls) { 1412 // Indicate service bind error 1413 params.serviceError(); 1414 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1415 System.identityHashCode(params)); 1416 if (params.traceMethod != null) { 1417 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1418 params.traceMethod, params.traceCookie); 1419 } 1420 return; 1421 } 1422 mPendingInstalls.clear(); 1423 } else { 1424 Slog.w(TAG, "Waiting to connect to media container service"); 1425 } 1426 } else if (mPendingInstalls.size() > 0) { 1427 HandlerParams params = mPendingInstalls.get(0); 1428 if (params != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1430 System.identityHashCode(params)); 1431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1432 if (params.startCopy()) { 1433 // We are done... look for more work or to 1434 // go idle. 1435 if (DEBUG_SD_INSTALL) Log.i(TAG, 1436 "Checking for more work or unbind..."); 1437 // Delete pending install 1438 if (mPendingInstalls.size() > 0) { 1439 mPendingInstalls.remove(0); 1440 } 1441 if (mPendingInstalls.size() == 0) { 1442 if (mBound) { 1443 if (DEBUG_SD_INSTALL) Log.i(TAG, 1444 "Posting delayed MCS_UNBIND"); 1445 removeMessages(MCS_UNBIND); 1446 Message ubmsg = obtainMessage(MCS_UNBIND); 1447 // Unbind after a little delay, to avoid 1448 // continual thrashing. 1449 sendMessageDelayed(ubmsg, 10000); 1450 } 1451 } else { 1452 // There are more pending requests in queue. 1453 // Just post MCS_BOUND message to trigger processing 1454 // of next pending install. 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting MCS_BOUND for next work"); 1457 mHandler.sendEmptyMessage(MCS_BOUND); 1458 } 1459 } 1460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1461 } 1462 } else { 1463 // Should never happen ideally. 1464 Slog.w(TAG, "Empty queue"); 1465 } 1466 break; 1467 } 1468 case MCS_RECONNECT: { 1469 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1470 if (mPendingInstalls.size() > 0) { 1471 if (mBound) { 1472 disconnectService(); 1473 } 1474 if (!connectToService()) { 1475 Slog.e(TAG, "Failed to bind to media container service"); 1476 for (HandlerParams params : mPendingInstalls) { 1477 // Indicate service bind error 1478 params.serviceError(); 1479 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1480 System.identityHashCode(params)); 1481 } 1482 mPendingInstalls.clear(); 1483 } 1484 } 1485 break; 1486 } 1487 case MCS_UNBIND: { 1488 // If there is no actual work left, then time to unbind. 1489 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1490 1491 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1492 if (mBound) { 1493 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1494 1495 disconnectService(); 1496 } 1497 } else if (mPendingInstalls.size() > 0) { 1498 // There are more pending requests in queue. 1499 // Just post MCS_BOUND message to trigger processing 1500 // of next pending install. 1501 mHandler.sendEmptyMessage(MCS_BOUND); 1502 } 1503 1504 break; 1505 } 1506 case MCS_GIVE_UP: { 1507 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1508 HandlerParams params = mPendingInstalls.remove(0); 1509 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1510 System.identityHashCode(params)); 1511 break; 1512 } 1513 case SEND_PENDING_BROADCAST: { 1514 String packages[]; 1515 ArrayList<String> components[]; 1516 int size = 0; 1517 int uids[]; 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 if (mPendingBroadcasts == null) { 1521 return; 1522 } 1523 size = mPendingBroadcasts.size(); 1524 if (size <= 0) { 1525 // Nothing to be done. Just return 1526 return; 1527 } 1528 packages = new String[size]; 1529 components = new ArrayList[size]; 1530 uids = new int[size]; 1531 int i = 0; // filling out the above arrays 1532 1533 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1534 int packageUserId = mPendingBroadcasts.userIdAt(n); 1535 Iterator<Map.Entry<String, ArrayList<String>>> it 1536 = mPendingBroadcasts.packagesForUserId(packageUserId) 1537 .entrySet().iterator(); 1538 while (it.hasNext() && i < size) { 1539 Map.Entry<String, ArrayList<String>> ent = it.next(); 1540 packages[i] = ent.getKey(); 1541 components[i] = ent.getValue(); 1542 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1543 uids[i] = (ps != null) 1544 ? UserHandle.getUid(packageUserId, ps.appId) 1545 : -1; 1546 i++; 1547 } 1548 } 1549 size = i; 1550 mPendingBroadcasts.clear(); 1551 } 1552 // Send broadcasts 1553 for (int i = 0; i < size; i++) { 1554 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1555 } 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1557 break; 1558 } 1559 case START_CLEANING_PACKAGE: { 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1561 final String packageName = (String)msg.obj; 1562 final int userId = msg.arg1; 1563 final boolean andCode = msg.arg2 != 0; 1564 synchronized (mPackages) { 1565 if (userId == UserHandle.USER_ALL) { 1566 int[] users = sUserManager.getUserIds(); 1567 for (int user : users) { 1568 mSettings.addPackageToCleanLPw( 1569 new PackageCleanItem(user, packageName, andCode)); 1570 } 1571 } else { 1572 mSettings.addPackageToCleanLPw( 1573 new PackageCleanItem(userId, packageName, andCode)); 1574 } 1575 } 1576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1577 startCleaningPackages(); 1578 } break; 1579 case POST_INSTALL: { 1580 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1581 1582 PostInstallData data = mRunningInstalls.get(msg.arg1); 1583 final boolean didRestore = (msg.arg2 != 0); 1584 mRunningInstalls.delete(msg.arg1); 1585 1586 if (data != null) { 1587 InstallArgs args = data.args; 1588 PackageInstalledInfo parentRes = data.res; 1589 1590 final boolean grantPermissions = (args.installFlags 1591 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1592 final boolean killApp = (args.installFlags 1593 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1594 final String[] grantedPermissions = args.installGrantPermissions; 1595 1596 // Handle the parent package 1597 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1598 grantedPermissions, didRestore, args.installerPackageName, 1599 args.observer); 1600 1601 // Handle the child packages 1602 final int childCount = (parentRes.addedChildPackages != null) 1603 ? parentRes.addedChildPackages.size() : 0; 1604 for (int i = 0; i < childCount; i++) { 1605 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1606 handlePackagePostInstall(childRes, grantPermissions, killApp, 1607 grantedPermissions, false, args.installerPackageName, 1608 args.observer); 1609 } 1610 1611 // Log tracing if needed 1612 if (args.traceMethod != null) { 1613 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1614 args.traceCookie); 1615 } 1616 } else { 1617 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1618 } 1619 1620 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1621 } break; 1622 case UPDATED_MEDIA_STATUS: { 1623 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1624 boolean reportStatus = msg.arg1 == 1; 1625 boolean doGc = msg.arg2 == 1; 1626 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1627 if (doGc) { 1628 // Force a gc to clear up stale containers. 1629 Runtime.getRuntime().gc(); 1630 } 1631 if (msg.obj != null) { 1632 @SuppressWarnings("unchecked") 1633 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1635 // Unload containers 1636 unloadAllContainers(args); 1637 } 1638 if (reportStatus) { 1639 try { 1640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1641 PackageHelper.getMountService().finishMediaUpdate(); 1642 } catch (RemoteException e) { 1643 Log.e(TAG, "MountService not running?"); 1644 } 1645 } 1646 } break; 1647 case WRITE_SETTINGS: { 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1649 synchronized (mPackages) { 1650 removeMessages(WRITE_SETTINGS); 1651 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1652 mSettings.writeLPr(); 1653 mDirtyUsers.clear(); 1654 } 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1656 } break; 1657 case WRITE_PACKAGE_RESTRICTIONS: { 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1659 synchronized (mPackages) { 1660 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1661 for (int userId : mDirtyUsers) { 1662 mSettings.writePackageRestrictionsLPr(userId); 1663 } 1664 mDirtyUsers.clear(); 1665 } 1666 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1667 } break; 1668 case CHECK_PENDING_VERIFICATION: { 1669 final int verificationId = msg.arg1; 1670 final PackageVerificationState state = mPendingVerification.get(verificationId); 1671 1672 if ((state != null) && !state.timeoutExtended()) { 1673 final InstallArgs args = state.getInstallArgs(); 1674 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1675 1676 Slog.i(TAG, "Verification timed out for " + originUri); 1677 mPendingVerification.remove(verificationId); 1678 1679 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1680 1681 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1682 Slog.i(TAG, "Continuing with installation of " + originUri); 1683 state.setVerifierResponse(Binder.getCallingUid(), 1684 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1685 broadcastPackageVerified(verificationId, originUri, 1686 PackageManager.VERIFICATION_ALLOW, 1687 state.getInstallArgs().getUser()); 1688 try { 1689 ret = args.copyApk(mContainerService, true); 1690 } catch (RemoteException e) { 1691 Slog.e(TAG, "Could not contact the ContainerService"); 1692 } 1693 } else { 1694 broadcastPackageVerified(verificationId, originUri, 1695 PackageManager.VERIFICATION_REJECT, 1696 state.getInstallArgs().getUser()); 1697 } 1698 1699 Trace.asyncTraceEnd( 1700 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1701 1702 processPendingInstall(args, ret); 1703 mHandler.sendEmptyMessage(MCS_UNBIND); 1704 } 1705 break; 1706 } 1707 case PACKAGE_VERIFIED: { 1708 final int verificationId = msg.arg1; 1709 1710 final PackageVerificationState state = mPendingVerification.get(verificationId); 1711 if (state == null) { 1712 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1713 break; 1714 } 1715 1716 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1717 1718 state.setVerifierResponse(response.callerUid, response.code); 1719 1720 if (state.isVerificationComplete()) { 1721 mPendingVerification.remove(verificationId); 1722 1723 final InstallArgs args = state.getInstallArgs(); 1724 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1725 1726 int ret; 1727 if (state.isInstallAllowed()) { 1728 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1729 broadcastPackageVerified(verificationId, originUri, 1730 response.code, state.getInstallArgs().getUser()); 1731 try { 1732 ret = args.copyApk(mContainerService, true); 1733 } catch (RemoteException e) { 1734 Slog.e(TAG, "Could not contact the ContainerService"); 1735 } 1736 } else { 1737 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1738 } 1739 1740 Trace.asyncTraceEnd( 1741 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1742 1743 processPendingInstall(args, ret); 1744 mHandler.sendEmptyMessage(MCS_UNBIND); 1745 } 1746 1747 break; 1748 } 1749 case START_INTENT_FILTER_VERIFICATIONS: { 1750 IFVerificationParams params = (IFVerificationParams) msg.obj; 1751 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1752 params.replacing, params.pkg); 1753 break; 1754 } 1755 case INTENT_FILTER_VERIFIED: { 1756 final int verificationId = msg.arg1; 1757 1758 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1759 verificationId); 1760 if (state == null) { 1761 Slog.w(TAG, "Invalid IntentFilter verification token " 1762 + verificationId + " received"); 1763 break; 1764 } 1765 1766 final int userId = state.getUserId(); 1767 1768 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1769 "Processing IntentFilter verification with token:" 1770 + verificationId + " and userId:" + userId); 1771 1772 final IntentFilterVerificationResponse response = 1773 (IntentFilterVerificationResponse) msg.obj; 1774 1775 state.setVerifierResponse(response.callerUid, response.code); 1776 1777 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1778 "IntentFilter verification with token:" + verificationId 1779 + " and userId:" + userId 1780 + " is settings verifier response with response code:" 1781 + response.code); 1782 1783 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1784 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1785 + response.getFailedDomainsString()); 1786 } 1787 1788 if (state.isVerificationComplete()) { 1789 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1790 } else { 1791 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1792 "IntentFilter verification with token:" + verificationId 1793 + " was not said to be complete"); 1794 } 1795 1796 break; 1797 } 1798 } 1799 } 1800 } 1801 1802 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1803 boolean killApp, String[] grantedPermissions, 1804 boolean launchedForRestore, String installerPackage, 1805 IPackageInstallObserver2 installObserver) { 1806 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1807 // Send the removed broadcasts 1808 if (res.removedInfo != null) { 1809 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1810 } 1811 1812 // Now that we successfully installed the package, grant runtime 1813 // permissions if requested before broadcasting the install. 1814 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1815 >= Build.VERSION_CODES.M) { 1816 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1817 } 1818 1819 final boolean update = res.removedInfo != null 1820 && res.removedInfo.removedPackage != null; 1821 1822 // If this is the first time we have child packages for a disabled privileged 1823 // app that had no children, we grant requested runtime permissions to the new 1824 // children if the parent on the system image had them already granted. 1825 if (res.pkg.parentPackage != null) { 1826 synchronized (mPackages) { 1827 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1828 } 1829 } 1830 1831 synchronized (mPackages) { 1832 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1833 } 1834 1835 final String packageName = res.pkg.applicationInfo.packageName; 1836 Bundle extras = new Bundle(1); 1837 extras.putInt(Intent.EXTRA_UID, res.uid); 1838 1839 // Determine the set of users who are adding this package for 1840 // the first time vs. those who are seeing an update. 1841 int[] firstUsers = EMPTY_INT_ARRAY; 1842 int[] updateUsers = EMPTY_INT_ARRAY; 1843 if (res.origUsers == null || res.origUsers.length == 0) { 1844 firstUsers = res.newUsers; 1845 } else { 1846 for (int newUser : res.newUsers) { 1847 boolean isNew = true; 1848 for (int origUser : res.origUsers) { 1849 if (origUser == newUser) { 1850 isNew = false; 1851 break; 1852 } 1853 } 1854 if (isNew) { 1855 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1856 } else { 1857 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1858 } 1859 } 1860 } 1861 1862 // Send installed broadcasts if the install/update is not ephemeral 1863 if (!isEphemeral(res.pkg)) { 1864 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1865 1866 // Send added for users that see the package for the first time 1867 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1868 extras, 0 /*flags*/, null /*targetPackage*/, 1869 null /*finishedReceiver*/, firstUsers); 1870 1871 // Send added for users that don't see the package for the first time 1872 if (update) { 1873 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1874 } 1875 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1876 extras, 0 /*flags*/, null /*targetPackage*/, 1877 null /*finishedReceiver*/, updateUsers); 1878 1879 // Send replaced for users that don't see the package for the first time 1880 if (update) { 1881 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1882 packageName, extras, 0 /*flags*/, 1883 null /*targetPackage*/, null /*finishedReceiver*/, 1884 updateUsers); 1885 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1886 null /*package*/, null /*extras*/, 0 /*flags*/, 1887 packageName /*targetPackage*/, 1888 null /*finishedReceiver*/, updateUsers); 1889 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1890 // First-install and we did a restore, so we're responsible for the 1891 // first-launch broadcast. 1892 if (DEBUG_BACKUP) { 1893 Slog.i(TAG, "Post-restore of " + packageName 1894 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1895 } 1896 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1897 } 1898 1899 // Send broadcast package appeared if forward locked/external for all users 1900 // treat asec-hosted packages like removable media on upgrade 1901 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1902 if (DEBUG_INSTALL) { 1903 Slog.i(TAG, "upgrading pkg " + res.pkg 1904 + " is ASEC-hosted -> AVAILABLE"); 1905 } 1906 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1907 ArrayList<String> pkgList = new ArrayList<>(1); 1908 pkgList.add(packageName); 1909 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1910 } 1911 } 1912 1913 // Work that needs to happen on first install within each user 1914 if (firstUsers != null && firstUsers.length > 0) { 1915 synchronized (mPackages) { 1916 for (int userId : firstUsers) { 1917 // If this app is a browser and it's newly-installed for some 1918 // users, clear any default-browser state in those users. The 1919 // app's nature doesn't depend on the user, so we can just check 1920 // its browser nature in any user and generalize. 1921 if (packageIsBrowser(packageName, userId)) { 1922 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1923 } 1924 1925 // We may also need to apply pending (restored) runtime 1926 // permission grants within these users. 1927 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1928 } 1929 } 1930 } 1931 1932 // Log current value of "unknown sources" setting 1933 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1934 getUnknownSourcesSettings()); 1935 1936 // Force a gc to clear up things 1937 Runtime.getRuntime().gc(); 1938 1939 // Remove the replaced package's older resources safely now 1940 // We delete after a gc for applications on sdcard. 1941 if (res.removedInfo != null && res.removedInfo.args != null) { 1942 synchronized (mInstallLock) { 1943 res.removedInfo.args.doPostDeleteLI(true); 1944 } 1945 } 1946 } 1947 1948 // If someone is watching installs - notify them 1949 if (installObserver != null) { 1950 try { 1951 Bundle extras = extrasForInstallResult(res); 1952 installObserver.onPackageInstalled(res.name, res.returnCode, 1953 res.returnMsg, extras); 1954 } catch (RemoteException e) { 1955 Slog.i(TAG, "Observer no longer exists."); 1956 } 1957 } 1958 } 1959 1960 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1961 PackageParser.Package pkg) { 1962 if (pkg.parentPackage == null) { 1963 return; 1964 } 1965 if (pkg.requestedPermissions == null) { 1966 return; 1967 } 1968 final PackageSetting disabledSysParentPs = mSettings 1969 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1970 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1971 || !disabledSysParentPs.isPrivileged() 1972 || (disabledSysParentPs.childPackageNames != null 1973 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1974 return; 1975 } 1976 final int[] allUserIds = sUserManager.getUserIds(); 1977 final int permCount = pkg.requestedPermissions.size(); 1978 for (int i = 0; i < permCount; i++) { 1979 String permission = pkg.requestedPermissions.get(i); 1980 BasePermission bp = mSettings.mPermissions.get(permission); 1981 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1982 continue; 1983 } 1984 for (int userId : allUserIds) { 1985 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1986 permission, userId)) { 1987 grantRuntimePermission(pkg.packageName, permission, userId); 1988 } 1989 } 1990 } 1991 } 1992 1993 private StorageEventListener mStorageListener = new StorageEventListener() { 1994 @Override 1995 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1996 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1997 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1998 final String volumeUuid = vol.getFsUuid(); 1999 2000 // Clean up any users or apps that were removed or recreated 2001 // while this volume was missing 2002 reconcileUsers(volumeUuid); 2003 reconcileApps(volumeUuid); 2004 2005 // Clean up any install sessions that expired or were 2006 // cancelled while this volume was missing 2007 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2008 2009 loadPrivatePackages(vol); 2010 2011 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2012 unloadPrivatePackages(vol); 2013 } 2014 } 2015 2016 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2017 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2018 updateExternalMediaStatus(true, false); 2019 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2020 updateExternalMediaStatus(false, false); 2021 } 2022 } 2023 } 2024 2025 @Override 2026 public void onVolumeForgotten(String fsUuid) { 2027 if (TextUtils.isEmpty(fsUuid)) { 2028 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2029 return; 2030 } 2031 2032 // Remove any apps installed on the forgotten volume 2033 synchronized (mPackages) { 2034 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2035 for (PackageSetting ps : packages) { 2036 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2037 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2038 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2039 } 2040 2041 mSettings.onVolumeForgotten(fsUuid); 2042 mSettings.writeLPr(); 2043 } 2044 } 2045 }; 2046 2047 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2048 String[] grantedPermissions) { 2049 for (int userId : userIds) { 2050 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2051 } 2052 2053 // We could have touched GID membership, so flush out packages.list 2054 synchronized (mPackages) { 2055 mSettings.writePackageListLPr(); 2056 } 2057 } 2058 2059 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2060 String[] grantedPermissions) { 2061 SettingBase sb = (SettingBase) pkg.mExtras; 2062 if (sb == null) { 2063 return; 2064 } 2065 2066 PermissionsState permissionsState = sb.getPermissionsState(); 2067 2068 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2069 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2070 2071 for (String permission : pkg.requestedPermissions) { 2072 final BasePermission bp; 2073 synchronized (mPackages) { 2074 bp = mSettings.mPermissions.get(permission); 2075 } 2076 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2077 && (grantedPermissions == null 2078 || ArrayUtils.contains(grantedPermissions, permission))) { 2079 final int flags = permissionsState.getPermissionFlags(permission, userId); 2080 // Installer cannot change immutable permissions. 2081 if ((flags & immutableFlags) == 0) { 2082 grantRuntimePermission(pkg.packageName, permission, userId); 2083 } 2084 } 2085 } 2086 } 2087 2088 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2089 Bundle extras = null; 2090 switch (res.returnCode) { 2091 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2092 extras = new Bundle(); 2093 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2094 res.origPermission); 2095 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2096 res.origPackage); 2097 break; 2098 } 2099 case PackageManager.INSTALL_SUCCEEDED: { 2100 extras = new Bundle(); 2101 extras.putBoolean(Intent.EXTRA_REPLACING, 2102 res.removedInfo != null && res.removedInfo.removedPackage != null); 2103 break; 2104 } 2105 } 2106 return extras; 2107 } 2108 2109 void scheduleWriteSettingsLocked() { 2110 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2111 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2112 } 2113 } 2114 2115 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2116 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2117 scheduleWritePackageRestrictionsLocked(userId); 2118 } 2119 2120 void scheduleWritePackageRestrictionsLocked(int userId) { 2121 final int[] userIds = (userId == UserHandle.USER_ALL) 2122 ? sUserManager.getUserIds() : new int[]{userId}; 2123 for (int nextUserId : userIds) { 2124 if (!sUserManager.exists(nextUserId)) return; 2125 mDirtyUsers.add(nextUserId); 2126 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2127 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2128 } 2129 } 2130 } 2131 2132 public static PackageManagerService main(Context context, Installer installer, 2133 boolean factoryTest, boolean onlyCore) { 2134 // Self-check for initial settings. 2135 PackageManagerServiceCompilerMapping.checkProperties(); 2136 2137 PackageManagerService m = new PackageManagerService(context, installer, 2138 factoryTest, onlyCore); 2139 m.enableSystemUserPackages(); 2140 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2141 // disabled after already being started. 2142 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2143 UserHandle.USER_SYSTEM); 2144 ServiceManager.addService("package", m); 2145 return m; 2146 } 2147 2148 private void enableSystemUserPackages() { 2149 if (!UserManager.isSplitSystemUser()) { 2150 return; 2151 } 2152 // For system user, enable apps based on the following conditions: 2153 // - app is whitelisted or belong to one of these groups: 2154 // -- system app which has no launcher icons 2155 // -- system app which has INTERACT_ACROSS_USERS permission 2156 // -- system IME app 2157 // - app is not in the blacklist 2158 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2159 Set<String> enableApps = new ArraySet<>(); 2160 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2161 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2162 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2163 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2164 enableApps.addAll(wlApps); 2165 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2166 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2167 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2168 enableApps.removeAll(blApps); 2169 Log.i(TAG, "Applications installed for system user: " + enableApps); 2170 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2171 UserHandle.SYSTEM); 2172 final int allAppsSize = allAps.size(); 2173 synchronized (mPackages) { 2174 for (int i = 0; i < allAppsSize; i++) { 2175 String pName = allAps.get(i); 2176 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2177 // Should not happen, but we shouldn't be failing if it does 2178 if (pkgSetting == null) { 2179 continue; 2180 } 2181 boolean install = enableApps.contains(pName); 2182 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2183 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2184 + " for system user"); 2185 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2186 } 2187 } 2188 } 2189 } 2190 2191 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2192 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2193 Context.DISPLAY_SERVICE); 2194 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2195 } 2196 2197 public PackageManagerService(Context context, Installer installer, 2198 boolean factoryTest, boolean onlyCore) { 2199 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2200 SystemClock.uptimeMillis()); 2201 2202 if (mSdkVersion <= 0) { 2203 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2204 } 2205 2206 mContext = context; 2207 mFactoryTest = factoryTest; 2208 mOnlyCore = onlyCore; 2209 mMetrics = new DisplayMetrics(); 2210 mSettings = new Settings(mPackages); 2211 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2214 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2215 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2216 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2217 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2218 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2219 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2220 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2221 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2222 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2223 2224 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2225 if (separateProcesses != null && separateProcesses.length() > 0) { 2226 if ("*".equals(separateProcesses)) { 2227 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2228 mSeparateProcesses = null; 2229 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2230 } else { 2231 mDefParseFlags = 0; 2232 mSeparateProcesses = separateProcesses.split(","); 2233 Slog.w(TAG, "Running with debug.separate_processes: " 2234 + separateProcesses); 2235 } 2236 } else { 2237 mDefParseFlags = 0; 2238 mSeparateProcesses = null; 2239 } 2240 2241 mInstaller = installer; 2242 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2243 "*dexopt*"); 2244 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2245 2246 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2247 FgThread.get().getLooper()); 2248 2249 getDefaultDisplayMetrics(context, mMetrics); 2250 2251 SystemConfig systemConfig = SystemConfig.getInstance(); 2252 mGlobalGids = systemConfig.getGlobalGids(); 2253 mSystemPermissions = systemConfig.getSystemPermissions(); 2254 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2255 2256 synchronized (mInstallLock) { 2257 // writer 2258 synchronized (mPackages) { 2259 mHandlerThread = new ServiceThread(TAG, 2260 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2261 mHandlerThread.start(); 2262 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2263 mProcessLoggingHandler = new ProcessLoggingHandler(); 2264 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2265 2266 File dataDir = Environment.getDataDirectory(); 2267 mAppInstallDir = new File(dataDir, "app"); 2268 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2269 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2270 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2271 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2272 2273 sUserManager = new UserManagerService(context, this, mPackages); 2274 2275 // Propagate permission configuration in to package manager. 2276 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2277 = systemConfig.getPermissions(); 2278 for (int i=0; i<permConfig.size(); i++) { 2279 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2280 BasePermission bp = mSettings.mPermissions.get(perm.name); 2281 if (bp == null) { 2282 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2283 mSettings.mPermissions.put(perm.name, bp); 2284 } 2285 if (perm.gids != null) { 2286 bp.setGids(perm.gids, perm.perUser); 2287 } 2288 } 2289 2290 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2291 for (int i=0; i<libConfig.size(); i++) { 2292 mSharedLibraries.put(libConfig.keyAt(i), 2293 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2294 } 2295 2296 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2297 2298 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2299 2300 String customResolverActivity = Resources.getSystem().getString( 2301 R.string.config_customResolverActivity); 2302 if (TextUtils.isEmpty(customResolverActivity)) { 2303 customResolverActivity = null; 2304 } else { 2305 mCustomResolverComponentName = ComponentName.unflattenFromString( 2306 customResolverActivity); 2307 } 2308 2309 long startTime = SystemClock.uptimeMillis(); 2310 2311 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2312 startTime); 2313 2314 // Set flag to monitor and not change apk file paths when 2315 // scanning install directories. 2316 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2317 2318 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2319 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2320 2321 if (bootClassPath == null) { 2322 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2323 } 2324 2325 if (systemServerClassPath == null) { 2326 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2327 } 2328 2329 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2330 final String[] dexCodeInstructionSets = 2331 getDexCodeInstructionSets( 2332 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2333 2334 /** 2335 * Ensure all external libraries have had dexopt run on them. 2336 */ 2337 if (mSharedLibraries.size() > 0) { 2338 // NOTE: For now, we're compiling these system "shared libraries" 2339 // (and framework jars) into all available architectures. It's possible 2340 // to compile them only when we come across an app that uses them (there's 2341 // already logic for that in scanPackageLI) but that adds some complexity. 2342 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2343 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2344 final String lib = libEntry.path; 2345 if (lib == null) { 2346 continue; 2347 } 2348 2349 try { 2350 // Shared libraries do not have profiles so we perform a full 2351 // AOT compilation (if needed). 2352 int dexoptNeeded = DexFile.getDexOptNeeded( 2353 lib, dexCodeInstructionSet, 2354 getCompilerFilterForReason(REASON_SHARED_APK), 2355 false /* newProfile */); 2356 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2357 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2358 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2359 getCompilerFilterForReason(REASON_SHARED_APK), 2360 StorageManager.UUID_PRIVATE_INTERNAL, 2361 SKIP_SHARED_LIBRARY_CHECK); 2362 } 2363 } catch (FileNotFoundException e) { 2364 Slog.w(TAG, "Library not found: " + lib); 2365 } catch (IOException | InstallerException e) { 2366 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2367 + e.getMessage()); 2368 } 2369 } 2370 } 2371 } 2372 2373 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2374 2375 final VersionInfo ver = mSettings.getInternalVersion(); 2376 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2377 2378 // when upgrading from pre-M, promote system app permissions from install to runtime 2379 mPromoteSystemApps = 2380 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2381 2382 // save off the names of pre-existing system packages prior to scanning; we don't 2383 // want to automatically grant runtime permissions for new system apps 2384 if (mPromoteSystemApps) { 2385 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2386 while (pkgSettingIter.hasNext()) { 2387 PackageSetting ps = pkgSettingIter.next(); 2388 if (isSystemApp(ps)) { 2389 mExistingSystemPackages.add(ps.name); 2390 } 2391 } 2392 } 2393 2394 // When upgrading from pre-N, we need to handle package extraction like first boot, 2395 // as there is no profiling data available. 2396 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2397 mSettings.setNWorkDone(); 2398 2399 // Collect vendor overlay packages. 2400 // (Do this before scanning any apps.) 2401 // For security and version matching reason, only consider 2402 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2403 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2404 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2405 | PackageParser.PARSE_IS_SYSTEM 2406 | PackageParser.PARSE_IS_SYSTEM_DIR 2407 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2408 2409 // Find base frameworks (resource packages without code). 2410 scanDirTracedLI(frameworkDir, mDefParseFlags 2411 | PackageParser.PARSE_IS_SYSTEM 2412 | PackageParser.PARSE_IS_SYSTEM_DIR 2413 | PackageParser.PARSE_IS_PRIVILEGED, 2414 scanFlags | SCAN_NO_DEX, 0); 2415 2416 // Collected privileged system packages. 2417 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2418 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2419 | PackageParser.PARSE_IS_SYSTEM 2420 | PackageParser.PARSE_IS_SYSTEM_DIR 2421 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2422 2423 // Collect ordinary system packages. 2424 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2425 scanDirTracedLI(systemAppDir, mDefParseFlags 2426 | PackageParser.PARSE_IS_SYSTEM 2427 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2428 2429 // Collect all vendor packages. 2430 File vendorAppDir = new File("/vendor/app"); 2431 try { 2432 vendorAppDir = vendorAppDir.getCanonicalFile(); 2433 } catch (IOException e) { 2434 // failed to look up canonical path, continue with original one 2435 } 2436 scanDirTracedLI(vendorAppDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2439 2440 // Collect all OEM packages. 2441 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2442 scanDirTracedLI(oemAppDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2445 2446 // Prune any system packages that no longer exist. 2447 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2448 if (!mOnlyCore) { 2449 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2450 while (psit.hasNext()) { 2451 PackageSetting ps = psit.next(); 2452 2453 /* 2454 * If this is not a system app, it can't be a 2455 * disable system app. 2456 */ 2457 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2458 continue; 2459 } 2460 2461 /* 2462 * If the package is scanned, it's not erased. 2463 */ 2464 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2465 if (scannedPkg != null) { 2466 /* 2467 * If the system app is both scanned and in the 2468 * disabled packages list, then it must have been 2469 * added via OTA. Remove it from the currently 2470 * scanned package so the previously user-installed 2471 * application can be scanned. 2472 */ 2473 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2474 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2475 + ps.name + "; removing system app. Last known codePath=" 2476 + ps.codePathString + ", installStatus=" + ps.installStatus 2477 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2478 + scannedPkg.mVersionCode); 2479 removePackageLI(scannedPkg, true); 2480 mExpectingBetter.put(ps.name, ps.codePath); 2481 } 2482 2483 continue; 2484 } 2485 2486 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2487 psit.remove(); 2488 logCriticalInfo(Log.WARN, "System package " + ps.name 2489 + " no longer exists; it's data will be wiped"); 2490 // Actual deletion of code and data will be handled by later 2491 // reconciliation step 2492 } else { 2493 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2494 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2495 possiblyDeletedUpdatedSystemApps.add(ps.name); 2496 } 2497 } 2498 } 2499 } 2500 2501 //look for any incomplete package installations 2502 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2503 for (int i = 0; i < deletePkgsList.size(); i++) { 2504 // Actual deletion of code and data will be handled by later 2505 // reconciliation step 2506 final String packageName = deletePkgsList.get(i).name; 2507 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2508 synchronized (mPackages) { 2509 mSettings.removePackageLPw(packageName); 2510 } 2511 } 2512 2513 //delete tmp files 2514 deleteTempPackageFiles(); 2515 2516 // Remove any shared userIDs that have no associated packages 2517 mSettings.pruneSharedUsersLPw(); 2518 2519 if (!mOnlyCore) { 2520 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2521 SystemClock.uptimeMillis()); 2522 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2523 2524 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2525 | PackageParser.PARSE_FORWARD_LOCK, 2526 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2527 2528 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2529 | PackageParser.PARSE_IS_EPHEMERAL, 2530 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2531 2532 /** 2533 * Remove disable package settings for any updated system 2534 * apps that were removed via an OTA. If they're not a 2535 * previously-updated app, remove them completely. 2536 * Otherwise, just revoke their system-level permissions. 2537 */ 2538 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2539 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2540 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2541 2542 String msg; 2543 if (deletedPkg == null) { 2544 msg = "Updated system package " + deletedAppName 2545 + " no longer exists; it's data will be wiped"; 2546 // Actual deletion of code and data will be handled by later 2547 // reconciliation step 2548 } else { 2549 msg = "Updated system app + " + deletedAppName 2550 + " no longer present; removing system privileges for " 2551 + deletedAppName; 2552 2553 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2554 2555 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2556 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2557 } 2558 logCriticalInfo(Log.WARN, msg); 2559 } 2560 2561 /** 2562 * Make sure all system apps that we expected to appear on 2563 * the userdata partition actually showed up. If they never 2564 * appeared, crawl back and revive the system version. 2565 */ 2566 for (int i = 0; i < mExpectingBetter.size(); i++) { 2567 final String packageName = mExpectingBetter.keyAt(i); 2568 if (!mPackages.containsKey(packageName)) { 2569 final File scanFile = mExpectingBetter.valueAt(i); 2570 2571 logCriticalInfo(Log.WARN, "Expected better " + packageName 2572 + " but never showed up; reverting to system"); 2573 2574 int reparseFlags = mDefParseFlags; 2575 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2576 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2577 | PackageParser.PARSE_IS_SYSTEM_DIR 2578 | PackageParser.PARSE_IS_PRIVILEGED; 2579 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2580 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2581 | PackageParser.PARSE_IS_SYSTEM_DIR; 2582 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2583 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2584 | PackageParser.PARSE_IS_SYSTEM_DIR; 2585 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2586 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2587 | PackageParser.PARSE_IS_SYSTEM_DIR; 2588 } else { 2589 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2590 continue; 2591 } 2592 2593 mSettings.enableSystemPackageLPw(packageName); 2594 2595 try { 2596 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2597 } catch (PackageManagerException e) { 2598 Slog.e(TAG, "Failed to parse original system package: " 2599 + e.getMessage()); 2600 } 2601 } 2602 } 2603 } 2604 mExpectingBetter.clear(); 2605 2606 // Resolve protected action filters. Only the setup wizard is allowed to 2607 // have a high priority filter for these actions. 2608 mSetupWizardPackage = getSetupWizardPackageName(); 2609 if (mProtectedFilters.size() > 0) { 2610 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2611 Slog.i(TAG, "No setup wizard;" 2612 + " All protected intents capped to priority 0"); 2613 } 2614 for (ActivityIntentInfo filter : mProtectedFilters) { 2615 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2616 if (DEBUG_FILTERS) { 2617 Slog.i(TAG, "Found setup wizard;" 2618 + " allow priority " + filter.getPriority() + ";" 2619 + " package: " + filter.activity.info.packageName 2620 + " activity: " + filter.activity.className 2621 + " priority: " + filter.getPriority()); 2622 } 2623 // skip setup wizard; allow it to keep the high priority filter 2624 continue; 2625 } 2626 Slog.w(TAG, "Protected action; cap priority to 0;" 2627 + " package: " + filter.activity.info.packageName 2628 + " activity: " + filter.activity.className 2629 + " origPrio: " + filter.getPriority()); 2630 filter.setPriority(0); 2631 } 2632 } 2633 mDeferProtectedFilters = false; 2634 mProtectedFilters.clear(); 2635 2636 // Now that we know all of the shared libraries, update all clients to have 2637 // the correct library paths. 2638 updateAllSharedLibrariesLPw(); 2639 2640 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2641 // NOTE: We ignore potential failures here during a system scan (like 2642 // the rest of the commands above) because there's precious little we 2643 // can do about it. A settings error is reported, though. 2644 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2645 false /* boot complete */); 2646 } 2647 2648 // Now that we know all the packages we are keeping, 2649 // read and update their last usage times. 2650 mPackageUsage.readLP(); 2651 2652 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2653 SystemClock.uptimeMillis()); 2654 Slog.i(TAG, "Time to scan packages: " 2655 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2656 + " seconds"); 2657 2658 // If the platform SDK has changed since the last time we booted, 2659 // we need to re-grant app permission to catch any new ones that 2660 // appear. This is really a hack, and means that apps can in some 2661 // cases get permissions that the user didn't initially explicitly 2662 // allow... it would be nice to have some better way to handle 2663 // this situation. 2664 int updateFlags = UPDATE_PERMISSIONS_ALL; 2665 if (ver.sdkVersion != mSdkVersion) { 2666 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2667 + mSdkVersion + "; regranting permissions for internal storage"); 2668 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2669 } 2670 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2671 ver.sdkVersion = mSdkVersion; 2672 2673 // If this is the first boot or an update from pre-M, and it is a normal 2674 // boot, then we need to initialize the default preferred apps across 2675 // all defined users. 2676 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2677 for (UserInfo user : sUserManager.getUsers(true)) { 2678 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2679 applyFactoryDefaultBrowserLPw(user.id); 2680 primeDomainVerificationsLPw(user.id); 2681 } 2682 } 2683 2684 // Prepare storage for system user really early during boot, 2685 // since core system apps like SettingsProvider and SystemUI 2686 // can't wait for user to start 2687 final int storageFlags; 2688 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2689 storageFlags = StorageManager.FLAG_STORAGE_DE; 2690 } else { 2691 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2692 } 2693 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2694 storageFlags); 2695 2696 // If this is first boot after an OTA, and a normal boot, then 2697 // we need to clear code cache directories. 2698 if (mIsUpgrade && !onlyCore) { 2699 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2700 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2701 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2702 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2703 // No apps are running this early, so no need to freeze 2704 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2705 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2706 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2707 } 2708 clearAppProfilesLIF(ps.pkg); 2709 } 2710 ver.fingerprint = Build.FINGERPRINT; 2711 } 2712 2713 checkDefaultBrowser(); 2714 2715 // clear only after permissions and other defaults have been updated 2716 mExistingSystemPackages.clear(); 2717 mPromoteSystemApps = false; 2718 2719 // All the changes are done during package scanning. 2720 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2721 2722 // can downgrade to reader 2723 mSettings.writeLPr(); 2724 2725 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2726 SystemClock.uptimeMillis()); 2727 2728 if (!mOnlyCore) { 2729 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2730 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2731 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2732 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2733 mIntentFilterVerifierComponent); 2734 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2735 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2736 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2737 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2738 } else { 2739 mRequiredVerifierPackage = null; 2740 mRequiredInstallerPackage = null; 2741 mIntentFilterVerifierComponent = null; 2742 mIntentFilterVerifier = null; 2743 mServicesSystemSharedLibraryPackageName = null; 2744 mSharedSystemSharedLibraryPackageName = null; 2745 } 2746 2747 mInstallerService = new PackageInstallerService(context, this); 2748 2749 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2750 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2751 // both the installer and resolver must be present to enable ephemeral 2752 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2753 if (DEBUG_EPHEMERAL) { 2754 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2755 + " installer:" + ephemeralInstallerComponent); 2756 } 2757 mEphemeralResolverComponent = ephemeralResolverComponent; 2758 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2759 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2760 mEphemeralResolverConnection = 2761 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2762 } else { 2763 if (DEBUG_EPHEMERAL) { 2764 final String missingComponent = 2765 (ephemeralResolverComponent == null) 2766 ? (ephemeralInstallerComponent == null) 2767 ? "resolver and installer" 2768 : "resolver" 2769 : "installer"; 2770 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2771 } 2772 mEphemeralResolverComponent = null; 2773 mEphemeralInstallerComponent = null; 2774 mEphemeralResolverConnection = null; 2775 } 2776 2777 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2778 } // synchronized (mPackages) 2779 } // synchronized (mInstallLock) 2780 2781 // Now after opening every single application zip, make sure they 2782 // are all flushed. Not really needed, but keeps things nice and 2783 // tidy. 2784 Runtime.getRuntime().gc(); 2785 2786 // The initial scanning above does many calls into installd while 2787 // holding the mPackages lock, but we're mostly interested in yelling 2788 // once we have a booted system. 2789 mInstaller.setWarnIfHeld(mPackages); 2790 2791 // Expose private service for system components to use. 2792 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2793 } 2794 2795 @Override 2796 public boolean isFirstBoot() { 2797 return !mRestoredSettings; 2798 } 2799 2800 @Override 2801 public boolean isOnlyCoreApps() { 2802 return mOnlyCore; 2803 } 2804 2805 @Override 2806 public boolean isUpgrade() { 2807 return mIsUpgrade; 2808 } 2809 2810 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2811 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2812 2813 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2814 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2815 UserHandle.USER_SYSTEM); 2816 if (matches.size() == 1) { 2817 return matches.get(0).getComponentInfo().packageName; 2818 } else { 2819 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2820 return null; 2821 } 2822 } 2823 2824 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2825 synchronized (mPackages) { 2826 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2827 if (libraryEntry == null) { 2828 throw new IllegalStateException("Missing required shared library:" + libraryName); 2829 } 2830 return libraryEntry.apk; 2831 } 2832 } 2833 2834 private @NonNull String getRequiredInstallerLPr() { 2835 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2836 intent.addCategory(Intent.CATEGORY_DEFAULT); 2837 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2838 2839 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2840 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2841 UserHandle.USER_SYSTEM); 2842 if (matches.size() == 1) { 2843 ResolveInfo resolveInfo = matches.get(0); 2844 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2845 throw new RuntimeException("The installer must be a privileged app"); 2846 } 2847 return matches.get(0).getComponentInfo().packageName; 2848 } else { 2849 throw new RuntimeException("There must be exactly one installer; found " + matches); 2850 } 2851 } 2852 2853 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2854 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2855 2856 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2857 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2858 UserHandle.USER_SYSTEM); 2859 ResolveInfo best = null; 2860 final int N = matches.size(); 2861 for (int i = 0; i < N; i++) { 2862 final ResolveInfo cur = matches.get(i); 2863 final String packageName = cur.getComponentInfo().packageName; 2864 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2865 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2866 continue; 2867 } 2868 2869 if (best == null || cur.priority > best.priority) { 2870 best = cur; 2871 } 2872 } 2873 2874 if (best != null) { 2875 return best.getComponentInfo().getComponentName(); 2876 } else { 2877 throw new RuntimeException("There must be at least one intent filter verifier"); 2878 } 2879 } 2880 2881 private @Nullable ComponentName getEphemeralResolverLPr() { 2882 final String[] packageArray = 2883 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2884 if (packageArray.length == 0) { 2885 if (DEBUG_EPHEMERAL) { 2886 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2887 } 2888 return null; 2889 } 2890 2891 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2892 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2893 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2894 UserHandle.USER_SYSTEM); 2895 2896 final int N = resolvers.size(); 2897 if (N == 0) { 2898 if (DEBUG_EPHEMERAL) { 2899 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2900 } 2901 return null; 2902 } 2903 2904 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2905 for (int i = 0; i < N; i++) { 2906 final ResolveInfo info = resolvers.get(i); 2907 2908 if (info.serviceInfo == null) { 2909 continue; 2910 } 2911 2912 final String packageName = info.serviceInfo.packageName; 2913 if (!possiblePackages.contains(packageName)) { 2914 if (DEBUG_EPHEMERAL) { 2915 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2916 + " pkg: " + packageName + ", info:" + info); 2917 } 2918 continue; 2919 } 2920 2921 if (DEBUG_EPHEMERAL) { 2922 Slog.v(TAG, "Ephemeral resolver found;" 2923 + " pkg: " + packageName + ", info:" + info); 2924 } 2925 return new ComponentName(packageName, info.serviceInfo.name); 2926 } 2927 if (DEBUG_EPHEMERAL) { 2928 Slog.v(TAG, "Ephemeral resolver NOT found"); 2929 } 2930 return null; 2931 } 2932 2933 private @Nullable ComponentName getEphemeralInstallerLPr() { 2934 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2935 intent.addCategory(Intent.CATEGORY_DEFAULT); 2936 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2937 2938 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2939 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2940 UserHandle.USER_SYSTEM); 2941 if (matches.size() == 0) { 2942 return null; 2943 } else if (matches.size() == 1) { 2944 return matches.get(0).getComponentInfo().getComponentName(); 2945 } else { 2946 throw new RuntimeException( 2947 "There must be at most one ephemeral installer; found " + matches); 2948 } 2949 } 2950 2951 private void primeDomainVerificationsLPw(int userId) { 2952 if (DEBUG_DOMAIN_VERIFICATION) { 2953 Slog.d(TAG, "Priming domain verifications in user " + userId); 2954 } 2955 2956 SystemConfig systemConfig = SystemConfig.getInstance(); 2957 ArraySet<String> packages = systemConfig.getLinkedApps(); 2958 ArraySet<String> domains = new ArraySet<String>(); 2959 2960 for (String packageName : packages) { 2961 PackageParser.Package pkg = mPackages.get(packageName); 2962 if (pkg != null) { 2963 if (!pkg.isSystemApp()) { 2964 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2965 continue; 2966 } 2967 2968 domains.clear(); 2969 for (PackageParser.Activity a : pkg.activities) { 2970 for (ActivityIntentInfo filter : a.intents) { 2971 if (hasValidDomains(filter)) { 2972 domains.addAll(filter.getHostsList()); 2973 } 2974 } 2975 } 2976 2977 if (domains.size() > 0) { 2978 if (DEBUG_DOMAIN_VERIFICATION) { 2979 Slog.v(TAG, " + " + packageName); 2980 } 2981 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2982 // state w.r.t. the formal app-linkage "no verification attempted" state; 2983 // and then 'always' in the per-user state actually used for intent resolution. 2984 final IntentFilterVerificationInfo ivi; 2985 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2986 new ArrayList<String>(domains)); 2987 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2988 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2989 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2990 } else { 2991 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2992 + "' does not handle web links"); 2993 } 2994 } else { 2995 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2996 } 2997 } 2998 2999 scheduleWritePackageRestrictionsLocked(userId); 3000 scheduleWriteSettingsLocked(); 3001 } 3002 3003 private void applyFactoryDefaultBrowserLPw(int userId) { 3004 // The default browser app's package name is stored in a string resource, 3005 // with a product-specific overlay used for vendor customization. 3006 String browserPkg = mContext.getResources().getString( 3007 com.android.internal.R.string.default_browser); 3008 if (!TextUtils.isEmpty(browserPkg)) { 3009 // non-empty string => required to be a known package 3010 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3011 if (ps == null) { 3012 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3013 browserPkg = null; 3014 } else { 3015 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3016 } 3017 } 3018 3019 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3020 // default. If there's more than one, just leave everything alone. 3021 if (browserPkg == null) { 3022 calculateDefaultBrowserLPw(userId); 3023 } 3024 } 3025 3026 private void calculateDefaultBrowserLPw(int userId) { 3027 List<String> allBrowsers = resolveAllBrowserApps(userId); 3028 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3029 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3030 } 3031 3032 private List<String> resolveAllBrowserApps(int userId) { 3033 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3034 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3035 PackageManager.MATCH_ALL, userId); 3036 3037 final int count = list.size(); 3038 List<String> result = new ArrayList<String>(count); 3039 for (int i=0; i<count; i++) { 3040 ResolveInfo info = list.get(i); 3041 if (info.activityInfo == null 3042 || !info.handleAllWebDataURI 3043 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3044 || result.contains(info.activityInfo.packageName)) { 3045 continue; 3046 } 3047 result.add(info.activityInfo.packageName); 3048 } 3049 3050 return result; 3051 } 3052 3053 private boolean packageIsBrowser(String packageName, int userId) { 3054 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3055 PackageManager.MATCH_ALL, userId); 3056 final int N = list.size(); 3057 for (int i = 0; i < N; i++) { 3058 ResolveInfo info = list.get(i); 3059 if (packageName.equals(info.activityInfo.packageName)) { 3060 return true; 3061 } 3062 } 3063 return false; 3064 } 3065 3066 private void checkDefaultBrowser() { 3067 final int myUserId = UserHandle.myUserId(); 3068 final String packageName = getDefaultBrowserPackageName(myUserId); 3069 if (packageName != null) { 3070 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3071 if (info == null) { 3072 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3073 synchronized (mPackages) { 3074 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3075 } 3076 } 3077 } 3078 } 3079 3080 @Override 3081 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3082 throws RemoteException { 3083 try { 3084 return super.onTransact(code, data, reply, flags); 3085 } catch (RuntimeException e) { 3086 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3087 Slog.wtf(TAG, "Package Manager Crash", e); 3088 } 3089 throw e; 3090 } 3091 } 3092 3093 static int[] appendInts(int[] cur, int[] add) { 3094 if (add == null) return cur; 3095 if (cur == null) return add; 3096 final int N = add.length; 3097 for (int i=0; i<N; i++) { 3098 cur = appendInt(cur, add[i]); 3099 } 3100 return cur; 3101 } 3102 3103 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3104 if (!sUserManager.exists(userId)) return null; 3105 if (ps == null) { 3106 return null; 3107 } 3108 final PackageParser.Package p = ps.pkg; 3109 if (p == null) { 3110 return null; 3111 } 3112 3113 final PermissionsState permissionsState = ps.getPermissionsState(); 3114 3115 final int[] gids = permissionsState.computeGids(userId); 3116 final Set<String> permissions = permissionsState.getPermissions(userId); 3117 final PackageUserState state = ps.readUserState(userId); 3118 3119 return PackageParser.generatePackageInfo(p, gids, flags, 3120 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3121 } 3122 3123 @Override 3124 public void checkPackageStartable(String packageName, int userId) { 3125 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3126 3127 synchronized (mPackages) { 3128 final PackageSetting ps = mSettings.mPackages.get(packageName); 3129 if (ps == null) { 3130 throw new SecurityException("Package " + packageName + " was not found!"); 3131 } 3132 3133 if (!ps.getInstalled(userId)) { 3134 throw new SecurityException( 3135 "Package " + packageName + " was not installed for user " + userId + "!"); 3136 } 3137 3138 if (mSafeMode && !ps.isSystem()) { 3139 throw new SecurityException("Package " + packageName + " not a system app!"); 3140 } 3141 3142 if (mFrozenPackages.contains(packageName)) { 3143 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3144 } 3145 3146 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3147 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3148 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3149 } 3150 } 3151 } 3152 3153 @Override 3154 public boolean isPackageAvailable(String packageName, int userId) { 3155 if (!sUserManager.exists(userId)) return false; 3156 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3157 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3158 synchronized (mPackages) { 3159 PackageParser.Package p = mPackages.get(packageName); 3160 if (p != null) { 3161 final PackageSetting ps = (PackageSetting) p.mExtras; 3162 if (ps != null) { 3163 final PackageUserState state = ps.readUserState(userId); 3164 if (state != null) { 3165 return PackageParser.isAvailable(state); 3166 } 3167 } 3168 } 3169 } 3170 return false; 3171 } 3172 3173 @Override 3174 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3175 if (!sUserManager.exists(userId)) return null; 3176 flags = updateFlagsForPackage(flags, userId, packageName); 3177 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3178 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3179 // reader 3180 synchronized (mPackages) { 3181 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3182 PackageParser.Package p = null; 3183 if (matchFactoryOnly) { 3184 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3185 if (ps != null) { 3186 return generatePackageInfo(ps, flags, userId); 3187 } 3188 } 3189 if (p == null) { 3190 p = mPackages.get(packageName); 3191 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3192 return null; 3193 } 3194 } 3195 if (DEBUG_PACKAGE_INFO) 3196 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3197 if (p != null) { 3198 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3199 } 3200 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3201 final PackageSetting ps = mSettings.mPackages.get(packageName); 3202 return generatePackageInfo(ps, flags, userId); 3203 } 3204 } 3205 return null; 3206 } 3207 3208 @Override 3209 public String[] currentToCanonicalPackageNames(String[] names) { 3210 String[] out = new String[names.length]; 3211 // reader 3212 synchronized (mPackages) { 3213 for (int i=names.length-1; i>=0; i--) { 3214 PackageSetting ps = mSettings.mPackages.get(names[i]); 3215 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3216 } 3217 } 3218 return out; 3219 } 3220 3221 @Override 3222 public String[] canonicalToCurrentPackageNames(String[] names) { 3223 String[] out = new String[names.length]; 3224 // reader 3225 synchronized (mPackages) { 3226 for (int i=names.length-1; i>=0; i--) { 3227 String cur = mSettings.mRenamedPackages.get(names[i]); 3228 out[i] = cur != null ? cur : names[i]; 3229 } 3230 } 3231 return out; 3232 } 3233 3234 @Override 3235 public int getPackageUid(String packageName, int flags, int userId) { 3236 if (!sUserManager.exists(userId)) return -1; 3237 flags = updateFlagsForPackage(flags, userId, packageName); 3238 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3239 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3240 3241 // reader 3242 synchronized (mPackages) { 3243 final PackageParser.Package p = mPackages.get(packageName); 3244 if (p != null && p.isMatch(flags)) { 3245 return UserHandle.getUid(userId, p.applicationInfo.uid); 3246 } 3247 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3248 final PackageSetting ps = mSettings.mPackages.get(packageName); 3249 if (ps != null && ps.isMatch(flags)) { 3250 return UserHandle.getUid(userId, ps.appId); 3251 } 3252 } 3253 } 3254 3255 return -1; 3256 } 3257 3258 @Override 3259 public int[] getPackageGids(String packageName, int flags, int userId) { 3260 if (!sUserManager.exists(userId)) return null; 3261 flags = updateFlagsForPackage(flags, userId, packageName); 3262 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3263 false /* requireFullPermission */, false /* checkShell */, 3264 "getPackageGids"); 3265 3266 // reader 3267 synchronized (mPackages) { 3268 final PackageParser.Package p = mPackages.get(packageName); 3269 if (p != null && p.isMatch(flags)) { 3270 PackageSetting ps = (PackageSetting) p.mExtras; 3271 return ps.getPermissionsState().computeGids(userId); 3272 } 3273 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3274 final PackageSetting ps = mSettings.mPackages.get(packageName); 3275 if (ps != null && ps.isMatch(flags)) { 3276 return ps.getPermissionsState().computeGids(userId); 3277 } 3278 } 3279 } 3280 3281 return null; 3282 } 3283 3284 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3285 if (bp.perm != null) { 3286 return PackageParser.generatePermissionInfo(bp.perm, flags); 3287 } 3288 PermissionInfo pi = new PermissionInfo(); 3289 pi.name = bp.name; 3290 pi.packageName = bp.sourcePackage; 3291 pi.nonLocalizedLabel = bp.name; 3292 pi.protectionLevel = bp.protectionLevel; 3293 return pi; 3294 } 3295 3296 @Override 3297 public PermissionInfo getPermissionInfo(String name, int flags) { 3298 // reader 3299 synchronized (mPackages) { 3300 final BasePermission p = mSettings.mPermissions.get(name); 3301 if (p != null) { 3302 return generatePermissionInfo(p, flags); 3303 } 3304 return null; 3305 } 3306 } 3307 3308 @Override 3309 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3310 int flags) { 3311 // reader 3312 synchronized (mPackages) { 3313 if (group != null && !mPermissionGroups.containsKey(group)) { 3314 // This is thrown as NameNotFoundException 3315 return null; 3316 } 3317 3318 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3319 for (BasePermission p : mSettings.mPermissions.values()) { 3320 if (group == null) { 3321 if (p.perm == null || p.perm.info.group == null) { 3322 out.add(generatePermissionInfo(p, flags)); 3323 } 3324 } else { 3325 if (p.perm != null && group.equals(p.perm.info.group)) { 3326 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3327 } 3328 } 3329 } 3330 return new ParceledListSlice<>(out); 3331 } 3332 } 3333 3334 @Override 3335 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3336 // reader 3337 synchronized (mPackages) { 3338 return PackageParser.generatePermissionGroupInfo( 3339 mPermissionGroups.get(name), flags); 3340 } 3341 } 3342 3343 @Override 3344 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3345 // reader 3346 synchronized (mPackages) { 3347 final int N = mPermissionGroups.size(); 3348 ArrayList<PermissionGroupInfo> out 3349 = new ArrayList<PermissionGroupInfo>(N); 3350 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3351 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3352 } 3353 return new ParceledListSlice<>(out); 3354 } 3355 } 3356 3357 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3358 int userId) { 3359 if (!sUserManager.exists(userId)) return null; 3360 PackageSetting ps = mSettings.mPackages.get(packageName); 3361 if (ps != null) { 3362 if (ps.pkg == null) { 3363 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3364 if (pInfo != null) { 3365 return pInfo.applicationInfo; 3366 } 3367 return null; 3368 } 3369 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3370 ps.readUserState(userId), userId); 3371 } 3372 return null; 3373 } 3374 3375 @Override 3376 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3377 if (!sUserManager.exists(userId)) return null; 3378 flags = updateFlagsForApplication(flags, userId, packageName); 3379 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3380 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3381 // writer 3382 synchronized (mPackages) { 3383 PackageParser.Package p = mPackages.get(packageName); 3384 if (DEBUG_PACKAGE_INFO) Log.v( 3385 TAG, "getApplicationInfo " + packageName 3386 + ": " + p); 3387 if (p != null) { 3388 PackageSetting ps = mSettings.mPackages.get(packageName); 3389 if (ps == null) return null; 3390 // Note: isEnabledLP() does not apply here - always return info 3391 return PackageParser.generateApplicationInfo( 3392 p, flags, ps.readUserState(userId), userId); 3393 } 3394 if ("android".equals(packageName)||"system".equals(packageName)) { 3395 return mAndroidApplication; 3396 } 3397 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3398 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3399 } 3400 } 3401 return null; 3402 } 3403 3404 @Override 3405 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3406 final IPackageDataObserver observer) { 3407 mContext.enforceCallingOrSelfPermission( 3408 android.Manifest.permission.CLEAR_APP_CACHE, null); 3409 // Queue up an async operation since clearing cache may take a little while. 3410 mHandler.post(new Runnable() { 3411 public void run() { 3412 mHandler.removeCallbacks(this); 3413 boolean success = true; 3414 synchronized (mInstallLock) { 3415 try { 3416 mInstaller.freeCache(volumeUuid, freeStorageSize); 3417 } catch (InstallerException e) { 3418 Slog.w(TAG, "Couldn't clear application caches: " + e); 3419 success = false; 3420 } 3421 } 3422 if (observer != null) { 3423 try { 3424 observer.onRemoveCompleted(null, success); 3425 } catch (RemoteException e) { 3426 Slog.w(TAG, "RemoveException when invoking call back"); 3427 } 3428 } 3429 } 3430 }); 3431 } 3432 3433 @Override 3434 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3435 final IntentSender pi) { 3436 mContext.enforceCallingOrSelfPermission( 3437 android.Manifest.permission.CLEAR_APP_CACHE, null); 3438 // Queue up an async operation since clearing cache may take a little while. 3439 mHandler.post(new Runnable() { 3440 public void run() { 3441 mHandler.removeCallbacks(this); 3442 boolean success = true; 3443 synchronized (mInstallLock) { 3444 try { 3445 mInstaller.freeCache(volumeUuid, freeStorageSize); 3446 } catch (InstallerException e) { 3447 Slog.w(TAG, "Couldn't clear application caches: " + e); 3448 success = false; 3449 } 3450 } 3451 if(pi != null) { 3452 try { 3453 // Callback via pending intent 3454 int code = success ? 1 : 0; 3455 pi.sendIntent(null, code, null, 3456 null, null); 3457 } catch (SendIntentException e1) { 3458 Slog.i(TAG, "Failed to send pending intent"); 3459 } 3460 } 3461 } 3462 }); 3463 } 3464 3465 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3466 synchronized (mInstallLock) { 3467 try { 3468 mInstaller.freeCache(volumeUuid, freeStorageSize); 3469 } catch (InstallerException e) { 3470 throw new IOException("Failed to free enough space", e); 3471 } 3472 } 3473 } 3474 3475 /** 3476 * Update given flags based on encryption status of current user. 3477 */ 3478 private int updateFlags(int flags, int userId) { 3479 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3480 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3481 // Caller expressed an explicit opinion about what encryption 3482 // aware/unaware components they want to see, so fall through and 3483 // give them what they want 3484 } else { 3485 // Caller expressed no opinion, so match based on user state 3486 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3487 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3488 } else { 3489 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3490 } 3491 } 3492 return flags; 3493 } 3494 3495 private UserManagerInternal getUserManagerInternal() { 3496 if (mUserManagerInternal == null) { 3497 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3498 } 3499 return mUserManagerInternal; 3500 } 3501 3502 /** 3503 * Update given flags when being used to request {@link PackageInfo}. 3504 */ 3505 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3506 boolean triaged = true; 3507 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3508 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3509 // Caller is asking for component details, so they'd better be 3510 // asking for specific encryption matching behavior, or be triaged 3511 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3512 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3513 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3514 triaged = false; 3515 } 3516 } 3517 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3518 | PackageManager.MATCH_SYSTEM_ONLY 3519 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3520 triaged = false; 3521 } 3522 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3523 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3524 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3525 } 3526 return updateFlags(flags, userId); 3527 } 3528 3529 /** 3530 * Update given flags when being used to request {@link ApplicationInfo}. 3531 */ 3532 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3533 return updateFlagsForPackage(flags, userId, cookie); 3534 } 3535 3536 /** 3537 * Update given flags when being used to request {@link ComponentInfo}. 3538 */ 3539 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3540 if (cookie instanceof Intent) { 3541 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3542 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3543 } 3544 } 3545 3546 boolean triaged = true; 3547 // Caller is asking for component details, so they'd better be 3548 // asking for specific encryption matching behavior, or be triaged 3549 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3550 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3551 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3552 triaged = false; 3553 } 3554 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3555 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3556 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3557 } 3558 3559 return updateFlags(flags, userId); 3560 } 3561 3562 /** 3563 * Update given flags when being used to request {@link ResolveInfo}. 3564 */ 3565 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3566 // Safe mode means we shouldn't match any third-party components 3567 if (mSafeMode) { 3568 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3569 } 3570 3571 return updateFlagsForComponent(flags, userId, cookie); 3572 } 3573 3574 @Override 3575 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3576 if (!sUserManager.exists(userId)) return null; 3577 flags = updateFlagsForComponent(flags, userId, component); 3578 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3579 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3580 synchronized (mPackages) { 3581 PackageParser.Activity a = mActivities.mActivities.get(component); 3582 3583 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3584 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3585 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3586 if (ps == null) return null; 3587 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3588 userId); 3589 } 3590 if (mResolveComponentName.equals(component)) { 3591 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3592 new PackageUserState(), userId); 3593 } 3594 } 3595 return null; 3596 } 3597 3598 @Override 3599 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3600 String resolvedType) { 3601 synchronized (mPackages) { 3602 if (component.equals(mResolveComponentName)) { 3603 // The resolver supports EVERYTHING! 3604 return true; 3605 } 3606 PackageParser.Activity a = mActivities.mActivities.get(component); 3607 if (a == null) { 3608 return false; 3609 } 3610 for (int i=0; i<a.intents.size(); i++) { 3611 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3612 intent.getData(), intent.getCategories(), TAG) >= 0) { 3613 return true; 3614 } 3615 } 3616 return false; 3617 } 3618 } 3619 3620 @Override 3621 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3622 if (!sUserManager.exists(userId)) return null; 3623 flags = updateFlagsForComponent(flags, userId, component); 3624 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3625 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3626 synchronized (mPackages) { 3627 PackageParser.Activity a = mReceivers.mActivities.get(component); 3628 if (DEBUG_PACKAGE_INFO) Log.v( 3629 TAG, "getReceiverInfo " + component + ": " + a); 3630 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3631 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3632 if (ps == null) return null; 3633 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3634 userId); 3635 } 3636 } 3637 return null; 3638 } 3639 3640 @Override 3641 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3642 if (!sUserManager.exists(userId)) return null; 3643 flags = updateFlagsForComponent(flags, userId, component); 3644 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3645 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3646 synchronized (mPackages) { 3647 PackageParser.Service s = mServices.mServices.get(component); 3648 if (DEBUG_PACKAGE_INFO) Log.v( 3649 TAG, "getServiceInfo " + component + ": " + s); 3650 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3651 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3652 if (ps == null) return null; 3653 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3654 userId); 3655 } 3656 } 3657 return null; 3658 } 3659 3660 @Override 3661 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3662 if (!sUserManager.exists(userId)) return null; 3663 flags = updateFlagsForComponent(flags, userId, component); 3664 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3665 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3666 synchronized (mPackages) { 3667 PackageParser.Provider p = mProviders.mProviders.get(component); 3668 if (DEBUG_PACKAGE_INFO) Log.v( 3669 TAG, "getProviderInfo " + component + ": " + p); 3670 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3671 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3672 if (ps == null) return null; 3673 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3674 userId); 3675 } 3676 } 3677 return null; 3678 } 3679 3680 @Override 3681 public String[] getSystemSharedLibraryNames() { 3682 Set<String> libSet; 3683 synchronized (mPackages) { 3684 libSet = mSharedLibraries.keySet(); 3685 int size = libSet.size(); 3686 if (size > 0) { 3687 String[] libs = new String[size]; 3688 libSet.toArray(libs); 3689 return libs; 3690 } 3691 } 3692 return null; 3693 } 3694 3695 @Override 3696 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3697 synchronized (mPackages) { 3698 return mServicesSystemSharedLibraryPackageName; 3699 } 3700 } 3701 3702 @Override 3703 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3704 synchronized (mPackages) { 3705 return mSharedSystemSharedLibraryPackageName; 3706 } 3707 } 3708 3709 @Override 3710 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3711 synchronized (mPackages) { 3712 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3713 3714 final FeatureInfo fi = new FeatureInfo(); 3715 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3716 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3717 res.add(fi); 3718 3719 return new ParceledListSlice<>(res); 3720 } 3721 } 3722 3723 @Override 3724 public boolean hasSystemFeature(String name, int version) { 3725 synchronized (mPackages) { 3726 final FeatureInfo feat = mAvailableFeatures.get(name); 3727 if (feat == null) { 3728 return false; 3729 } else { 3730 return feat.version >= version; 3731 } 3732 } 3733 } 3734 3735 @Override 3736 public int checkPermission(String permName, String pkgName, int userId) { 3737 if (!sUserManager.exists(userId)) { 3738 return PackageManager.PERMISSION_DENIED; 3739 } 3740 3741 synchronized (mPackages) { 3742 final PackageParser.Package p = mPackages.get(pkgName); 3743 if (p != null && p.mExtras != null) { 3744 final PackageSetting ps = (PackageSetting) p.mExtras; 3745 final PermissionsState permissionsState = ps.getPermissionsState(); 3746 if (permissionsState.hasPermission(permName, userId)) { 3747 return PackageManager.PERMISSION_GRANTED; 3748 } 3749 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3750 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3751 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3752 return PackageManager.PERMISSION_GRANTED; 3753 } 3754 } 3755 } 3756 3757 return PackageManager.PERMISSION_DENIED; 3758 } 3759 3760 @Override 3761 public int checkUidPermission(String permName, int uid) { 3762 final int userId = UserHandle.getUserId(uid); 3763 3764 if (!sUserManager.exists(userId)) { 3765 return PackageManager.PERMISSION_DENIED; 3766 } 3767 3768 synchronized (mPackages) { 3769 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3770 if (obj != null) { 3771 final SettingBase ps = (SettingBase) obj; 3772 final PermissionsState permissionsState = ps.getPermissionsState(); 3773 if (permissionsState.hasPermission(permName, userId)) { 3774 return PackageManager.PERMISSION_GRANTED; 3775 } 3776 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3777 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3778 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3779 return PackageManager.PERMISSION_GRANTED; 3780 } 3781 } else { 3782 ArraySet<String> perms = mSystemPermissions.get(uid); 3783 if (perms != null) { 3784 if (perms.contains(permName)) { 3785 return PackageManager.PERMISSION_GRANTED; 3786 } 3787 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3788 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3789 return PackageManager.PERMISSION_GRANTED; 3790 } 3791 } 3792 } 3793 } 3794 3795 return PackageManager.PERMISSION_DENIED; 3796 } 3797 3798 @Override 3799 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3800 if (UserHandle.getCallingUserId() != userId) { 3801 mContext.enforceCallingPermission( 3802 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3803 "isPermissionRevokedByPolicy for user " + userId); 3804 } 3805 3806 if (checkPermission(permission, packageName, userId) 3807 == PackageManager.PERMISSION_GRANTED) { 3808 return false; 3809 } 3810 3811 final long identity = Binder.clearCallingIdentity(); 3812 try { 3813 final int flags = getPermissionFlags(permission, packageName, userId); 3814 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3815 } finally { 3816 Binder.restoreCallingIdentity(identity); 3817 } 3818 } 3819 3820 @Override 3821 public String getPermissionControllerPackageName() { 3822 synchronized (mPackages) { 3823 return mRequiredInstallerPackage; 3824 } 3825 } 3826 3827 /** 3828 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3829 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3830 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3831 * @param message the message to log on security exception 3832 */ 3833 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3834 boolean checkShell, String message) { 3835 if (userId < 0) { 3836 throw new IllegalArgumentException("Invalid userId " + userId); 3837 } 3838 if (checkShell) { 3839 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3840 } 3841 if (userId == UserHandle.getUserId(callingUid)) return; 3842 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3843 if (requireFullPermission) { 3844 mContext.enforceCallingOrSelfPermission( 3845 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3846 } else { 3847 try { 3848 mContext.enforceCallingOrSelfPermission( 3849 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3850 } catch (SecurityException se) { 3851 mContext.enforceCallingOrSelfPermission( 3852 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3853 } 3854 } 3855 } 3856 } 3857 3858 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3859 if (callingUid == Process.SHELL_UID) { 3860 if (userHandle >= 0 3861 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3862 throw new SecurityException("Shell does not have permission to access user " 3863 + userHandle); 3864 } else if (userHandle < 0) { 3865 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3866 + Debug.getCallers(3)); 3867 } 3868 } 3869 } 3870 3871 private BasePermission findPermissionTreeLP(String permName) { 3872 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3873 if (permName.startsWith(bp.name) && 3874 permName.length() > bp.name.length() && 3875 permName.charAt(bp.name.length()) == '.') { 3876 return bp; 3877 } 3878 } 3879 return null; 3880 } 3881 3882 private BasePermission checkPermissionTreeLP(String permName) { 3883 if (permName != null) { 3884 BasePermission bp = findPermissionTreeLP(permName); 3885 if (bp != null) { 3886 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3887 return bp; 3888 } 3889 throw new SecurityException("Calling uid " 3890 + Binder.getCallingUid() 3891 + " is not allowed to add to permission tree " 3892 + bp.name + " owned by uid " + bp.uid); 3893 } 3894 } 3895 throw new SecurityException("No permission tree found for " + permName); 3896 } 3897 3898 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3899 if (s1 == null) { 3900 return s2 == null; 3901 } 3902 if (s2 == null) { 3903 return false; 3904 } 3905 if (s1.getClass() != s2.getClass()) { 3906 return false; 3907 } 3908 return s1.equals(s2); 3909 } 3910 3911 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3912 if (pi1.icon != pi2.icon) return false; 3913 if (pi1.logo != pi2.logo) return false; 3914 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3915 if (!compareStrings(pi1.name, pi2.name)) return false; 3916 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3917 // We'll take care of setting this one. 3918 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3919 // These are not currently stored in settings. 3920 //if (!compareStrings(pi1.group, pi2.group)) return false; 3921 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3922 //if (pi1.labelRes != pi2.labelRes) return false; 3923 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3924 return true; 3925 } 3926 3927 int permissionInfoFootprint(PermissionInfo info) { 3928 int size = info.name.length(); 3929 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3930 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3931 return size; 3932 } 3933 3934 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3935 int size = 0; 3936 for (BasePermission perm : mSettings.mPermissions.values()) { 3937 if (perm.uid == tree.uid) { 3938 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3939 } 3940 } 3941 return size; 3942 } 3943 3944 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3945 // We calculate the max size of permissions defined by this uid and throw 3946 // if that plus the size of 'info' would exceed our stated maximum. 3947 if (tree.uid != Process.SYSTEM_UID) { 3948 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3949 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3950 throw new SecurityException("Permission tree size cap exceeded"); 3951 } 3952 } 3953 } 3954 3955 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3956 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3957 throw new SecurityException("Label must be specified in permission"); 3958 } 3959 BasePermission tree = checkPermissionTreeLP(info.name); 3960 BasePermission bp = mSettings.mPermissions.get(info.name); 3961 boolean added = bp == null; 3962 boolean changed = true; 3963 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3964 if (added) { 3965 enforcePermissionCapLocked(info, tree); 3966 bp = new BasePermission(info.name, tree.sourcePackage, 3967 BasePermission.TYPE_DYNAMIC); 3968 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3969 throw new SecurityException( 3970 "Not allowed to modify non-dynamic permission " 3971 + info.name); 3972 } else { 3973 if (bp.protectionLevel == fixedLevel 3974 && bp.perm.owner.equals(tree.perm.owner) 3975 && bp.uid == tree.uid 3976 && comparePermissionInfos(bp.perm.info, info)) { 3977 changed = false; 3978 } 3979 } 3980 bp.protectionLevel = fixedLevel; 3981 info = new PermissionInfo(info); 3982 info.protectionLevel = fixedLevel; 3983 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3984 bp.perm.info.packageName = tree.perm.info.packageName; 3985 bp.uid = tree.uid; 3986 if (added) { 3987 mSettings.mPermissions.put(info.name, bp); 3988 } 3989 if (changed) { 3990 if (!async) { 3991 mSettings.writeLPr(); 3992 } else { 3993 scheduleWriteSettingsLocked(); 3994 } 3995 } 3996 return added; 3997 } 3998 3999 @Override 4000 public boolean addPermission(PermissionInfo info) { 4001 synchronized (mPackages) { 4002 return addPermissionLocked(info, false); 4003 } 4004 } 4005 4006 @Override 4007 public boolean addPermissionAsync(PermissionInfo info) { 4008 synchronized (mPackages) { 4009 return addPermissionLocked(info, true); 4010 } 4011 } 4012 4013 @Override 4014 public void removePermission(String name) { 4015 synchronized (mPackages) { 4016 checkPermissionTreeLP(name); 4017 BasePermission bp = mSettings.mPermissions.get(name); 4018 if (bp != null) { 4019 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4020 throw new SecurityException( 4021 "Not allowed to modify non-dynamic permission " 4022 + name); 4023 } 4024 mSettings.mPermissions.remove(name); 4025 mSettings.writeLPr(); 4026 } 4027 } 4028 } 4029 4030 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4031 BasePermission bp) { 4032 int index = pkg.requestedPermissions.indexOf(bp.name); 4033 if (index == -1) { 4034 throw new SecurityException("Package " + pkg.packageName 4035 + " has not requested permission " + bp.name); 4036 } 4037 if (!bp.isRuntime() && !bp.isDevelopment()) { 4038 throw new SecurityException("Permission " + bp.name 4039 + " is not a changeable permission type"); 4040 } 4041 } 4042 4043 @Override 4044 public void grantRuntimePermission(String packageName, String name, final int userId) { 4045 if (!sUserManager.exists(userId)) { 4046 Log.e(TAG, "No such user:" + userId); 4047 return; 4048 } 4049 4050 mContext.enforceCallingOrSelfPermission( 4051 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4052 "grantRuntimePermission"); 4053 4054 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4055 true /* requireFullPermission */, true /* checkShell */, 4056 "grantRuntimePermission"); 4057 4058 final int uid; 4059 final SettingBase sb; 4060 4061 synchronized (mPackages) { 4062 final PackageParser.Package pkg = mPackages.get(packageName); 4063 if (pkg == null) { 4064 throw new IllegalArgumentException("Unknown package: " + packageName); 4065 } 4066 4067 final BasePermission bp = mSettings.mPermissions.get(name); 4068 if (bp == null) { 4069 throw new IllegalArgumentException("Unknown permission: " + name); 4070 } 4071 4072 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4073 4074 // If a permission review is required for legacy apps we represent 4075 // their permissions as always granted runtime ones since we need 4076 // to keep the review required permission flag per user while an 4077 // install permission's state is shared across all users. 4078 if (Build.PERMISSIONS_REVIEW_REQUIRED 4079 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4080 && bp.isRuntime()) { 4081 return; 4082 } 4083 4084 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4085 sb = (SettingBase) pkg.mExtras; 4086 if (sb == null) { 4087 throw new IllegalArgumentException("Unknown package: " + packageName); 4088 } 4089 4090 final PermissionsState permissionsState = sb.getPermissionsState(); 4091 4092 final int flags = permissionsState.getPermissionFlags(name, userId); 4093 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4094 throw new SecurityException("Cannot grant system fixed permission " 4095 + name + " for package " + packageName); 4096 } 4097 4098 if (bp.isDevelopment()) { 4099 // Development permissions must be handled specially, since they are not 4100 // normal runtime permissions. For now they apply to all users. 4101 if (permissionsState.grantInstallPermission(bp) != 4102 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4103 scheduleWriteSettingsLocked(); 4104 } 4105 return; 4106 } 4107 4108 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4109 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4110 return; 4111 } 4112 4113 final int result = permissionsState.grantRuntimePermission(bp, userId); 4114 switch (result) { 4115 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4116 return; 4117 } 4118 4119 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4120 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4121 mHandler.post(new Runnable() { 4122 @Override 4123 public void run() { 4124 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4125 } 4126 }); 4127 } 4128 break; 4129 } 4130 4131 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4132 4133 // Not critical if that is lost - app has to request again. 4134 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4135 } 4136 4137 // Only need to do this if user is initialized. Otherwise it's a new user 4138 // and there are no processes running as the user yet and there's no need 4139 // to make an expensive call to remount processes for the changed permissions. 4140 if (READ_EXTERNAL_STORAGE.equals(name) 4141 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4142 final long token = Binder.clearCallingIdentity(); 4143 try { 4144 if (sUserManager.isInitialized(userId)) { 4145 MountServiceInternal mountServiceInternal = LocalServices.getService( 4146 MountServiceInternal.class); 4147 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4148 } 4149 } finally { 4150 Binder.restoreCallingIdentity(token); 4151 } 4152 } 4153 } 4154 4155 @Override 4156 public void revokeRuntimePermission(String packageName, String name, int userId) { 4157 if (!sUserManager.exists(userId)) { 4158 Log.e(TAG, "No such user:" + userId); 4159 return; 4160 } 4161 4162 mContext.enforceCallingOrSelfPermission( 4163 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4164 "revokeRuntimePermission"); 4165 4166 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4167 true /* requireFullPermission */, true /* checkShell */, 4168 "revokeRuntimePermission"); 4169 4170 final int appId; 4171 4172 synchronized (mPackages) { 4173 final PackageParser.Package pkg = mPackages.get(packageName); 4174 if (pkg == null) { 4175 throw new IllegalArgumentException("Unknown package: " + packageName); 4176 } 4177 4178 final BasePermission bp = mSettings.mPermissions.get(name); 4179 if (bp == null) { 4180 throw new IllegalArgumentException("Unknown permission: " + name); 4181 } 4182 4183 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4184 4185 // If a permission review is required for legacy apps we represent 4186 // their permissions as always granted runtime ones since we need 4187 // to keep the review required permission flag per user while an 4188 // install permission's state is shared across all users. 4189 if (Build.PERMISSIONS_REVIEW_REQUIRED 4190 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4191 && bp.isRuntime()) { 4192 return; 4193 } 4194 4195 SettingBase sb = (SettingBase) pkg.mExtras; 4196 if (sb == null) { 4197 throw new IllegalArgumentException("Unknown package: " + packageName); 4198 } 4199 4200 final PermissionsState permissionsState = sb.getPermissionsState(); 4201 4202 final int flags = permissionsState.getPermissionFlags(name, userId); 4203 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4204 throw new SecurityException("Cannot revoke system fixed permission " 4205 + name + " for package " + packageName); 4206 } 4207 4208 if (bp.isDevelopment()) { 4209 // Development permissions must be handled specially, since they are not 4210 // normal runtime permissions. For now they apply to all users. 4211 if (permissionsState.revokeInstallPermission(bp) != 4212 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4213 scheduleWriteSettingsLocked(); 4214 } 4215 return; 4216 } 4217 4218 if (permissionsState.revokeRuntimePermission(bp, userId) == 4219 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4220 return; 4221 } 4222 4223 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4224 4225 // Critical, after this call app should never have the permission. 4226 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4227 4228 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4229 } 4230 4231 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4232 } 4233 4234 @Override 4235 public void resetRuntimePermissions() { 4236 mContext.enforceCallingOrSelfPermission( 4237 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4238 "revokeRuntimePermission"); 4239 4240 int callingUid = Binder.getCallingUid(); 4241 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4242 mContext.enforceCallingOrSelfPermission( 4243 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4244 "resetRuntimePermissions"); 4245 } 4246 4247 synchronized (mPackages) { 4248 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4249 for (int userId : UserManagerService.getInstance().getUserIds()) { 4250 final int packageCount = mPackages.size(); 4251 for (int i = 0; i < packageCount; i++) { 4252 PackageParser.Package pkg = mPackages.valueAt(i); 4253 if (!(pkg.mExtras instanceof PackageSetting)) { 4254 continue; 4255 } 4256 PackageSetting ps = (PackageSetting) pkg.mExtras; 4257 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4258 } 4259 } 4260 } 4261 } 4262 4263 @Override 4264 public int getPermissionFlags(String name, String packageName, int userId) { 4265 if (!sUserManager.exists(userId)) { 4266 return 0; 4267 } 4268 4269 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4270 4271 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4272 true /* requireFullPermission */, false /* checkShell */, 4273 "getPermissionFlags"); 4274 4275 synchronized (mPackages) { 4276 final PackageParser.Package pkg = mPackages.get(packageName); 4277 if (pkg == null) { 4278 return 0; 4279 } 4280 4281 final BasePermission bp = mSettings.mPermissions.get(name); 4282 if (bp == null) { 4283 return 0; 4284 } 4285 4286 SettingBase sb = (SettingBase) pkg.mExtras; 4287 if (sb == null) { 4288 return 0; 4289 } 4290 4291 PermissionsState permissionsState = sb.getPermissionsState(); 4292 return permissionsState.getPermissionFlags(name, userId); 4293 } 4294 } 4295 4296 @Override 4297 public void updatePermissionFlags(String name, String packageName, int flagMask, 4298 int flagValues, int userId) { 4299 if (!sUserManager.exists(userId)) { 4300 return; 4301 } 4302 4303 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4304 4305 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4306 true /* requireFullPermission */, true /* checkShell */, 4307 "updatePermissionFlags"); 4308 4309 // Only the system can change these flags and nothing else. 4310 if (getCallingUid() != Process.SYSTEM_UID) { 4311 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4312 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4313 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4314 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4315 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4316 } 4317 4318 synchronized (mPackages) { 4319 final PackageParser.Package pkg = mPackages.get(packageName); 4320 if (pkg == null) { 4321 throw new IllegalArgumentException("Unknown package: " + packageName); 4322 } 4323 4324 final BasePermission bp = mSettings.mPermissions.get(name); 4325 if (bp == null) { 4326 throw new IllegalArgumentException("Unknown permission: " + name); 4327 } 4328 4329 SettingBase sb = (SettingBase) pkg.mExtras; 4330 if (sb == null) { 4331 throw new IllegalArgumentException("Unknown package: " + packageName); 4332 } 4333 4334 PermissionsState permissionsState = sb.getPermissionsState(); 4335 4336 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4337 4338 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4339 // Install and runtime permissions are stored in different places, 4340 // so figure out what permission changed and persist the change. 4341 if (permissionsState.getInstallPermissionState(name) != null) { 4342 scheduleWriteSettingsLocked(); 4343 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4344 || hadState) { 4345 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4346 } 4347 } 4348 } 4349 } 4350 4351 /** 4352 * Update the permission flags for all packages and runtime permissions of a user in order 4353 * to allow device or profile owner to remove POLICY_FIXED. 4354 */ 4355 @Override 4356 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4357 if (!sUserManager.exists(userId)) { 4358 return; 4359 } 4360 4361 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4362 4363 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4364 true /* requireFullPermission */, true /* checkShell */, 4365 "updatePermissionFlagsForAllApps"); 4366 4367 // Only the system can change system fixed flags. 4368 if (getCallingUid() != Process.SYSTEM_UID) { 4369 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4370 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4371 } 4372 4373 synchronized (mPackages) { 4374 boolean changed = false; 4375 final int packageCount = mPackages.size(); 4376 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4377 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4378 SettingBase sb = (SettingBase) pkg.mExtras; 4379 if (sb == null) { 4380 continue; 4381 } 4382 PermissionsState permissionsState = sb.getPermissionsState(); 4383 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4384 userId, flagMask, flagValues); 4385 } 4386 if (changed) { 4387 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4388 } 4389 } 4390 } 4391 4392 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4393 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4394 != PackageManager.PERMISSION_GRANTED 4395 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4396 != PackageManager.PERMISSION_GRANTED) { 4397 throw new SecurityException(message + " requires " 4398 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4399 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4400 } 4401 } 4402 4403 @Override 4404 public boolean shouldShowRequestPermissionRationale(String permissionName, 4405 String packageName, int userId) { 4406 if (UserHandle.getCallingUserId() != userId) { 4407 mContext.enforceCallingPermission( 4408 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4409 "canShowRequestPermissionRationale for user " + userId); 4410 } 4411 4412 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4413 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4414 return false; 4415 } 4416 4417 if (checkPermission(permissionName, packageName, userId) 4418 == PackageManager.PERMISSION_GRANTED) { 4419 return false; 4420 } 4421 4422 final int flags; 4423 4424 final long identity = Binder.clearCallingIdentity(); 4425 try { 4426 flags = getPermissionFlags(permissionName, 4427 packageName, userId); 4428 } finally { 4429 Binder.restoreCallingIdentity(identity); 4430 } 4431 4432 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4433 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4434 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4435 4436 if ((flags & fixedFlags) != 0) { 4437 return false; 4438 } 4439 4440 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4441 } 4442 4443 @Override 4444 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4445 mContext.enforceCallingOrSelfPermission( 4446 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4447 "addOnPermissionsChangeListener"); 4448 4449 synchronized (mPackages) { 4450 mOnPermissionChangeListeners.addListenerLocked(listener); 4451 } 4452 } 4453 4454 @Override 4455 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4456 synchronized (mPackages) { 4457 mOnPermissionChangeListeners.removeListenerLocked(listener); 4458 } 4459 } 4460 4461 @Override 4462 public boolean isProtectedBroadcast(String actionName) { 4463 synchronized (mPackages) { 4464 if (mProtectedBroadcasts.contains(actionName)) { 4465 return true; 4466 } else if (actionName != null) { 4467 // TODO: remove these terrible hacks 4468 if (actionName.startsWith("android.net.netmon.lingerExpired") 4469 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4470 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4471 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4472 return true; 4473 } 4474 } 4475 } 4476 return false; 4477 } 4478 4479 @Override 4480 public int checkSignatures(String pkg1, String pkg2) { 4481 synchronized (mPackages) { 4482 final PackageParser.Package p1 = mPackages.get(pkg1); 4483 final PackageParser.Package p2 = mPackages.get(pkg2); 4484 if (p1 == null || p1.mExtras == null 4485 || p2 == null || p2.mExtras == null) { 4486 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4487 } 4488 return compareSignatures(p1.mSignatures, p2.mSignatures); 4489 } 4490 } 4491 4492 @Override 4493 public int checkUidSignatures(int uid1, int uid2) { 4494 // Map to base uids. 4495 uid1 = UserHandle.getAppId(uid1); 4496 uid2 = UserHandle.getAppId(uid2); 4497 // reader 4498 synchronized (mPackages) { 4499 Signature[] s1; 4500 Signature[] s2; 4501 Object obj = mSettings.getUserIdLPr(uid1); 4502 if (obj != null) { 4503 if (obj instanceof SharedUserSetting) { 4504 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4505 } else if (obj instanceof PackageSetting) { 4506 s1 = ((PackageSetting)obj).signatures.mSignatures; 4507 } else { 4508 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4509 } 4510 } else { 4511 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4512 } 4513 obj = mSettings.getUserIdLPr(uid2); 4514 if (obj != null) { 4515 if (obj instanceof SharedUserSetting) { 4516 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4517 } else if (obj instanceof PackageSetting) { 4518 s2 = ((PackageSetting)obj).signatures.mSignatures; 4519 } else { 4520 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4521 } 4522 } else { 4523 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4524 } 4525 return compareSignatures(s1, s2); 4526 } 4527 } 4528 4529 /** 4530 * This method should typically only be used when granting or revoking 4531 * permissions, since the app may immediately restart after this call. 4532 * <p> 4533 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4534 * guard your work against the app being relaunched. 4535 */ 4536 private void killUid(int appId, int userId, String reason) { 4537 final long identity = Binder.clearCallingIdentity(); 4538 try { 4539 IActivityManager am = ActivityManagerNative.getDefault(); 4540 if (am != null) { 4541 try { 4542 am.killUid(appId, userId, reason); 4543 } catch (RemoteException e) { 4544 /* ignore - same process */ 4545 } 4546 } 4547 } finally { 4548 Binder.restoreCallingIdentity(identity); 4549 } 4550 } 4551 4552 /** 4553 * Compares two sets of signatures. Returns: 4554 * <br /> 4555 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4556 * <br /> 4557 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4558 * <br /> 4559 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4560 * <br /> 4561 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4562 * <br /> 4563 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4564 */ 4565 static int compareSignatures(Signature[] s1, Signature[] s2) { 4566 if (s1 == null) { 4567 return s2 == null 4568 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4569 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4570 } 4571 4572 if (s2 == null) { 4573 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4574 } 4575 4576 if (s1.length != s2.length) { 4577 return PackageManager.SIGNATURE_NO_MATCH; 4578 } 4579 4580 // Since both signature sets are of size 1, we can compare without HashSets. 4581 if (s1.length == 1) { 4582 return s1[0].equals(s2[0]) ? 4583 PackageManager.SIGNATURE_MATCH : 4584 PackageManager.SIGNATURE_NO_MATCH; 4585 } 4586 4587 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4588 for (Signature sig : s1) { 4589 set1.add(sig); 4590 } 4591 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4592 for (Signature sig : s2) { 4593 set2.add(sig); 4594 } 4595 // Make sure s2 contains all signatures in s1. 4596 if (set1.equals(set2)) { 4597 return PackageManager.SIGNATURE_MATCH; 4598 } 4599 return PackageManager.SIGNATURE_NO_MATCH; 4600 } 4601 4602 /** 4603 * If the database version for this type of package (internal storage or 4604 * external storage) is less than the version where package signatures 4605 * were updated, return true. 4606 */ 4607 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4608 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4609 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4610 } 4611 4612 /** 4613 * Used for backward compatibility to make sure any packages with 4614 * certificate chains get upgraded to the new style. {@code existingSigs} 4615 * will be in the old format (since they were stored on disk from before the 4616 * system upgrade) and {@code scannedSigs} will be in the newer format. 4617 */ 4618 private int compareSignaturesCompat(PackageSignatures existingSigs, 4619 PackageParser.Package scannedPkg) { 4620 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4621 return PackageManager.SIGNATURE_NO_MATCH; 4622 } 4623 4624 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4625 for (Signature sig : existingSigs.mSignatures) { 4626 existingSet.add(sig); 4627 } 4628 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4629 for (Signature sig : scannedPkg.mSignatures) { 4630 try { 4631 Signature[] chainSignatures = sig.getChainSignatures(); 4632 for (Signature chainSig : chainSignatures) { 4633 scannedCompatSet.add(chainSig); 4634 } 4635 } catch (CertificateEncodingException e) { 4636 scannedCompatSet.add(sig); 4637 } 4638 } 4639 /* 4640 * Make sure the expanded scanned set contains all signatures in the 4641 * existing one. 4642 */ 4643 if (scannedCompatSet.equals(existingSet)) { 4644 // Migrate the old signatures to the new scheme. 4645 existingSigs.assignSignatures(scannedPkg.mSignatures); 4646 // The new KeySets will be re-added later in the scanning process. 4647 synchronized (mPackages) { 4648 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4649 } 4650 return PackageManager.SIGNATURE_MATCH; 4651 } 4652 return PackageManager.SIGNATURE_NO_MATCH; 4653 } 4654 4655 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4656 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4657 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4658 } 4659 4660 private int compareSignaturesRecover(PackageSignatures existingSigs, 4661 PackageParser.Package scannedPkg) { 4662 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4663 return PackageManager.SIGNATURE_NO_MATCH; 4664 } 4665 4666 String msg = null; 4667 try { 4668 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4669 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4670 + scannedPkg.packageName); 4671 return PackageManager.SIGNATURE_MATCH; 4672 } 4673 } catch (CertificateException e) { 4674 msg = e.getMessage(); 4675 } 4676 4677 logCriticalInfo(Log.INFO, 4678 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4679 return PackageManager.SIGNATURE_NO_MATCH; 4680 } 4681 4682 @Override 4683 public List<String> getAllPackages() { 4684 synchronized (mPackages) { 4685 return new ArrayList<String>(mPackages.keySet()); 4686 } 4687 } 4688 4689 @Override 4690 public String[] getPackagesForUid(int uid) { 4691 uid = UserHandle.getAppId(uid); 4692 // reader 4693 synchronized (mPackages) { 4694 Object obj = mSettings.getUserIdLPr(uid); 4695 if (obj instanceof SharedUserSetting) { 4696 final SharedUserSetting sus = (SharedUserSetting) obj; 4697 final int N = sus.packages.size(); 4698 final String[] res = new String[N]; 4699 final Iterator<PackageSetting> it = sus.packages.iterator(); 4700 int i = 0; 4701 while (it.hasNext()) { 4702 res[i++] = it.next().name; 4703 } 4704 return res; 4705 } else if (obj instanceof PackageSetting) { 4706 final PackageSetting ps = (PackageSetting) obj; 4707 return new String[] { ps.name }; 4708 } 4709 } 4710 return null; 4711 } 4712 4713 @Override 4714 public String getNameForUid(int uid) { 4715 // reader 4716 synchronized (mPackages) { 4717 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4718 if (obj instanceof SharedUserSetting) { 4719 final SharedUserSetting sus = (SharedUserSetting) obj; 4720 return sus.name + ":" + sus.userId; 4721 } else if (obj instanceof PackageSetting) { 4722 final PackageSetting ps = (PackageSetting) obj; 4723 return ps.name; 4724 } 4725 } 4726 return null; 4727 } 4728 4729 @Override 4730 public int getUidForSharedUser(String sharedUserName) { 4731 if(sharedUserName == null) { 4732 return -1; 4733 } 4734 // reader 4735 synchronized (mPackages) { 4736 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4737 if (suid == null) { 4738 return -1; 4739 } 4740 return suid.userId; 4741 } 4742 } 4743 4744 @Override 4745 public int getFlagsForUid(int uid) { 4746 synchronized (mPackages) { 4747 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4748 if (obj instanceof SharedUserSetting) { 4749 final SharedUserSetting sus = (SharedUserSetting) obj; 4750 return sus.pkgFlags; 4751 } else if (obj instanceof PackageSetting) { 4752 final PackageSetting ps = (PackageSetting) obj; 4753 return ps.pkgFlags; 4754 } 4755 } 4756 return 0; 4757 } 4758 4759 @Override 4760 public int getPrivateFlagsForUid(int uid) { 4761 synchronized (mPackages) { 4762 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4763 if (obj instanceof SharedUserSetting) { 4764 final SharedUserSetting sus = (SharedUserSetting) obj; 4765 return sus.pkgPrivateFlags; 4766 } else if (obj instanceof PackageSetting) { 4767 final PackageSetting ps = (PackageSetting) obj; 4768 return ps.pkgPrivateFlags; 4769 } 4770 } 4771 return 0; 4772 } 4773 4774 @Override 4775 public boolean isUidPrivileged(int uid) { 4776 uid = UserHandle.getAppId(uid); 4777 // reader 4778 synchronized (mPackages) { 4779 Object obj = mSettings.getUserIdLPr(uid); 4780 if (obj instanceof SharedUserSetting) { 4781 final SharedUserSetting sus = (SharedUserSetting) obj; 4782 final Iterator<PackageSetting> it = sus.packages.iterator(); 4783 while (it.hasNext()) { 4784 if (it.next().isPrivileged()) { 4785 return true; 4786 } 4787 } 4788 } else if (obj instanceof PackageSetting) { 4789 final PackageSetting ps = (PackageSetting) obj; 4790 return ps.isPrivileged(); 4791 } 4792 } 4793 return false; 4794 } 4795 4796 @Override 4797 public String[] getAppOpPermissionPackages(String permissionName) { 4798 synchronized (mPackages) { 4799 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4800 if (pkgs == null) { 4801 return null; 4802 } 4803 return pkgs.toArray(new String[pkgs.size()]); 4804 } 4805 } 4806 4807 @Override 4808 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4809 int flags, int userId) { 4810 try { 4811 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4812 4813 if (!sUserManager.exists(userId)) return null; 4814 flags = updateFlagsForResolve(flags, userId, intent); 4815 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4816 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4817 4818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4819 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4820 flags, userId); 4821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4822 4823 final ResolveInfo bestChoice = 4824 chooseBestActivity(intent, resolvedType, flags, query, userId); 4825 4826 if (isEphemeralAllowed(intent, query, userId)) { 4827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4828 final EphemeralResolveInfo ai = 4829 getEphemeralResolveInfo(intent, resolvedType, userId); 4830 if (ai != null) { 4831 if (DEBUG_EPHEMERAL) { 4832 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4833 } 4834 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4835 bestChoice.ephemeralResolveInfo = ai; 4836 } 4837 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4838 } 4839 return bestChoice; 4840 } finally { 4841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4842 } 4843 } 4844 4845 @Override 4846 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4847 IntentFilter filter, int match, ComponentName activity) { 4848 final int userId = UserHandle.getCallingUserId(); 4849 if (DEBUG_PREFERRED) { 4850 Log.v(TAG, "setLastChosenActivity intent=" + intent 4851 + " resolvedType=" + resolvedType 4852 + " flags=" + flags 4853 + " filter=" + filter 4854 + " match=" + match 4855 + " activity=" + activity); 4856 filter.dump(new PrintStreamPrinter(System.out), " "); 4857 } 4858 intent.setComponent(null); 4859 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4860 userId); 4861 // Find any earlier preferred or last chosen entries and nuke them 4862 findPreferredActivity(intent, resolvedType, 4863 flags, query, 0, false, true, false, userId); 4864 // Add the new activity as the last chosen for this filter 4865 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4866 "Setting last chosen"); 4867 } 4868 4869 @Override 4870 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4871 final int userId = UserHandle.getCallingUserId(); 4872 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4873 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4874 userId); 4875 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4876 false, false, false, userId); 4877 } 4878 4879 4880 private boolean isEphemeralAllowed( 4881 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4882 // Short circuit and return early if possible. 4883 if (DISABLE_EPHEMERAL_APPS) { 4884 return false; 4885 } 4886 final int callingUser = UserHandle.getCallingUserId(); 4887 if (callingUser != UserHandle.USER_SYSTEM) { 4888 return false; 4889 } 4890 if (mEphemeralResolverConnection == null) { 4891 return false; 4892 } 4893 if (intent.getComponent() != null) { 4894 return false; 4895 } 4896 if (intent.getPackage() != null) { 4897 return false; 4898 } 4899 final boolean isWebUri = hasWebURI(intent); 4900 if (!isWebUri) { 4901 return false; 4902 } 4903 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4904 synchronized (mPackages) { 4905 final int count = resolvedActivites.size(); 4906 for (int n = 0; n < count; n++) { 4907 ResolveInfo info = resolvedActivites.get(n); 4908 String packageName = info.activityInfo.packageName; 4909 PackageSetting ps = mSettings.mPackages.get(packageName); 4910 if (ps != null) { 4911 // Try to get the status from User settings first 4912 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4913 int status = (int) (packedStatus >> 32); 4914 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4915 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4916 if (DEBUG_EPHEMERAL) { 4917 Slog.v(TAG, "DENY ephemeral apps;" 4918 + " pkg: " + packageName + ", status: " + status); 4919 } 4920 return false; 4921 } 4922 } 4923 } 4924 } 4925 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4926 return true; 4927 } 4928 4929 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4930 int userId) { 4931 MessageDigest digest = null; 4932 try { 4933 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4934 } catch (NoSuchAlgorithmException e) { 4935 // If we can't create a digest, ignore ephemeral apps. 4936 return null; 4937 } 4938 4939 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4940 final byte[] digestBytes = digest.digest(hostBytes); 4941 int shaPrefix = 4942 digestBytes[0] << 24 4943 | digestBytes[1] << 16 4944 | digestBytes[2] << 8 4945 | digestBytes[3] << 0; 4946 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4947 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4948 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4949 // No hash prefix match; there are no ephemeral apps for this domain. 4950 return null; 4951 } 4952 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4953 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4954 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4955 continue; 4956 } 4957 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4958 // No filters; this should never happen. 4959 if (filters.isEmpty()) { 4960 continue; 4961 } 4962 // We have a domain match; resolve the filters to see if anything matches. 4963 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4964 for (int j = filters.size() - 1; j >= 0; --j) { 4965 final EphemeralResolveIntentInfo intentInfo = 4966 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4967 ephemeralResolver.addFilter(intentInfo); 4968 } 4969 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4970 intent, resolvedType, false /*defaultOnly*/, userId); 4971 if (!matchedResolveInfoList.isEmpty()) { 4972 return matchedResolveInfoList.get(0); 4973 } 4974 } 4975 // Hash or filter mis-match; no ephemeral apps for this domain. 4976 return null; 4977 } 4978 4979 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4980 int flags, List<ResolveInfo> query, int userId) { 4981 if (query != null) { 4982 final int N = query.size(); 4983 if (N == 1) { 4984 return query.get(0); 4985 } else if (N > 1) { 4986 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4987 // If there is more than one activity with the same priority, 4988 // then let the user decide between them. 4989 ResolveInfo r0 = query.get(0); 4990 ResolveInfo r1 = query.get(1); 4991 if (DEBUG_INTENT_MATCHING || debug) { 4992 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4993 + r1.activityInfo.name + "=" + r1.priority); 4994 } 4995 // If the first activity has a higher priority, or a different 4996 // default, then it is always desirable to pick it. 4997 if (r0.priority != r1.priority 4998 || r0.preferredOrder != r1.preferredOrder 4999 || r0.isDefault != r1.isDefault) { 5000 return query.get(0); 5001 } 5002 // If we have saved a preference for a preferred activity for 5003 // this Intent, use that. 5004 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5005 flags, query, r0.priority, true, false, debug, userId); 5006 if (ri != null) { 5007 return ri; 5008 } 5009 ri = new ResolveInfo(mResolveInfo); 5010 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5011 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5012 ri.activityInfo.applicationInfo = new ApplicationInfo( 5013 ri.activityInfo.applicationInfo); 5014 if (userId != 0) { 5015 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5016 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5017 } 5018 // Make sure that the resolver is displayable in car mode 5019 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5020 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5021 return ri; 5022 } 5023 } 5024 return null; 5025 } 5026 5027 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5028 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5029 final int N = query.size(); 5030 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5031 .get(userId); 5032 // Get the list of persistent preferred activities that handle the intent 5033 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5034 List<PersistentPreferredActivity> pprefs = ppir != null 5035 ? ppir.queryIntent(intent, resolvedType, 5036 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5037 : null; 5038 if (pprefs != null && pprefs.size() > 0) { 5039 final int M = pprefs.size(); 5040 for (int i=0; i<M; i++) { 5041 final PersistentPreferredActivity ppa = pprefs.get(i); 5042 if (DEBUG_PREFERRED || debug) { 5043 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5044 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5045 + "\n component=" + ppa.mComponent); 5046 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5047 } 5048 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5049 flags | MATCH_DISABLED_COMPONENTS, userId); 5050 if (DEBUG_PREFERRED || debug) { 5051 Slog.v(TAG, "Found persistent preferred activity:"); 5052 if (ai != null) { 5053 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5054 } else { 5055 Slog.v(TAG, " null"); 5056 } 5057 } 5058 if (ai == null) { 5059 // This previously registered persistent preferred activity 5060 // component is no longer known. Ignore it and do NOT remove it. 5061 continue; 5062 } 5063 for (int j=0; j<N; j++) { 5064 final ResolveInfo ri = query.get(j); 5065 if (!ri.activityInfo.applicationInfo.packageName 5066 .equals(ai.applicationInfo.packageName)) { 5067 continue; 5068 } 5069 if (!ri.activityInfo.name.equals(ai.name)) { 5070 continue; 5071 } 5072 // Found a persistent preference that can handle the intent. 5073 if (DEBUG_PREFERRED || debug) { 5074 Slog.v(TAG, "Returning persistent preferred activity: " + 5075 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5076 } 5077 return ri; 5078 } 5079 } 5080 } 5081 return null; 5082 } 5083 5084 // TODO: handle preferred activities missing while user has amnesia 5085 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5086 List<ResolveInfo> query, int priority, boolean always, 5087 boolean removeMatches, boolean debug, int userId) { 5088 if (!sUserManager.exists(userId)) return null; 5089 flags = updateFlagsForResolve(flags, userId, intent); 5090 // writer 5091 synchronized (mPackages) { 5092 if (intent.getSelector() != null) { 5093 intent = intent.getSelector(); 5094 } 5095 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5096 5097 // Try to find a matching persistent preferred activity. 5098 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5099 debug, userId); 5100 5101 // If a persistent preferred activity matched, use it. 5102 if (pri != null) { 5103 return pri; 5104 } 5105 5106 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5107 // Get the list of preferred activities that handle the intent 5108 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5109 List<PreferredActivity> prefs = pir != null 5110 ? pir.queryIntent(intent, resolvedType, 5111 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5112 : null; 5113 if (prefs != null && prefs.size() > 0) { 5114 boolean changed = false; 5115 try { 5116 // First figure out how good the original match set is. 5117 // We will only allow preferred activities that came 5118 // from the same match quality. 5119 int match = 0; 5120 5121 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5122 5123 final int N = query.size(); 5124 for (int j=0; j<N; j++) { 5125 final ResolveInfo ri = query.get(j); 5126 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5127 + ": 0x" + Integer.toHexString(match)); 5128 if (ri.match > match) { 5129 match = ri.match; 5130 } 5131 } 5132 5133 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5134 + Integer.toHexString(match)); 5135 5136 match &= IntentFilter.MATCH_CATEGORY_MASK; 5137 final int M = prefs.size(); 5138 for (int i=0; i<M; i++) { 5139 final PreferredActivity pa = prefs.get(i); 5140 if (DEBUG_PREFERRED || debug) { 5141 Slog.v(TAG, "Checking PreferredActivity ds=" 5142 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5143 + "\n component=" + pa.mPref.mComponent); 5144 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5145 } 5146 if (pa.mPref.mMatch != match) { 5147 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5148 + Integer.toHexString(pa.mPref.mMatch)); 5149 continue; 5150 } 5151 // If it's not an "always" type preferred activity and that's what we're 5152 // looking for, skip it. 5153 if (always && !pa.mPref.mAlways) { 5154 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5155 continue; 5156 } 5157 final ActivityInfo ai = getActivityInfo( 5158 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5159 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5160 userId); 5161 if (DEBUG_PREFERRED || debug) { 5162 Slog.v(TAG, "Found preferred activity:"); 5163 if (ai != null) { 5164 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5165 } else { 5166 Slog.v(TAG, " null"); 5167 } 5168 } 5169 if (ai == null) { 5170 // This previously registered preferred activity 5171 // component is no longer known. Most likely an update 5172 // to the app was installed and in the new version this 5173 // component no longer exists. Clean it up by removing 5174 // it from the preferred activities list, and skip it. 5175 Slog.w(TAG, "Removing dangling preferred activity: " 5176 + pa.mPref.mComponent); 5177 pir.removeFilter(pa); 5178 changed = true; 5179 continue; 5180 } 5181 for (int j=0; j<N; j++) { 5182 final ResolveInfo ri = query.get(j); 5183 if (!ri.activityInfo.applicationInfo.packageName 5184 .equals(ai.applicationInfo.packageName)) { 5185 continue; 5186 } 5187 if (!ri.activityInfo.name.equals(ai.name)) { 5188 continue; 5189 } 5190 5191 if (removeMatches) { 5192 pir.removeFilter(pa); 5193 changed = true; 5194 if (DEBUG_PREFERRED) { 5195 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5196 } 5197 break; 5198 } 5199 5200 // Okay we found a previously set preferred or last chosen app. 5201 // If the result set is different from when this 5202 // was created, we need to clear it and re-ask the 5203 // user their preference, if we're looking for an "always" type entry. 5204 if (always && !pa.mPref.sameSet(query)) { 5205 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5206 + intent + " type " + resolvedType); 5207 if (DEBUG_PREFERRED) { 5208 Slog.v(TAG, "Removing preferred activity since set changed " 5209 + pa.mPref.mComponent); 5210 } 5211 pir.removeFilter(pa); 5212 // Re-add the filter as a "last chosen" entry (!always) 5213 PreferredActivity lastChosen = new PreferredActivity( 5214 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5215 pir.addFilter(lastChosen); 5216 changed = true; 5217 return null; 5218 } 5219 5220 // Yay! Either the set matched or we're looking for the last chosen 5221 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5222 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5223 return ri; 5224 } 5225 } 5226 } finally { 5227 if (changed) { 5228 if (DEBUG_PREFERRED) { 5229 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5230 } 5231 scheduleWritePackageRestrictionsLocked(userId); 5232 } 5233 } 5234 } 5235 } 5236 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5237 return null; 5238 } 5239 5240 /* 5241 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5242 */ 5243 @Override 5244 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5245 int targetUserId) { 5246 mContext.enforceCallingOrSelfPermission( 5247 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5248 List<CrossProfileIntentFilter> matches = 5249 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5250 if (matches != null) { 5251 int size = matches.size(); 5252 for (int i = 0; i < size; i++) { 5253 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5254 } 5255 } 5256 if (hasWebURI(intent)) { 5257 // cross-profile app linking works only towards the parent. 5258 final UserInfo parent = getProfileParent(sourceUserId); 5259 synchronized(mPackages) { 5260 int flags = updateFlagsForResolve(0, parent.id, intent); 5261 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5262 intent, resolvedType, flags, sourceUserId, parent.id); 5263 return xpDomainInfo != null; 5264 } 5265 } 5266 return false; 5267 } 5268 5269 private UserInfo getProfileParent(int userId) { 5270 final long identity = Binder.clearCallingIdentity(); 5271 try { 5272 return sUserManager.getProfileParent(userId); 5273 } finally { 5274 Binder.restoreCallingIdentity(identity); 5275 } 5276 } 5277 5278 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5279 String resolvedType, int userId) { 5280 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5281 if (resolver != null) { 5282 return resolver.queryIntent(intent, resolvedType, false, userId); 5283 } 5284 return null; 5285 } 5286 5287 @Override 5288 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5289 String resolvedType, int flags, int userId) { 5290 try { 5291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5292 5293 return new ParceledListSlice<>( 5294 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5295 } finally { 5296 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5297 } 5298 } 5299 5300 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5301 String resolvedType, int flags, int userId) { 5302 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5303 flags = updateFlagsForResolve(flags, userId, intent); 5304 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5305 false /* requireFullPermission */, false /* checkShell */, 5306 "query intent activities"); 5307 ComponentName comp = intent.getComponent(); 5308 if (comp == null) { 5309 if (intent.getSelector() != null) { 5310 intent = intent.getSelector(); 5311 comp = intent.getComponent(); 5312 } 5313 } 5314 5315 if (comp != null) { 5316 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5317 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5318 if (ai != null) { 5319 final ResolveInfo ri = new ResolveInfo(); 5320 ri.activityInfo = ai; 5321 list.add(ri); 5322 } 5323 return list; 5324 } 5325 5326 // reader 5327 synchronized (mPackages) { 5328 final String pkgName = intent.getPackage(); 5329 if (pkgName == null) { 5330 List<CrossProfileIntentFilter> matchingFilters = 5331 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5332 // Check for results that need to skip the current profile. 5333 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5334 resolvedType, flags, userId); 5335 if (xpResolveInfo != null) { 5336 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5337 result.add(xpResolveInfo); 5338 return filterIfNotSystemUser(result, userId); 5339 } 5340 5341 // Check for results in the current profile. 5342 List<ResolveInfo> result = mActivities.queryIntent( 5343 intent, resolvedType, flags, userId); 5344 result = filterIfNotSystemUser(result, userId); 5345 5346 // Check for cross profile results. 5347 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5348 xpResolveInfo = queryCrossProfileIntents( 5349 matchingFilters, intent, resolvedType, flags, userId, 5350 hasNonNegativePriorityResult); 5351 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5352 boolean isVisibleToUser = filterIfNotSystemUser( 5353 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5354 if (isVisibleToUser) { 5355 result.add(xpResolveInfo); 5356 Collections.sort(result, mResolvePrioritySorter); 5357 } 5358 } 5359 if (hasWebURI(intent)) { 5360 CrossProfileDomainInfo xpDomainInfo = null; 5361 final UserInfo parent = getProfileParent(userId); 5362 if (parent != null) { 5363 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5364 flags, userId, parent.id); 5365 } 5366 if (xpDomainInfo != null) { 5367 if (xpResolveInfo != null) { 5368 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5369 // in the result. 5370 result.remove(xpResolveInfo); 5371 } 5372 if (result.size() == 0) { 5373 result.add(xpDomainInfo.resolveInfo); 5374 return result; 5375 } 5376 } else if (result.size() <= 1) { 5377 return result; 5378 } 5379 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5380 xpDomainInfo, userId); 5381 Collections.sort(result, mResolvePrioritySorter); 5382 } 5383 return result; 5384 } 5385 final PackageParser.Package pkg = mPackages.get(pkgName); 5386 if (pkg != null) { 5387 return filterIfNotSystemUser( 5388 mActivities.queryIntentForPackage( 5389 intent, resolvedType, flags, pkg.activities, userId), 5390 userId); 5391 } 5392 return new ArrayList<ResolveInfo>(); 5393 } 5394 } 5395 5396 private static class CrossProfileDomainInfo { 5397 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5398 ResolveInfo resolveInfo; 5399 /* Best domain verification status of the activities found in the other profile */ 5400 int bestDomainVerificationStatus; 5401 } 5402 5403 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5404 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5405 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5406 sourceUserId)) { 5407 return null; 5408 } 5409 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5410 resolvedType, flags, parentUserId); 5411 5412 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5413 return null; 5414 } 5415 CrossProfileDomainInfo result = null; 5416 int size = resultTargetUser.size(); 5417 for (int i = 0; i < size; i++) { 5418 ResolveInfo riTargetUser = resultTargetUser.get(i); 5419 // Intent filter verification is only for filters that specify a host. So don't return 5420 // those that handle all web uris. 5421 if (riTargetUser.handleAllWebDataURI) { 5422 continue; 5423 } 5424 String packageName = riTargetUser.activityInfo.packageName; 5425 PackageSetting ps = mSettings.mPackages.get(packageName); 5426 if (ps == null) { 5427 continue; 5428 } 5429 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5430 int status = (int)(verificationState >> 32); 5431 if (result == null) { 5432 result = new CrossProfileDomainInfo(); 5433 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5434 sourceUserId, parentUserId); 5435 result.bestDomainVerificationStatus = status; 5436 } else { 5437 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5438 result.bestDomainVerificationStatus); 5439 } 5440 } 5441 // Don't consider matches with status NEVER across profiles. 5442 if (result != null && result.bestDomainVerificationStatus 5443 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5444 return null; 5445 } 5446 return result; 5447 } 5448 5449 /** 5450 * Verification statuses are ordered from the worse to the best, except for 5451 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5452 */ 5453 private int bestDomainVerificationStatus(int status1, int status2) { 5454 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5455 return status2; 5456 } 5457 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5458 return status1; 5459 } 5460 return (int) MathUtils.max(status1, status2); 5461 } 5462 5463 private boolean isUserEnabled(int userId) { 5464 long callingId = Binder.clearCallingIdentity(); 5465 try { 5466 UserInfo userInfo = sUserManager.getUserInfo(userId); 5467 return userInfo != null && userInfo.isEnabled(); 5468 } finally { 5469 Binder.restoreCallingIdentity(callingId); 5470 } 5471 } 5472 5473 /** 5474 * Filter out activities with systemUserOnly flag set, when current user is not System. 5475 * 5476 * @return filtered list 5477 */ 5478 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5479 if (userId == UserHandle.USER_SYSTEM) { 5480 return resolveInfos; 5481 } 5482 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5483 ResolveInfo info = resolveInfos.get(i); 5484 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5485 resolveInfos.remove(i); 5486 } 5487 } 5488 return resolveInfos; 5489 } 5490 5491 /** 5492 * @param resolveInfos list of resolve infos in descending priority order 5493 * @return if the list contains a resolve info with non-negative priority 5494 */ 5495 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5496 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5497 } 5498 5499 private static boolean hasWebURI(Intent intent) { 5500 if (intent.getData() == null) { 5501 return false; 5502 } 5503 final String scheme = intent.getScheme(); 5504 if (TextUtils.isEmpty(scheme)) { 5505 return false; 5506 } 5507 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5508 } 5509 5510 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5511 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5512 int userId) { 5513 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5514 5515 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5516 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5517 candidates.size()); 5518 } 5519 5520 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5521 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5522 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5523 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5524 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5525 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5526 5527 synchronized (mPackages) { 5528 final int count = candidates.size(); 5529 // First, try to use linked apps. Partition the candidates into four lists: 5530 // one for the final results, one for the "do not use ever", one for "undefined status" 5531 // and finally one for "browser app type". 5532 for (int n=0; n<count; n++) { 5533 ResolveInfo info = candidates.get(n); 5534 String packageName = info.activityInfo.packageName; 5535 PackageSetting ps = mSettings.mPackages.get(packageName); 5536 if (ps != null) { 5537 // Add to the special match all list (Browser use case) 5538 if (info.handleAllWebDataURI) { 5539 matchAllList.add(info); 5540 continue; 5541 } 5542 // Try to get the status from User settings first 5543 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5544 int status = (int)(packedStatus >> 32); 5545 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5546 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5547 if (DEBUG_DOMAIN_VERIFICATION) { 5548 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5549 + " : linkgen=" + linkGeneration); 5550 } 5551 // Use link-enabled generation as preferredOrder, i.e. 5552 // prefer newly-enabled over earlier-enabled. 5553 info.preferredOrder = linkGeneration; 5554 alwaysList.add(info); 5555 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5556 if (DEBUG_DOMAIN_VERIFICATION) { 5557 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5558 } 5559 neverList.add(info); 5560 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5561 if (DEBUG_DOMAIN_VERIFICATION) { 5562 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5563 } 5564 alwaysAskList.add(info); 5565 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5566 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5567 if (DEBUG_DOMAIN_VERIFICATION) { 5568 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5569 } 5570 undefinedList.add(info); 5571 } 5572 } 5573 } 5574 5575 // We'll want to include browser possibilities in a few cases 5576 boolean includeBrowser = false; 5577 5578 // First try to add the "always" resolution(s) for the current user, if any 5579 if (alwaysList.size() > 0) { 5580 result.addAll(alwaysList); 5581 } else { 5582 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5583 result.addAll(undefinedList); 5584 // Maybe add one for the other profile. 5585 if (xpDomainInfo != null && ( 5586 xpDomainInfo.bestDomainVerificationStatus 5587 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5588 result.add(xpDomainInfo.resolveInfo); 5589 } 5590 includeBrowser = true; 5591 } 5592 5593 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5594 // If there were 'always' entries their preferred order has been set, so we also 5595 // back that off to make the alternatives equivalent 5596 if (alwaysAskList.size() > 0) { 5597 for (ResolveInfo i : result) { 5598 i.preferredOrder = 0; 5599 } 5600 result.addAll(alwaysAskList); 5601 includeBrowser = true; 5602 } 5603 5604 if (includeBrowser) { 5605 // Also add browsers (all of them or only the default one) 5606 if (DEBUG_DOMAIN_VERIFICATION) { 5607 Slog.v(TAG, " ...including browsers in candidate set"); 5608 } 5609 if ((matchFlags & MATCH_ALL) != 0) { 5610 result.addAll(matchAllList); 5611 } else { 5612 // Browser/generic handling case. If there's a default browser, go straight 5613 // to that (but only if there is no other higher-priority match). 5614 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5615 int maxMatchPrio = 0; 5616 ResolveInfo defaultBrowserMatch = null; 5617 final int numCandidates = matchAllList.size(); 5618 for (int n = 0; n < numCandidates; n++) { 5619 ResolveInfo info = matchAllList.get(n); 5620 // track the highest overall match priority... 5621 if (info.priority > maxMatchPrio) { 5622 maxMatchPrio = info.priority; 5623 } 5624 // ...and the highest-priority default browser match 5625 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5626 if (defaultBrowserMatch == null 5627 || (defaultBrowserMatch.priority < info.priority)) { 5628 if (debug) { 5629 Slog.v(TAG, "Considering default browser match " + info); 5630 } 5631 defaultBrowserMatch = info; 5632 } 5633 } 5634 } 5635 if (defaultBrowserMatch != null 5636 && defaultBrowserMatch.priority >= maxMatchPrio 5637 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5638 { 5639 if (debug) { 5640 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5641 } 5642 result.add(defaultBrowserMatch); 5643 } else { 5644 result.addAll(matchAllList); 5645 } 5646 } 5647 5648 // If there is nothing selected, add all candidates and remove the ones that the user 5649 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5650 if (result.size() == 0) { 5651 result.addAll(candidates); 5652 result.removeAll(neverList); 5653 } 5654 } 5655 } 5656 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5657 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5658 result.size()); 5659 for (ResolveInfo info : result) { 5660 Slog.v(TAG, " + " + info.activityInfo); 5661 } 5662 } 5663 return result; 5664 } 5665 5666 // Returns a packed value as a long: 5667 // 5668 // high 'int'-sized word: link status: undefined/ask/never/always. 5669 // low 'int'-sized word: relative priority among 'always' results. 5670 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5671 long result = ps.getDomainVerificationStatusForUser(userId); 5672 // if none available, get the master status 5673 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5674 if (ps.getIntentFilterVerificationInfo() != null) { 5675 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5676 } 5677 } 5678 return result; 5679 } 5680 5681 private ResolveInfo querySkipCurrentProfileIntents( 5682 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5683 int flags, int sourceUserId) { 5684 if (matchingFilters != null) { 5685 int size = matchingFilters.size(); 5686 for (int i = 0; i < size; i ++) { 5687 CrossProfileIntentFilter filter = matchingFilters.get(i); 5688 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5689 // Checking if there are activities in the target user that can handle the 5690 // intent. 5691 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5692 resolvedType, flags, sourceUserId); 5693 if (resolveInfo != null) { 5694 return resolveInfo; 5695 } 5696 } 5697 } 5698 } 5699 return null; 5700 } 5701 5702 // Return matching ResolveInfo in target user if any. 5703 private ResolveInfo queryCrossProfileIntents( 5704 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5705 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5706 if (matchingFilters != null) { 5707 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5708 // match the same intent. For performance reasons, it is better not to 5709 // run queryIntent twice for the same userId 5710 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5711 int size = matchingFilters.size(); 5712 for (int i = 0; i < size; i++) { 5713 CrossProfileIntentFilter filter = matchingFilters.get(i); 5714 int targetUserId = filter.getTargetUserId(); 5715 boolean skipCurrentProfile = 5716 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5717 boolean skipCurrentProfileIfNoMatchFound = 5718 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5719 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5720 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5721 // Checking if there are activities in the target user that can handle the 5722 // intent. 5723 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5724 resolvedType, flags, sourceUserId); 5725 if (resolveInfo != null) return resolveInfo; 5726 alreadyTriedUserIds.put(targetUserId, true); 5727 } 5728 } 5729 } 5730 return null; 5731 } 5732 5733 /** 5734 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5735 * will forward the intent to the filter's target user. 5736 * Otherwise, returns null. 5737 */ 5738 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5739 String resolvedType, int flags, int sourceUserId) { 5740 int targetUserId = filter.getTargetUserId(); 5741 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5742 resolvedType, flags, targetUserId); 5743 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5744 // If all the matches in the target profile are suspended, return null. 5745 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5746 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5747 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5748 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5749 targetUserId); 5750 } 5751 } 5752 } 5753 return null; 5754 } 5755 5756 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5757 int sourceUserId, int targetUserId) { 5758 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5759 long ident = Binder.clearCallingIdentity(); 5760 boolean targetIsProfile; 5761 try { 5762 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5763 } finally { 5764 Binder.restoreCallingIdentity(ident); 5765 } 5766 String className; 5767 if (targetIsProfile) { 5768 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5769 } else { 5770 className = FORWARD_INTENT_TO_PARENT; 5771 } 5772 ComponentName forwardingActivityComponentName = new ComponentName( 5773 mAndroidApplication.packageName, className); 5774 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5775 sourceUserId); 5776 if (!targetIsProfile) { 5777 forwardingActivityInfo.showUserIcon = targetUserId; 5778 forwardingResolveInfo.noResourceId = true; 5779 } 5780 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5781 forwardingResolveInfo.priority = 0; 5782 forwardingResolveInfo.preferredOrder = 0; 5783 forwardingResolveInfo.match = 0; 5784 forwardingResolveInfo.isDefault = true; 5785 forwardingResolveInfo.filter = filter; 5786 forwardingResolveInfo.targetUserId = targetUserId; 5787 return forwardingResolveInfo; 5788 } 5789 5790 @Override 5791 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5792 Intent[] specifics, String[] specificTypes, Intent intent, 5793 String resolvedType, int flags, int userId) { 5794 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5795 specificTypes, intent, resolvedType, flags, userId)); 5796 } 5797 5798 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5799 Intent[] specifics, String[] specificTypes, Intent intent, 5800 String resolvedType, int flags, int userId) { 5801 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5802 flags = updateFlagsForResolve(flags, userId, intent); 5803 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5804 false /* requireFullPermission */, false /* checkShell */, 5805 "query intent activity options"); 5806 final String resultsAction = intent.getAction(); 5807 5808 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5809 | PackageManager.GET_RESOLVED_FILTER, userId); 5810 5811 if (DEBUG_INTENT_MATCHING) { 5812 Log.v(TAG, "Query " + intent + ": " + results); 5813 } 5814 5815 int specificsPos = 0; 5816 int N; 5817 5818 // todo: note that the algorithm used here is O(N^2). This 5819 // isn't a problem in our current environment, but if we start running 5820 // into situations where we have more than 5 or 10 matches then this 5821 // should probably be changed to something smarter... 5822 5823 // First we go through and resolve each of the specific items 5824 // that were supplied, taking care of removing any corresponding 5825 // duplicate items in the generic resolve list. 5826 if (specifics != null) { 5827 for (int i=0; i<specifics.length; i++) { 5828 final Intent sintent = specifics[i]; 5829 if (sintent == null) { 5830 continue; 5831 } 5832 5833 if (DEBUG_INTENT_MATCHING) { 5834 Log.v(TAG, "Specific #" + i + ": " + sintent); 5835 } 5836 5837 String action = sintent.getAction(); 5838 if (resultsAction != null && resultsAction.equals(action)) { 5839 // If this action was explicitly requested, then don't 5840 // remove things that have it. 5841 action = null; 5842 } 5843 5844 ResolveInfo ri = null; 5845 ActivityInfo ai = null; 5846 5847 ComponentName comp = sintent.getComponent(); 5848 if (comp == null) { 5849 ri = resolveIntent( 5850 sintent, 5851 specificTypes != null ? specificTypes[i] : null, 5852 flags, userId); 5853 if (ri == null) { 5854 continue; 5855 } 5856 if (ri == mResolveInfo) { 5857 // ACK! Must do something better with this. 5858 } 5859 ai = ri.activityInfo; 5860 comp = new ComponentName(ai.applicationInfo.packageName, 5861 ai.name); 5862 } else { 5863 ai = getActivityInfo(comp, flags, userId); 5864 if (ai == null) { 5865 continue; 5866 } 5867 } 5868 5869 // Look for any generic query activities that are duplicates 5870 // of this specific one, and remove them from the results. 5871 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5872 N = results.size(); 5873 int j; 5874 for (j=specificsPos; j<N; j++) { 5875 ResolveInfo sri = results.get(j); 5876 if ((sri.activityInfo.name.equals(comp.getClassName()) 5877 && sri.activityInfo.applicationInfo.packageName.equals( 5878 comp.getPackageName())) 5879 || (action != null && sri.filter.matchAction(action))) { 5880 results.remove(j); 5881 if (DEBUG_INTENT_MATCHING) Log.v( 5882 TAG, "Removing duplicate item from " + j 5883 + " due to specific " + specificsPos); 5884 if (ri == null) { 5885 ri = sri; 5886 } 5887 j--; 5888 N--; 5889 } 5890 } 5891 5892 // Add this specific item to its proper place. 5893 if (ri == null) { 5894 ri = new ResolveInfo(); 5895 ri.activityInfo = ai; 5896 } 5897 results.add(specificsPos, ri); 5898 ri.specificIndex = i; 5899 specificsPos++; 5900 } 5901 } 5902 5903 // Now we go through the remaining generic results and remove any 5904 // duplicate actions that are found here. 5905 N = results.size(); 5906 for (int i=specificsPos; i<N-1; i++) { 5907 final ResolveInfo rii = results.get(i); 5908 if (rii.filter == null) { 5909 continue; 5910 } 5911 5912 // Iterate over all of the actions of this result's intent 5913 // filter... typically this should be just one. 5914 final Iterator<String> it = rii.filter.actionsIterator(); 5915 if (it == null) { 5916 continue; 5917 } 5918 while (it.hasNext()) { 5919 final String action = it.next(); 5920 if (resultsAction != null && resultsAction.equals(action)) { 5921 // If this action was explicitly requested, then don't 5922 // remove things that have it. 5923 continue; 5924 } 5925 for (int j=i+1; j<N; j++) { 5926 final ResolveInfo rij = results.get(j); 5927 if (rij.filter != null && rij.filter.hasAction(action)) { 5928 results.remove(j); 5929 if (DEBUG_INTENT_MATCHING) Log.v( 5930 TAG, "Removing duplicate item from " + j 5931 + " due to action " + action + " at " + i); 5932 j--; 5933 N--; 5934 } 5935 } 5936 } 5937 5938 // If the caller didn't request filter information, drop it now 5939 // so we don't have to marshall/unmarshall it. 5940 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5941 rii.filter = null; 5942 } 5943 } 5944 5945 // Filter out the caller activity if so requested. 5946 if (caller != null) { 5947 N = results.size(); 5948 for (int i=0; i<N; i++) { 5949 ActivityInfo ainfo = results.get(i).activityInfo; 5950 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5951 && caller.getClassName().equals(ainfo.name)) { 5952 results.remove(i); 5953 break; 5954 } 5955 } 5956 } 5957 5958 // If the caller didn't request filter information, 5959 // drop them now so we don't have to 5960 // marshall/unmarshall it. 5961 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5962 N = results.size(); 5963 for (int i=0; i<N; i++) { 5964 results.get(i).filter = null; 5965 } 5966 } 5967 5968 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5969 return results; 5970 } 5971 5972 @Override 5973 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5974 String resolvedType, int flags, int userId) { 5975 return new ParceledListSlice<>( 5976 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5977 } 5978 5979 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5980 String resolvedType, int flags, int userId) { 5981 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5982 flags = updateFlagsForResolve(flags, userId, intent); 5983 ComponentName comp = intent.getComponent(); 5984 if (comp == null) { 5985 if (intent.getSelector() != null) { 5986 intent = intent.getSelector(); 5987 comp = intent.getComponent(); 5988 } 5989 } 5990 if (comp != null) { 5991 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5992 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5993 if (ai != null) { 5994 ResolveInfo ri = new ResolveInfo(); 5995 ri.activityInfo = ai; 5996 list.add(ri); 5997 } 5998 return list; 5999 } 6000 6001 // reader 6002 synchronized (mPackages) { 6003 String pkgName = intent.getPackage(); 6004 if (pkgName == null) { 6005 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6006 } 6007 final PackageParser.Package pkg = mPackages.get(pkgName); 6008 if (pkg != null) { 6009 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6010 userId); 6011 } 6012 return Collections.emptyList(); 6013 } 6014 } 6015 6016 @Override 6017 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6018 if (!sUserManager.exists(userId)) return null; 6019 flags = updateFlagsForResolve(flags, userId, intent); 6020 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6021 if (query != null) { 6022 if (query.size() >= 1) { 6023 // If there is more than one service with the same priority, 6024 // just arbitrarily pick the first one. 6025 return query.get(0); 6026 } 6027 } 6028 return null; 6029 } 6030 6031 @Override 6032 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6033 String resolvedType, int flags, int userId) { 6034 return new ParceledListSlice<>( 6035 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6036 } 6037 6038 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6039 String resolvedType, int flags, int userId) { 6040 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6041 flags = updateFlagsForResolve(flags, userId, intent); 6042 ComponentName comp = intent.getComponent(); 6043 if (comp == null) { 6044 if (intent.getSelector() != null) { 6045 intent = intent.getSelector(); 6046 comp = intent.getComponent(); 6047 } 6048 } 6049 if (comp != null) { 6050 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6051 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6052 if (si != null) { 6053 final ResolveInfo ri = new ResolveInfo(); 6054 ri.serviceInfo = si; 6055 list.add(ri); 6056 } 6057 return list; 6058 } 6059 6060 // reader 6061 synchronized (mPackages) { 6062 String pkgName = intent.getPackage(); 6063 if (pkgName == null) { 6064 return mServices.queryIntent(intent, resolvedType, flags, userId); 6065 } 6066 final PackageParser.Package pkg = mPackages.get(pkgName); 6067 if (pkg != null) { 6068 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6069 userId); 6070 } 6071 return Collections.emptyList(); 6072 } 6073 } 6074 6075 @Override 6076 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6077 String resolvedType, int flags, int userId) { 6078 return new ParceledListSlice<>( 6079 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6080 } 6081 6082 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6083 Intent intent, String resolvedType, int flags, int userId) { 6084 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6085 flags = updateFlagsForResolve(flags, userId, intent); 6086 ComponentName comp = intent.getComponent(); 6087 if (comp == null) { 6088 if (intent.getSelector() != null) { 6089 intent = intent.getSelector(); 6090 comp = intent.getComponent(); 6091 } 6092 } 6093 if (comp != null) { 6094 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6095 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6096 if (pi != null) { 6097 final ResolveInfo ri = new ResolveInfo(); 6098 ri.providerInfo = pi; 6099 list.add(ri); 6100 } 6101 return list; 6102 } 6103 6104 // reader 6105 synchronized (mPackages) { 6106 String pkgName = intent.getPackage(); 6107 if (pkgName == null) { 6108 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6109 } 6110 final PackageParser.Package pkg = mPackages.get(pkgName); 6111 if (pkg != null) { 6112 return mProviders.queryIntentForPackage( 6113 intent, resolvedType, flags, pkg.providers, userId); 6114 } 6115 return Collections.emptyList(); 6116 } 6117 } 6118 6119 @Override 6120 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6121 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6122 flags = updateFlagsForPackage(flags, userId, null); 6123 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6124 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6125 true /* requireFullPermission */, false /* checkShell */, 6126 "get installed packages"); 6127 6128 // writer 6129 synchronized (mPackages) { 6130 ArrayList<PackageInfo> list; 6131 if (listUninstalled) { 6132 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6133 for (PackageSetting ps : mSettings.mPackages.values()) { 6134 final PackageInfo pi; 6135 if (ps.pkg != null) { 6136 pi = generatePackageInfo(ps, flags, userId); 6137 } else { 6138 pi = generatePackageInfo(ps, flags, userId); 6139 } 6140 if (pi != null) { 6141 list.add(pi); 6142 } 6143 } 6144 } else { 6145 list = new ArrayList<PackageInfo>(mPackages.size()); 6146 for (PackageParser.Package p : mPackages.values()) { 6147 final PackageInfo pi = 6148 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6149 if (pi != null) { 6150 list.add(pi); 6151 } 6152 } 6153 } 6154 6155 return new ParceledListSlice<PackageInfo>(list); 6156 } 6157 } 6158 6159 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6160 String[] permissions, boolean[] tmp, int flags, int userId) { 6161 int numMatch = 0; 6162 final PermissionsState permissionsState = ps.getPermissionsState(); 6163 for (int i=0; i<permissions.length; i++) { 6164 final String permission = permissions[i]; 6165 if (permissionsState.hasPermission(permission, userId)) { 6166 tmp[i] = true; 6167 numMatch++; 6168 } else { 6169 tmp[i] = false; 6170 } 6171 } 6172 if (numMatch == 0) { 6173 return; 6174 } 6175 final PackageInfo pi; 6176 if (ps.pkg != null) { 6177 pi = generatePackageInfo(ps, flags, userId); 6178 } else { 6179 pi = generatePackageInfo(ps, flags, userId); 6180 } 6181 // The above might return null in cases of uninstalled apps or install-state 6182 // skew across users/profiles. 6183 if (pi != null) { 6184 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6185 if (numMatch == permissions.length) { 6186 pi.requestedPermissions = permissions; 6187 } else { 6188 pi.requestedPermissions = new String[numMatch]; 6189 numMatch = 0; 6190 for (int i=0; i<permissions.length; i++) { 6191 if (tmp[i]) { 6192 pi.requestedPermissions[numMatch] = permissions[i]; 6193 numMatch++; 6194 } 6195 } 6196 } 6197 } 6198 list.add(pi); 6199 } 6200 } 6201 6202 @Override 6203 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6204 String[] permissions, int flags, int userId) { 6205 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6206 flags = updateFlagsForPackage(flags, userId, permissions); 6207 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6208 6209 // writer 6210 synchronized (mPackages) { 6211 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6212 boolean[] tmpBools = new boolean[permissions.length]; 6213 if (listUninstalled) { 6214 for (PackageSetting ps : mSettings.mPackages.values()) { 6215 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6216 } 6217 } else { 6218 for (PackageParser.Package pkg : mPackages.values()) { 6219 PackageSetting ps = (PackageSetting)pkg.mExtras; 6220 if (ps != null) { 6221 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6222 userId); 6223 } 6224 } 6225 } 6226 6227 return new ParceledListSlice<PackageInfo>(list); 6228 } 6229 } 6230 6231 @Override 6232 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6233 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6234 flags = updateFlagsForApplication(flags, userId, null); 6235 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6236 6237 // writer 6238 synchronized (mPackages) { 6239 ArrayList<ApplicationInfo> list; 6240 if (listUninstalled) { 6241 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6242 for (PackageSetting ps : mSettings.mPackages.values()) { 6243 ApplicationInfo ai; 6244 if (ps.pkg != null) { 6245 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6246 ps.readUserState(userId), userId); 6247 } else { 6248 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6249 } 6250 if (ai != null) { 6251 list.add(ai); 6252 } 6253 } 6254 } else { 6255 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6256 for (PackageParser.Package p : mPackages.values()) { 6257 if (p.mExtras != null) { 6258 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6259 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6260 if (ai != null) { 6261 list.add(ai); 6262 } 6263 } 6264 } 6265 } 6266 6267 return new ParceledListSlice<ApplicationInfo>(list); 6268 } 6269 } 6270 6271 @Override 6272 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6273 if (DISABLE_EPHEMERAL_APPS) { 6274 return null; 6275 } 6276 6277 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6278 "getEphemeralApplications"); 6279 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6280 true /* requireFullPermission */, false /* checkShell */, 6281 "getEphemeralApplications"); 6282 synchronized (mPackages) { 6283 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6284 .getEphemeralApplicationsLPw(userId); 6285 if (ephemeralApps != null) { 6286 return new ParceledListSlice<>(ephemeralApps); 6287 } 6288 } 6289 return null; 6290 } 6291 6292 @Override 6293 public boolean isEphemeralApplication(String packageName, int userId) { 6294 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6295 true /* requireFullPermission */, false /* checkShell */, 6296 "isEphemeral"); 6297 if (DISABLE_EPHEMERAL_APPS) { 6298 return false; 6299 } 6300 6301 if (!isCallerSameApp(packageName)) { 6302 return false; 6303 } 6304 synchronized (mPackages) { 6305 PackageParser.Package pkg = mPackages.get(packageName); 6306 if (pkg != null) { 6307 return pkg.applicationInfo.isEphemeralApp(); 6308 } 6309 } 6310 return false; 6311 } 6312 6313 @Override 6314 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6315 if (DISABLE_EPHEMERAL_APPS) { 6316 return null; 6317 } 6318 6319 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6320 true /* requireFullPermission */, false /* checkShell */, 6321 "getCookie"); 6322 if (!isCallerSameApp(packageName)) { 6323 return null; 6324 } 6325 synchronized (mPackages) { 6326 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6327 packageName, userId); 6328 } 6329 } 6330 6331 @Override 6332 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6333 if (DISABLE_EPHEMERAL_APPS) { 6334 return true; 6335 } 6336 6337 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6338 true /* requireFullPermission */, true /* checkShell */, 6339 "setCookie"); 6340 if (!isCallerSameApp(packageName)) { 6341 return false; 6342 } 6343 synchronized (mPackages) { 6344 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6345 packageName, cookie, userId); 6346 } 6347 } 6348 6349 @Override 6350 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6351 if (DISABLE_EPHEMERAL_APPS) { 6352 return null; 6353 } 6354 6355 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6356 "getEphemeralApplicationIcon"); 6357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6358 true /* requireFullPermission */, false /* checkShell */, 6359 "getEphemeralApplicationIcon"); 6360 synchronized (mPackages) { 6361 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6362 packageName, userId); 6363 } 6364 } 6365 6366 private boolean isCallerSameApp(String packageName) { 6367 PackageParser.Package pkg = mPackages.get(packageName); 6368 return pkg != null 6369 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6370 } 6371 6372 @Override 6373 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6374 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6375 } 6376 6377 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6378 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6379 6380 // reader 6381 synchronized (mPackages) { 6382 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6383 final int userId = UserHandle.getCallingUserId(); 6384 while (i.hasNext()) { 6385 final PackageParser.Package p = i.next(); 6386 if (p.applicationInfo == null) continue; 6387 6388 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6389 && !p.applicationInfo.isDirectBootAware(); 6390 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6391 && p.applicationInfo.isDirectBootAware(); 6392 6393 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6394 && (!mSafeMode || isSystemApp(p)) 6395 && (matchesUnaware || matchesAware)) { 6396 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6397 if (ps != null) { 6398 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6399 ps.readUserState(userId), userId); 6400 if (ai != null) { 6401 finalList.add(ai); 6402 } 6403 } 6404 } 6405 } 6406 } 6407 6408 return finalList; 6409 } 6410 6411 @Override 6412 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6413 if (!sUserManager.exists(userId)) return null; 6414 flags = updateFlagsForComponent(flags, userId, name); 6415 // reader 6416 synchronized (mPackages) { 6417 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6418 PackageSetting ps = provider != null 6419 ? mSettings.mPackages.get(provider.owner.packageName) 6420 : null; 6421 return ps != null 6422 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6423 ? PackageParser.generateProviderInfo(provider, flags, 6424 ps.readUserState(userId), userId) 6425 : null; 6426 } 6427 } 6428 6429 /** 6430 * @deprecated 6431 */ 6432 @Deprecated 6433 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6434 // reader 6435 synchronized (mPackages) { 6436 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6437 .entrySet().iterator(); 6438 final int userId = UserHandle.getCallingUserId(); 6439 while (i.hasNext()) { 6440 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6441 PackageParser.Provider p = entry.getValue(); 6442 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6443 6444 if (ps != null && p.syncable 6445 && (!mSafeMode || (p.info.applicationInfo.flags 6446 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6447 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6448 ps.readUserState(userId), userId); 6449 if (info != null) { 6450 outNames.add(entry.getKey()); 6451 outInfo.add(info); 6452 } 6453 } 6454 } 6455 } 6456 } 6457 6458 @Override 6459 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6460 int uid, int flags) { 6461 final int userId = processName != null ? UserHandle.getUserId(uid) 6462 : UserHandle.getCallingUserId(); 6463 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6464 flags = updateFlagsForComponent(flags, userId, processName); 6465 6466 ArrayList<ProviderInfo> finalList = null; 6467 // reader 6468 synchronized (mPackages) { 6469 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6470 while (i.hasNext()) { 6471 final PackageParser.Provider p = i.next(); 6472 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6473 if (ps != null && p.info.authority != null 6474 && (processName == null 6475 || (p.info.processName.equals(processName) 6476 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6477 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6478 if (finalList == null) { 6479 finalList = new ArrayList<ProviderInfo>(3); 6480 } 6481 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6482 ps.readUserState(userId), userId); 6483 if (info != null) { 6484 finalList.add(info); 6485 } 6486 } 6487 } 6488 } 6489 6490 if (finalList != null) { 6491 Collections.sort(finalList, mProviderInitOrderSorter); 6492 return new ParceledListSlice<ProviderInfo>(finalList); 6493 } 6494 6495 return ParceledListSlice.emptyList(); 6496 } 6497 6498 @Override 6499 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6500 // reader 6501 synchronized (mPackages) { 6502 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6503 return PackageParser.generateInstrumentationInfo(i, flags); 6504 } 6505 } 6506 6507 @Override 6508 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6509 String targetPackage, int flags) { 6510 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6511 } 6512 6513 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6514 int flags) { 6515 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6516 6517 // reader 6518 synchronized (mPackages) { 6519 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6520 while (i.hasNext()) { 6521 final PackageParser.Instrumentation p = i.next(); 6522 if (targetPackage == null 6523 || targetPackage.equals(p.info.targetPackage)) { 6524 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6525 flags); 6526 if (ii != null) { 6527 finalList.add(ii); 6528 } 6529 } 6530 } 6531 } 6532 6533 return finalList; 6534 } 6535 6536 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6537 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6538 if (overlays == null) { 6539 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6540 return; 6541 } 6542 for (PackageParser.Package opkg : overlays.values()) { 6543 // Not much to do if idmap fails: we already logged the error 6544 // and we certainly don't want to abort installation of pkg simply 6545 // because an overlay didn't fit properly. For these reasons, 6546 // ignore the return value of createIdmapForPackagePairLI. 6547 createIdmapForPackagePairLI(pkg, opkg); 6548 } 6549 } 6550 6551 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6552 PackageParser.Package opkg) { 6553 if (!opkg.mTrustedOverlay) { 6554 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6555 opkg.baseCodePath + ": overlay not trusted"); 6556 return false; 6557 } 6558 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6559 if (overlaySet == null) { 6560 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6561 opkg.baseCodePath + " but target package has no known overlays"); 6562 return false; 6563 } 6564 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6565 // TODO: generate idmap for split APKs 6566 try { 6567 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6568 } catch (InstallerException e) { 6569 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6570 + opkg.baseCodePath); 6571 return false; 6572 } 6573 PackageParser.Package[] overlayArray = 6574 overlaySet.values().toArray(new PackageParser.Package[0]); 6575 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6576 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6577 return p1.mOverlayPriority - p2.mOverlayPriority; 6578 } 6579 }; 6580 Arrays.sort(overlayArray, cmp); 6581 6582 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6583 int i = 0; 6584 for (PackageParser.Package p : overlayArray) { 6585 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6586 } 6587 return true; 6588 } 6589 6590 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6592 try { 6593 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6594 } finally { 6595 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6596 } 6597 } 6598 6599 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6600 final File[] files = dir.listFiles(); 6601 if (ArrayUtils.isEmpty(files)) { 6602 Log.d(TAG, "No files in app dir " + dir); 6603 return; 6604 } 6605 6606 if (DEBUG_PACKAGE_SCANNING) { 6607 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6608 + " flags=0x" + Integer.toHexString(parseFlags)); 6609 } 6610 6611 for (File file : files) { 6612 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6613 && !PackageInstallerService.isStageName(file.getName()); 6614 if (!isPackage) { 6615 // Ignore entries which are not packages 6616 continue; 6617 } 6618 try { 6619 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6620 scanFlags, currentTime, null); 6621 } catch (PackageManagerException e) { 6622 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6623 6624 // Delete invalid userdata apps 6625 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6626 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6627 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6628 removeCodePathLI(file); 6629 } 6630 } 6631 } 6632 } 6633 6634 private static File getSettingsProblemFile() { 6635 File dataDir = Environment.getDataDirectory(); 6636 File systemDir = new File(dataDir, "system"); 6637 File fname = new File(systemDir, "uiderrors.txt"); 6638 return fname; 6639 } 6640 6641 static void reportSettingsProblem(int priority, String msg) { 6642 logCriticalInfo(priority, msg); 6643 } 6644 6645 static void logCriticalInfo(int priority, String msg) { 6646 Slog.println(priority, TAG, msg); 6647 EventLogTags.writePmCriticalInfo(msg); 6648 try { 6649 File fname = getSettingsProblemFile(); 6650 FileOutputStream out = new FileOutputStream(fname, true); 6651 PrintWriter pw = new FastPrintWriter(out); 6652 SimpleDateFormat formatter = new SimpleDateFormat(); 6653 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6654 pw.println(dateString + ": " + msg); 6655 pw.close(); 6656 FileUtils.setPermissions( 6657 fname.toString(), 6658 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6659 -1, -1); 6660 } catch (java.io.IOException e) { 6661 } 6662 } 6663 6664 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6665 final int policyFlags) throws PackageManagerException { 6666 if (ps != null 6667 && ps.codePath.equals(srcFile) 6668 && ps.timeStamp == srcFile.lastModified() 6669 && !isCompatSignatureUpdateNeeded(pkg) 6670 && !isRecoverSignatureUpdateNeeded(pkg)) { 6671 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6672 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6673 ArraySet<PublicKey> signingKs; 6674 synchronized (mPackages) { 6675 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6676 } 6677 if (ps.signatures.mSignatures != null 6678 && ps.signatures.mSignatures.length != 0 6679 && signingKs != null) { 6680 // Optimization: reuse the existing cached certificates 6681 // if the package appears to be unchanged. 6682 pkg.mSignatures = ps.signatures.mSignatures; 6683 pkg.mSigningKeys = signingKs; 6684 return; 6685 } 6686 6687 Slog.w(TAG, "PackageSetting for " + ps.name 6688 + " is missing signatures. Collecting certs again to recover them."); 6689 } else { 6690 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6691 } 6692 6693 try { 6694 PackageParser.collectCertificates(pkg, policyFlags); 6695 } catch (PackageParserException e) { 6696 throw PackageManagerException.from(e); 6697 } 6698 } 6699 6700 /** 6701 * Traces a package scan. 6702 * @see #scanPackageLI(File, int, int, long, UserHandle) 6703 */ 6704 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6705 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6707 try { 6708 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6709 } finally { 6710 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6711 } 6712 } 6713 6714 /** 6715 * Scans a package and returns the newly parsed package. 6716 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6717 */ 6718 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6719 long currentTime, UserHandle user) throws PackageManagerException { 6720 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6721 PackageParser pp = new PackageParser(); 6722 pp.setSeparateProcesses(mSeparateProcesses); 6723 pp.setOnlyCoreApps(mOnlyCore); 6724 pp.setDisplayMetrics(mMetrics); 6725 6726 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6727 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6728 } 6729 6730 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6731 final PackageParser.Package pkg; 6732 try { 6733 pkg = pp.parsePackage(scanFile, parseFlags); 6734 } catch (PackageParserException e) { 6735 throw PackageManagerException.from(e); 6736 } finally { 6737 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6738 } 6739 6740 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6741 } 6742 6743 /** 6744 * Scans a package and returns the newly parsed package. 6745 * @throws PackageManagerException on a parse error. 6746 */ 6747 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6748 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6749 throws PackageManagerException { 6750 // If the package has children and this is the first dive in the function 6751 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6752 // packages (parent and children) would be successfully scanned before the 6753 // actual scan since scanning mutates internal state and we want to atomically 6754 // install the package and its children. 6755 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6756 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6757 scanFlags |= SCAN_CHECK_ONLY; 6758 } 6759 } else { 6760 scanFlags &= ~SCAN_CHECK_ONLY; 6761 } 6762 6763 // Scan the parent 6764 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6765 scanFlags, currentTime, user); 6766 6767 // Scan the children 6768 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6769 for (int i = 0; i < childCount; i++) { 6770 PackageParser.Package childPackage = pkg.childPackages.get(i); 6771 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6772 currentTime, user); 6773 } 6774 6775 6776 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6777 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6778 } 6779 6780 return scannedPkg; 6781 } 6782 6783 /** 6784 * Scans a package and returns the newly parsed package. 6785 * @throws PackageManagerException on a parse error. 6786 */ 6787 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6788 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6789 throws PackageManagerException { 6790 PackageSetting ps = null; 6791 PackageSetting updatedPkg; 6792 // reader 6793 synchronized (mPackages) { 6794 // Look to see if we already know about this package. 6795 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6796 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6797 // This package has been renamed to its original name. Let's 6798 // use that. 6799 ps = mSettings.peekPackageLPr(oldName); 6800 } 6801 // If there was no original package, see one for the real package name. 6802 if (ps == null) { 6803 ps = mSettings.peekPackageLPr(pkg.packageName); 6804 } 6805 // Check to see if this package could be hiding/updating a system 6806 // package. Must look for it either under the original or real 6807 // package name depending on our state. 6808 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6809 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6810 6811 // If this is a package we don't know about on the system partition, we 6812 // may need to remove disabled child packages on the system partition 6813 // or may need to not add child packages if the parent apk is updated 6814 // on the data partition and no longer defines this child package. 6815 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6816 // If this is a parent package for an updated system app and this system 6817 // app got an OTA update which no longer defines some of the child packages 6818 // we have to prune them from the disabled system packages. 6819 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6820 if (disabledPs != null) { 6821 final int scannedChildCount = (pkg.childPackages != null) 6822 ? pkg.childPackages.size() : 0; 6823 final int disabledChildCount = disabledPs.childPackageNames != null 6824 ? disabledPs.childPackageNames.size() : 0; 6825 for (int i = 0; i < disabledChildCount; i++) { 6826 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6827 boolean disabledPackageAvailable = false; 6828 for (int j = 0; j < scannedChildCount; j++) { 6829 PackageParser.Package childPkg = pkg.childPackages.get(j); 6830 if (childPkg.packageName.equals(disabledChildPackageName)) { 6831 disabledPackageAvailable = true; 6832 break; 6833 } 6834 } 6835 if (!disabledPackageAvailable) { 6836 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6837 } 6838 } 6839 } 6840 } 6841 } 6842 6843 boolean updatedPkgBetter = false; 6844 // First check if this is a system package that may involve an update 6845 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6846 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6847 // it needs to drop FLAG_PRIVILEGED. 6848 if (locationIsPrivileged(scanFile)) { 6849 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6850 } else { 6851 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6852 } 6853 6854 if (ps != null && !ps.codePath.equals(scanFile)) { 6855 // The path has changed from what was last scanned... check the 6856 // version of the new path against what we have stored to determine 6857 // what to do. 6858 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6859 if (pkg.mVersionCode <= ps.versionCode) { 6860 // The system package has been updated and the code path does not match 6861 // Ignore entry. Skip it. 6862 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6863 + " ignored: updated version " + ps.versionCode 6864 + " better than this " + pkg.mVersionCode); 6865 if (!updatedPkg.codePath.equals(scanFile)) { 6866 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6867 + ps.name + " changing from " + updatedPkg.codePathString 6868 + " to " + scanFile); 6869 updatedPkg.codePath = scanFile; 6870 updatedPkg.codePathString = scanFile.toString(); 6871 updatedPkg.resourcePath = scanFile; 6872 updatedPkg.resourcePathString = scanFile.toString(); 6873 } 6874 updatedPkg.pkg = pkg; 6875 updatedPkg.versionCode = pkg.mVersionCode; 6876 6877 // Update the disabled system child packages to point to the package too. 6878 final int childCount = updatedPkg.childPackageNames != null 6879 ? updatedPkg.childPackageNames.size() : 0; 6880 for (int i = 0; i < childCount; i++) { 6881 String childPackageName = updatedPkg.childPackageNames.get(i); 6882 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6883 childPackageName); 6884 if (updatedChildPkg != null) { 6885 updatedChildPkg.pkg = pkg; 6886 updatedChildPkg.versionCode = pkg.mVersionCode; 6887 } 6888 } 6889 6890 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6891 + scanFile + " ignored: updated version " + ps.versionCode 6892 + " better than this " + pkg.mVersionCode); 6893 } else { 6894 // The current app on the system partition is better than 6895 // what we have updated to on the data partition; switch 6896 // back to the system partition version. 6897 // At this point, its safely assumed that package installation for 6898 // apps in system partition will go through. If not there won't be a working 6899 // version of the app 6900 // writer 6901 synchronized (mPackages) { 6902 // Just remove the loaded entries from package lists. 6903 mPackages.remove(ps.name); 6904 } 6905 6906 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6907 + " reverting from " + ps.codePathString 6908 + ": new version " + pkg.mVersionCode 6909 + " better than installed " + ps.versionCode); 6910 6911 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6912 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6913 synchronized (mInstallLock) { 6914 args.cleanUpResourcesLI(); 6915 } 6916 synchronized (mPackages) { 6917 mSettings.enableSystemPackageLPw(ps.name); 6918 } 6919 updatedPkgBetter = true; 6920 } 6921 } 6922 } 6923 6924 if (updatedPkg != null) { 6925 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6926 // initially 6927 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6928 6929 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6930 // flag set initially 6931 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6932 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6933 } 6934 } 6935 6936 // Verify certificates against what was last scanned 6937 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6938 6939 /* 6940 * A new system app appeared, but we already had a non-system one of the 6941 * same name installed earlier. 6942 */ 6943 boolean shouldHideSystemApp = false; 6944 if (updatedPkg == null && ps != null 6945 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6946 /* 6947 * Check to make sure the signatures match first. If they don't, 6948 * wipe the installed application and its data. 6949 */ 6950 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6951 != PackageManager.SIGNATURE_MATCH) { 6952 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6953 + " signatures don't match existing userdata copy; removing"); 6954 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6955 "scanPackageInternalLI")) { 6956 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6957 } 6958 ps = null; 6959 } else { 6960 /* 6961 * If the newly-added system app is an older version than the 6962 * already installed version, hide it. It will be scanned later 6963 * and re-added like an update. 6964 */ 6965 if (pkg.mVersionCode <= ps.versionCode) { 6966 shouldHideSystemApp = true; 6967 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6968 + " but new version " + pkg.mVersionCode + " better than installed " 6969 + ps.versionCode + "; hiding system"); 6970 } else { 6971 /* 6972 * The newly found system app is a newer version that the 6973 * one previously installed. Simply remove the 6974 * already-installed application and replace it with our own 6975 * while keeping the application data. 6976 */ 6977 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6978 + " reverting from " + ps.codePathString + ": new version " 6979 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6980 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6981 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6982 synchronized (mInstallLock) { 6983 args.cleanUpResourcesLI(); 6984 } 6985 } 6986 } 6987 } 6988 6989 // The apk is forward locked (not public) if its code and resources 6990 // are kept in different files. (except for app in either system or 6991 // vendor path). 6992 // TODO grab this value from PackageSettings 6993 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6994 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6995 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6996 } 6997 } 6998 6999 // TODO: extend to support forward-locked splits 7000 String resourcePath = null; 7001 String baseResourcePath = null; 7002 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7003 if (ps != null && ps.resourcePathString != null) { 7004 resourcePath = ps.resourcePathString; 7005 baseResourcePath = ps.resourcePathString; 7006 } else { 7007 // Should not happen at all. Just log an error. 7008 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7009 } 7010 } else { 7011 resourcePath = pkg.codePath; 7012 baseResourcePath = pkg.baseCodePath; 7013 } 7014 7015 // Set application objects path explicitly. 7016 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7017 pkg.setApplicationInfoCodePath(pkg.codePath); 7018 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7019 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7020 pkg.setApplicationInfoResourcePath(resourcePath); 7021 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7022 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7023 7024 // Note that we invoke the following method only if we are about to unpack an application 7025 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7026 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7027 7028 /* 7029 * If the system app should be overridden by a previously installed 7030 * data, hide the system app now and let the /data/app scan pick it up 7031 * again. 7032 */ 7033 if (shouldHideSystemApp) { 7034 synchronized (mPackages) { 7035 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7036 } 7037 } 7038 7039 return scannedPkg; 7040 } 7041 7042 private static String fixProcessName(String defProcessName, 7043 String processName, int uid) { 7044 if (processName == null) { 7045 return defProcessName; 7046 } 7047 return processName; 7048 } 7049 7050 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7051 throws PackageManagerException { 7052 if (pkgSetting.signatures.mSignatures != null) { 7053 // Already existing package. Make sure signatures match 7054 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7055 == PackageManager.SIGNATURE_MATCH; 7056 if (!match) { 7057 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7058 == PackageManager.SIGNATURE_MATCH; 7059 } 7060 if (!match) { 7061 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7062 == PackageManager.SIGNATURE_MATCH; 7063 } 7064 if (!match) { 7065 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7066 + pkg.packageName + " signatures do not match the " 7067 + "previously installed version; ignoring!"); 7068 } 7069 } 7070 7071 // Check for shared user signatures 7072 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7073 // Already existing package. Make sure signatures match 7074 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7075 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7076 if (!match) { 7077 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7078 == PackageManager.SIGNATURE_MATCH; 7079 } 7080 if (!match) { 7081 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7082 == PackageManager.SIGNATURE_MATCH; 7083 } 7084 if (!match) { 7085 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7086 "Package " + pkg.packageName 7087 + " has no signatures that match those in shared user " 7088 + pkgSetting.sharedUser.name + "; ignoring!"); 7089 } 7090 } 7091 } 7092 7093 /** 7094 * Enforces that only the system UID or root's UID can call a method exposed 7095 * via Binder. 7096 * 7097 * @param message used as message if SecurityException is thrown 7098 * @throws SecurityException if the caller is not system or root 7099 */ 7100 private static final void enforceSystemOrRoot(String message) { 7101 final int uid = Binder.getCallingUid(); 7102 if (uid != Process.SYSTEM_UID && uid != 0) { 7103 throw new SecurityException(message); 7104 } 7105 } 7106 7107 @Override 7108 public void performFstrimIfNeeded() { 7109 enforceSystemOrRoot("Only the system can request fstrim"); 7110 7111 // Before everything else, see whether we need to fstrim. 7112 try { 7113 IMountService ms = PackageHelper.getMountService(); 7114 if (ms != null) { 7115 final boolean isUpgrade = isUpgrade(); 7116 boolean doTrim = isUpgrade; 7117 if (doTrim) { 7118 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7119 } else { 7120 final long interval = android.provider.Settings.Global.getLong( 7121 mContext.getContentResolver(), 7122 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7123 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7124 if (interval > 0) { 7125 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7126 if (timeSinceLast > interval) { 7127 doTrim = true; 7128 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7129 + "; running immediately"); 7130 } 7131 } 7132 } 7133 if (doTrim) { 7134 if (!isFirstBoot()) { 7135 try { 7136 ActivityManagerNative.getDefault().showBootMessage( 7137 mContext.getResources().getString( 7138 R.string.android_upgrading_fstrim), true); 7139 } catch (RemoteException e) { 7140 } 7141 } 7142 ms.runMaintenance(); 7143 } 7144 } else { 7145 Slog.e(TAG, "Mount service unavailable!"); 7146 } 7147 } catch (RemoteException e) { 7148 // Can't happen; MountService is local 7149 } 7150 } 7151 7152 @Override 7153 public void updatePackagesIfNeeded() { 7154 enforceSystemOrRoot("Only the system can request package update"); 7155 7156 // We need to re-extract after an OTA. 7157 boolean causeUpgrade = isUpgrade(); 7158 7159 // First boot or factory reset. 7160 // Note: we also handle devices that are upgrading to N right now as if it is their 7161 // first boot, as they do not have profile data. 7162 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7163 7164 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7165 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7166 7167 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7168 return; 7169 } 7170 7171 List<PackageParser.Package> pkgs; 7172 synchronized (mPackages) { 7173 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7174 } 7175 7176 int numberOfPackagesVisited = 0; 7177 int numberOfPackagesOptimized = 0; 7178 int numberOfPackagesSkipped = 0; 7179 int numberOfPackagesFailed = 0; 7180 final int numberOfPackagesToDexopt = pkgs.size(); 7181 final long startTime = System.nanoTime(); 7182 7183 for (PackageParser.Package pkg : pkgs) { 7184 numberOfPackagesVisited++; 7185 7186 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7187 if (DEBUG_DEXOPT) { 7188 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7189 } 7190 numberOfPackagesSkipped++; 7191 continue; 7192 } 7193 7194 if (DEBUG_DEXOPT) { 7195 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7196 numberOfPackagesToDexopt + ": " + pkg.packageName); 7197 } 7198 7199 if (mIsPreNUpgrade) { 7200 try { 7201 ActivityManagerNative.getDefault().showBootMessage( 7202 mContext.getResources().getString(R.string.android_upgrading_apk, 7203 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7204 } catch (RemoteException e) { 7205 } 7206 } 7207 7208 // checkProfiles is false to avoid merging profiles during boot which 7209 // might interfere with background compilation (b/28612421). 7210 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7211 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7212 // trade-off worth doing to save boot time work. 7213 int dexOptStatus = performDexOptTraced(pkg.packageName, 7214 null /* instructionSet */, 7215 false /* checkProfiles */, 7216 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7217 false /* force */); 7218 switch (dexOptStatus) { 7219 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7220 numberOfPackagesOptimized++; 7221 break; 7222 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7223 numberOfPackagesSkipped++; 7224 break; 7225 case PackageDexOptimizer.DEX_OPT_FAILED: 7226 numberOfPackagesFailed++; 7227 break; 7228 default: 7229 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7230 break; 7231 } 7232 } 7233 7234 final int elapsedTimeSeconds = 7235 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7236 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7237 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7238 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7239 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7240 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7241 } 7242 7243 @Override 7244 public void notifyPackageUse(String packageName, int reason) { 7245 synchronized (mPackages) { 7246 PackageParser.Package p = mPackages.get(packageName); 7247 if (p == null) { 7248 return; 7249 } 7250 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7251 } 7252 } 7253 7254 // TODO: this is not used nor needed. Delete it. 7255 @Override 7256 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7257 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7258 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7259 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7260 } 7261 7262 @Override 7263 public boolean performDexOpt(String packageName, String instructionSet, 7264 boolean checkProfiles, int compileReason, boolean force) { 7265 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7266 getCompilerFilterForReason(compileReason), force); 7267 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7268 } 7269 7270 @Override 7271 public boolean performDexOptMode(String packageName, String instructionSet, 7272 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7273 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7274 targetCompilerFilter, force); 7275 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7276 } 7277 7278 private int performDexOptTraced(String packageName, String instructionSet, 7279 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7281 try { 7282 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7283 targetCompilerFilter, force); 7284 } finally { 7285 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7286 } 7287 } 7288 7289 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7290 // if the package can now be considered up to date for the given filter. 7291 private int performDexOptInternal(String packageName, String instructionSet, 7292 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7293 PackageParser.Package p; 7294 final String targetInstructionSet; 7295 synchronized (mPackages) { 7296 p = mPackages.get(packageName); 7297 if (p == null) { 7298 // Package could not be found. Report failure. 7299 return PackageDexOptimizer.DEX_OPT_FAILED; 7300 } 7301 mPackageUsage.write(false); 7302 7303 targetInstructionSet = instructionSet != null ? instructionSet : 7304 getPrimaryInstructionSet(p.applicationInfo); 7305 } 7306 long callingId = Binder.clearCallingIdentity(); 7307 try { 7308 synchronized (mInstallLock) { 7309 final String[] instructionSets = new String[] { targetInstructionSet }; 7310 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7311 targetCompilerFilter, force); 7312 } 7313 } finally { 7314 Binder.restoreCallingIdentity(callingId); 7315 } 7316 } 7317 7318 public ArraySet<String> getOptimizablePackages() { 7319 ArraySet<String> pkgs = new ArraySet<String>(); 7320 synchronized (mPackages) { 7321 for (PackageParser.Package p : mPackages.values()) { 7322 if (PackageDexOptimizer.canOptimizePackage(p)) { 7323 pkgs.add(p.packageName); 7324 } 7325 } 7326 } 7327 return pkgs; 7328 } 7329 7330 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7331 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7332 boolean force) { 7333 // Select the dex optimizer based on the force parameter. 7334 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7335 // allocate an object here. 7336 PackageDexOptimizer pdo = force 7337 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7338 : mPackageDexOptimizer; 7339 7340 // Optimize all dependencies first. Note: we ignore the return value and march on 7341 // on errors. 7342 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7343 if (!deps.isEmpty()) { 7344 for (PackageParser.Package depPackage : deps) { 7345 // TODO: Analyze and investigate if we (should) profile libraries. 7346 // Currently this will do a full compilation of the library by default. 7347 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7348 false /* checkProfiles */, 7349 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7350 } 7351 } 7352 7353 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7354 targetCompilerFilter); 7355 } 7356 7357 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7358 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7359 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7360 Set<String> collectedNames = new HashSet<>(); 7361 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7362 7363 retValue.remove(p); 7364 7365 return retValue; 7366 } else { 7367 return Collections.emptyList(); 7368 } 7369 } 7370 7371 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7372 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7373 if (!collectedNames.contains(p.packageName)) { 7374 collectedNames.add(p.packageName); 7375 collected.add(p); 7376 7377 if (p.usesLibraries != null) { 7378 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7379 } 7380 if (p.usesOptionalLibraries != null) { 7381 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7382 collectedNames); 7383 } 7384 } 7385 } 7386 7387 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7388 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7389 for (String libName : libs) { 7390 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7391 if (libPkg != null) { 7392 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7393 } 7394 } 7395 } 7396 7397 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7398 synchronized (mPackages) { 7399 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7400 if (lib != null && lib.apk != null) { 7401 return mPackages.get(lib.apk); 7402 } 7403 } 7404 return null; 7405 } 7406 7407 public void shutdown() { 7408 mPackageUsage.write(true); 7409 } 7410 7411 @Override 7412 public void forceDexOpt(String packageName) { 7413 enforceSystemOrRoot("forceDexOpt"); 7414 7415 PackageParser.Package pkg; 7416 synchronized (mPackages) { 7417 pkg = mPackages.get(packageName); 7418 if (pkg == null) { 7419 throw new IllegalArgumentException("Unknown package: " + packageName); 7420 } 7421 } 7422 7423 synchronized (mInstallLock) { 7424 final String[] instructionSets = new String[] { 7425 getPrimaryInstructionSet(pkg.applicationInfo) }; 7426 7427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7428 7429 // Whoever is calling forceDexOpt wants a fully compiled package. 7430 // Don't use profiles since that may cause compilation to be skipped. 7431 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7432 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7433 true /* force */); 7434 7435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7436 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7437 throw new IllegalStateException("Failed to dexopt: " + res); 7438 } 7439 } 7440 } 7441 7442 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7443 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7444 Slog.w(TAG, "Unable to update from " + oldPkg.name 7445 + " to " + newPkg.packageName 7446 + ": old package not in system partition"); 7447 return false; 7448 } else if (mPackages.get(oldPkg.name) != null) { 7449 Slog.w(TAG, "Unable to update from " + oldPkg.name 7450 + " to " + newPkg.packageName 7451 + ": old package still exists"); 7452 return false; 7453 } 7454 return true; 7455 } 7456 7457 void removeCodePathLI(File codePath) { 7458 if (codePath.isDirectory()) { 7459 try { 7460 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7461 } catch (InstallerException e) { 7462 Slog.w(TAG, "Failed to remove code path", e); 7463 } 7464 } else { 7465 codePath.delete(); 7466 } 7467 } 7468 7469 private int[] resolveUserIds(int userId) { 7470 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7471 } 7472 7473 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7474 if (pkg == null) { 7475 Slog.wtf(TAG, "Package was null!", new Throwable()); 7476 return; 7477 } 7478 clearAppDataLeafLIF(pkg, userId, flags); 7479 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7480 for (int i = 0; i < childCount; i++) { 7481 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7482 } 7483 } 7484 7485 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7486 final PackageSetting ps; 7487 synchronized (mPackages) { 7488 ps = mSettings.mPackages.get(pkg.packageName); 7489 } 7490 for (int realUserId : resolveUserIds(userId)) { 7491 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7492 try { 7493 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7494 ceDataInode); 7495 } catch (InstallerException e) { 7496 Slog.w(TAG, String.valueOf(e)); 7497 } 7498 } 7499 } 7500 7501 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7502 if (pkg == null) { 7503 Slog.wtf(TAG, "Package was null!", new Throwable()); 7504 return; 7505 } 7506 destroyAppDataLeafLIF(pkg, userId, flags); 7507 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7508 for (int i = 0; i < childCount; i++) { 7509 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7510 } 7511 } 7512 7513 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7514 final PackageSetting ps; 7515 synchronized (mPackages) { 7516 ps = mSettings.mPackages.get(pkg.packageName); 7517 } 7518 for (int realUserId : resolveUserIds(userId)) { 7519 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7520 try { 7521 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7522 ceDataInode); 7523 } catch (InstallerException e) { 7524 Slog.w(TAG, String.valueOf(e)); 7525 } 7526 } 7527 } 7528 7529 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7530 if (pkg == null) { 7531 Slog.wtf(TAG, "Package was null!", new Throwable()); 7532 return; 7533 } 7534 destroyAppProfilesLeafLIF(pkg); 7535 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7536 for (int i = 0; i < childCount; i++) { 7537 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7538 } 7539 } 7540 7541 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7542 try { 7543 mInstaller.destroyAppProfiles(pkg.packageName); 7544 } catch (InstallerException e) { 7545 Slog.w(TAG, String.valueOf(e)); 7546 } 7547 } 7548 7549 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7550 if (pkg == null) { 7551 Slog.wtf(TAG, "Package was null!", new Throwable()); 7552 return; 7553 } 7554 clearAppProfilesLeafLIF(pkg); 7555 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7556 for (int i = 0; i < childCount; i++) { 7557 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7558 } 7559 } 7560 7561 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7562 try { 7563 mInstaller.clearAppProfiles(pkg.packageName); 7564 } catch (InstallerException e) { 7565 Slog.w(TAG, String.valueOf(e)); 7566 } 7567 } 7568 7569 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7570 long lastUpdateTime) { 7571 // Set parent install/update time 7572 PackageSetting ps = (PackageSetting) pkg.mExtras; 7573 if (ps != null) { 7574 ps.firstInstallTime = firstInstallTime; 7575 ps.lastUpdateTime = lastUpdateTime; 7576 } 7577 // Set children install/update time 7578 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7579 for (int i = 0; i < childCount; i++) { 7580 PackageParser.Package childPkg = pkg.childPackages.get(i); 7581 ps = (PackageSetting) childPkg.mExtras; 7582 if (ps != null) { 7583 ps.firstInstallTime = firstInstallTime; 7584 ps.lastUpdateTime = lastUpdateTime; 7585 } 7586 } 7587 } 7588 7589 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7590 PackageParser.Package changingLib) { 7591 if (file.path != null) { 7592 usesLibraryFiles.add(file.path); 7593 return; 7594 } 7595 PackageParser.Package p = mPackages.get(file.apk); 7596 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7597 // If we are doing this while in the middle of updating a library apk, 7598 // then we need to make sure to use that new apk for determining the 7599 // dependencies here. (We haven't yet finished committing the new apk 7600 // to the package manager state.) 7601 if (p == null || p.packageName.equals(changingLib.packageName)) { 7602 p = changingLib; 7603 } 7604 } 7605 if (p != null) { 7606 usesLibraryFiles.addAll(p.getAllCodePaths()); 7607 } 7608 } 7609 7610 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7611 PackageParser.Package changingLib) throws PackageManagerException { 7612 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7613 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7614 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7615 for (int i=0; i<N; i++) { 7616 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7617 if (file == null) { 7618 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7619 "Package " + pkg.packageName + " requires unavailable shared library " 7620 + pkg.usesLibraries.get(i) + "; failing!"); 7621 } 7622 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7623 } 7624 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7625 for (int i=0; i<N; i++) { 7626 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7627 if (file == null) { 7628 Slog.w(TAG, "Package " + pkg.packageName 7629 + " desires unavailable shared library " 7630 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7631 } else { 7632 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7633 } 7634 } 7635 N = usesLibraryFiles.size(); 7636 if (N > 0) { 7637 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7638 } else { 7639 pkg.usesLibraryFiles = null; 7640 } 7641 } 7642 } 7643 7644 private static boolean hasString(List<String> list, List<String> which) { 7645 if (list == null) { 7646 return false; 7647 } 7648 for (int i=list.size()-1; i>=0; i--) { 7649 for (int j=which.size()-1; j>=0; j--) { 7650 if (which.get(j).equals(list.get(i))) { 7651 return true; 7652 } 7653 } 7654 } 7655 return false; 7656 } 7657 7658 private void updateAllSharedLibrariesLPw() { 7659 for (PackageParser.Package pkg : mPackages.values()) { 7660 try { 7661 updateSharedLibrariesLPw(pkg, null); 7662 } catch (PackageManagerException e) { 7663 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7664 } 7665 } 7666 } 7667 7668 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7669 PackageParser.Package changingPkg) { 7670 ArrayList<PackageParser.Package> res = null; 7671 for (PackageParser.Package pkg : mPackages.values()) { 7672 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7673 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7674 if (res == null) { 7675 res = new ArrayList<PackageParser.Package>(); 7676 } 7677 res.add(pkg); 7678 try { 7679 updateSharedLibrariesLPw(pkg, changingPkg); 7680 } catch (PackageManagerException e) { 7681 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7682 } 7683 } 7684 } 7685 return res; 7686 } 7687 7688 /** 7689 * Derive the value of the {@code cpuAbiOverride} based on the provided 7690 * value and an optional stored value from the package settings. 7691 */ 7692 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7693 String cpuAbiOverride = null; 7694 7695 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7696 cpuAbiOverride = null; 7697 } else if (abiOverride != null) { 7698 cpuAbiOverride = abiOverride; 7699 } else if (settings != null) { 7700 cpuAbiOverride = settings.cpuAbiOverrideString; 7701 } 7702 7703 return cpuAbiOverride; 7704 } 7705 7706 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7707 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7708 throws PackageManagerException { 7709 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7710 // If the package has children and this is the first dive in the function 7711 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7712 // whether all packages (parent and children) would be successfully scanned 7713 // before the actual scan since scanning mutates internal state and we want 7714 // to atomically install the package and its children. 7715 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7716 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7717 scanFlags |= SCAN_CHECK_ONLY; 7718 } 7719 } else { 7720 scanFlags &= ~SCAN_CHECK_ONLY; 7721 } 7722 7723 final PackageParser.Package scannedPkg; 7724 try { 7725 // Scan the parent 7726 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7727 // Scan the children 7728 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7729 for (int i = 0; i < childCount; i++) { 7730 PackageParser.Package childPkg = pkg.childPackages.get(i); 7731 scanPackageLI(childPkg, policyFlags, 7732 scanFlags, currentTime, user); 7733 } 7734 } finally { 7735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7736 } 7737 7738 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7739 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7740 } 7741 7742 return scannedPkg; 7743 } 7744 7745 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7746 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7747 boolean success = false; 7748 try { 7749 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7750 currentTime, user); 7751 success = true; 7752 return res; 7753 } finally { 7754 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7755 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7756 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7757 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7758 destroyAppProfilesLIF(pkg); 7759 } 7760 } 7761 } 7762 7763 /** 7764 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7765 */ 7766 private static boolean apkHasCode(String fileName) { 7767 StrictJarFile jarFile = null; 7768 try { 7769 jarFile = new StrictJarFile(fileName, 7770 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7771 return jarFile.findEntry("classes.dex") != null; 7772 } catch (IOException ignore) { 7773 } finally { 7774 try { 7775 jarFile.close(); 7776 } catch (IOException ignore) {} 7777 } 7778 return false; 7779 } 7780 7781 /** 7782 * Enforces code policy for the package. This ensures that if an APK has 7783 * declared hasCode="true" in its manifest that the APK actually contains 7784 * code. 7785 * 7786 * @throws PackageManagerException If bytecode could not be found when it should exist 7787 */ 7788 private static void enforceCodePolicy(PackageParser.Package pkg) 7789 throws PackageManagerException { 7790 final boolean shouldHaveCode = 7791 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7792 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7793 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7794 "Package " + pkg.baseCodePath + " code is missing"); 7795 } 7796 7797 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7798 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7799 final boolean splitShouldHaveCode = 7800 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7801 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7802 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7803 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7804 } 7805 } 7806 } 7807 } 7808 7809 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7810 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7811 throws PackageManagerException { 7812 final File scanFile = new File(pkg.codePath); 7813 if (pkg.applicationInfo.getCodePath() == null || 7814 pkg.applicationInfo.getResourcePath() == null) { 7815 // Bail out. The resource and code paths haven't been set. 7816 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7817 "Code and resource paths haven't been set correctly"); 7818 } 7819 7820 // Apply policy 7821 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7822 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7823 if (pkg.applicationInfo.isDirectBootAware()) { 7824 // we're direct boot aware; set for all components 7825 for (PackageParser.Service s : pkg.services) { 7826 s.info.encryptionAware = s.info.directBootAware = true; 7827 } 7828 for (PackageParser.Provider p : pkg.providers) { 7829 p.info.encryptionAware = p.info.directBootAware = true; 7830 } 7831 for (PackageParser.Activity a : pkg.activities) { 7832 a.info.encryptionAware = a.info.directBootAware = true; 7833 } 7834 for (PackageParser.Activity r : pkg.receivers) { 7835 r.info.encryptionAware = r.info.directBootAware = true; 7836 } 7837 } 7838 } else { 7839 // Only allow system apps to be flagged as core apps. 7840 pkg.coreApp = false; 7841 // clear flags not applicable to regular apps 7842 pkg.applicationInfo.privateFlags &= 7843 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7844 pkg.applicationInfo.privateFlags &= 7845 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7846 } 7847 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7848 7849 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7850 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7851 } 7852 7853 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7854 enforceCodePolicy(pkg); 7855 } 7856 7857 if (mCustomResolverComponentName != null && 7858 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7859 setUpCustomResolverActivity(pkg); 7860 } 7861 7862 if (pkg.packageName.equals("android")) { 7863 synchronized (mPackages) { 7864 if (mAndroidApplication != null) { 7865 Slog.w(TAG, "*************************************************"); 7866 Slog.w(TAG, "Core android package being redefined. Skipping."); 7867 Slog.w(TAG, " file=" + scanFile); 7868 Slog.w(TAG, "*************************************************"); 7869 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7870 "Core android package being redefined. Skipping."); 7871 } 7872 7873 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7874 // Set up information for our fall-back user intent resolution activity. 7875 mPlatformPackage = pkg; 7876 pkg.mVersionCode = mSdkVersion; 7877 mAndroidApplication = pkg.applicationInfo; 7878 7879 if (!mResolverReplaced) { 7880 mResolveActivity.applicationInfo = mAndroidApplication; 7881 mResolveActivity.name = ResolverActivity.class.getName(); 7882 mResolveActivity.packageName = mAndroidApplication.packageName; 7883 mResolveActivity.processName = "system:ui"; 7884 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7885 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7886 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7887 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7888 mResolveActivity.exported = true; 7889 mResolveActivity.enabled = true; 7890 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7891 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7892 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7893 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7894 | ActivityInfo.CONFIG_ORIENTATION 7895 | ActivityInfo.CONFIG_KEYBOARD 7896 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7897 mResolveInfo.activityInfo = mResolveActivity; 7898 mResolveInfo.priority = 0; 7899 mResolveInfo.preferredOrder = 0; 7900 mResolveInfo.match = 0; 7901 mResolveComponentName = new ComponentName( 7902 mAndroidApplication.packageName, mResolveActivity.name); 7903 } 7904 } 7905 } 7906 } 7907 7908 if (DEBUG_PACKAGE_SCANNING) { 7909 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7910 Log.d(TAG, "Scanning package " + pkg.packageName); 7911 } 7912 7913 synchronized (mPackages) { 7914 if (mPackages.containsKey(pkg.packageName) 7915 || mSharedLibraries.containsKey(pkg.packageName)) { 7916 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7917 "Application package " + pkg.packageName 7918 + " already installed. Skipping duplicate."); 7919 } 7920 7921 // If we're only installing presumed-existing packages, require that the 7922 // scanned APK is both already known and at the path previously established 7923 // for it. Previously unknown packages we pick up normally, but if we have an 7924 // a priori expectation about this package's install presence, enforce it. 7925 // With a singular exception for new system packages. When an OTA contains 7926 // a new system package, we allow the codepath to change from a system location 7927 // to the user-installed location. If we don't allow this change, any newer, 7928 // user-installed version of the application will be ignored. 7929 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7930 if (mExpectingBetter.containsKey(pkg.packageName)) { 7931 logCriticalInfo(Log.WARN, 7932 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7933 } else { 7934 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7935 if (known != null) { 7936 if (DEBUG_PACKAGE_SCANNING) { 7937 Log.d(TAG, "Examining " + pkg.codePath 7938 + " and requiring known paths " + known.codePathString 7939 + " & " + known.resourcePathString); 7940 } 7941 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7942 || !pkg.applicationInfo.getResourcePath().equals( 7943 known.resourcePathString)) { 7944 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7945 "Application package " + pkg.packageName 7946 + " found at " + pkg.applicationInfo.getCodePath() 7947 + " but expected at " + known.codePathString 7948 + "; ignoring."); 7949 } 7950 } 7951 } 7952 } 7953 } 7954 7955 // Initialize package source and resource directories 7956 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7957 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7958 7959 SharedUserSetting suid = null; 7960 PackageSetting pkgSetting = null; 7961 7962 if (!isSystemApp(pkg)) { 7963 // Only system apps can use these features. 7964 pkg.mOriginalPackages = null; 7965 pkg.mRealPackage = null; 7966 pkg.mAdoptPermissions = null; 7967 } 7968 7969 // Getting the package setting may have a side-effect, so if we 7970 // are only checking if scan would succeed, stash a copy of the 7971 // old setting to restore at the end. 7972 PackageSetting nonMutatedPs = null; 7973 7974 // writer 7975 synchronized (mPackages) { 7976 if (pkg.mSharedUserId != null) { 7977 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7978 if (suid == null) { 7979 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7980 "Creating application package " + pkg.packageName 7981 + " for shared user failed"); 7982 } 7983 if (DEBUG_PACKAGE_SCANNING) { 7984 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7985 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7986 + "): packages=" + suid.packages); 7987 } 7988 } 7989 7990 // Check if we are renaming from an original package name. 7991 PackageSetting origPackage = null; 7992 String realName = null; 7993 if (pkg.mOriginalPackages != null) { 7994 // This package may need to be renamed to a previously 7995 // installed name. Let's check on that... 7996 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7997 if (pkg.mOriginalPackages.contains(renamed)) { 7998 // This package had originally been installed as the 7999 // original name, and we have already taken care of 8000 // transitioning to the new one. Just update the new 8001 // one to continue using the old name. 8002 realName = pkg.mRealPackage; 8003 if (!pkg.packageName.equals(renamed)) { 8004 // Callers into this function may have already taken 8005 // care of renaming the package; only do it here if 8006 // it is not already done. 8007 pkg.setPackageName(renamed); 8008 } 8009 8010 } else { 8011 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8012 if ((origPackage = mSettings.peekPackageLPr( 8013 pkg.mOriginalPackages.get(i))) != null) { 8014 // We do have the package already installed under its 8015 // original name... should we use it? 8016 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8017 // New package is not compatible with original. 8018 origPackage = null; 8019 continue; 8020 } else if (origPackage.sharedUser != null) { 8021 // Make sure uid is compatible between packages. 8022 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8023 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8024 + " to " + pkg.packageName + ": old uid " 8025 + origPackage.sharedUser.name 8026 + " differs from " + pkg.mSharedUserId); 8027 origPackage = null; 8028 continue; 8029 } 8030 // TODO: Add case when shared user id is added [b/28144775] 8031 } else { 8032 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8033 + pkg.packageName + " to old name " + origPackage.name); 8034 } 8035 break; 8036 } 8037 } 8038 } 8039 } 8040 8041 if (mTransferedPackages.contains(pkg.packageName)) { 8042 Slog.w(TAG, "Package " + pkg.packageName 8043 + " was transferred to another, but its .apk remains"); 8044 } 8045 8046 // See comments in nonMutatedPs declaration 8047 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8048 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8049 if (foundPs != null) { 8050 nonMutatedPs = new PackageSetting(foundPs); 8051 } 8052 } 8053 8054 // Just create the setting, don't add it yet. For already existing packages 8055 // the PkgSetting exists already and doesn't have to be created. 8056 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8057 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8058 pkg.applicationInfo.primaryCpuAbi, 8059 pkg.applicationInfo.secondaryCpuAbi, 8060 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8061 user, false); 8062 if (pkgSetting == null) { 8063 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8064 "Creating application package " + pkg.packageName + " failed"); 8065 } 8066 8067 if (pkgSetting.origPackage != null) { 8068 // If we are first transitioning from an original package, 8069 // fix up the new package's name now. We need to do this after 8070 // looking up the package under its new name, so getPackageLP 8071 // can take care of fiddling things correctly. 8072 pkg.setPackageName(origPackage.name); 8073 8074 // File a report about this. 8075 String msg = "New package " + pkgSetting.realName 8076 + " renamed to replace old package " + pkgSetting.name; 8077 reportSettingsProblem(Log.WARN, msg); 8078 8079 // Make a note of it. 8080 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8081 mTransferedPackages.add(origPackage.name); 8082 } 8083 8084 // No longer need to retain this. 8085 pkgSetting.origPackage = null; 8086 } 8087 8088 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8089 // Make a note of it. 8090 mTransferedPackages.add(pkg.packageName); 8091 } 8092 8093 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8094 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8095 } 8096 8097 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8098 // Check all shared libraries and map to their actual file path. 8099 // We only do this here for apps not on a system dir, because those 8100 // are the only ones that can fail an install due to this. We 8101 // will take care of the system apps by updating all of their 8102 // library paths after the scan is done. 8103 updateSharedLibrariesLPw(pkg, null); 8104 } 8105 8106 if (mFoundPolicyFile) { 8107 SELinuxMMAC.assignSeinfoValue(pkg); 8108 } 8109 8110 pkg.applicationInfo.uid = pkgSetting.appId; 8111 pkg.mExtras = pkgSetting; 8112 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8113 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8114 // We just determined the app is signed correctly, so bring 8115 // over the latest parsed certs. 8116 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8117 } else { 8118 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8119 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8120 "Package " + pkg.packageName + " upgrade keys do not match the " 8121 + "previously installed version"); 8122 } else { 8123 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8124 String msg = "System package " + pkg.packageName 8125 + " signature changed; retaining data."; 8126 reportSettingsProblem(Log.WARN, msg); 8127 } 8128 } 8129 } else { 8130 try { 8131 verifySignaturesLP(pkgSetting, pkg); 8132 // We just determined the app is signed correctly, so bring 8133 // over the latest parsed certs. 8134 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8135 } catch (PackageManagerException e) { 8136 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8137 throw e; 8138 } 8139 // The signature has changed, but this package is in the system 8140 // image... let's recover! 8141 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8142 // However... if this package is part of a shared user, but it 8143 // doesn't match the signature of the shared user, let's fail. 8144 // What this means is that you can't change the signatures 8145 // associated with an overall shared user, which doesn't seem all 8146 // that unreasonable. 8147 if (pkgSetting.sharedUser != null) { 8148 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8149 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8150 throw new PackageManagerException( 8151 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8152 "Signature mismatch for shared user: " 8153 + pkgSetting.sharedUser); 8154 } 8155 } 8156 // File a report about this. 8157 String msg = "System package " + pkg.packageName 8158 + " signature changed; retaining data."; 8159 reportSettingsProblem(Log.WARN, msg); 8160 } 8161 } 8162 // Verify that this new package doesn't have any content providers 8163 // that conflict with existing packages. Only do this if the 8164 // package isn't already installed, since we don't want to break 8165 // things that are installed. 8166 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8167 final int N = pkg.providers.size(); 8168 int i; 8169 for (i=0; i<N; i++) { 8170 PackageParser.Provider p = pkg.providers.get(i); 8171 if (p.info.authority != null) { 8172 String names[] = p.info.authority.split(";"); 8173 for (int j = 0; j < names.length; j++) { 8174 if (mProvidersByAuthority.containsKey(names[j])) { 8175 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8176 final String otherPackageName = 8177 ((other != null && other.getComponentName() != null) ? 8178 other.getComponentName().getPackageName() : "?"); 8179 throw new PackageManagerException( 8180 INSTALL_FAILED_CONFLICTING_PROVIDER, 8181 "Can't install because provider name " + names[j] 8182 + " (in package " + pkg.applicationInfo.packageName 8183 + ") is already used by " + otherPackageName); 8184 } 8185 } 8186 } 8187 } 8188 } 8189 8190 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8191 // This package wants to adopt ownership of permissions from 8192 // another package. 8193 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8194 final String origName = pkg.mAdoptPermissions.get(i); 8195 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8196 if (orig != null) { 8197 if (verifyPackageUpdateLPr(orig, pkg)) { 8198 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8199 + pkg.packageName); 8200 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8201 } 8202 } 8203 } 8204 } 8205 } 8206 8207 final String pkgName = pkg.packageName; 8208 8209 final long scanFileTime = scanFile.lastModified(); 8210 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8211 pkg.applicationInfo.processName = fixProcessName( 8212 pkg.applicationInfo.packageName, 8213 pkg.applicationInfo.processName, 8214 pkg.applicationInfo.uid); 8215 8216 if (pkg != mPlatformPackage) { 8217 // Get all of our default paths setup 8218 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8219 } 8220 8221 final String path = scanFile.getPath(); 8222 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8223 8224 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8225 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8226 8227 // Some system apps still use directory structure for native libraries 8228 // in which case we might end up not detecting abi solely based on apk 8229 // structure. Try to detect abi based on directory structure. 8230 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8231 pkg.applicationInfo.primaryCpuAbi == null) { 8232 setBundledAppAbisAndRoots(pkg, pkgSetting); 8233 setNativeLibraryPaths(pkg); 8234 } 8235 8236 } else { 8237 if ((scanFlags & SCAN_MOVE) != 0) { 8238 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8239 // but we already have this packages package info in the PackageSetting. We just 8240 // use that and derive the native library path based on the new codepath. 8241 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8242 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8243 } 8244 8245 // Set native library paths again. For moves, the path will be updated based on the 8246 // ABIs we've determined above. For non-moves, the path will be updated based on the 8247 // ABIs we determined during compilation, but the path will depend on the final 8248 // package path (after the rename away from the stage path). 8249 setNativeLibraryPaths(pkg); 8250 } 8251 8252 // This is a special case for the "system" package, where the ABI is 8253 // dictated by the zygote configuration (and init.rc). We should keep track 8254 // of this ABI so that we can deal with "normal" applications that run under 8255 // the same UID correctly. 8256 if (mPlatformPackage == pkg) { 8257 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8258 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8259 } 8260 8261 // If there's a mismatch between the abi-override in the package setting 8262 // and the abiOverride specified for the install. Warn about this because we 8263 // would've already compiled the app without taking the package setting into 8264 // account. 8265 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8266 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8267 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8268 " for package " + pkg.packageName); 8269 } 8270 } 8271 8272 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8273 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8274 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8275 8276 // Copy the derived override back to the parsed package, so that we can 8277 // update the package settings accordingly. 8278 pkg.cpuAbiOverride = cpuAbiOverride; 8279 8280 if (DEBUG_ABI_SELECTION) { 8281 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8282 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8283 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8284 } 8285 8286 // Push the derived path down into PackageSettings so we know what to 8287 // clean up at uninstall time. 8288 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8289 8290 if (DEBUG_ABI_SELECTION) { 8291 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8292 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8293 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8294 } 8295 8296 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8297 // We don't do this here during boot because we can do it all 8298 // at once after scanning all existing packages. 8299 // 8300 // We also do this *before* we perform dexopt on this package, so that 8301 // we can avoid redundant dexopts, and also to make sure we've got the 8302 // code and package path correct. 8303 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8304 pkg, true /* boot complete */); 8305 } 8306 8307 if (mFactoryTest && pkg.requestedPermissions.contains( 8308 android.Manifest.permission.FACTORY_TEST)) { 8309 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8310 } 8311 8312 ArrayList<PackageParser.Package> clientLibPkgs = null; 8313 8314 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8315 if (nonMutatedPs != null) { 8316 synchronized (mPackages) { 8317 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8318 } 8319 } 8320 return pkg; 8321 } 8322 8323 // Only privileged apps and updated privileged apps can add child packages. 8324 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8325 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8326 throw new PackageManagerException("Only privileged apps and updated " 8327 + "privileged apps can add child packages. Ignoring package " 8328 + pkg.packageName); 8329 } 8330 final int childCount = pkg.childPackages.size(); 8331 for (int i = 0; i < childCount; i++) { 8332 PackageParser.Package childPkg = pkg.childPackages.get(i); 8333 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8334 childPkg.packageName)) { 8335 throw new PackageManagerException("Cannot override a child package of " 8336 + "another disabled system app. Ignoring package " + pkg.packageName); 8337 } 8338 } 8339 } 8340 8341 // writer 8342 synchronized (mPackages) { 8343 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8344 // Only system apps can add new shared libraries. 8345 if (pkg.libraryNames != null) { 8346 for (int i=0; i<pkg.libraryNames.size(); i++) { 8347 String name = pkg.libraryNames.get(i); 8348 boolean allowed = false; 8349 if (pkg.isUpdatedSystemApp()) { 8350 // New library entries can only be added through the 8351 // system image. This is important to get rid of a lot 8352 // of nasty edge cases: for example if we allowed a non- 8353 // system update of the app to add a library, then uninstalling 8354 // the update would make the library go away, and assumptions 8355 // we made such as through app install filtering would now 8356 // have allowed apps on the device which aren't compatible 8357 // with it. Better to just have the restriction here, be 8358 // conservative, and create many fewer cases that can negatively 8359 // impact the user experience. 8360 final PackageSetting sysPs = mSettings 8361 .getDisabledSystemPkgLPr(pkg.packageName); 8362 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8363 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8364 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8365 allowed = true; 8366 break; 8367 } 8368 } 8369 } 8370 } else { 8371 allowed = true; 8372 } 8373 if (allowed) { 8374 if (!mSharedLibraries.containsKey(name)) { 8375 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8376 } else if (!name.equals(pkg.packageName)) { 8377 Slog.w(TAG, "Package " + pkg.packageName + " library " 8378 + name + " already exists; skipping"); 8379 } 8380 } else { 8381 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8382 + name + " that is not declared on system image; skipping"); 8383 } 8384 } 8385 if ((scanFlags & SCAN_BOOTING) == 0) { 8386 // If we are not booting, we need to update any applications 8387 // that are clients of our shared library. If we are booting, 8388 // this will all be done once the scan is complete. 8389 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8390 } 8391 } 8392 } 8393 } 8394 8395 if ((scanFlags & SCAN_BOOTING) != 0) { 8396 // No apps can run during boot scan, so they don't need to be frozen 8397 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8398 // Caller asked to not kill app, so it's probably not frozen 8399 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8400 // Caller asked us to ignore frozen check for some reason; they 8401 // probably didn't know the package name 8402 } else { 8403 // We're doing major surgery on this package, so it better be frozen 8404 // right now to keep it from launching 8405 checkPackageFrozen(pkgName); 8406 } 8407 8408 // Also need to kill any apps that are dependent on the library. 8409 if (clientLibPkgs != null) { 8410 for (int i=0; i<clientLibPkgs.size(); i++) { 8411 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8412 killApplication(clientPkg.applicationInfo.packageName, 8413 clientPkg.applicationInfo.uid, "update lib"); 8414 } 8415 } 8416 8417 // Make sure we're not adding any bogus keyset info 8418 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8419 ksms.assertScannedPackageValid(pkg); 8420 8421 // writer 8422 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8423 8424 boolean createIdmapFailed = false; 8425 synchronized (mPackages) { 8426 // We don't expect installation to fail beyond this point 8427 8428 // Add the new setting to mSettings 8429 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8430 // Add the new setting to mPackages 8431 mPackages.put(pkg.applicationInfo.packageName, pkg); 8432 // Make sure we don't accidentally delete its data. 8433 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8434 while (iter.hasNext()) { 8435 PackageCleanItem item = iter.next(); 8436 if (pkgName.equals(item.packageName)) { 8437 iter.remove(); 8438 } 8439 } 8440 8441 // Take care of first install / last update times. 8442 if (currentTime != 0) { 8443 if (pkgSetting.firstInstallTime == 0) { 8444 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8445 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8446 pkgSetting.lastUpdateTime = currentTime; 8447 } 8448 } else if (pkgSetting.firstInstallTime == 0) { 8449 // We need *something*. Take time time stamp of the file. 8450 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8451 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8452 if (scanFileTime != pkgSetting.timeStamp) { 8453 // A package on the system image has changed; consider this 8454 // to be an update. 8455 pkgSetting.lastUpdateTime = scanFileTime; 8456 } 8457 } 8458 8459 // Add the package's KeySets to the global KeySetManagerService 8460 ksms.addScannedPackageLPw(pkg); 8461 8462 int N = pkg.providers.size(); 8463 StringBuilder r = null; 8464 int i; 8465 for (i=0; i<N; i++) { 8466 PackageParser.Provider p = pkg.providers.get(i); 8467 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8468 p.info.processName, pkg.applicationInfo.uid); 8469 mProviders.addProvider(p); 8470 p.syncable = p.info.isSyncable; 8471 if (p.info.authority != null) { 8472 String names[] = p.info.authority.split(";"); 8473 p.info.authority = null; 8474 for (int j = 0; j < names.length; j++) { 8475 if (j == 1 && p.syncable) { 8476 // We only want the first authority for a provider to possibly be 8477 // syncable, so if we already added this provider using a different 8478 // authority clear the syncable flag. We copy the provider before 8479 // changing it because the mProviders object contains a reference 8480 // to a provider that we don't want to change. 8481 // Only do this for the second authority since the resulting provider 8482 // object can be the same for all future authorities for this provider. 8483 p = new PackageParser.Provider(p); 8484 p.syncable = false; 8485 } 8486 if (!mProvidersByAuthority.containsKey(names[j])) { 8487 mProvidersByAuthority.put(names[j], p); 8488 if (p.info.authority == null) { 8489 p.info.authority = names[j]; 8490 } else { 8491 p.info.authority = p.info.authority + ";" + names[j]; 8492 } 8493 if (DEBUG_PACKAGE_SCANNING) { 8494 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8495 Log.d(TAG, "Registered content provider: " + names[j] 8496 + ", className = " + p.info.name + ", isSyncable = " 8497 + p.info.isSyncable); 8498 } 8499 } else { 8500 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8501 Slog.w(TAG, "Skipping provider name " + names[j] + 8502 " (in package " + pkg.applicationInfo.packageName + 8503 "): name already used by " 8504 + ((other != null && other.getComponentName() != null) 8505 ? other.getComponentName().getPackageName() : "?")); 8506 } 8507 } 8508 } 8509 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8510 if (r == null) { 8511 r = new StringBuilder(256); 8512 } else { 8513 r.append(' '); 8514 } 8515 r.append(p.info.name); 8516 } 8517 } 8518 if (r != null) { 8519 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8520 } 8521 8522 N = pkg.services.size(); 8523 r = null; 8524 for (i=0; i<N; i++) { 8525 PackageParser.Service s = pkg.services.get(i); 8526 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8527 s.info.processName, pkg.applicationInfo.uid); 8528 mServices.addService(s); 8529 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8530 if (r == null) { 8531 r = new StringBuilder(256); 8532 } else { 8533 r.append(' '); 8534 } 8535 r.append(s.info.name); 8536 } 8537 } 8538 if (r != null) { 8539 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8540 } 8541 8542 N = pkg.receivers.size(); 8543 r = null; 8544 for (i=0; i<N; i++) { 8545 PackageParser.Activity a = pkg.receivers.get(i); 8546 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8547 a.info.processName, pkg.applicationInfo.uid); 8548 mReceivers.addActivity(a, "receiver"); 8549 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8550 if (r == null) { 8551 r = new StringBuilder(256); 8552 } else { 8553 r.append(' '); 8554 } 8555 r.append(a.info.name); 8556 } 8557 } 8558 if (r != null) { 8559 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8560 } 8561 8562 N = pkg.activities.size(); 8563 r = null; 8564 for (i=0; i<N; i++) { 8565 PackageParser.Activity a = pkg.activities.get(i); 8566 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8567 a.info.processName, pkg.applicationInfo.uid); 8568 mActivities.addActivity(a, "activity"); 8569 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8570 if (r == null) { 8571 r = new StringBuilder(256); 8572 } else { 8573 r.append(' '); 8574 } 8575 r.append(a.info.name); 8576 } 8577 } 8578 if (r != null) { 8579 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8580 } 8581 8582 N = pkg.permissionGroups.size(); 8583 r = null; 8584 for (i=0; i<N; i++) { 8585 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8586 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8587 if (cur == null) { 8588 mPermissionGroups.put(pg.info.name, pg); 8589 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8590 if (r == null) { 8591 r = new StringBuilder(256); 8592 } else { 8593 r.append(' '); 8594 } 8595 r.append(pg.info.name); 8596 } 8597 } else { 8598 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8599 + pg.info.packageName + " ignored: original from " 8600 + cur.info.packageName); 8601 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8602 if (r == null) { 8603 r = new StringBuilder(256); 8604 } else { 8605 r.append(' '); 8606 } 8607 r.append("DUP:"); 8608 r.append(pg.info.name); 8609 } 8610 } 8611 } 8612 if (r != null) { 8613 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8614 } 8615 8616 N = pkg.permissions.size(); 8617 r = null; 8618 for (i=0; i<N; i++) { 8619 PackageParser.Permission p = pkg.permissions.get(i); 8620 8621 // Assume by default that we did not install this permission into the system. 8622 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8623 8624 // Now that permission groups have a special meaning, we ignore permission 8625 // groups for legacy apps to prevent unexpected behavior. In particular, 8626 // permissions for one app being granted to someone just becase they happen 8627 // to be in a group defined by another app (before this had no implications). 8628 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8629 p.group = mPermissionGroups.get(p.info.group); 8630 // Warn for a permission in an unknown group. 8631 if (p.info.group != null && p.group == null) { 8632 Slog.w(TAG, "Permission " + p.info.name + " from package " 8633 + p.info.packageName + " in an unknown group " + p.info.group); 8634 } 8635 } 8636 8637 ArrayMap<String, BasePermission> permissionMap = 8638 p.tree ? mSettings.mPermissionTrees 8639 : mSettings.mPermissions; 8640 BasePermission bp = permissionMap.get(p.info.name); 8641 8642 // Allow system apps to redefine non-system permissions 8643 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8644 final boolean currentOwnerIsSystem = (bp.perm != null 8645 && isSystemApp(bp.perm.owner)); 8646 if (isSystemApp(p.owner)) { 8647 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8648 // It's a built-in permission and no owner, take ownership now 8649 bp.packageSetting = pkgSetting; 8650 bp.perm = p; 8651 bp.uid = pkg.applicationInfo.uid; 8652 bp.sourcePackage = p.info.packageName; 8653 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8654 } else if (!currentOwnerIsSystem) { 8655 String msg = "New decl " + p.owner + " of permission " 8656 + p.info.name + " is system; overriding " + bp.sourcePackage; 8657 reportSettingsProblem(Log.WARN, msg); 8658 bp = null; 8659 } 8660 } 8661 } 8662 8663 if (bp == null) { 8664 bp = new BasePermission(p.info.name, p.info.packageName, 8665 BasePermission.TYPE_NORMAL); 8666 permissionMap.put(p.info.name, bp); 8667 } 8668 8669 if (bp.perm == null) { 8670 if (bp.sourcePackage == null 8671 || bp.sourcePackage.equals(p.info.packageName)) { 8672 BasePermission tree = findPermissionTreeLP(p.info.name); 8673 if (tree == null 8674 || tree.sourcePackage.equals(p.info.packageName)) { 8675 bp.packageSetting = pkgSetting; 8676 bp.perm = p; 8677 bp.uid = pkg.applicationInfo.uid; 8678 bp.sourcePackage = p.info.packageName; 8679 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8680 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8681 if (r == null) { 8682 r = new StringBuilder(256); 8683 } else { 8684 r.append(' '); 8685 } 8686 r.append(p.info.name); 8687 } 8688 } else { 8689 Slog.w(TAG, "Permission " + p.info.name + " from package " 8690 + p.info.packageName + " ignored: base tree " 8691 + tree.name + " is from package " 8692 + tree.sourcePackage); 8693 } 8694 } else { 8695 Slog.w(TAG, "Permission " + p.info.name + " from package " 8696 + p.info.packageName + " ignored: original from " 8697 + bp.sourcePackage); 8698 } 8699 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8700 if (r == null) { 8701 r = new StringBuilder(256); 8702 } else { 8703 r.append(' '); 8704 } 8705 r.append("DUP:"); 8706 r.append(p.info.name); 8707 } 8708 if (bp.perm == p) { 8709 bp.protectionLevel = p.info.protectionLevel; 8710 } 8711 } 8712 8713 if (r != null) { 8714 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8715 } 8716 8717 N = pkg.instrumentation.size(); 8718 r = null; 8719 for (i=0; i<N; i++) { 8720 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8721 a.info.packageName = pkg.applicationInfo.packageName; 8722 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8723 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8724 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8725 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8726 a.info.dataDir = pkg.applicationInfo.dataDir; 8727 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8728 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8729 8730 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8731 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8732 mInstrumentation.put(a.getComponentName(), a); 8733 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8734 if (r == null) { 8735 r = new StringBuilder(256); 8736 } else { 8737 r.append(' '); 8738 } 8739 r.append(a.info.name); 8740 } 8741 } 8742 if (r != null) { 8743 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8744 } 8745 8746 if (pkg.protectedBroadcasts != null) { 8747 N = pkg.protectedBroadcasts.size(); 8748 for (i=0; i<N; i++) { 8749 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8750 } 8751 } 8752 8753 pkgSetting.setTimeStamp(scanFileTime); 8754 8755 // Create idmap files for pairs of (packages, overlay packages). 8756 // Note: "android", ie framework-res.apk, is handled by native layers. 8757 if (pkg.mOverlayTarget != null) { 8758 // This is an overlay package. 8759 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8760 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8761 mOverlays.put(pkg.mOverlayTarget, 8762 new ArrayMap<String, PackageParser.Package>()); 8763 } 8764 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8765 map.put(pkg.packageName, pkg); 8766 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8767 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8768 createIdmapFailed = true; 8769 } 8770 } 8771 } else if (mOverlays.containsKey(pkg.packageName) && 8772 !pkg.packageName.equals("android")) { 8773 // This is a regular package, with one or more known overlay packages. 8774 createIdmapsForPackageLI(pkg); 8775 } 8776 } 8777 8778 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8779 8780 if (createIdmapFailed) { 8781 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8782 "scanPackageLI failed to createIdmap"); 8783 } 8784 return pkg; 8785 } 8786 8787 /** 8788 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8789 * is derived purely on the basis of the contents of {@code scanFile} and 8790 * {@code cpuAbiOverride}. 8791 * 8792 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8793 */ 8794 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8795 String cpuAbiOverride, boolean extractLibs) 8796 throws PackageManagerException { 8797 // TODO: We can probably be smarter about this stuff. For installed apps, 8798 // we can calculate this information at install time once and for all. For 8799 // system apps, we can probably assume that this information doesn't change 8800 // after the first boot scan. As things stand, we do lots of unnecessary work. 8801 8802 // Give ourselves some initial paths; we'll come back for another 8803 // pass once we've determined ABI below. 8804 setNativeLibraryPaths(pkg); 8805 8806 // We would never need to extract libs for forward-locked and external packages, 8807 // since the container service will do it for us. We shouldn't attempt to 8808 // extract libs from system app when it was not updated. 8809 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8810 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8811 extractLibs = false; 8812 } 8813 8814 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8815 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8816 8817 NativeLibraryHelper.Handle handle = null; 8818 try { 8819 handle = NativeLibraryHelper.Handle.create(pkg); 8820 // TODO(multiArch): This can be null for apps that didn't go through the 8821 // usual installation process. We can calculate it again, like we 8822 // do during install time. 8823 // 8824 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8825 // unnecessary. 8826 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8827 8828 // Null out the abis so that they can be recalculated. 8829 pkg.applicationInfo.primaryCpuAbi = null; 8830 pkg.applicationInfo.secondaryCpuAbi = null; 8831 if (isMultiArch(pkg.applicationInfo)) { 8832 // Warn if we've set an abiOverride for multi-lib packages.. 8833 // By definition, we need to copy both 32 and 64 bit libraries for 8834 // such packages. 8835 if (pkg.cpuAbiOverride != null 8836 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8837 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8838 } 8839 8840 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8841 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8842 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8843 if (extractLibs) { 8844 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8845 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8846 useIsaSpecificSubdirs); 8847 } else { 8848 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8849 } 8850 } 8851 8852 maybeThrowExceptionForMultiArchCopy( 8853 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8854 8855 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8856 if (extractLibs) { 8857 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8858 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8859 useIsaSpecificSubdirs); 8860 } else { 8861 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8862 } 8863 } 8864 8865 maybeThrowExceptionForMultiArchCopy( 8866 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8867 8868 if (abi64 >= 0) { 8869 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8870 } 8871 8872 if (abi32 >= 0) { 8873 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8874 if (abi64 >= 0) { 8875 if (pkg.use32bitAbi) { 8876 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8877 pkg.applicationInfo.primaryCpuAbi = abi; 8878 } else { 8879 pkg.applicationInfo.secondaryCpuAbi = abi; 8880 } 8881 } else { 8882 pkg.applicationInfo.primaryCpuAbi = abi; 8883 } 8884 } 8885 8886 } else { 8887 String[] abiList = (cpuAbiOverride != null) ? 8888 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8889 8890 // Enable gross and lame hacks for apps that are built with old 8891 // SDK tools. We must scan their APKs for renderscript bitcode and 8892 // not launch them if it's present. Don't bother checking on devices 8893 // that don't have 64 bit support. 8894 boolean needsRenderScriptOverride = false; 8895 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8896 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8897 abiList = Build.SUPPORTED_32_BIT_ABIS; 8898 needsRenderScriptOverride = true; 8899 } 8900 8901 final int copyRet; 8902 if (extractLibs) { 8903 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8904 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8905 } else { 8906 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8907 } 8908 8909 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8910 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8911 "Error unpackaging native libs for app, errorCode=" + copyRet); 8912 } 8913 8914 if (copyRet >= 0) { 8915 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8916 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8917 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8918 } else if (needsRenderScriptOverride) { 8919 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8920 } 8921 } 8922 } catch (IOException ioe) { 8923 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8924 } finally { 8925 IoUtils.closeQuietly(handle); 8926 } 8927 8928 // Now that we've calculated the ABIs and determined if it's an internal app, 8929 // we will go ahead and populate the nativeLibraryPath. 8930 setNativeLibraryPaths(pkg); 8931 } 8932 8933 /** 8934 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8935 * i.e, so that all packages can be run inside a single process if required. 8936 * 8937 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8938 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8939 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8940 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8941 * updating a package that belongs to a shared user. 8942 * 8943 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8944 * adds unnecessary complexity. 8945 */ 8946 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8947 PackageParser.Package scannedPackage, boolean bootComplete) { 8948 String requiredInstructionSet = null; 8949 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8950 requiredInstructionSet = VMRuntime.getInstructionSet( 8951 scannedPackage.applicationInfo.primaryCpuAbi); 8952 } 8953 8954 PackageSetting requirer = null; 8955 for (PackageSetting ps : packagesForUser) { 8956 // If packagesForUser contains scannedPackage, we skip it. This will happen 8957 // when scannedPackage is an update of an existing package. Without this check, 8958 // we will never be able to change the ABI of any package belonging to a shared 8959 // user, even if it's compatible with other packages. 8960 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8961 if (ps.primaryCpuAbiString == null) { 8962 continue; 8963 } 8964 8965 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8966 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8967 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8968 // this but there's not much we can do. 8969 String errorMessage = "Instruction set mismatch, " 8970 + ((requirer == null) ? "[caller]" : requirer) 8971 + " requires " + requiredInstructionSet + " whereas " + ps 8972 + " requires " + instructionSet; 8973 Slog.w(TAG, errorMessage); 8974 } 8975 8976 if (requiredInstructionSet == null) { 8977 requiredInstructionSet = instructionSet; 8978 requirer = ps; 8979 } 8980 } 8981 } 8982 8983 if (requiredInstructionSet != null) { 8984 String adjustedAbi; 8985 if (requirer != null) { 8986 // requirer != null implies that either scannedPackage was null or that scannedPackage 8987 // did not require an ABI, in which case we have to adjust scannedPackage to match 8988 // the ABI of the set (which is the same as requirer's ABI) 8989 adjustedAbi = requirer.primaryCpuAbiString; 8990 if (scannedPackage != null) { 8991 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8992 } 8993 } else { 8994 // requirer == null implies that we're updating all ABIs in the set to 8995 // match scannedPackage. 8996 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8997 } 8998 8999 for (PackageSetting ps : packagesForUser) { 9000 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9001 if (ps.primaryCpuAbiString != null) { 9002 continue; 9003 } 9004 9005 ps.primaryCpuAbiString = adjustedAbi; 9006 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9007 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9008 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9009 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9010 + " (requirer=" 9011 + (requirer == null ? "null" : requirer.pkg.packageName) 9012 + ", scannedPackage=" 9013 + (scannedPackage != null ? scannedPackage.packageName : "null") 9014 + ")"); 9015 try { 9016 mInstaller.rmdex(ps.codePathString, 9017 getDexCodeInstructionSet(getPreferredInstructionSet())); 9018 } catch (InstallerException ignored) { 9019 } 9020 } 9021 } 9022 } 9023 } 9024 } 9025 9026 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9027 synchronized (mPackages) { 9028 mResolverReplaced = true; 9029 // Set up information for custom user intent resolution activity. 9030 mResolveActivity.applicationInfo = pkg.applicationInfo; 9031 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9032 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9033 mResolveActivity.processName = pkg.applicationInfo.packageName; 9034 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9035 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9036 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9037 mResolveActivity.theme = 0; 9038 mResolveActivity.exported = true; 9039 mResolveActivity.enabled = true; 9040 mResolveInfo.activityInfo = mResolveActivity; 9041 mResolveInfo.priority = 0; 9042 mResolveInfo.preferredOrder = 0; 9043 mResolveInfo.match = 0; 9044 mResolveComponentName = mCustomResolverComponentName; 9045 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9046 mResolveComponentName); 9047 } 9048 } 9049 9050 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9051 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9052 9053 // Set up information for ephemeral installer activity 9054 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9055 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9056 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9057 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9058 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9059 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9060 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9061 mEphemeralInstallerActivity.theme = 0; 9062 mEphemeralInstallerActivity.exported = true; 9063 mEphemeralInstallerActivity.enabled = true; 9064 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9065 mEphemeralInstallerInfo.priority = 0; 9066 mEphemeralInstallerInfo.preferredOrder = 0; 9067 mEphemeralInstallerInfo.match = 0; 9068 9069 if (DEBUG_EPHEMERAL) { 9070 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9071 } 9072 } 9073 9074 private static String calculateBundledApkRoot(final String codePathString) { 9075 final File codePath = new File(codePathString); 9076 final File codeRoot; 9077 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9078 codeRoot = Environment.getRootDirectory(); 9079 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9080 codeRoot = Environment.getOemDirectory(); 9081 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9082 codeRoot = Environment.getVendorDirectory(); 9083 } else { 9084 // Unrecognized code path; take its top real segment as the apk root: 9085 // e.g. /something/app/blah.apk => /something 9086 try { 9087 File f = codePath.getCanonicalFile(); 9088 File parent = f.getParentFile(); // non-null because codePath is a file 9089 File tmp; 9090 while ((tmp = parent.getParentFile()) != null) { 9091 f = parent; 9092 parent = tmp; 9093 } 9094 codeRoot = f; 9095 Slog.w(TAG, "Unrecognized code path " 9096 + codePath + " - using " + codeRoot); 9097 } catch (IOException e) { 9098 // Can't canonicalize the code path -- shenanigans? 9099 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9100 return Environment.getRootDirectory().getPath(); 9101 } 9102 } 9103 return codeRoot.getPath(); 9104 } 9105 9106 /** 9107 * Derive and set the location of native libraries for the given package, 9108 * which varies depending on where and how the package was installed. 9109 */ 9110 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9111 final ApplicationInfo info = pkg.applicationInfo; 9112 final String codePath = pkg.codePath; 9113 final File codeFile = new File(codePath); 9114 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9115 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9116 9117 info.nativeLibraryRootDir = null; 9118 info.nativeLibraryRootRequiresIsa = false; 9119 info.nativeLibraryDir = null; 9120 info.secondaryNativeLibraryDir = null; 9121 9122 if (isApkFile(codeFile)) { 9123 // Monolithic install 9124 if (bundledApp) { 9125 // If "/system/lib64/apkname" exists, assume that is the per-package 9126 // native library directory to use; otherwise use "/system/lib/apkname". 9127 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9128 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9129 getPrimaryInstructionSet(info)); 9130 9131 // This is a bundled system app so choose the path based on the ABI. 9132 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9133 // is just the default path. 9134 final String apkName = deriveCodePathName(codePath); 9135 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9136 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9137 apkName).getAbsolutePath(); 9138 9139 if (info.secondaryCpuAbi != null) { 9140 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9141 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9142 secondaryLibDir, apkName).getAbsolutePath(); 9143 } 9144 } else if (asecApp) { 9145 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9146 .getAbsolutePath(); 9147 } else { 9148 final String apkName = deriveCodePathName(codePath); 9149 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9150 .getAbsolutePath(); 9151 } 9152 9153 info.nativeLibraryRootRequiresIsa = false; 9154 info.nativeLibraryDir = info.nativeLibraryRootDir; 9155 } else { 9156 // Cluster install 9157 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9158 info.nativeLibraryRootRequiresIsa = true; 9159 9160 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9161 getPrimaryInstructionSet(info)).getAbsolutePath(); 9162 9163 if (info.secondaryCpuAbi != null) { 9164 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9165 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9166 } 9167 } 9168 } 9169 9170 /** 9171 * Calculate the abis and roots for a bundled app. These can uniquely 9172 * be determined from the contents of the system partition, i.e whether 9173 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9174 * of this information, and instead assume that the system was built 9175 * sensibly. 9176 */ 9177 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9178 PackageSetting pkgSetting) { 9179 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9180 9181 // If "/system/lib64/apkname" exists, assume that is the per-package 9182 // native library directory to use; otherwise use "/system/lib/apkname". 9183 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9184 setBundledAppAbi(pkg, apkRoot, apkName); 9185 // pkgSetting might be null during rescan following uninstall of updates 9186 // to a bundled app, so accommodate that possibility. The settings in 9187 // that case will be established later from the parsed package. 9188 // 9189 // If the settings aren't null, sync them up with what we've just derived. 9190 // note that apkRoot isn't stored in the package settings. 9191 if (pkgSetting != null) { 9192 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9193 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9194 } 9195 } 9196 9197 /** 9198 * Deduces the ABI of a bundled app and sets the relevant fields on the 9199 * parsed pkg object. 9200 * 9201 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9202 * under which system libraries are installed. 9203 * @param apkName the name of the installed package. 9204 */ 9205 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9206 final File codeFile = new File(pkg.codePath); 9207 9208 final boolean has64BitLibs; 9209 final boolean has32BitLibs; 9210 if (isApkFile(codeFile)) { 9211 // Monolithic install 9212 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9213 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9214 } else { 9215 // Cluster install 9216 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9217 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9218 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9219 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9220 has64BitLibs = (new File(rootDir, isa)).exists(); 9221 } else { 9222 has64BitLibs = false; 9223 } 9224 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9225 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9226 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9227 has32BitLibs = (new File(rootDir, isa)).exists(); 9228 } else { 9229 has32BitLibs = false; 9230 } 9231 } 9232 9233 if (has64BitLibs && !has32BitLibs) { 9234 // The package has 64 bit libs, but not 32 bit libs. Its primary 9235 // ABI should be 64 bit. We can safely assume here that the bundled 9236 // native libraries correspond to the most preferred ABI in the list. 9237 9238 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9239 pkg.applicationInfo.secondaryCpuAbi = null; 9240 } else if (has32BitLibs && !has64BitLibs) { 9241 // The package has 32 bit libs but not 64 bit libs. Its primary 9242 // ABI should be 32 bit. 9243 9244 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9245 pkg.applicationInfo.secondaryCpuAbi = null; 9246 } else if (has32BitLibs && has64BitLibs) { 9247 // The application has both 64 and 32 bit bundled libraries. We check 9248 // here that the app declares multiArch support, and warn if it doesn't. 9249 // 9250 // We will be lenient here and record both ABIs. The primary will be the 9251 // ABI that's higher on the list, i.e, a device that's configured to prefer 9252 // 64 bit apps will see a 64 bit primary ABI, 9253 9254 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9255 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9256 } 9257 9258 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9259 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9260 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9261 } else { 9262 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9263 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9264 } 9265 } else { 9266 pkg.applicationInfo.primaryCpuAbi = null; 9267 pkg.applicationInfo.secondaryCpuAbi = null; 9268 } 9269 } 9270 9271 private void killApplication(String pkgName, int appId, String reason) { 9272 // Request the ActivityManager to kill the process(only for existing packages) 9273 // so that we do not end up in a confused state while the user is still using the older 9274 // version of the application while the new one gets installed. 9275 final long token = Binder.clearCallingIdentity(); 9276 try { 9277 IActivityManager am = ActivityManagerNative.getDefault(); 9278 if (am != null) { 9279 try { 9280 am.killApplicationWithAppId(pkgName, appId, reason); 9281 } catch (RemoteException e) { 9282 } 9283 } 9284 } finally { 9285 Binder.restoreCallingIdentity(token); 9286 } 9287 } 9288 9289 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9290 // Remove the parent package setting 9291 PackageSetting ps = (PackageSetting) pkg.mExtras; 9292 if (ps != null) { 9293 removePackageLI(ps, chatty); 9294 } 9295 // Remove the child package setting 9296 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9297 for (int i = 0; i < childCount; i++) { 9298 PackageParser.Package childPkg = pkg.childPackages.get(i); 9299 ps = (PackageSetting) childPkg.mExtras; 9300 if (ps != null) { 9301 removePackageLI(ps, chatty); 9302 } 9303 } 9304 } 9305 9306 void removePackageLI(PackageSetting ps, boolean chatty) { 9307 if (DEBUG_INSTALL) { 9308 if (chatty) 9309 Log.d(TAG, "Removing package " + ps.name); 9310 } 9311 9312 // writer 9313 synchronized (mPackages) { 9314 mPackages.remove(ps.name); 9315 final PackageParser.Package pkg = ps.pkg; 9316 if (pkg != null) { 9317 cleanPackageDataStructuresLILPw(pkg, chatty); 9318 } 9319 } 9320 } 9321 9322 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9323 if (DEBUG_INSTALL) { 9324 if (chatty) 9325 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9326 } 9327 9328 // writer 9329 synchronized (mPackages) { 9330 // Remove the parent package 9331 mPackages.remove(pkg.applicationInfo.packageName); 9332 cleanPackageDataStructuresLILPw(pkg, chatty); 9333 9334 // Remove the child packages 9335 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9336 for (int i = 0; i < childCount; i++) { 9337 PackageParser.Package childPkg = pkg.childPackages.get(i); 9338 mPackages.remove(childPkg.applicationInfo.packageName); 9339 cleanPackageDataStructuresLILPw(childPkg, chatty); 9340 } 9341 } 9342 } 9343 9344 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9345 int N = pkg.providers.size(); 9346 StringBuilder r = null; 9347 int i; 9348 for (i=0; i<N; i++) { 9349 PackageParser.Provider p = pkg.providers.get(i); 9350 mProviders.removeProvider(p); 9351 if (p.info.authority == null) { 9352 9353 /* There was another ContentProvider with this authority when 9354 * this app was installed so this authority is null, 9355 * Ignore it as we don't have to unregister the provider. 9356 */ 9357 continue; 9358 } 9359 String names[] = p.info.authority.split(";"); 9360 for (int j = 0; j < names.length; j++) { 9361 if (mProvidersByAuthority.get(names[j]) == p) { 9362 mProvidersByAuthority.remove(names[j]); 9363 if (DEBUG_REMOVE) { 9364 if (chatty) 9365 Log.d(TAG, "Unregistered content provider: " + names[j] 9366 + ", className = " + p.info.name + ", isSyncable = " 9367 + p.info.isSyncable); 9368 } 9369 } 9370 } 9371 if (DEBUG_REMOVE && chatty) { 9372 if (r == null) { 9373 r = new StringBuilder(256); 9374 } else { 9375 r.append(' '); 9376 } 9377 r.append(p.info.name); 9378 } 9379 } 9380 if (r != null) { 9381 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9382 } 9383 9384 N = pkg.services.size(); 9385 r = null; 9386 for (i=0; i<N; i++) { 9387 PackageParser.Service s = pkg.services.get(i); 9388 mServices.removeService(s); 9389 if (chatty) { 9390 if (r == null) { 9391 r = new StringBuilder(256); 9392 } else { 9393 r.append(' '); 9394 } 9395 r.append(s.info.name); 9396 } 9397 } 9398 if (r != null) { 9399 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9400 } 9401 9402 N = pkg.receivers.size(); 9403 r = null; 9404 for (i=0; i<N; i++) { 9405 PackageParser.Activity a = pkg.receivers.get(i); 9406 mReceivers.removeActivity(a, "receiver"); 9407 if (DEBUG_REMOVE && chatty) { 9408 if (r == null) { 9409 r = new StringBuilder(256); 9410 } else { 9411 r.append(' '); 9412 } 9413 r.append(a.info.name); 9414 } 9415 } 9416 if (r != null) { 9417 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9418 } 9419 9420 N = pkg.activities.size(); 9421 r = null; 9422 for (i=0; i<N; i++) { 9423 PackageParser.Activity a = pkg.activities.get(i); 9424 mActivities.removeActivity(a, "activity"); 9425 if (DEBUG_REMOVE && chatty) { 9426 if (r == null) { 9427 r = new StringBuilder(256); 9428 } else { 9429 r.append(' '); 9430 } 9431 r.append(a.info.name); 9432 } 9433 } 9434 if (r != null) { 9435 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9436 } 9437 9438 N = pkg.permissions.size(); 9439 r = null; 9440 for (i=0; i<N; i++) { 9441 PackageParser.Permission p = pkg.permissions.get(i); 9442 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9443 if (bp == null) { 9444 bp = mSettings.mPermissionTrees.get(p.info.name); 9445 } 9446 if (bp != null && bp.perm == p) { 9447 bp.perm = null; 9448 if (DEBUG_REMOVE && chatty) { 9449 if (r == null) { 9450 r = new StringBuilder(256); 9451 } else { 9452 r.append(' '); 9453 } 9454 r.append(p.info.name); 9455 } 9456 } 9457 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9458 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9459 if (appOpPkgs != null) { 9460 appOpPkgs.remove(pkg.packageName); 9461 } 9462 } 9463 } 9464 if (r != null) { 9465 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9466 } 9467 9468 N = pkg.requestedPermissions.size(); 9469 r = null; 9470 for (i=0; i<N; i++) { 9471 String perm = pkg.requestedPermissions.get(i); 9472 BasePermission bp = mSettings.mPermissions.get(perm); 9473 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9474 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9475 if (appOpPkgs != null) { 9476 appOpPkgs.remove(pkg.packageName); 9477 if (appOpPkgs.isEmpty()) { 9478 mAppOpPermissionPackages.remove(perm); 9479 } 9480 } 9481 } 9482 } 9483 if (r != null) { 9484 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9485 } 9486 9487 N = pkg.instrumentation.size(); 9488 r = null; 9489 for (i=0; i<N; i++) { 9490 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9491 mInstrumentation.remove(a.getComponentName()); 9492 if (DEBUG_REMOVE && chatty) { 9493 if (r == null) { 9494 r = new StringBuilder(256); 9495 } else { 9496 r.append(' '); 9497 } 9498 r.append(a.info.name); 9499 } 9500 } 9501 if (r != null) { 9502 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9503 } 9504 9505 r = null; 9506 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9507 // Only system apps can hold shared libraries. 9508 if (pkg.libraryNames != null) { 9509 for (i=0; i<pkg.libraryNames.size(); i++) { 9510 String name = pkg.libraryNames.get(i); 9511 SharedLibraryEntry cur = mSharedLibraries.get(name); 9512 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9513 mSharedLibraries.remove(name); 9514 if (DEBUG_REMOVE && chatty) { 9515 if (r == null) { 9516 r = new StringBuilder(256); 9517 } else { 9518 r.append(' '); 9519 } 9520 r.append(name); 9521 } 9522 } 9523 } 9524 } 9525 } 9526 if (r != null) { 9527 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9528 } 9529 } 9530 9531 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9532 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9533 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9534 return true; 9535 } 9536 } 9537 return false; 9538 } 9539 9540 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9541 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9542 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9543 9544 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9545 // Update the parent permissions 9546 updatePermissionsLPw(pkg.packageName, pkg, flags); 9547 // Update the child permissions 9548 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9549 for (int i = 0; i < childCount; i++) { 9550 PackageParser.Package childPkg = pkg.childPackages.get(i); 9551 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9552 } 9553 } 9554 9555 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9556 int flags) { 9557 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9558 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9559 } 9560 9561 private void updatePermissionsLPw(String changingPkg, 9562 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9563 // Make sure there are no dangling permission trees. 9564 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9565 while (it.hasNext()) { 9566 final BasePermission bp = it.next(); 9567 if (bp.packageSetting == null) { 9568 // We may not yet have parsed the package, so just see if 9569 // we still know about its settings. 9570 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9571 } 9572 if (bp.packageSetting == null) { 9573 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9574 + " from package " + bp.sourcePackage); 9575 it.remove(); 9576 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9577 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9578 Slog.i(TAG, "Removing old permission tree: " + bp.name 9579 + " from package " + bp.sourcePackage); 9580 flags |= UPDATE_PERMISSIONS_ALL; 9581 it.remove(); 9582 } 9583 } 9584 } 9585 9586 // Make sure all dynamic permissions have been assigned to a package, 9587 // and make sure there are no dangling permissions. 9588 it = mSettings.mPermissions.values().iterator(); 9589 while (it.hasNext()) { 9590 final BasePermission bp = it.next(); 9591 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9592 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9593 + bp.name + " pkg=" + bp.sourcePackage 9594 + " info=" + bp.pendingInfo); 9595 if (bp.packageSetting == null && bp.pendingInfo != null) { 9596 final BasePermission tree = findPermissionTreeLP(bp.name); 9597 if (tree != null && tree.perm != null) { 9598 bp.packageSetting = tree.packageSetting; 9599 bp.perm = new PackageParser.Permission(tree.perm.owner, 9600 new PermissionInfo(bp.pendingInfo)); 9601 bp.perm.info.packageName = tree.perm.info.packageName; 9602 bp.perm.info.name = bp.name; 9603 bp.uid = tree.uid; 9604 } 9605 } 9606 } 9607 if (bp.packageSetting == null) { 9608 // We may not yet have parsed the package, so just see if 9609 // we still know about its settings. 9610 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9611 } 9612 if (bp.packageSetting == null) { 9613 Slog.w(TAG, "Removing dangling permission: " + bp.name 9614 + " from package " + bp.sourcePackage); 9615 it.remove(); 9616 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9617 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9618 Slog.i(TAG, "Removing old permission: " + bp.name 9619 + " from package " + bp.sourcePackage); 9620 flags |= UPDATE_PERMISSIONS_ALL; 9621 it.remove(); 9622 } 9623 } 9624 } 9625 9626 // Now update the permissions for all packages, in particular 9627 // replace the granted permissions of the system packages. 9628 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9629 for (PackageParser.Package pkg : mPackages.values()) { 9630 if (pkg != pkgInfo) { 9631 // Only replace for packages on requested volume 9632 final String volumeUuid = getVolumeUuidForPackage(pkg); 9633 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9634 && Objects.equals(replaceVolumeUuid, volumeUuid); 9635 grantPermissionsLPw(pkg, replace, changingPkg); 9636 } 9637 } 9638 } 9639 9640 if (pkgInfo != null) { 9641 // Only replace for packages on requested volume 9642 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9643 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9644 && Objects.equals(replaceVolumeUuid, volumeUuid); 9645 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9646 } 9647 } 9648 9649 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9650 String packageOfInterest) { 9651 // IMPORTANT: There are two types of permissions: install and runtime. 9652 // Install time permissions are granted when the app is installed to 9653 // all device users and users added in the future. Runtime permissions 9654 // are granted at runtime explicitly to specific users. Normal and signature 9655 // protected permissions are install time permissions. Dangerous permissions 9656 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9657 // otherwise they are runtime permissions. This function does not manage 9658 // runtime permissions except for the case an app targeting Lollipop MR1 9659 // being upgraded to target a newer SDK, in which case dangerous permissions 9660 // are transformed from install time to runtime ones. 9661 9662 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9663 if (ps == null) { 9664 return; 9665 } 9666 9667 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9668 9669 PermissionsState permissionsState = ps.getPermissionsState(); 9670 PermissionsState origPermissions = permissionsState; 9671 9672 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9673 9674 boolean runtimePermissionsRevoked = false; 9675 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9676 9677 boolean changedInstallPermission = false; 9678 9679 if (replace) { 9680 ps.installPermissionsFixed = false; 9681 if (!ps.isSharedUser()) { 9682 origPermissions = new PermissionsState(permissionsState); 9683 permissionsState.reset(); 9684 } else { 9685 // We need to know only about runtime permission changes since the 9686 // calling code always writes the install permissions state but 9687 // the runtime ones are written only if changed. The only cases of 9688 // changed runtime permissions here are promotion of an install to 9689 // runtime and revocation of a runtime from a shared user. 9690 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9691 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9692 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9693 runtimePermissionsRevoked = true; 9694 } 9695 } 9696 } 9697 9698 permissionsState.setGlobalGids(mGlobalGids); 9699 9700 final int N = pkg.requestedPermissions.size(); 9701 for (int i=0; i<N; i++) { 9702 final String name = pkg.requestedPermissions.get(i); 9703 final BasePermission bp = mSettings.mPermissions.get(name); 9704 9705 if (DEBUG_INSTALL) { 9706 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9707 } 9708 9709 if (bp == null || bp.packageSetting == null) { 9710 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9711 Slog.w(TAG, "Unknown permission " + name 9712 + " in package " + pkg.packageName); 9713 } 9714 continue; 9715 } 9716 9717 final String perm = bp.name; 9718 boolean allowedSig = false; 9719 int grant = GRANT_DENIED; 9720 9721 // Keep track of app op permissions. 9722 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9723 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9724 if (pkgs == null) { 9725 pkgs = new ArraySet<>(); 9726 mAppOpPermissionPackages.put(bp.name, pkgs); 9727 } 9728 pkgs.add(pkg.packageName); 9729 } 9730 9731 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9732 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9733 >= Build.VERSION_CODES.M; 9734 switch (level) { 9735 case PermissionInfo.PROTECTION_NORMAL: { 9736 // For all apps normal permissions are install time ones. 9737 grant = GRANT_INSTALL; 9738 } break; 9739 9740 case PermissionInfo.PROTECTION_DANGEROUS: { 9741 // If a permission review is required for legacy apps we represent 9742 // their permissions as always granted runtime ones since we need 9743 // to keep the review required permission flag per user while an 9744 // install permission's state is shared across all users. 9745 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9746 // For legacy apps dangerous permissions are install time ones. 9747 grant = GRANT_INSTALL; 9748 } else if (origPermissions.hasInstallPermission(bp.name)) { 9749 // For legacy apps that became modern, install becomes runtime. 9750 grant = GRANT_UPGRADE; 9751 } else if (mPromoteSystemApps 9752 && isSystemApp(ps) 9753 && mExistingSystemPackages.contains(ps.name)) { 9754 // For legacy system apps, install becomes runtime. 9755 // We cannot check hasInstallPermission() for system apps since those 9756 // permissions were granted implicitly and not persisted pre-M. 9757 grant = GRANT_UPGRADE; 9758 } else { 9759 // For modern apps keep runtime permissions unchanged. 9760 grant = GRANT_RUNTIME; 9761 } 9762 } break; 9763 9764 case PermissionInfo.PROTECTION_SIGNATURE: { 9765 // For all apps signature permissions are install time ones. 9766 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9767 if (allowedSig) { 9768 grant = GRANT_INSTALL; 9769 } 9770 } break; 9771 } 9772 9773 if (DEBUG_INSTALL) { 9774 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9775 } 9776 9777 if (grant != GRANT_DENIED) { 9778 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9779 // If this is an existing, non-system package, then 9780 // we can't add any new permissions to it. 9781 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9782 // Except... if this is a permission that was added 9783 // to the platform (note: need to only do this when 9784 // updating the platform). 9785 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9786 grant = GRANT_DENIED; 9787 } 9788 } 9789 } 9790 9791 switch (grant) { 9792 case GRANT_INSTALL: { 9793 // Revoke this as runtime permission to handle the case of 9794 // a runtime permission being downgraded to an install one. 9795 // Also in permission review mode we keep dangerous permissions 9796 // for legacy apps 9797 for (int userId : UserManagerService.getInstance().getUserIds()) { 9798 if (origPermissions.getRuntimePermissionState( 9799 bp.name, userId) != null) { 9800 // Revoke the runtime permission and clear the flags. 9801 origPermissions.revokeRuntimePermission(bp, userId); 9802 origPermissions.updatePermissionFlags(bp, userId, 9803 PackageManager.MASK_PERMISSION_FLAGS, 0); 9804 // If we revoked a permission permission, we have to write. 9805 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9806 changedRuntimePermissionUserIds, userId); 9807 } 9808 } 9809 // Grant an install permission. 9810 if (permissionsState.grantInstallPermission(bp) != 9811 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9812 changedInstallPermission = true; 9813 } 9814 } break; 9815 9816 case GRANT_RUNTIME: { 9817 // Grant previously granted runtime permissions. 9818 for (int userId : UserManagerService.getInstance().getUserIds()) { 9819 PermissionState permissionState = origPermissions 9820 .getRuntimePermissionState(bp.name, userId); 9821 int flags = permissionState != null 9822 ? permissionState.getFlags() : 0; 9823 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9824 if (permissionsState.grantRuntimePermission(bp, userId) == 9825 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9826 // If we cannot put the permission as it was, we have to write. 9827 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9828 changedRuntimePermissionUserIds, userId); 9829 } 9830 // If the app supports runtime permissions no need for a review. 9831 if (Build.PERMISSIONS_REVIEW_REQUIRED 9832 && appSupportsRuntimePermissions 9833 && (flags & PackageManager 9834 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9835 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9836 // Since we changed the flags, we have to write. 9837 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9838 changedRuntimePermissionUserIds, userId); 9839 } 9840 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9841 && !appSupportsRuntimePermissions) { 9842 // For legacy apps that need a permission review, every new 9843 // runtime permission is granted but it is pending a review. 9844 // We also need to review only platform defined runtime 9845 // permissions as these are the only ones the platform knows 9846 // how to disable the API to simulate revocation as legacy 9847 // apps don't expect to run with revoked permissions. 9848 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9849 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9850 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9851 // We changed the flags, hence have to write. 9852 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9853 changedRuntimePermissionUserIds, userId); 9854 } 9855 } 9856 if (permissionsState.grantRuntimePermission(bp, userId) 9857 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9858 // We changed the permission, hence have to write. 9859 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9860 changedRuntimePermissionUserIds, userId); 9861 } 9862 } 9863 // Propagate the permission flags. 9864 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9865 } 9866 } break; 9867 9868 case GRANT_UPGRADE: { 9869 // Grant runtime permissions for a previously held install permission. 9870 PermissionState permissionState = origPermissions 9871 .getInstallPermissionState(bp.name); 9872 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9873 9874 if (origPermissions.revokeInstallPermission(bp) 9875 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9876 // We will be transferring the permission flags, so clear them. 9877 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9878 PackageManager.MASK_PERMISSION_FLAGS, 0); 9879 changedInstallPermission = true; 9880 } 9881 9882 // If the permission is not to be promoted to runtime we ignore it and 9883 // also its other flags as they are not applicable to install permissions. 9884 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9885 for (int userId : currentUserIds) { 9886 if (permissionsState.grantRuntimePermission(bp, userId) != 9887 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9888 // Transfer the permission flags. 9889 permissionsState.updatePermissionFlags(bp, userId, 9890 flags, flags); 9891 // If we granted the permission, we have to write. 9892 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9893 changedRuntimePermissionUserIds, userId); 9894 } 9895 } 9896 } 9897 } break; 9898 9899 default: { 9900 if (packageOfInterest == null 9901 || packageOfInterest.equals(pkg.packageName)) { 9902 Slog.w(TAG, "Not granting permission " + perm 9903 + " to package " + pkg.packageName 9904 + " because it was previously installed without"); 9905 } 9906 } break; 9907 } 9908 } else { 9909 if (permissionsState.revokeInstallPermission(bp) != 9910 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9911 // Also drop the permission flags. 9912 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9913 PackageManager.MASK_PERMISSION_FLAGS, 0); 9914 changedInstallPermission = true; 9915 Slog.i(TAG, "Un-granting permission " + perm 9916 + " from package " + pkg.packageName 9917 + " (protectionLevel=" + bp.protectionLevel 9918 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9919 + ")"); 9920 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9921 // Don't print warning for app op permissions, since it is fine for them 9922 // not to be granted, there is a UI for the user to decide. 9923 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9924 Slog.w(TAG, "Not granting permission " + perm 9925 + " to package " + pkg.packageName 9926 + " (protectionLevel=" + bp.protectionLevel 9927 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9928 + ")"); 9929 } 9930 } 9931 } 9932 } 9933 9934 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9935 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9936 // This is the first that we have heard about this package, so the 9937 // permissions we have now selected are fixed until explicitly 9938 // changed. 9939 ps.installPermissionsFixed = true; 9940 } 9941 9942 // Persist the runtime permissions state for users with changes. If permissions 9943 // were revoked because no app in the shared user declares them we have to 9944 // write synchronously to avoid losing runtime permissions state. 9945 for (int userId : changedRuntimePermissionUserIds) { 9946 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9947 } 9948 9949 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9950 } 9951 9952 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9953 boolean allowed = false; 9954 final int NP = PackageParser.NEW_PERMISSIONS.length; 9955 for (int ip=0; ip<NP; ip++) { 9956 final PackageParser.NewPermissionInfo npi 9957 = PackageParser.NEW_PERMISSIONS[ip]; 9958 if (npi.name.equals(perm) 9959 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9960 allowed = true; 9961 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9962 + pkg.packageName); 9963 break; 9964 } 9965 } 9966 return allowed; 9967 } 9968 9969 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9970 BasePermission bp, PermissionsState origPermissions) { 9971 boolean allowed; 9972 allowed = (compareSignatures( 9973 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9974 == PackageManager.SIGNATURE_MATCH) 9975 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9976 == PackageManager.SIGNATURE_MATCH); 9977 if (!allowed && (bp.protectionLevel 9978 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9979 if (isSystemApp(pkg)) { 9980 // For updated system applications, a system permission 9981 // is granted only if it had been defined by the original application. 9982 if (pkg.isUpdatedSystemApp()) { 9983 final PackageSetting sysPs = mSettings 9984 .getDisabledSystemPkgLPr(pkg.packageName); 9985 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9986 // If the original was granted this permission, we take 9987 // that grant decision as read and propagate it to the 9988 // update. 9989 if (sysPs.isPrivileged()) { 9990 allowed = true; 9991 } 9992 } else { 9993 // The system apk may have been updated with an older 9994 // version of the one on the data partition, but which 9995 // granted a new system permission that it didn't have 9996 // before. In this case we do want to allow the app to 9997 // now get the new permission if the ancestral apk is 9998 // privileged to get it. 9999 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10000 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10001 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10002 allowed = true; 10003 break; 10004 } 10005 } 10006 } 10007 // Also if a privileged parent package on the system image or any of 10008 // its children requested a privileged permission, the updated child 10009 // packages can also get the permission. 10010 if (pkg.parentPackage != null) { 10011 final PackageSetting disabledSysParentPs = mSettings 10012 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10013 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10014 && disabledSysParentPs.isPrivileged()) { 10015 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10016 allowed = true; 10017 } else if (disabledSysParentPs.pkg.childPackages != null) { 10018 final int count = disabledSysParentPs.pkg.childPackages.size(); 10019 for (int i = 0; i < count; i++) { 10020 PackageParser.Package disabledSysChildPkg = 10021 disabledSysParentPs.pkg.childPackages.get(i); 10022 if (isPackageRequestingPermission(disabledSysChildPkg, 10023 perm)) { 10024 allowed = true; 10025 break; 10026 } 10027 } 10028 } 10029 } 10030 } 10031 } 10032 } else { 10033 allowed = isPrivilegedApp(pkg); 10034 } 10035 } 10036 } 10037 if (!allowed) { 10038 if (!allowed && (bp.protectionLevel 10039 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10040 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10041 // If this was a previously normal/dangerous permission that got moved 10042 // to a system permission as part of the runtime permission redesign, then 10043 // we still want to blindly grant it to old apps. 10044 allowed = true; 10045 } 10046 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10047 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10048 // If this permission is to be granted to the system installer and 10049 // this app is an installer, then it gets the permission. 10050 allowed = true; 10051 } 10052 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10053 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10054 // If this permission is to be granted to the system verifier and 10055 // this app is a verifier, then it gets the permission. 10056 allowed = true; 10057 } 10058 if (!allowed && (bp.protectionLevel 10059 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10060 && isSystemApp(pkg)) { 10061 // Any pre-installed system app is allowed to get this permission. 10062 allowed = true; 10063 } 10064 if (!allowed && (bp.protectionLevel 10065 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10066 // For development permissions, a development permission 10067 // is granted only if it was already granted. 10068 allowed = origPermissions.hasInstallPermission(perm); 10069 } 10070 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10071 && pkg.packageName.equals(mSetupWizardPackage)) { 10072 // If this permission is to be granted to the system setup wizard and 10073 // this app is a setup wizard, then it gets the permission. 10074 allowed = true; 10075 } 10076 } 10077 return allowed; 10078 } 10079 10080 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10081 final int permCount = pkg.requestedPermissions.size(); 10082 for (int j = 0; j < permCount; j++) { 10083 String requestedPermission = pkg.requestedPermissions.get(j); 10084 if (permission.equals(requestedPermission)) { 10085 return true; 10086 } 10087 } 10088 return false; 10089 } 10090 10091 final class ActivityIntentResolver 10092 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10093 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10094 boolean defaultOnly, int userId) { 10095 if (!sUserManager.exists(userId)) return null; 10096 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10097 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10098 } 10099 10100 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10101 int userId) { 10102 if (!sUserManager.exists(userId)) return null; 10103 mFlags = flags; 10104 return super.queryIntent(intent, resolvedType, 10105 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10106 } 10107 10108 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10109 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10110 if (!sUserManager.exists(userId)) return null; 10111 if (packageActivities == null) { 10112 return null; 10113 } 10114 mFlags = flags; 10115 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10116 final int N = packageActivities.size(); 10117 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10118 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10119 10120 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10121 for (int i = 0; i < N; ++i) { 10122 intentFilters = packageActivities.get(i).intents; 10123 if (intentFilters != null && intentFilters.size() > 0) { 10124 PackageParser.ActivityIntentInfo[] array = 10125 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10126 intentFilters.toArray(array); 10127 listCut.add(array); 10128 } 10129 } 10130 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10131 } 10132 10133 /** 10134 * Finds a privileged activity that matches the specified activity names. 10135 */ 10136 private PackageParser.Activity findMatchingActivity( 10137 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10138 for (PackageParser.Activity sysActivity : activityList) { 10139 if (sysActivity.info.name.equals(activityInfo.name)) { 10140 return sysActivity; 10141 } 10142 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10143 return sysActivity; 10144 } 10145 if (sysActivity.info.targetActivity != null) { 10146 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10147 return sysActivity; 10148 } 10149 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10150 return sysActivity; 10151 } 10152 } 10153 } 10154 return null; 10155 } 10156 10157 public class IterGenerator<E> { 10158 public Iterator<E> generate(ActivityIntentInfo info) { 10159 return null; 10160 } 10161 } 10162 10163 public class ActionIterGenerator extends IterGenerator<String> { 10164 @Override 10165 public Iterator<String> generate(ActivityIntentInfo info) { 10166 return info.actionsIterator(); 10167 } 10168 } 10169 10170 public class CategoriesIterGenerator extends IterGenerator<String> { 10171 @Override 10172 public Iterator<String> generate(ActivityIntentInfo info) { 10173 return info.categoriesIterator(); 10174 } 10175 } 10176 10177 public class SchemesIterGenerator extends IterGenerator<String> { 10178 @Override 10179 public Iterator<String> generate(ActivityIntentInfo info) { 10180 return info.schemesIterator(); 10181 } 10182 } 10183 10184 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10185 @Override 10186 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10187 return info.authoritiesIterator(); 10188 } 10189 } 10190 10191 /** 10192 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10193 * MODIFIED. Do not pass in a list that should not be changed. 10194 */ 10195 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10196 IterGenerator<T> generator, Iterator<T> searchIterator) { 10197 // loop through the set of actions; every one must be found in the intent filter 10198 while (searchIterator.hasNext()) { 10199 // we must have at least one filter in the list to consider a match 10200 if (intentList.size() == 0) { 10201 break; 10202 } 10203 10204 final T searchAction = searchIterator.next(); 10205 10206 // loop through the set of intent filters 10207 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10208 while (intentIter.hasNext()) { 10209 final ActivityIntentInfo intentInfo = intentIter.next(); 10210 boolean selectionFound = false; 10211 10212 // loop through the intent filter's selection criteria; at least one 10213 // of them must match the searched criteria 10214 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10215 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10216 final T intentSelection = intentSelectionIter.next(); 10217 if (intentSelection != null && intentSelection.equals(searchAction)) { 10218 selectionFound = true; 10219 break; 10220 } 10221 } 10222 10223 // the selection criteria wasn't found in this filter's set; this filter 10224 // is not a potential match 10225 if (!selectionFound) { 10226 intentIter.remove(); 10227 } 10228 } 10229 } 10230 } 10231 10232 private boolean isProtectedAction(ActivityIntentInfo filter) { 10233 final Iterator<String> actionsIter = filter.actionsIterator(); 10234 while (actionsIter != null && actionsIter.hasNext()) { 10235 final String filterAction = actionsIter.next(); 10236 if (PROTECTED_ACTIONS.contains(filterAction)) { 10237 return true; 10238 } 10239 } 10240 return false; 10241 } 10242 10243 /** 10244 * Adjusts the priority of the given intent filter according to policy. 10245 * <p> 10246 * <ul> 10247 * <li>The priority for non privileged applications is capped to '0'</li> 10248 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10249 * <li>The priority for unbundled updates to privileged applications is capped to the 10250 * priority defined on the system partition</li> 10251 * </ul> 10252 * <p> 10253 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10254 * allowed to obtain any priority on any action. 10255 */ 10256 private void adjustPriority( 10257 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10258 // nothing to do; priority is fine as-is 10259 if (intent.getPriority() <= 0) { 10260 return; 10261 } 10262 10263 final ActivityInfo activityInfo = intent.activity.info; 10264 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10265 10266 final boolean privilegedApp = 10267 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10268 if (!privilegedApp) { 10269 // non-privileged applications can never define a priority >0 10270 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10271 + " package: " + applicationInfo.packageName 10272 + " activity: " + intent.activity.className 10273 + " origPrio: " + intent.getPriority()); 10274 intent.setPriority(0); 10275 return; 10276 } 10277 10278 if (systemActivities == null) { 10279 // the system package is not disabled; we're parsing the system partition 10280 if (isProtectedAction(intent)) { 10281 if (mDeferProtectedFilters) { 10282 // We can't deal with these just yet. No component should ever obtain a 10283 // >0 priority for a protected actions, with ONE exception -- the setup 10284 // wizard. The setup wizard, however, cannot be known until we're able to 10285 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10286 // until all intent filters have been processed. Chicken, meet egg. 10287 // Let the filter temporarily have a high priority and rectify the 10288 // priorities after all system packages have been scanned. 10289 mProtectedFilters.add(intent); 10290 if (DEBUG_FILTERS) { 10291 Slog.i(TAG, "Protected action; save for later;" 10292 + " package: " + applicationInfo.packageName 10293 + " activity: " + intent.activity.className 10294 + " origPrio: " + intent.getPriority()); 10295 } 10296 return; 10297 } else { 10298 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10299 Slog.i(TAG, "No setup wizard;" 10300 + " All protected intents capped to priority 0"); 10301 } 10302 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10303 if (DEBUG_FILTERS) { 10304 Slog.i(TAG, "Found setup wizard;" 10305 + " allow priority " + intent.getPriority() + ";" 10306 + " package: " + intent.activity.info.packageName 10307 + " activity: " + intent.activity.className 10308 + " priority: " + intent.getPriority()); 10309 } 10310 // setup wizard gets whatever it wants 10311 return; 10312 } 10313 Slog.w(TAG, "Protected action; cap priority to 0;" 10314 + " package: " + intent.activity.info.packageName 10315 + " activity: " + intent.activity.className 10316 + " origPrio: " + intent.getPriority()); 10317 intent.setPriority(0); 10318 return; 10319 } 10320 } 10321 // privileged apps on the system image get whatever priority they request 10322 return; 10323 } 10324 10325 // privileged app unbundled update ... try to find the same activity 10326 final PackageParser.Activity foundActivity = 10327 findMatchingActivity(systemActivities, activityInfo); 10328 if (foundActivity == null) { 10329 // this is a new activity; it cannot obtain >0 priority 10330 if (DEBUG_FILTERS) { 10331 Slog.i(TAG, "New activity; cap priority to 0;" 10332 + " package: " + applicationInfo.packageName 10333 + " activity: " + intent.activity.className 10334 + " origPrio: " + intent.getPriority()); 10335 } 10336 intent.setPriority(0); 10337 return; 10338 } 10339 10340 // found activity, now check for filter equivalence 10341 10342 // a shallow copy is enough; we modify the list, not its contents 10343 final List<ActivityIntentInfo> intentListCopy = 10344 new ArrayList<>(foundActivity.intents); 10345 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10346 10347 // find matching action subsets 10348 final Iterator<String> actionsIterator = intent.actionsIterator(); 10349 if (actionsIterator != null) { 10350 getIntentListSubset( 10351 intentListCopy, new ActionIterGenerator(), actionsIterator); 10352 if (intentListCopy.size() == 0) { 10353 // no more intents to match; we're not equivalent 10354 if (DEBUG_FILTERS) { 10355 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10356 + " package: " + applicationInfo.packageName 10357 + " activity: " + intent.activity.className 10358 + " origPrio: " + intent.getPriority()); 10359 } 10360 intent.setPriority(0); 10361 return; 10362 } 10363 } 10364 10365 // find matching category subsets 10366 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10367 if (categoriesIterator != null) { 10368 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10369 categoriesIterator); 10370 if (intentListCopy.size() == 0) { 10371 // no more intents to match; we're not equivalent 10372 if (DEBUG_FILTERS) { 10373 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10374 + " package: " + applicationInfo.packageName 10375 + " activity: " + intent.activity.className 10376 + " origPrio: " + intent.getPriority()); 10377 } 10378 intent.setPriority(0); 10379 return; 10380 } 10381 } 10382 10383 // find matching schemes subsets 10384 final Iterator<String> schemesIterator = intent.schemesIterator(); 10385 if (schemesIterator != null) { 10386 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10387 schemesIterator); 10388 if (intentListCopy.size() == 0) { 10389 // no more intents to match; we're not equivalent 10390 if (DEBUG_FILTERS) { 10391 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10392 + " package: " + applicationInfo.packageName 10393 + " activity: " + intent.activity.className 10394 + " origPrio: " + intent.getPriority()); 10395 } 10396 intent.setPriority(0); 10397 return; 10398 } 10399 } 10400 10401 // find matching authorities subsets 10402 final Iterator<IntentFilter.AuthorityEntry> 10403 authoritiesIterator = intent.authoritiesIterator(); 10404 if (authoritiesIterator != null) { 10405 getIntentListSubset(intentListCopy, 10406 new AuthoritiesIterGenerator(), 10407 authoritiesIterator); 10408 if (intentListCopy.size() == 0) { 10409 // no more intents to match; we're not equivalent 10410 if (DEBUG_FILTERS) { 10411 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10412 + " package: " + applicationInfo.packageName 10413 + " activity: " + intent.activity.className 10414 + " origPrio: " + intent.getPriority()); 10415 } 10416 intent.setPriority(0); 10417 return; 10418 } 10419 } 10420 10421 // we found matching filter(s); app gets the max priority of all intents 10422 int cappedPriority = 0; 10423 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10424 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10425 } 10426 if (intent.getPriority() > cappedPriority) { 10427 if (DEBUG_FILTERS) { 10428 Slog.i(TAG, "Found matching filter(s);" 10429 + " cap priority to " + cappedPriority + ";" 10430 + " package: " + applicationInfo.packageName 10431 + " activity: " + intent.activity.className 10432 + " origPrio: " + intent.getPriority()); 10433 } 10434 intent.setPriority(cappedPriority); 10435 return; 10436 } 10437 // all this for nothing; the requested priority was <= what was on the system 10438 } 10439 10440 public final void addActivity(PackageParser.Activity a, String type) { 10441 mActivities.put(a.getComponentName(), a); 10442 if (DEBUG_SHOW_INFO) 10443 Log.v( 10444 TAG, " " + type + " " + 10445 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10446 if (DEBUG_SHOW_INFO) 10447 Log.v(TAG, " Class=" + a.info.name); 10448 final int NI = a.intents.size(); 10449 for (int j=0; j<NI; j++) { 10450 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10451 if ("activity".equals(type)) { 10452 final PackageSetting ps = 10453 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10454 final List<PackageParser.Activity> systemActivities = 10455 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10456 adjustPriority(systemActivities, intent); 10457 } 10458 if (DEBUG_SHOW_INFO) { 10459 Log.v(TAG, " IntentFilter:"); 10460 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10461 } 10462 if (!intent.debugCheck()) { 10463 Log.w(TAG, "==> For Activity " + a.info.name); 10464 } 10465 addFilter(intent); 10466 } 10467 } 10468 10469 public final void removeActivity(PackageParser.Activity a, String type) { 10470 mActivities.remove(a.getComponentName()); 10471 if (DEBUG_SHOW_INFO) { 10472 Log.v(TAG, " " + type + " " 10473 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10474 : a.info.name) + ":"); 10475 Log.v(TAG, " Class=" + a.info.name); 10476 } 10477 final int NI = a.intents.size(); 10478 for (int j=0; j<NI; j++) { 10479 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10480 if (DEBUG_SHOW_INFO) { 10481 Log.v(TAG, " IntentFilter:"); 10482 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10483 } 10484 removeFilter(intent); 10485 } 10486 } 10487 10488 @Override 10489 protected boolean allowFilterResult( 10490 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10491 ActivityInfo filterAi = filter.activity.info; 10492 for (int i=dest.size()-1; i>=0; i--) { 10493 ActivityInfo destAi = dest.get(i).activityInfo; 10494 if (destAi.name == filterAi.name 10495 && destAi.packageName == filterAi.packageName) { 10496 return false; 10497 } 10498 } 10499 return true; 10500 } 10501 10502 @Override 10503 protected ActivityIntentInfo[] newArray(int size) { 10504 return new ActivityIntentInfo[size]; 10505 } 10506 10507 @Override 10508 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10509 if (!sUserManager.exists(userId)) return true; 10510 PackageParser.Package p = filter.activity.owner; 10511 if (p != null) { 10512 PackageSetting ps = (PackageSetting)p.mExtras; 10513 if (ps != null) { 10514 // System apps are never considered stopped for purposes of 10515 // filtering, because there may be no way for the user to 10516 // actually re-launch them. 10517 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10518 && ps.getStopped(userId); 10519 } 10520 } 10521 return false; 10522 } 10523 10524 @Override 10525 protected boolean isPackageForFilter(String packageName, 10526 PackageParser.ActivityIntentInfo info) { 10527 return packageName.equals(info.activity.owner.packageName); 10528 } 10529 10530 @Override 10531 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10532 int match, int userId) { 10533 if (!sUserManager.exists(userId)) return null; 10534 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10535 return null; 10536 } 10537 final PackageParser.Activity activity = info.activity; 10538 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10539 if (ps == null) { 10540 return null; 10541 } 10542 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10543 ps.readUserState(userId), userId); 10544 if (ai == null) { 10545 return null; 10546 } 10547 final ResolveInfo res = new ResolveInfo(); 10548 res.activityInfo = ai; 10549 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10550 res.filter = info; 10551 } 10552 if (info != null) { 10553 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10554 } 10555 res.priority = info.getPriority(); 10556 res.preferredOrder = activity.owner.mPreferredOrder; 10557 //System.out.println("Result: " + res.activityInfo.className + 10558 // " = " + res.priority); 10559 res.match = match; 10560 res.isDefault = info.hasDefault; 10561 res.labelRes = info.labelRes; 10562 res.nonLocalizedLabel = info.nonLocalizedLabel; 10563 if (userNeedsBadging(userId)) { 10564 res.noResourceId = true; 10565 } else { 10566 res.icon = info.icon; 10567 } 10568 res.iconResourceId = info.icon; 10569 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10570 return res; 10571 } 10572 10573 @Override 10574 protected void sortResults(List<ResolveInfo> results) { 10575 Collections.sort(results, mResolvePrioritySorter); 10576 } 10577 10578 @Override 10579 protected void dumpFilter(PrintWriter out, String prefix, 10580 PackageParser.ActivityIntentInfo filter) { 10581 out.print(prefix); out.print( 10582 Integer.toHexString(System.identityHashCode(filter.activity))); 10583 out.print(' '); 10584 filter.activity.printComponentShortName(out); 10585 out.print(" filter "); 10586 out.println(Integer.toHexString(System.identityHashCode(filter))); 10587 } 10588 10589 @Override 10590 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10591 return filter.activity; 10592 } 10593 10594 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10595 PackageParser.Activity activity = (PackageParser.Activity)label; 10596 out.print(prefix); out.print( 10597 Integer.toHexString(System.identityHashCode(activity))); 10598 out.print(' '); 10599 activity.printComponentShortName(out); 10600 if (count > 1) { 10601 out.print(" ("); out.print(count); out.print(" filters)"); 10602 } 10603 out.println(); 10604 } 10605 10606 // Keys are String (activity class name), values are Activity. 10607 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10608 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10609 private int mFlags; 10610 } 10611 10612 private final class ServiceIntentResolver 10613 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10614 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10615 boolean defaultOnly, int userId) { 10616 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10617 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10618 } 10619 10620 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10621 int userId) { 10622 if (!sUserManager.exists(userId)) return null; 10623 mFlags = flags; 10624 return super.queryIntent(intent, resolvedType, 10625 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10626 } 10627 10628 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10629 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10630 if (!sUserManager.exists(userId)) return null; 10631 if (packageServices == null) { 10632 return null; 10633 } 10634 mFlags = flags; 10635 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10636 final int N = packageServices.size(); 10637 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10638 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10639 10640 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10641 for (int i = 0; i < N; ++i) { 10642 intentFilters = packageServices.get(i).intents; 10643 if (intentFilters != null && intentFilters.size() > 0) { 10644 PackageParser.ServiceIntentInfo[] array = 10645 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10646 intentFilters.toArray(array); 10647 listCut.add(array); 10648 } 10649 } 10650 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10651 } 10652 10653 public final void addService(PackageParser.Service s) { 10654 mServices.put(s.getComponentName(), s); 10655 if (DEBUG_SHOW_INFO) { 10656 Log.v(TAG, " " 10657 + (s.info.nonLocalizedLabel != null 10658 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10659 Log.v(TAG, " Class=" + s.info.name); 10660 } 10661 final int NI = s.intents.size(); 10662 int j; 10663 for (j=0; j<NI; j++) { 10664 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10665 if (DEBUG_SHOW_INFO) { 10666 Log.v(TAG, " IntentFilter:"); 10667 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10668 } 10669 if (!intent.debugCheck()) { 10670 Log.w(TAG, "==> For Service " + s.info.name); 10671 } 10672 addFilter(intent); 10673 } 10674 } 10675 10676 public final void removeService(PackageParser.Service s) { 10677 mServices.remove(s.getComponentName()); 10678 if (DEBUG_SHOW_INFO) { 10679 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10680 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10681 Log.v(TAG, " Class=" + s.info.name); 10682 } 10683 final int NI = s.intents.size(); 10684 int j; 10685 for (j=0; j<NI; j++) { 10686 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10687 if (DEBUG_SHOW_INFO) { 10688 Log.v(TAG, " IntentFilter:"); 10689 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10690 } 10691 removeFilter(intent); 10692 } 10693 } 10694 10695 @Override 10696 protected boolean allowFilterResult( 10697 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10698 ServiceInfo filterSi = filter.service.info; 10699 for (int i=dest.size()-1; i>=0; i--) { 10700 ServiceInfo destAi = dest.get(i).serviceInfo; 10701 if (destAi.name == filterSi.name 10702 && destAi.packageName == filterSi.packageName) { 10703 return false; 10704 } 10705 } 10706 return true; 10707 } 10708 10709 @Override 10710 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10711 return new PackageParser.ServiceIntentInfo[size]; 10712 } 10713 10714 @Override 10715 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10716 if (!sUserManager.exists(userId)) return true; 10717 PackageParser.Package p = filter.service.owner; 10718 if (p != null) { 10719 PackageSetting ps = (PackageSetting)p.mExtras; 10720 if (ps != null) { 10721 // System apps are never considered stopped for purposes of 10722 // filtering, because there may be no way for the user to 10723 // actually re-launch them. 10724 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10725 && ps.getStopped(userId); 10726 } 10727 } 10728 return false; 10729 } 10730 10731 @Override 10732 protected boolean isPackageForFilter(String packageName, 10733 PackageParser.ServiceIntentInfo info) { 10734 return packageName.equals(info.service.owner.packageName); 10735 } 10736 10737 @Override 10738 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10739 int match, int userId) { 10740 if (!sUserManager.exists(userId)) return null; 10741 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10742 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10743 return null; 10744 } 10745 final PackageParser.Service service = info.service; 10746 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10747 if (ps == null) { 10748 return null; 10749 } 10750 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10751 ps.readUserState(userId), userId); 10752 if (si == null) { 10753 return null; 10754 } 10755 final ResolveInfo res = new ResolveInfo(); 10756 res.serviceInfo = si; 10757 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10758 res.filter = filter; 10759 } 10760 res.priority = info.getPriority(); 10761 res.preferredOrder = service.owner.mPreferredOrder; 10762 res.match = match; 10763 res.isDefault = info.hasDefault; 10764 res.labelRes = info.labelRes; 10765 res.nonLocalizedLabel = info.nonLocalizedLabel; 10766 res.icon = info.icon; 10767 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10768 return res; 10769 } 10770 10771 @Override 10772 protected void sortResults(List<ResolveInfo> results) { 10773 Collections.sort(results, mResolvePrioritySorter); 10774 } 10775 10776 @Override 10777 protected void dumpFilter(PrintWriter out, String prefix, 10778 PackageParser.ServiceIntentInfo filter) { 10779 out.print(prefix); out.print( 10780 Integer.toHexString(System.identityHashCode(filter.service))); 10781 out.print(' '); 10782 filter.service.printComponentShortName(out); 10783 out.print(" filter "); 10784 out.println(Integer.toHexString(System.identityHashCode(filter))); 10785 } 10786 10787 @Override 10788 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10789 return filter.service; 10790 } 10791 10792 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10793 PackageParser.Service service = (PackageParser.Service)label; 10794 out.print(prefix); out.print( 10795 Integer.toHexString(System.identityHashCode(service))); 10796 out.print(' '); 10797 service.printComponentShortName(out); 10798 if (count > 1) { 10799 out.print(" ("); out.print(count); out.print(" filters)"); 10800 } 10801 out.println(); 10802 } 10803 10804// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10805// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10806// final List<ResolveInfo> retList = Lists.newArrayList(); 10807// while (i.hasNext()) { 10808// final ResolveInfo resolveInfo = (ResolveInfo) i; 10809// if (isEnabledLP(resolveInfo.serviceInfo)) { 10810// retList.add(resolveInfo); 10811// } 10812// } 10813// return retList; 10814// } 10815 10816 // Keys are String (activity class name), values are Activity. 10817 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10818 = new ArrayMap<ComponentName, PackageParser.Service>(); 10819 private int mFlags; 10820 }; 10821 10822 private final class ProviderIntentResolver 10823 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10824 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10825 boolean defaultOnly, int userId) { 10826 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10827 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10828 } 10829 10830 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10831 int userId) { 10832 if (!sUserManager.exists(userId)) 10833 return null; 10834 mFlags = flags; 10835 return super.queryIntent(intent, resolvedType, 10836 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10837 } 10838 10839 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10840 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10841 if (!sUserManager.exists(userId)) 10842 return null; 10843 if (packageProviders == null) { 10844 return null; 10845 } 10846 mFlags = flags; 10847 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10848 final int N = packageProviders.size(); 10849 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10850 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10851 10852 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10853 for (int i = 0; i < N; ++i) { 10854 intentFilters = packageProviders.get(i).intents; 10855 if (intentFilters != null && intentFilters.size() > 0) { 10856 PackageParser.ProviderIntentInfo[] array = 10857 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10858 intentFilters.toArray(array); 10859 listCut.add(array); 10860 } 10861 } 10862 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10863 } 10864 10865 public final void addProvider(PackageParser.Provider p) { 10866 if (mProviders.containsKey(p.getComponentName())) { 10867 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10868 return; 10869 } 10870 10871 mProviders.put(p.getComponentName(), p); 10872 if (DEBUG_SHOW_INFO) { 10873 Log.v(TAG, " " 10874 + (p.info.nonLocalizedLabel != null 10875 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10876 Log.v(TAG, " Class=" + p.info.name); 10877 } 10878 final int NI = p.intents.size(); 10879 int j; 10880 for (j = 0; j < NI; j++) { 10881 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10882 if (DEBUG_SHOW_INFO) { 10883 Log.v(TAG, " IntentFilter:"); 10884 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10885 } 10886 if (!intent.debugCheck()) { 10887 Log.w(TAG, "==> For Provider " + p.info.name); 10888 } 10889 addFilter(intent); 10890 } 10891 } 10892 10893 public final void removeProvider(PackageParser.Provider p) { 10894 mProviders.remove(p.getComponentName()); 10895 if (DEBUG_SHOW_INFO) { 10896 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10897 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10898 Log.v(TAG, " Class=" + p.info.name); 10899 } 10900 final int NI = p.intents.size(); 10901 int j; 10902 for (j = 0; j < NI; j++) { 10903 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10904 if (DEBUG_SHOW_INFO) { 10905 Log.v(TAG, " IntentFilter:"); 10906 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10907 } 10908 removeFilter(intent); 10909 } 10910 } 10911 10912 @Override 10913 protected boolean allowFilterResult( 10914 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10915 ProviderInfo filterPi = filter.provider.info; 10916 for (int i = dest.size() - 1; i >= 0; i--) { 10917 ProviderInfo destPi = dest.get(i).providerInfo; 10918 if (destPi.name == filterPi.name 10919 && destPi.packageName == filterPi.packageName) { 10920 return false; 10921 } 10922 } 10923 return true; 10924 } 10925 10926 @Override 10927 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10928 return new PackageParser.ProviderIntentInfo[size]; 10929 } 10930 10931 @Override 10932 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10933 if (!sUserManager.exists(userId)) 10934 return true; 10935 PackageParser.Package p = filter.provider.owner; 10936 if (p != null) { 10937 PackageSetting ps = (PackageSetting) p.mExtras; 10938 if (ps != null) { 10939 // System apps are never considered stopped for purposes of 10940 // filtering, because there may be no way for the user to 10941 // actually re-launch them. 10942 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10943 && ps.getStopped(userId); 10944 } 10945 } 10946 return false; 10947 } 10948 10949 @Override 10950 protected boolean isPackageForFilter(String packageName, 10951 PackageParser.ProviderIntentInfo info) { 10952 return packageName.equals(info.provider.owner.packageName); 10953 } 10954 10955 @Override 10956 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10957 int match, int userId) { 10958 if (!sUserManager.exists(userId)) 10959 return null; 10960 final PackageParser.ProviderIntentInfo info = filter; 10961 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10962 return null; 10963 } 10964 final PackageParser.Provider provider = info.provider; 10965 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10966 if (ps == null) { 10967 return null; 10968 } 10969 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10970 ps.readUserState(userId), userId); 10971 if (pi == null) { 10972 return null; 10973 } 10974 final ResolveInfo res = new ResolveInfo(); 10975 res.providerInfo = pi; 10976 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10977 res.filter = filter; 10978 } 10979 res.priority = info.getPriority(); 10980 res.preferredOrder = provider.owner.mPreferredOrder; 10981 res.match = match; 10982 res.isDefault = info.hasDefault; 10983 res.labelRes = info.labelRes; 10984 res.nonLocalizedLabel = info.nonLocalizedLabel; 10985 res.icon = info.icon; 10986 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10987 return res; 10988 } 10989 10990 @Override 10991 protected void sortResults(List<ResolveInfo> results) { 10992 Collections.sort(results, mResolvePrioritySorter); 10993 } 10994 10995 @Override 10996 protected void dumpFilter(PrintWriter out, String prefix, 10997 PackageParser.ProviderIntentInfo filter) { 10998 out.print(prefix); 10999 out.print( 11000 Integer.toHexString(System.identityHashCode(filter.provider))); 11001 out.print(' '); 11002 filter.provider.printComponentShortName(out); 11003 out.print(" filter "); 11004 out.println(Integer.toHexString(System.identityHashCode(filter))); 11005 } 11006 11007 @Override 11008 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11009 return filter.provider; 11010 } 11011 11012 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11013 PackageParser.Provider provider = (PackageParser.Provider)label; 11014 out.print(prefix); out.print( 11015 Integer.toHexString(System.identityHashCode(provider))); 11016 out.print(' '); 11017 provider.printComponentShortName(out); 11018 if (count > 1) { 11019 out.print(" ("); out.print(count); out.print(" filters)"); 11020 } 11021 out.println(); 11022 } 11023 11024 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11025 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11026 private int mFlags; 11027 } 11028 11029 private static final class EphemeralIntentResolver 11030 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11031 @Override 11032 protected EphemeralResolveIntentInfo[] newArray(int size) { 11033 return new EphemeralResolveIntentInfo[size]; 11034 } 11035 11036 @Override 11037 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11038 return true; 11039 } 11040 11041 @Override 11042 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11043 int userId) { 11044 if (!sUserManager.exists(userId)) { 11045 return null; 11046 } 11047 return info.getEphemeralResolveInfo(); 11048 } 11049 } 11050 11051 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11052 new Comparator<ResolveInfo>() { 11053 public int compare(ResolveInfo r1, ResolveInfo r2) { 11054 int v1 = r1.priority; 11055 int v2 = r2.priority; 11056 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11057 if (v1 != v2) { 11058 return (v1 > v2) ? -1 : 1; 11059 } 11060 v1 = r1.preferredOrder; 11061 v2 = r2.preferredOrder; 11062 if (v1 != v2) { 11063 return (v1 > v2) ? -1 : 1; 11064 } 11065 if (r1.isDefault != r2.isDefault) { 11066 return r1.isDefault ? -1 : 1; 11067 } 11068 v1 = r1.match; 11069 v2 = r2.match; 11070 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11071 if (v1 != v2) { 11072 return (v1 > v2) ? -1 : 1; 11073 } 11074 if (r1.system != r2.system) { 11075 return r1.system ? -1 : 1; 11076 } 11077 if (r1.activityInfo != null) { 11078 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11079 } 11080 if (r1.serviceInfo != null) { 11081 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11082 } 11083 if (r1.providerInfo != null) { 11084 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11085 } 11086 return 0; 11087 } 11088 }; 11089 11090 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11091 new Comparator<ProviderInfo>() { 11092 public int compare(ProviderInfo p1, ProviderInfo p2) { 11093 final int v1 = p1.initOrder; 11094 final int v2 = p2.initOrder; 11095 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11096 } 11097 }; 11098 11099 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11100 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11101 final int[] userIds) { 11102 mHandler.post(new Runnable() { 11103 @Override 11104 public void run() { 11105 try { 11106 final IActivityManager am = ActivityManagerNative.getDefault(); 11107 if (am == null) return; 11108 final int[] resolvedUserIds; 11109 if (userIds == null) { 11110 resolvedUserIds = am.getRunningUserIds(); 11111 } else { 11112 resolvedUserIds = userIds; 11113 } 11114 for (int id : resolvedUserIds) { 11115 final Intent intent = new Intent(action, 11116 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11117 if (extras != null) { 11118 intent.putExtras(extras); 11119 } 11120 if (targetPkg != null) { 11121 intent.setPackage(targetPkg); 11122 } 11123 // Modify the UID when posting to other users 11124 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11125 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11126 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11127 intent.putExtra(Intent.EXTRA_UID, uid); 11128 } 11129 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11130 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11131 if (DEBUG_BROADCASTS) { 11132 RuntimeException here = new RuntimeException("here"); 11133 here.fillInStackTrace(); 11134 Slog.d(TAG, "Sending to user " + id + ": " 11135 + intent.toShortString(false, true, false, false) 11136 + " " + intent.getExtras(), here); 11137 } 11138 am.broadcastIntent(null, intent, null, finishedReceiver, 11139 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11140 null, finishedReceiver != null, false, id); 11141 } 11142 } catch (RemoteException ex) { 11143 } 11144 } 11145 }); 11146 } 11147 11148 /** 11149 * Check if the external storage media is available. This is true if there 11150 * is a mounted external storage medium or if the external storage is 11151 * emulated. 11152 */ 11153 private boolean isExternalMediaAvailable() { 11154 return mMediaMounted || Environment.isExternalStorageEmulated(); 11155 } 11156 11157 @Override 11158 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11159 // writer 11160 synchronized (mPackages) { 11161 if (!isExternalMediaAvailable()) { 11162 // If the external storage is no longer mounted at this point, 11163 // the caller may not have been able to delete all of this 11164 // packages files and can not delete any more. Bail. 11165 return null; 11166 } 11167 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11168 if (lastPackage != null) { 11169 pkgs.remove(lastPackage); 11170 } 11171 if (pkgs.size() > 0) { 11172 return pkgs.get(0); 11173 } 11174 } 11175 return null; 11176 } 11177 11178 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11179 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11180 userId, andCode ? 1 : 0, packageName); 11181 if (mSystemReady) { 11182 msg.sendToTarget(); 11183 } else { 11184 if (mPostSystemReadyMessages == null) { 11185 mPostSystemReadyMessages = new ArrayList<>(); 11186 } 11187 mPostSystemReadyMessages.add(msg); 11188 } 11189 } 11190 11191 void startCleaningPackages() { 11192 // reader 11193 if (!isExternalMediaAvailable()) { 11194 return; 11195 } 11196 synchronized (mPackages) { 11197 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11198 return; 11199 } 11200 } 11201 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11202 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11203 IActivityManager am = ActivityManagerNative.getDefault(); 11204 if (am != null) { 11205 try { 11206 am.startService(null, intent, null, mContext.getOpPackageName(), 11207 UserHandle.USER_SYSTEM); 11208 } catch (RemoteException e) { 11209 } 11210 } 11211 } 11212 11213 @Override 11214 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11215 int installFlags, String installerPackageName, int userId) { 11216 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11217 11218 final int callingUid = Binder.getCallingUid(); 11219 enforceCrossUserPermission(callingUid, userId, 11220 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11221 11222 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11223 try { 11224 if (observer != null) { 11225 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11226 } 11227 } catch (RemoteException re) { 11228 } 11229 return; 11230 } 11231 11232 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11233 installFlags |= PackageManager.INSTALL_FROM_ADB; 11234 11235 } else { 11236 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11237 // about installerPackageName. 11238 11239 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11240 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11241 } 11242 11243 UserHandle user; 11244 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11245 user = UserHandle.ALL; 11246 } else { 11247 user = new UserHandle(userId); 11248 } 11249 11250 // Only system components can circumvent runtime permissions when installing. 11251 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11252 && mContext.checkCallingOrSelfPermission(Manifest.permission 11253 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11254 throw new SecurityException("You need the " 11255 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11256 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11257 } 11258 11259 final File originFile = new File(originPath); 11260 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11261 11262 final Message msg = mHandler.obtainMessage(INIT_COPY); 11263 final VerificationInfo verificationInfo = new VerificationInfo( 11264 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11265 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11266 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11267 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11268 null /*certificates*/); 11269 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11270 msg.obj = params; 11271 11272 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11273 System.identityHashCode(msg.obj)); 11274 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11275 System.identityHashCode(msg.obj)); 11276 11277 mHandler.sendMessage(msg); 11278 } 11279 11280 void installStage(String packageName, File stagedDir, String stagedCid, 11281 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11282 String installerPackageName, int installerUid, UserHandle user, 11283 Certificate[][] certificates) { 11284 if (DEBUG_EPHEMERAL) { 11285 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11286 Slog.d(TAG, "Ephemeral install of " + packageName); 11287 } 11288 } 11289 final VerificationInfo verificationInfo = new VerificationInfo( 11290 sessionParams.originatingUri, sessionParams.referrerUri, 11291 sessionParams.originatingUid, installerUid); 11292 11293 final OriginInfo origin; 11294 if (stagedDir != null) { 11295 origin = OriginInfo.fromStagedFile(stagedDir); 11296 } else { 11297 origin = OriginInfo.fromStagedContainer(stagedCid); 11298 } 11299 11300 final Message msg = mHandler.obtainMessage(INIT_COPY); 11301 final InstallParams params = new InstallParams(origin, null, observer, 11302 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11303 verificationInfo, user, sessionParams.abiOverride, 11304 sessionParams.grantedRuntimePermissions, certificates); 11305 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11306 msg.obj = params; 11307 11308 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11309 System.identityHashCode(msg.obj)); 11310 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11311 System.identityHashCode(msg.obj)); 11312 11313 mHandler.sendMessage(msg); 11314 } 11315 11316 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11317 int userId) { 11318 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11319 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11320 } 11321 11322 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11323 int appId, int userId) { 11324 Bundle extras = new Bundle(1); 11325 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11326 11327 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11328 packageName, extras, 0, null, null, new int[] {userId}); 11329 try { 11330 IActivityManager am = ActivityManagerNative.getDefault(); 11331 if (isSystem && am.isUserRunning(userId, 0)) { 11332 // The just-installed/enabled app is bundled on the system, so presumed 11333 // to be able to run automatically without needing an explicit launch. 11334 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11335 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11336 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11337 .setPackage(packageName); 11338 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11339 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11340 } 11341 } catch (RemoteException e) { 11342 // shouldn't happen 11343 Slog.w(TAG, "Unable to bootstrap installed package", e); 11344 } 11345 } 11346 11347 @Override 11348 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11349 int userId) { 11350 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11351 PackageSetting pkgSetting; 11352 final int uid = Binder.getCallingUid(); 11353 enforceCrossUserPermission(uid, userId, 11354 true /* requireFullPermission */, true /* checkShell */, 11355 "setApplicationHiddenSetting for user " + userId); 11356 11357 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11358 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11359 return false; 11360 } 11361 11362 long callingId = Binder.clearCallingIdentity(); 11363 try { 11364 boolean sendAdded = false; 11365 boolean sendRemoved = false; 11366 // writer 11367 synchronized (mPackages) { 11368 pkgSetting = mSettings.mPackages.get(packageName); 11369 if (pkgSetting == null) { 11370 return false; 11371 } 11372 if (pkgSetting.getHidden(userId) != hidden) { 11373 pkgSetting.setHidden(hidden, userId); 11374 mSettings.writePackageRestrictionsLPr(userId); 11375 if (hidden) { 11376 sendRemoved = true; 11377 } else { 11378 sendAdded = true; 11379 } 11380 } 11381 } 11382 if (sendAdded) { 11383 sendPackageAddedForUser(packageName, pkgSetting, userId); 11384 return true; 11385 } 11386 if (sendRemoved) { 11387 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11388 "hiding pkg"); 11389 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11390 return true; 11391 } 11392 } finally { 11393 Binder.restoreCallingIdentity(callingId); 11394 } 11395 return false; 11396 } 11397 11398 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11399 int userId) { 11400 final PackageRemovedInfo info = new PackageRemovedInfo(); 11401 info.removedPackage = packageName; 11402 info.removedUsers = new int[] {userId}; 11403 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11404 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11405 } 11406 11407 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11408 if (pkgList.length > 0) { 11409 Bundle extras = new Bundle(1); 11410 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11411 11412 sendPackageBroadcast( 11413 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11414 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11415 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11416 new int[] {userId}); 11417 } 11418 } 11419 11420 /** 11421 * Returns true if application is not found or there was an error. Otherwise it returns 11422 * the hidden state of the package for the given user. 11423 */ 11424 @Override 11425 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11426 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11427 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11428 true /* requireFullPermission */, false /* checkShell */, 11429 "getApplicationHidden for user " + userId); 11430 PackageSetting pkgSetting; 11431 long callingId = Binder.clearCallingIdentity(); 11432 try { 11433 // writer 11434 synchronized (mPackages) { 11435 pkgSetting = mSettings.mPackages.get(packageName); 11436 if (pkgSetting == null) { 11437 return true; 11438 } 11439 return pkgSetting.getHidden(userId); 11440 } 11441 } finally { 11442 Binder.restoreCallingIdentity(callingId); 11443 } 11444 } 11445 11446 /** 11447 * @hide 11448 */ 11449 @Override 11450 public int installExistingPackageAsUser(String packageName, int userId) { 11451 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11452 null); 11453 PackageSetting pkgSetting; 11454 final int uid = Binder.getCallingUid(); 11455 enforceCrossUserPermission(uid, userId, 11456 true /* requireFullPermission */, true /* checkShell */, 11457 "installExistingPackage for user " + userId); 11458 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11459 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11460 } 11461 11462 long callingId = Binder.clearCallingIdentity(); 11463 try { 11464 boolean installed = false; 11465 11466 // writer 11467 synchronized (mPackages) { 11468 pkgSetting = mSettings.mPackages.get(packageName); 11469 if (pkgSetting == null) { 11470 return PackageManager.INSTALL_FAILED_INVALID_URI; 11471 } 11472 if (!pkgSetting.getInstalled(userId)) { 11473 pkgSetting.setInstalled(true, userId); 11474 pkgSetting.setHidden(false, userId); 11475 mSettings.writePackageRestrictionsLPr(userId); 11476 installed = true; 11477 } 11478 } 11479 11480 if (installed) { 11481 if (pkgSetting.pkg != null) { 11482 synchronized (mInstallLock) { 11483 // We don't need to freeze for a brand new install 11484 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11485 } 11486 } 11487 sendPackageAddedForUser(packageName, pkgSetting, userId); 11488 } 11489 } finally { 11490 Binder.restoreCallingIdentity(callingId); 11491 } 11492 11493 return PackageManager.INSTALL_SUCCEEDED; 11494 } 11495 11496 boolean isUserRestricted(int userId, String restrictionKey) { 11497 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11498 if (restrictions.getBoolean(restrictionKey, false)) { 11499 Log.w(TAG, "User is restricted: " + restrictionKey); 11500 return true; 11501 } 11502 return false; 11503 } 11504 11505 @Override 11506 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11507 int userId) { 11508 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11509 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11510 true /* requireFullPermission */, true /* checkShell */, 11511 "setPackagesSuspended for user " + userId); 11512 11513 if (ArrayUtils.isEmpty(packageNames)) { 11514 return packageNames; 11515 } 11516 11517 // List of package names for whom the suspended state has changed. 11518 List<String> changedPackages = new ArrayList<>(packageNames.length); 11519 // List of package names for whom the suspended state is not set as requested in this 11520 // method. 11521 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11522 long callingId = Binder.clearCallingIdentity(); 11523 try { 11524 for (int i = 0; i < packageNames.length; i++) { 11525 String packageName = packageNames[i]; 11526 boolean changed = false; 11527 final int appId; 11528 synchronized (mPackages) { 11529 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11530 if (pkgSetting == null) { 11531 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11532 + "\". Skipping suspending/un-suspending."); 11533 unactionedPackages.add(packageName); 11534 continue; 11535 } 11536 appId = pkgSetting.appId; 11537 if (pkgSetting.getSuspended(userId) != suspended) { 11538 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11539 unactionedPackages.add(packageName); 11540 continue; 11541 } 11542 pkgSetting.setSuspended(suspended, userId); 11543 mSettings.writePackageRestrictionsLPr(userId); 11544 changed = true; 11545 changedPackages.add(packageName); 11546 } 11547 } 11548 11549 if (changed && suspended) { 11550 killApplication(packageName, UserHandle.getUid(userId, appId), 11551 "suspending package"); 11552 } 11553 } 11554 } finally { 11555 Binder.restoreCallingIdentity(callingId); 11556 } 11557 11558 if (!changedPackages.isEmpty()) { 11559 sendPackagesSuspendedForUser(changedPackages.toArray( 11560 new String[changedPackages.size()]), userId, suspended); 11561 } 11562 11563 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11564 } 11565 11566 @Override 11567 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11568 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11569 true /* requireFullPermission */, false /* checkShell */, 11570 "isPackageSuspendedForUser for user " + userId); 11571 synchronized (mPackages) { 11572 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11573 if (pkgSetting == null) { 11574 throw new IllegalArgumentException("Unknown target package: " + packageName); 11575 } 11576 return pkgSetting.getSuspended(userId); 11577 } 11578 } 11579 11580 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11581 if (isPackageDeviceAdmin(packageName, userId)) { 11582 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11583 + "\": has an active device admin"); 11584 return false; 11585 } 11586 11587 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11588 if (packageName.equals(activeLauncherPackageName)) { 11589 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11590 + "\": contains the active launcher"); 11591 return false; 11592 } 11593 11594 if (packageName.equals(mRequiredInstallerPackage)) { 11595 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11596 + "\": required for package installation"); 11597 return false; 11598 } 11599 11600 if (packageName.equals(mRequiredVerifierPackage)) { 11601 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11602 + "\": required for package verification"); 11603 return false; 11604 } 11605 11606 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11607 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11608 + "\": is the default dialer"); 11609 return false; 11610 } 11611 11612 return true; 11613 } 11614 11615 private String getActiveLauncherPackageName(int userId) { 11616 Intent intent = new Intent(Intent.ACTION_MAIN); 11617 intent.addCategory(Intent.CATEGORY_HOME); 11618 ResolveInfo resolveInfo = resolveIntent( 11619 intent, 11620 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11621 PackageManager.MATCH_DEFAULT_ONLY, 11622 userId); 11623 11624 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11625 } 11626 11627 private String getDefaultDialerPackageName(int userId) { 11628 synchronized (mPackages) { 11629 return mSettings.getDefaultDialerPackageNameLPw(userId); 11630 } 11631 } 11632 11633 @Override 11634 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11635 mContext.enforceCallingOrSelfPermission( 11636 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11637 "Only package verification agents can verify applications"); 11638 11639 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11640 final PackageVerificationResponse response = new PackageVerificationResponse( 11641 verificationCode, Binder.getCallingUid()); 11642 msg.arg1 = id; 11643 msg.obj = response; 11644 mHandler.sendMessage(msg); 11645 } 11646 11647 @Override 11648 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11649 long millisecondsToDelay) { 11650 mContext.enforceCallingOrSelfPermission( 11651 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11652 "Only package verification agents can extend verification timeouts"); 11653 11654 final PackageVerificationState state = mPendingVerification.get(id); 11655 final PackageVerificationResponse response = new PackageVerificationResponse( 11656 verificationCodeAtTimeout, Binder.getCallingUid()); 11657 11658 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11659 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11660 } 11661 if (millisecondsToDelay < 0) { 11662 millisecondsToDelay = 0; 11663 } 11664 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11665 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11666 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11667 } 11668 11669 if ((state != null) && !state.timeoutExtended()) { 11670 state.extendTimeout(); 11671 11672 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11673 msg.arg1 = id; 11674 msg.obj = response; 11675 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11676 } 11677 } 11678 11679 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11680 int verificationCode, UserHandle user) { 11681 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11682 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11683 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11684 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11685 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11686 11687 mContext.sendBroadcastAsUser(intent, user, 11688 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11689 } 11690 11691 private ComponentName matchComponentForVerifier(String packageName, 11692 List<ResolveInfo> receivers) { 11693 ActivityInfo targetReceiver = null; 11694 11695 final int NR = receivers.size(); 11696 for (int i = 0; i < NR; i++) { 11697 final ResolveInfo info = receivers.get(i); 11698 if (info.activityInfo == null) { 11699 continue; 11700 } 11701 11702 if (packageName.equals(info.activityInfo.packageName)) { 11703 targetReceiver = info.activityInfo; 11704 break; 11705 } 11706 } 11707 11708 if (targetReceiver == null) { 11709 return null; 11710 } 11711 11712 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11713 } 11714 11715 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11716 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11717 if (pkgInfo.verifiers.length == 0) { 11718 return null; 11719 } 11720 11721 final int N = pkgInfo.verifiers.length; 11722 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11723 for (int i = 0; i < N; i++) { 11724 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11725 11726 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11727 receivers); 11728 if (comp == null) { 11729 continue; 11730 } 11731 11732 final int verifierUid = getUidForVerifier(verifierInfo); 11733 if (verifierUid == -1) { 11734 continue; 11735 } 11736 11737 if (DEBUG_VERIFY) { 11738 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11739 + " with the correct signature"); 11740 } 11741 sufficientVerifiers.add(comp); 11742 verificationState.addSufficientVerifier(verifierUid); 11743 } 11744 11745 return sufficientVerifiers; 11746 } 11747 11748 private int getUidForVerifier(VerifierInfo verifierInfo) { 11749 synchronized (mPackages) { 11750 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11751 if (pkg == null) { 11752 return -1; 11753 } else if (pkg.mSignatures.length != 1) { 11754 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11755 + " has more than one signature; ignoring"); 11756 return -1; 11757 } 11758 11759 /* 11760 * If the public key of the package's signature does not match 11761 * our expected public key, then this is a different package and 11762 * we should skip. 11763 */ 11764 11765 final byte[] expectedPublicKey; 11766 try { 11767 final Signature verifierSig = pkg.mSignatures[0]; 11768 final PublicKey publicKey = verifierSig.getPublicKey(); 11769 expectedPublicKey = publicKey.getEncoded(); 11770 } catch (CertificateException e) { 11771 return -1; 11772 } 11773 11774 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11775 11776 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11777 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11778 + " does not have the expected public key; ignoring"); 11779 return -1; 11780 } 11781 11782 return pkg.applicationInfo.uid; 11783 } 11784 } 11785 11786 @Override 11787 public void finishPackageInstall(int token, boolean didLaunch) { 11788 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11789 11790 if (DEBUG_INSTALL) { 11791 Slog.v(TAG, "BM finishing package install for " + token); 11792 } 11793 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11794 11795 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11796 mHandler.sendMessage(msg); 11797 } 11798 11799 /** 11800 * Get the verification agent timeout. 11801 * 11802 * @return verification timeout in milliseconds 11803 */ 11804 private long getVerificationTimeout() { 11805 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11806 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11807 DEFAULT_VERIFICATION_TIMEOUT); 11808 } 11809 11810 /** 11811 * Get the default verification agent response code. 11812 * 11813 * @return default verification response code 11814 */ 11815 private int getDefaultVerificationResponse() { 11816 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11817 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11818 DEFAULT_VERIFICATION_RESPONSE); 11819 } 11820 11821 /** 11822 * Check whether or not package verification has been enabled. 11823 * 11824 * @return true if verification should be performed 11825 */ 11826 private boolean isVerificationEnabled(int userId, int installFlags) { 11827 if (!DEFAULT_VERIFY_ENABLE) { 11828 return false; 11829 } 11830 // Ephemeral apps don't get the full verification treatment 11831 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11832 if (DEBUG_EPHEMERAL) { 11833 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11834 } 11835 return false; 11836 } 11837 11838 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11839 11840 // Check if installing from ADB 11841 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11842 // Do not run verification in a test harness environment 11843 if (ActivityManager.isRunningInTestHarness()) { 11844 return false; 11845 } 11846 if (ensureVerifyAppsEnabled) { 11847 return true; 11848 } 11849 // Check if the developer does not want package verification for ADB installs 11850 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11851 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11852 return false; 11853 } 11854 } 11855 11856 if (ensureVerifyAppsEnabled) { 11857 return true; 11858 } 11859 11860 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11861 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11862 } 11863 11864 @Override 11865 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11866 throws RemoteException { 11867 mContext.enforceCallingOrSelfPermission( 11868 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11869 "Only intentfilter verification agents can verify applications"); 11870 11871 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11872 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11873 Binder.getCallingUid(), verificationCode, failedDomains); 11874 msg.arg1 = id; 11875 msg.obj = response; 11876 mHandler.sendMessage(msg); 11877 } 11878 11879 @Override 11880 public int getIntentVerificationStatus(String packageName, int userId) { 11881 synchronized (mPackages) { 11882 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11883 } 11884 } 11885 11886 @Override 11887 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11888 mContext.enforceCallingOrSelfPermission( 11889 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11890 11891 boolean result = false; 11892 synchronized (mPackages) { 11893 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11894 } 11895 if (result) { 11896 scheduleWritePackageRestrictionsLocked(userId); 11897 } 11898 return result; 11899 } 11900 11901 @Override 11902 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11903 String packageName) { 11904 synchronized (mPackages) { 11905 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11906 } 11907 } 11908 11909 @Override 11910 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11911 if (TextUtils.isEmpty(packageName)) { 11912 return ParceledListSlice.emptyList(); 11913 } 11914 synchronized (mPackages) { 11915 PackageParser.Package pkg = mPackages.get(packageName); 11916 if (pkg == null || pkg.activities == null) { 11917 return ParceledListSlice.emptyList(); 11918 } 11919 final int count = pkg.activities.size(); 11920 ArrayList<IntentFilter> result = new ArrayList<>(); 11921 for (int n=0; n<count; n++) { 11922 PackageParser.Activity activity = pkg.activities.get(n); 11923 if (activity.intents != null && activity.intents.size() > 0) { 11924 result.addAll(activity.intents); 11925 } 11926 } 11927 return new ParceledListSlice<>(result); 11928 } 11929 } 11930 11931 @Override 11932 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11933 mContext.enforceCallingOrSelfPermission( 11934 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11935 11936 synchronized (mPackages) { 11937 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11938 if (packageName != null) { 11939 result |= updateIntentVerificationStatus(packageName, 11940 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11941 userId); 11942 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11943 packageName, userId); 11944 } 11945 return result; 11946 } 11947 } 11948 11949 @Override 11950 public String getDefaultBrowserPackageName(int userId) { 11951 synchronized (mPackages) { 11952 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11953 } 11954 } 11955 11956 /** 11957 * Get the "allow unknown sources" setting. 11958 * 11959 * @return the current "allow unknown sources" setting 11960 */ 11961 private int getUnknownSourcesSettings() { 11962 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11963 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11964 -1); 11965 } 11966 11967 @Override 11968 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11969 final int uid = Binder.getCallingUid(); 11970 // writer 11971 synchronized (mPackages) { 11972 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11973 if (targetPackageSetting == null) { 11974 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11975 } 11976 11977 PackageSetting installerPackageSetting; 11978 if (installerPackageName != null) { 11979 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11980 if (installerPackageSetting == null) { 11981 throw new IllegalArgumentException("Unknown installer package: " 11982 + installerPackageName); 11983 } 11984 } else { 11985 installerPackageSetting = null; 11986 } 11987 11988 Signature[] callerSignature; 11989 Object obj = mSettings.getUserIdLPr(uid); 11990 if (obj != null) { 11991 if (obj instanceof SharedUserSetting) { 11992 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11993 } else if (obj instanceof PackageSetting) { 11994 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11995 } else { 11996 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11997 } 11998 } else { 11999 throw new SecurityException("Unknown calling UID: " + uid); 12000 } 12001 12002 // Verify: can't set installerPackageName to a package that is 12003 // not signed with the same cert as the caller. 12004 if (installerPackageSetting != null) { 12005 if (compareSignatures(callerSignature, 12006 installerPackageSetting.signatures.mSignatures) 12007 != PackageManager.SIGNATURE_MATCH) { 12008 throw new SecurityException( 12009 "Caller does not have same cert as new installer package " 12010 + installerPackageName); 12011 } 12012 } 12013 12014 // Verify: if target already has an installer package, it must 12015 // be signed with the same cert as the caller. 12016 if (targetPackageSetting.installerPackageName != null) { 12017 PackageSetting setting = mSettings.mPackages.get( 12018 targetPackageSetting.installerPackageName); 12019 // If the currently set package isn't valid, then it's always 12020 // okay to change it. 12021 if (setting != null) { 12022 if (compareSignatures(callerSignature, 12023 setting.signatures.mSignatures) 12024 != PackageManager.SIGNATURE_MATCH) { 12025 throw new SecurityException( 12026 "Caller does not have same cert as old installer package " 12027 + targetPackageSetting.installerPackageName); 12028 } 12029 } 12030 } 12031 12032 // Okay! 12033 targetPackageSetting.installerPackageName = installerPackageName; 12034 if (installerPackageName != null) { 12035 mSettings.mInstallerPackages.add(installerPackageName); 12036 } 12037 scheduleWriteSettingsLocked(); 12038 } 12039 } 12040 12041 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12042 // Queue up an async operation since the package installation may take a little while. 12043 mHandler.post(new Runnable() { 12044 public void run() { 12045 mHandler.removeCallbacks(this); 12046 // Result object to be returned 12047 PackageInstalledInfo res = new PackageInstalledInfo(); 12048 res.setReturnCode(currentStatus); 12049 res.uid = -1; 12050 res.pkg = null; 12051 res.removedInfo = null; 12052 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12053 args.doPreInstall(res.returnCode); 12054 synchronized (mInstallLock) { 12055 installPackageTracedLI(args, res); 12056 } 12057 args.doPostInstall(res.returnCode, res.uid); 12058 } 12059 12060 // A restore should be performed at this point if (a) the install 12061 // succeeded, (b) the operation is not an update, and (c) the new 12062 // package has not opted out of backup participation. 12063 final boolean update = res.removedInfo != null 12064 && res.removedInfo.removedPackage != null; 12065 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12066 boolean doRestore = !update 12067 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12068 12069 // Set up the post-install work request bookkeeping. This will be used 12070 // and cleaned up by the post-install event handling regardless of whether 12071 // there's a restore pass performed. Token values are >= 1. 12072 int token; 12073 if (mNextInstallToken < 0) mNextInstallToken = 1; 12074 token = mNextInstallToken++; 12075 12076 PostInstallData data = new PostInstallData(args, res); 12077 mRunningInstalls.put(token, data); 12078 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12079 12080 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12081 // Pass responsibility to the Backup Manager. It will perform a 12082 // restore if appropriate, then pass responsibility back to the 12083 // Package Manager to run the post-install observer callbacks 12084 // and broadcasts. 12085 IBackupManager bm = IBackupManager.Stub.asInterface( 12086 ServiceManager.getService(Context.BACKUP_SERVICE)); 12087 if (bm != null) { 12088 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12089 + " to BM for possible restore"); 12090 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12091 try { 12092 // TODO: http://b/22388012 12093 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12094 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12095 } else { 12096 doRestore = false; 12097 } 12098 } catch (RemoteException e) { 12099 // can't happen; the backup manager is local 12100 } catch (Exception e) { 12101 Slog.e(TAG, "Exception trying to enqueue restore", e); 12102 doRestore = false; 12103 } 12104 } else { 12105 Slog.e(TAG, "Backup Manager not found!"); 12106 doRestore = false; 12107 } 12108 } 12109 12110 if (!doRestore) { 12111 // No restore possible, or the Backup Manager was mysteriously not 12112 // available -- just fire the post-install work request directly. 12113 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12114 12115 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12116 12117 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12118 mHandler.sendMessage(msg); 12119 } 12120 } 12121 }); 12122 } 12123 12124 /** 12125 * Callback from PackageSettings whenever an app is first transitioned out of the 12126 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12127 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12128 * here whether the app is the target of an ongoing install, and only send the 12129 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12130 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12131 * handling. 12132 */ 12133 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12134 // Serialize this with the rest of the install-process message chain. In the 12135 // restore-at-install case, this Runnable will necessarily run before the 12136 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12137 // are coherent. In the non-restore case, the app has already completed install 12138 // and been launched through some other means, so it is not in a problematic 12139 // state for observers to see the FIRST_LAUNCH signal. 12140 mHandler.post(new Runnable() { 12141 @Override 12142 public void run() { 12143 for (int i = 0; i < mRunningInstalls.size(); i++) { 12144 final PostInstallData data = mRunningInstalls.valueAt(i); 12145 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12146 // right package; but is it for the right user? 12147 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12148 if (userId == data.res.newUsers[uIndex]) { 12149 if (DEBUG_BACKUP) { 12150 Slog.i(TAG, "Package " + pkgName 12151 + " being restored so deferring FIRST_LAUNCH"); 12152 } 12153 return; 12154 } 12155 } 12156 } 12157 } 12158 // didn't find it, so not being restored 12159 if (DEBUG_BACKUP) { 12160 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12161 } 12162 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12163 } 12164 }); 12165 } 12166 12167 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12168 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12169 installerPkg, null, userIds); 12170 } 12171 12172 private abstract class HandlerParams { 12173 private static final int MAX_RETRIES = 4; 12174 12175 /** 12176 * Number of times startCopy() has been attempted and had a non-fatal 12177 * error. 12178 */ 12179 private int mRetries = 0; 12180 12181 /** User handle for the user requesting the information or installation. */ 12182 private final UserHandle mUser; 12183 String traceMethod; 12184 int traceCookie; 12185 12186 HandlerParams(UserHandle user) { 12187 mUser = user; 12188 } 12189 12190 UserHandle getUser() { 12191 return mUser; 12192 } 12193 12194 HandlerParams setTraceMethod(String traceMethod) { 12195 this.traceMethod = traceMethod; 12196 return this; 12197 } 12198 12199 HandlerParams setTraceCookie(int traceCookie) { 12200 this.traceCookie = traceCookie; 12201 return this; 12202 } 12203 12204 final boolean startCopy() { 12205 boolean res; 12206 try { 12207 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12208 12209 if (++mRetries > MAX_RETRIES) { 12210 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12211 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12212 handleServiceError(); 12213 return false; 12214 } else { 12215 handleStartCopy(); 12216 res = true; 12217 } 12218 } catch (RemoteException e) { 12219 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12220 mHandler.sendEmptyMessage(MCS_RECONNECT); 12221 res = false; 12222 } 12223 handleReturnCode(); 12224 return res; 12225 } 12226 12227 final void serviceError() { 12228 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12229 handleServiceError(); 12230 handleReturnCode(); 12231 } 12232 12233 abstract void handleStartCopy() throws RemoteException; 12234 abstract void handleServiceError(); 12235 abstract void handleReturnCode(); 12236 } 12237 12238 class MeasureParams extends HandlerParams { 12239 private final PackageStats mStats; 12240 private boolean mSuccess; 12241 12242 private final IPackageStatsObserver mObserver; 12243 12244 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12245 super(new UserHandle(stats.userHandle)); 12246 mObserver = observer; 12247 mStats = stats; 12248 } 12249 12250 @Override 12251 public String toString() { 12252 return "MeasureParams{" 12253 + Integer.toHexString(System.identityHashCode(this)) 12254 + " " + mStats.packageName + "}"; 12255 } 12256 12257 @Override 12258 void handleStartCopy() throws RemoteException { 12259 synchronized (mInstallLock) { 12260 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12261 } 12262 12263 if (mSuccess) { 12264 final boolean mounted; 12265 if (Environment.isExternalStorageEmulated()) { 12266 mounted = true; 12267 } else { 12268 final String status = Environment.getExternalStorageState(); 12269 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12270 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12271 } 12272 12273 if (mounted) { 12274 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12275 12276 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12277 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12278 12279 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12280 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12281 12282 // Always subtract cache size, since it's a subdirectory 12283 mStats.externalDataSize -= mStats.externalCacheSize; 12284 12285 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12286 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12287 12288 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12289 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12290 } 12291 } 12292 } 12293 12294 @Override 12295 void handleReturnCode() { 12296 if (mObserver != null) { 12297 try { 12298 mObserver.onGetStatsCompleted(mStats, mSuccess); 12299 } catch (RemoteException e) { 12300 Slog.i(TAG, "Observer no longer exists."); 12301 } 12302 } 12303 } 12304 12305 @Override 12306 void handleServiceError() { 12307 Slog.e(TAG, "Could not measure application " + mStats.packageName 12308 + " external storage"); 12309 } 12310 } 12311 12312 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12313 throws RemoteException { 12314 long result = 0; 12315 for (File path : paths) { 12316 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12317 } 12318 return result; 12319 } 12320 12321 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12322 for (File path : paths) { 12323 try { 12324 mcs.clearDirectory(path.getAbsolutePath()); 12325 } catch (RemoteException e) { 12326 } 12327 } 12328 } 12329 12330 static class OriginInfo { 12331 /** 12332 * Location where install is coming from, before it has been 12333 * copied/renamed into place. This could be a single monolithic APK 12334 * file, or a cluster directory. This location may be untrusted. 12335 */ 12336 final File file; 12337 final String cid; 12338 12339 /** 12340 * Flag indicating that {@link #file} or {@link #cid} has already been 12341 * staged, meaning downstream users don't need to defensively copy the 12342 * contents. 12343 */ 12344 final boolean staged; 12345 12346 /** 12347 * Flag indicating that {@link #file} or {@link #cid} is an already 12348 * installed app that is being moved. 12349 */ 12350 final boolean existing; 12351 12352 final String resolvedPath; 12353 final File resolvedFile; 12354 12355 static OriginInfo fromNothing() { 12356 return new OriginInfo(null, null, false, false); 12357 } 12358 12359 static OriginInfo fromUntrustedFile(File file) { 12360 return new OriginInfo(file, null, false, false); 12361 } 12362 12363 static OriginInfo fromExistingFile(File file) { 12364 return new OriginInfo(file, null, false, true); 12365 } 12366 12367 static OriginInfo fromStagedFile(File file) { 12368 return new OriginInfo(file, null, true, false); 12369 } 12370 12371 static OriginInfo fromStagedContainer(String cid) { 12372 return new OriginInfo(null, cid, true, false); 12373 } 12374 12375 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12376 this.file = file; 12377 this.cid = cid; 12378 this.staged = staged; 12379 this.existing = existing; 12380 12381 if (cid != null) { 12382 resolvedPath = PackageHelper.getSdDir(cid); 12383 resolvedFile = new File(resolvedPath); 12384 } else if (file != null) { 12385 resolvedPath = file.getAbsolutePath(); 12386 resolvedFile = file; 12387 } else { 12388 resolvedPath = null; 12389 resolvedFile = null; 12390 } 12391 } 12392 } 12393 12394 static class MoveInfo { 12395 final int moveId; 12396 final String fromUuid; 12397 final String toUuid; 12398 final String packageName; 12399 final String dataAppName; 12400 final int appId; 12401 final String seinfo; 12402 final int targetSdkVersion; 12403 12404 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12405 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12406 this.moveId = moveId; 12407 this.fromUuid = fromUuid; 12408 this.toUuid = toUuid; 12409 this.packageName = packageName; 12410 this.dataAppName = dataAppName; 12411 this.appId = appId; 12412 this.seinfo = seinfo; 12413 this.targetSdkVersion = targetSdkVersion; 12414 } 12415 } 12416 12417 static class VerificationInfo { 12418 /** A constant used to indicate that a uid value is not present. */ 12419 public static final int NO_UID = -1; 12420 12421 /** URI referencing where the package was downloaded from. */ 12422 final Uri originatingUri; 12423 12424 /** HTTP referrer URI associated with the originatingURI. */ 12425 final Uri referrer; 12426 12427 /** UID of the application that the install request originated from. */ 12428 final int originatingUid; 12429 12430 /** UID of application requesting the install */ 12431 final int installerUid; 12432 12433 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12434 this.originatingUri = originatingUri; 12435 this.referrer = referrer; 12436 this.originatingUid = originatingUid; 12437 this.installerUid = installerUid; 12438 } 12439 } 12440 12441 class InstallParams extends HandlerParams { 12442 final OriginInfo origin; 12443 final MoveInfo move; 12444 final IPackageInstallObserver2 observer; 12445 int installFlags; 12446 final String installerPackageName; 12447 final String volumeUuid; 12448 private InstallArgs mArgs; 12449 private int mRet; 12450 final String packageAbiOverride; 12451 final String[] grantedRuntimePermissions; 12452 final VerificationInfo verificationInfo; 12453 final Certificate[][] certificates; 12454 12455 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12456 int installFlags, String installerPackageName, String volumeUuid, 12457 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12458 String[] grantedPermissions, Certificate[][] certificates) { 12459 super(user); 12460 this.origin = origin; 12461 this.move = move; 12462 this.observer = observer; 12463 this.installFlags = installFlags; 12464 this.installerPackageName = installerPackageName; 12465 this.volumeUuid = volumeUuid; 12466 this.verificationInfo = verificationInfo; 12467 this.packageAbiOverride = packageAbiOverride; 12468 this.grantedRuntimePermissions = grantedPermissions; 12469 this.certificates = certificates; 12470 } 12471 12472 @Override 12473 public String toString() { 12474 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12475 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12476 } 12477 12478 private int installLocationPolicy(PackageInfoLite pkgLite) { 12479 String packageName = pkgLite.packageName; 12480 int installLocation = pkgLite.installLocation; 12481 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12482 // reader 12483 synchronized (mPackages) { 12484 // Currently installed package which the new package is attempting to replace or 12485 // null if no such package is installed. 12486 PackageParser.Package installedPkg = mPackages.get(packageName); 12487 // Package which currently owns the data which the new package will own if installed. 12488 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12489 // will be null whereas dataOwnerPkg will contain information about the package 12490 // which was uninstalled while keeping its data. 12491 PackageParser.Package dataOwnerPkg = installedPkg; 12492 if (dataOwnerPkg == null) { 12493 PackageSetting ps = mSettings.mPackages.get(packageName); 12494 if (ps != null) { 12495 dataOwnerPkg = ps.pkg; 12496 } 12497 } 12498 12499 if (dataOwnerPkg != null) { 12500 // If installed, the package will get access to data left on the device by its 12501 // predecessor. As a security measure, this is permited only if this is not a 12502 // version downgrade or if the predecessor package is marked as debuggable and 12503 // a downgrade is explicitly requested. 12504 // 12505 // On debuggable platform builds, downgrades are permitted even for 12506 // non-debuggable packages to make testing easier. Debuggable platform builds do 12507 // not offer security guarantees and thus it's OK to disable some security 12508 // mechanisms to make debugging/testing easier on those builds. However, even on 12509 // debuggable builds downgrades of packages are permitted only if requested via 12510 // installFlags. This is because we aim to keep the behavior of debuggable 12511 // platform builds as close as possible to the behavior of non-debuggable 12512 // platform builds. 12513 final boolean downgradeRequested = 12514 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12515 final boolean packageDebuggable = 12516 (dataOwnerPkg.applicationInfo.flags 12517 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12518 final boolean downgradePermitted = 12519 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12520 if (!downgradePermitted) { 12521 try { 12522 checkDowngrade(dataOwnerPkg, pkgLite); 12523 } catch (PackageManagerException e) { 12524 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12525 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12526 } 12527 } 12528 } 12529 12530 if (installedPkg != null) { 12531 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12532 // Check for updated system application. 12533 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12534 if (onSd) { 12535 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12536 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12537 } 12538 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12539 } else { 12540 if (onSd) { 12541 // Install flag overrides everything. 12542 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12543 } 12544 // If current upgrade specifies particular preference 12545 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12546 // Application explicitly specified internal. 12547 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12548 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12549 // App explictly prefers external. Let policy decide 12550 } else { 12551 // Prefer previous location 12552 if (isExternal(installedPkg)) { 12553 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12554 } 12555 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12556 } 12557 } 12558 } else { 12559 // Invalid install. Return error code 12560 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12561 } 12562 } 12563 } 12564 // All the special cases have been taken care of. 12565 // Return result based on recommended install location. 12566 if (onSd) { 12567 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12568 } 12569 return pkgLite.recommendedInstallLocation; 12570 } 12571 12572 /* 12573 * Invoke remote method to get package information and install 12574 * location values. Override install location based on default 12575 * policy if needed and then create install arguments based 12576 * on the install location. 12577 */ 12578 public void handleStartCopy() throws RemoteException { 12579 int ret = PackageManager.INSTALL_SUCCEEDED; 12580 12581 // If we're already staged, we've firmly committed to an install location 12582 if (origin.staged) { 12583 if (origin.file != null) { 12584 installFlags |= PackageManager.INSTALL_INTERNAL; 12585 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12586 } else if (origin.cid != null) { 12587 installFlags |= PackageManager.INSTALL_EXTERNAL; 12588 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12589 } else { 12590 throw new IllegalStateException("Invalid stage location"); 12591 } 12592 } 12593 12594 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12595 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12596 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12597 PackageInfoLite pkgLite = null; 12598 12599 if (onInt && onSd) { 12600 // Check if both bits are set. 12601 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12602 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12603 } else if (onSd && ephemeral) { 12604 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12605 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12606 } else { 12607 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12608 packageAbiOverride); 12609 12610 if (DEBUG_EPHEMERAL && ephemeral) { 12611 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12612 } 12613 12614 /* 12615 * If we have too little free space, try to free cache 12616 * before giving up. 12617 */ 12618 if (!origin.staged && pkgLite.recommendedInstallLocation 12619 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12620 // TODO: focus freeing disk space on the target device 12621 final StorageManager storage = StorageManager.from(mContext); 12622 final long lowThreshold = storage.getStorageLowBytes( 12623 Environment.getDataDirectory()); 12624 12625 final long sizeBytes = mContainerService.calculateInstalledSize( 12626 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12627 12628 try { 12629 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12630 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12631 installFlags, packageAbiOverride); 12632 } catch (InstallerException e) { 12633 Slog.w(TAG, "Failed to free cache", e); 12634 } 12635 12636 /* 12637 * The cache free must have deleted the file we 12638 * downloaded to install. 12639 * 12640 * TODO: fix the "freeCache" call to not delete 12641 * the file we care about. 12642 */ 12643 if (pkgLite.recommendedInstallLocation 12644 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12645 pkgLite.recommendedInstallLocation 12646 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12647 } 12648 } 12649 } 12650 12651 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12652 int loc = pkgLite.recommendedInstallLocation; 12653 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12654 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12655 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12656 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12657 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12658 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12659 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12660 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12661 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12662 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12663 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12664 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12665 } else { 12666 // Override with defaults if needed. 12667 loc = installLocationPolicy(pkgLite); 12668 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12669 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12670 } else if (!onSd && !onInt) { 12671 // Override install location with flags 12672 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12673 // Set the flag to install on external media. 12674 installFlags |= PackageManager.INSTALL_EXTERNAL; 12675 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12676 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12677 if (DEBUG_EPHEMERAL) { 12678 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12679 } 12680 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12681 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12682 |PackageManager.INSTALL_INTERNAL); 12683 } else { 12684 // Make sure the flag for installing on external 12685 // media is unset 12686 installFlags |= PackageManager.INSTALL_INTERNAL; 12687 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12688 } 12689 } 12690 } 12691 } 12692 12693 final InstallArgs args = createInstallArgs(this); 12694 mArgs = args; 12695 12696 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12697 // TODO: http://b/22976637 12698 // Apps installed for "all" users use the device owner to verify the app 12699 UserHandle verifierUser = getUser(); 12700 if (verifierUser == UserHandle.ALL) { 12701 verifierUser = UserHandle.SYSTEM; 12702 } 12703 12704 /* 12705 * Determine if we have any installed package verifiers. If we 12706 * do, then we'll defer to them to verify the packages. 12707 */ 12708 final int requiredUid = mRequiredVerifierPackage == null ? -1 12709 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12710 verifierUser.getIdentifier()); 12711 if (!origin.existing && requiredUid != -1 12712 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12713 final Intent verification = new Intent( 12714 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12715 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12716 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12717 PACKAGE_MIME_TYPE); 12718 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12719 12720 // Query all live verifiers based on current user state 12721 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12722 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12723 12724 if (DEBUG_VERIFY) { 12725 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12726 + verification.toString() + " with " + pkgLite.verifiers.length 12727 + " optional verifiers"); 12728 } 12729 12730 final int verificationId = mPendingVerificationToken++; 12731 12732 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12733 12734 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12735 installerPackageName); 12736 12737 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12738 installFlags); 12739 12740 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12741 pkgLite.packageName); 12742 12743 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12744 pkgLite.versionCode); 12745 12746 if (verificationInfo != null) { 12747 if (verificationInfo.originatingUri != null) { 12748 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12749 verificationInfo.originatingUri); 12750 } 12751 if (verificationInfo.referrer != null) { 12752 verification.putExtra(Intent.EXTRA_REFERRER, 12753 verificationInfo.referrer); 12754 } 12755 if (verificationInfo.originatingUid >= 0) { 12756 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12757 verificationInfo.originatingUid); 12758 } 12759 if (verificationInfo.installerUid >= 0) { 12760 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12761 verificationInfo.installerUid); 12762 } 12763 } 12764 12765 final PackageVerificationState verificationState = new PackageVerificationState( 12766 requiredUid, args); 12767 12768 mPendingVerification.append(verificationId, verificationState); 12769 12770 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12771 receivers, verificationState); 12772 12773 /* 12774 * If any sufficient verifiers were listed in the package 12775 * manifest, attempt to ask them. 12776 */ 12777 if (sufficientVerifiers != null) { 12778 final int N = sufficientVerifiers.size(); 12779 if (N == 0) { 12780 Slog.i(TAG, "Additional verifiers required, but none installed."); 12781 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12782 } else { 12783 for (int i = 0; i < N; i++) { 12784 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12785 12786 final Intent sufficientIntent = new Intent(verification); 12787 sufficientIntent.setComponent(verifierComponent); 12788 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12789 } 12790 } 12791 } 12792 12793 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12794 mRequiredVerifierPackage, receivers); 12795 if (ret == PackageManager.INSTALL_SUCCEEDED 12796 && mRequiredVerifierPackage != null) { 12797 Trace.asyncTraceBegin( 12798 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12799 /* 12800 * Send the intent to the required verification agent, 12801 * but only start the verification timeout after the 12802 * target BroadcastReceivers have run. 12803 */ 12804 verification.setComponent(requiredVerifierComponent); 12805 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12806 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12807 new BroadcastReceiver() { 12808 @Override 12809 public void onReceive(Context context, Intent intent) { 12810 final Message msg = mHandler 12811 .obtainMessage(CHECK_PENDING_VERIFICATION); 12812 msg.arg1 = verificationId; 12813 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12814 } 12815 }, null, 0, null, null); 12816 12817 /* 12818 * We don't want the copy to proceed until verification 12819 * succeeds, so null out this field. 12820 */ 12821 mArgs = null; 12822 } 12823 } else { 12824 /* 12825 * No package verification is enabled, so immediately start 12826 * the remote call to initiate copy using temporary file. 12827 */ 12828 ret = args.copyApk(mContainerService, true); 12829 } 12830 } 12831 12832 mRet = ret; 12833 } 12834 12835 @Override 12836 void handleReturnCode() { 12837 // If mArgs is null, then MCS couldn't be reached. When it 12838 // reconnects, it will try again to install. At that point, this 12839 // will succeed. 12840 if (mArgs != null) { 12841 processPendingInstall(mArgs, mRet); 12842 } 12843 } 12844 12845 @Override 12846 void handleServiceError() { 12847 mArgs = createInstallArgs(this); 12848 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12849 } 12850 12851 public boolean isForwardLocked() { 12852 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12853 } 12854 } 12855 12856 /** 12857 * Used during creation of InstallArgs 12858 * 12859 * @param installFlags package installation flags 12860 * @return true if should be installed on external storage 12861 */ 12862 private static boolean installOnExternalAsec(int installFlags) { 12863 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12864 return false; 12865 } 12866 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12867 return true; 12868 } 12869 return false; 12870 } 12871 12872 /** 12873 * Used during creation of InstallArgs 12874 * 12875 * @param installFlags package installation flags 12876 * @return true if should be installed as forward locked 12877 */ 12878 private static boolean installForwardLocked(int installFlags) { 12879 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12880 } 12881 12882 private InstallArgs createInstallArgs(InstallParams params) { 12883 if (params.move != null) { 12884 return new MoveInstallArgs(params); 12885 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12886 return new AsecInstallArgs(params); 12887 } else { 12888 return new FileInstallArgs(params); 12889 } 12890 } 12891 12892 /** 12893 * Create args that describe an existing installed package. Typically used 12894 * when cleaning up old installs, or used as a move source. 12895 */ 12896 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12897 String resourcePath, String[] instructionSets) { 12898 final boolean isInAsec; 12899 if (installOnExternalAsec(installFlags)) { 12900 /* Apps on SD card are always in ASEC containers. */ 12901 isInAsec = true; 12902 } else if (installForwardLocked(installFlags) 12903 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12904 /* 12905 * Forward-locked apps are only in ASEC containers if they're the 12906 * new style 12907 */ 12908 isInAsec = true; 12909 } else { 12910 isInAsec = false; 12911 } 12912 12913 if (isInAsec) { 12914 return new AsecInstallArgs(codePath, instructionSets, 12915 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12916 } else { 12917 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12918 } 12919 } 12920 12921 static abstract class InstallArgs { 12922 /** @see InstallParams#origin */ 12923 final OriginInfo origin; 12924 /** @see InstallParams#move */ 12925 final MoveInfo move; 12926 12927 final IPackageInstallObserver2 observer; 12928 // Always refers to PackageManager flags only 12929 final int installFlags; 12930 final String installerPackageName; 12931 final String volumeUuid; 12932 final UserHandle user; 12933 final String abiOverride; 12934 final String[] installGrantPermissions; 12935 /** If non-null, drop an async trace when the install completes */ 12936 final String traceMethod; 12937 final int traceCookie; 12938 final Certificate[][] certificates; 12939 12940 // The list of instruction sets supported by this app. This is currently 12941 // only used during the rmdex() phase to clean up resources. We can get rid of this 12942 // if we move dex files under the common app path. 12943 /* nullable */ String[] instructionSets; 12944 12945 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12946 int installFlags, String installerPackageName, String volumeUuid, 12947 UserHandle user, String[] instructionSets, 12948 String abiOverride, String[] installGrantPermissions, 12949 String traceMethod, int traceCookie, Certificate[][] certificates) { 12950 this.origin = origin; 12951 this.move = move; 12952 this.installFlags = installFlags; 12953 this.observer = observer; 12954 this.installerPackageName = installerPackageName; 12955 this.volumeUuid = volumeUuid; 12956 this.user = user; 12957 this.instructionSets = instructionSets; 12958 this.abiOverride = abiOverride; 12959 this.installGrantPermissions = installGrantPermissions; 12960 this.traceMethod = traceMethod; 12961 this.traceCookie = traceCookie; 12962 this.certificates = certificates; 12963 } 12964 12965 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12966 abstract int doPreInstall(int status); 12967 12968 /** 12969 * Rename package into final resting place. All paths on the given 12970 * scanned package should be updated to reflect the rename. 12971 */ 12972 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12973 abstract int doPostInstall(int status, int uid); 12974 12975 /** @see PackageSettingBase#codePathString */ 12976 abstract String getCodePath(); 12977 /** @see PackageSettingBase#resourcePathString */ 12978 abstract String getResourcePath(); 12979 12980 // Need installer lock especially for dex file removal. 12981 abstract void cleanUpResourcesLI(); 12982 abstract boolean doPostDeleteLI(boolean delete); 12983 12984 /** 12985 * Called before the source arguments are copied. This is used mostly 12986 * for MoveParams when it needs to read the source file to put it in the 12987 * destination. 12988 */ 12989 int doPreCopy() { 12990 return PackageManager.INSTALL_SUCCEEDED; 12991 } 12992 12993 /** 12994 * Called after the source arguments are copied. This is used mostly for 12995 * MoveParams when it needs to read the source file to put it in the 12996 * destination. 12997 */ 12998 int doPostCopy(int uid) { 12999 return PackageManager.INSTALL_SUCCEEDED; 13000 } 13001 13002 protected boolean isFwdLocked() { 13003 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13004 } 13005 13006 protected boolean isExternalAsec() { 13007 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13008 } 13009 13010 protected boolean isEphemeral() { 13011 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13012 } 13013 13014 UserHandle getUser() { 13015 return user; 13016 } 13017 } 13018 13019 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13020 if (!allCodePaths.isEmpty()) { 13021 if (instructionSets == null) { 13022 throw new IllegalStateException("instructionSet == null"); 13023 } 13024 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13025 for (String codePath : allCodePaths) { 13026 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13027 try { 13028 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13029 } catch (InstallerException ignored) { 13030 } 13031 } 13032 } 13033 } 13034 } 13035 13036 /** 13037 * Logic to handle installation of non-ASEC applications, including copying 13038 * and renaming logic. 13039 */ 13040 class FileInstallArgs extends InstallArgs { 13041 private File codeFile; 13042 private File resourceFile; 13043 13044 // Example topology: 13045 // /data/app/com.example/base.apk 13046 // /data/app/com.example/split_foo.apk 13047 // /data/app/com.example/lib/arm/libfoo.so 13048 // /data/app/com.example/lib/arm64/libfoo.so 13049 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13050 13051 /** New install */ 13052 FileInstallArgs(InstallParams params) { 13053 super(params.origin, params.move, params.observer, params.installFlags, 13054 params.installerPackageName, params.volumeUuid, 13055 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13056 params.grantedRuntimePermissions, 13057 params.traceMethod, params.traceCookie, params.certificates); 13058 if (isFwdLocked()) { 13059 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13060 } 13061 } 13062 13063 /** Existing install */ 13064 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13065 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13066 null, null, null, 0, null /*certificates*/); 13067 this.codeFile = (codePath != null) ? new File(codePath) : null; 13068 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13069 } 13070 13071 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13072 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13073 try { 13074 return doCopyApk(imcs, temp); 13075 } finally { 13076 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13077 } 13078 } 13079 13080 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13081 if (origin.staged) { 13082 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13083 codeFile = origin.file; 13084 resourceFile = origin.file; 13085 return PackageManager.INSTALL_SUCCEEDED; 13086 } 13087 13088 try { 13089 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13090 final File tempDir = 13091 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13092 codeFile = tempDir; 13093 resourceFile = tempDir; 13094 } catch (IOException e) { 13095 Slog.w(TAG, "Failed to create copy file: " + e); 13096 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13097 } 13098 13099 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13100 @Override 13101 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13102 if (!FileUtils.isValidExtFilename(name)) { 13103 throw new IllegalArgumentException("Invalid filename: " + name); 13104 } 13105 try { 13106 final File file = new File(codeFile, name); 13107 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13108 O_RDWR | O_CREAT, 0644); 13109 Os.chmod(file.getAbsolutePath(), 0644); 13110 return new ParcelFileDescriptor(fd); 13111 } catch (ErrnoException e) { 13112 throw new RemoteException("Failed to open: " + e.getMessage()); 13113 } 13114 } 13115 }; 13116 13117 int ret = PackageManager.INSTALL_SUCCEEDED; 13118 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13119 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13120 Slog.e(TAG, "Failed to copy package"); 13121 return ret; 13122 } 13123 13124 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13125 NativeLibraryHelper.Handle handle = null; 13126 try { 13127 handle = NativeLibraryHelper.Handle.create(codeFile); 13128 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13129 abiOverride); 13130 } catch (IOException e) { 13131 Slog.e(TAG, "Copying native libraries failed", e); 13132 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13133 } finally { 13134 IoUtils.closeQuietly(handle); 13135 } 13136 13137 return ret; 13138 } 13139 13140 int doPreInstall(int status) { 13141 if (status != PackageManager.INSTALL_SUCCEEDED) { 13142 cleanUp(); 13143 } 13144 return status; 13145 } 13146 13147 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13148 if (status != PackageManager.INSTALL_SUCCEEDED) { 13149 cleanUp(); 13150 return false; 13151 } 13152 13153 final File targetDir = codeFile.getParentFile(); 13154 final File beforeCodeFile = codeFile; 13155 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13156 13157 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13158 try { 13159 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13160 } catch (ErrnoException e) { 13161 Slog.w(TAG, "Failed to rename", e); 13162 return false; 13163 } 13164 13165 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13166 Slog.w(TAG, "Failed to restorecon"); 13167 return false; 13168 } 13169 13170 // Reflect the rename internally 13171 codeFile = afterCodeFile; 13172 resourceFile = afterCodeFile; 13173 13174 // Reflect the rename in scanned details 13175 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13176 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13177 afterCodeFile, pkg.baseCodePath)); 13178 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13179 afterCodeFile, pkg.splitCodePaths)); 13180 13181 // Reflect the rename in app info 13182 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13183 pkg.setApplicationInfoCodePath(pkg.codePath); 13184 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13185 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13186 pkg.setApplicationInfoResourcePath(pkg.codePath); 13187 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13188 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13189 13190 return true; 13191 } 13192 13193 int doPostInstall(int status, int uid) { 13194 if (status != PackageManager.INSTALL_SUCCEEDED) { 13195 cleanUp(); 13196 } 13197 return status; 13198 } 13199 13200 @Override 13201 String getCodePath() { 13202 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13203 } 13204 13205 @Override 13206 String getResourcePath() { 13207 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13208 } 13209 13210 private boolean cleanUp() { 13211 if (codeFile == null || !codeFile.exists()) { 13212 return false; 13213 } 13214 13215 removeCodePathLI(codeFile); 13216 13217 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13218 resourceFile.delete(); 13219 } 13220 13221 return true; 13222 } 13223 13224 void cleanUpResourcesLI() { 13225 // Try enumerating all code paths before deleting 13226 List<String> allCodePaths = Collections.EMPTY_LIST; 13227 if (codeFile != null && codeFile.exists()) { 13228 try { 13229 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13230 allCodePaths = pkg.getAllCodePaths(); 13231 } catch (PackageParserException e) { 13232 // Ignored; we tried our best 13233 } 13234 } 13235 13236 cleanUp(); 13237 removeDexFiles(allCodePaths, instructionSets); 13238 } 13239 13240 boolean doPostDeleteLI(boolean delete) { 13241 // XXX err, shouldn't we respect the delete flag? 13242 cleanUpResourcesLI(); 13243 return true; 13244 } 13245 } 13246 13247 private boolean isAsecExternal(String cid) { 13248 final String asecPath = PackageHelper.getSdFilesystem(cid); 13249 return !asecPath.startsWith(mAsecInternalPath); 13250 } 13251 13252 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13253 PackageManagerException { 13254 if (copyRet < 0) { 13255 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13256 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13257 throw new PackageManagerException(copyRet, message); 13258 } 13259 } 13260 } 13261 13262 /** 13263 * Extract the MountService "container ID" from the full code path of an 13264 * .apk. 13265 */ 13266 static String cidFromCodePath(String fullCodePath) { 13267 int eidx = fullCodePath.lastIndexOf("/"); 13268 String subStr1 = fullCodePath.substring(0, eidx); 13269 int sidx = subStr1.lastIndexOf("/"); 13270 return subStr1.substring(sidx+1, eidx); 13271 } 13272 13273 /** 13274 * Logic to handle installation of ASEC applications, including copying and 13275 * renaming logic. 13276 */ 13277 class AsecInstallArgs extends InstallArgs { 13278 static final String RES_FILE_NAME = "pkg.apk"; 13279 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13280 13281 String cid; 13282 String packagePath; 13283 String resourcePath; 13284 13285 /** New install */ 13286 AsecInstallArgs(InstallParams params) { 13287 super(params.origin, params.move, params.observer, params.installFlags, 13288 params.installerPackageName, params.volumeUuid, 13289 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13290 params.grantedRuntimePermissions, 13291 params.traceMethod, params.traceCookie, params.certificates); 13292 } 13293 13294 /** Existing install */ 13295 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13296 boolean isExternal, boolean isForwardLocked) { 13297 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13298 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13299 instructionSets, null, null, null, 0, null /*certificates*/); 13300 // Hackily pretend we're still looking at a full code path 13301 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13302 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13303 } 13304 13305 // Extract cid from fullCodePath 13306 int eidx = fullCodePath.lastIndexOf("/"); 13307 String subStr1 = fullCodePath.substring(0, eidx); 13308 int sidx = subStr1.lastIndexOf("/"); 13309 cid = subStr1.substring(sidx+1, eidx); 13310 setMountPath(subStr1); 13311 } 13312 13313 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13314 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13315 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13316 instructionSets, null, null, null, 0, null /*certificates*/); 13317 this.cid = cid; 13318 setMountPath(PackageHelper.getSdDir(cid)); 13319 } 13320 13321 void createCopyFile() { 13322 cid = mInstallerService.allocateExternalStageCidLegacy(); 13323 } 13324 13325 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13326 if (origin.staged && origin.cid != null) { 13327 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13328 cid = origin.cid; 13329 setMountPath(PackageHelper.getSdDir(cid)); 13330 return PackageManager.INSTALL_SUCCEEDED; 13331 } 13332 13333 if (temp) { 13334 createCopyFile(); 13335 } else { 13336 /* 13337 * Pre-emptively destroy the container since it's destroyed if 13338 * copying fails due to it existing anyway. 13339 */ 13340 PackageHelper.destroySdDir(cid); 13341 } 13342 13343 final String newMountPath = imcs.copyPackageToContainer( 13344 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13345 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13346 13347 if (newMountPath != null) { 13348 setMountPath(newMountPath); 13349 return PackageManager.INSTALL_SUCCEEDED; 13350 } else { 13351 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13352 } 13353 } 13354 13355 @Override 13356 String getCodePath() { 13357 return packagePath; 13358 } 13359 13360 @Override 13361 String getResourcePath() { 13362 return resourcePath; 13363 } 13364 13365 int doPreInstall(int status) { 13366 if (status != PackageManager.INSTALL_SUCCEEDED) { 13367 // Destroy container 13368 PackageHelper.destroySdDir(cid); 13369 } else { 13370 boolean mounted = PackageHelper.isContainerMounted(cid); 13371 if (!mounted) { 13372 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13373 Process.SYSTEM_UID); 13374 if (newMountPath != null) { 13375 setMountPath(newMountPath); 13376 } else { 13377 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13378 } 13379 } 13380 } 13381 return status; 13382 } 13383 13384 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13385 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13386 String newMountPath = null; 13387 if (PackageHelper.isContainerMounted(cid)) { 13388 // Unmount the container 13389 if (!PackageHelper.unMountSdDir(cid)) { 13390 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13391 return false; 13392 } 13393 } 13394 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13395 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13396 " which might be stale. Will try to clean up."); 13397 // Clean up the stale container and proceed to recreate. 13398 if (!PackageHelper.destroySdDir(newCacheId)) { 13399 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13400 return false; 13401 } 13402 // Successfully cleaned up stale container. Try to rename again. 13403 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13404 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13405 + " inspite of cleaning it up."); 13406 return false; 13407 } 13408 } 13409 if (!PackageHelper.isContainerMounted(newCacheId)) { 13410 Slog.w(TAG, "Mounting container " + newCacheId); 13411 newMountPath = PackageHelper.mountSdDir(newCacheId, 13412 getEncryptKey(), Process.SYSTEM_UID); 13413 } else { 13414 newMountPath = PackageHelper.getSdDir(newCacheId); 13415 } 13416 if (newMountPath == null) { 13417 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13418 return false; 13419 } 13420 Log.i(TAG, "Succesfully renamed " + cid + 13421 " to " + newCacheId + 13422 " at new path: " + newMountPath); 13423 cid = newCacheId; 13424 13425 final File beforeCodeFile = new File(packagePath); 13426 setMountPath(newMountPath); 13427 final File afterCodeFile = new File(packagePath); 13428 13429 // Reflect the rename in scanned details 13430 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13431 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13432 afterCodeFile, pkg.baseCodePath)); 13433 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13434 afterCodeFile, pkg.splitCodePaths)); 13435 13436 // Reflect the rename in app info 13437 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13438 pkg.setApplicationInfoCodePath(pkg.codePath); 13439 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13440 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13441 pkg.setApplicationInfoResourcePath(pkg.codePath); 13442 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13443 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13444 13445 return true; 13446 } 13447 13448 private void setMountPath(String mountPath) { 13449 final File mountFile = new File(mountPath); 13450 13451 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13452 if (monolithicFile.exists()) { 13453 packagePath = monolithicFile.getAbsolutePath(); 13454 if (isFwdLocked()) { 13455 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13456 } else { 13457 resourcePath = packagePath; 13458 } 13459 } else { 13460 packagePath = mountFile.getAbsolutePath(); 13461 resourcePath = packagePath; 13462 } 13463 } 13464 13465 int doPostInstall(int status, int uid) { 13466 if (status != PackageManager.INSTALL_SUCCEEDED) { 13467 cleanUp(); 13468 } else { 13469 final int groupOwner; 13470 final String protectedFile; 13471 if (isFwdLocked()) { 13472 groupOwner = UserHandle.getSharedAppGid(uid); 13473 protectedFile = RES_FILE_NAME; 13474 } else { 13475 groupOwner = -1; 13476 protectedFile = null; 13477 } 13478 13479 if (uid < Process.FIRST_APPLICATION_UID 13480 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13481 Slog.e(TAG, "Failed to finalize " + cid); 13482 PackageHelper.destroySdDir(cid); 13483 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13484 } 13485 13486 boolean mounted = PackageHelper.isContainerMounted(cid); 13487 if (!mounted) { 13488 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13489 } 13490 } 13491 return status; 13492 } 13493 13494 private void cleanUp() { 13495 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13496 13497 // Destroy secure container 13498 PackageHelper.destroySdDir(cid); 13499 } 13500 13501 private List<String> getAllCodePaths() { 13502 final File codeFile = new File(getCodePath()); 13503 if (codeFile != null && codeFile.exists()) { 13504 try { 13505 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13506 return pkg.getAllCodePaths(); 13507 } catch (PackageParserException e) { 13508 // Ignored; we tried our best 13509 } 13510 } 13511 return Collections.EMPTY_LIST; 13512 } 13513 13514 void cleanUpResourcesLI() { 13515 // Enumerate all code paths before deleting 13516 cleanUpResourcesLI(getAllCodePaths()); 13517 } 13518 13519 private void cleanUpResourcesLI(List<String> allCodePaths) { 13520 cleanUp(); 13521 removeDexFiles(allCodePaths, instructionSets); 13522 } 13523 13524 String getPackageName() { 13525 return getAsecPackageName(cid); 13526 } 13527 13528 boolean doPostDeleteLI(boolean delete) { 13529 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13530 final List<String> allCodePaths = getAllCodePaths(); 13531 boolean mounted = PackageHelper.isContainerMounted(cid); 13532 if (mounted) { 13533 // Unmount first 13534 if (PackageHelper.unMountSdDir(cid)) { 13535 mounted = false; 13536 } 13537 } 13538 if (!mounted && delete) { 13539 cleanUpResourcesLI(allCodePaths); 13540 } 13541 return !mounted; 13542 } 13543 13544 @Override 13545 int doPreCopy() { 13546 if (isFwdLocked()) { 13547 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13548 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13549 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13550 } 13551 } 13552 13553 return PackageManager.INSTALL_SUCCEEDED; 13554 } 13555 13556 @Override 13557 int doPostCopy(int uid) { 13558 if (isFwdLocked()) { 13559 if (uid < Process.FIRST_APPLICATION_UID 13560 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13561 RES_FILE_NAME)) { 13562 Slog.e(TAG, "Failed to finalize " + cid); 13563 PackageHelper.destroySdDir(cid); 13564 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13565 } 13566 } 13567 13568 return PackageManager.INSTALL_SUCCEEDED; 13569 } 13570 } 13571 13572 /** 13573 * Logic to handle movement of existing installed applications. 13574 */ 13575 class MoveInstallArgs extends InstallArgs { 13576 private File codeFile; 13577 private File resourceFile; 13578 13579 /** New install */ 13580 MoveInstallArgs(InstallParams params) { 13581 super(params.origin, params.move, params.observer, params.installFlags, 13582 params.installerPackageName, params.volumeUuid, 13583 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13584 params.grantedRuntimePermissions, 13585 params.traceMethod, params.traceCookie, params.certificates); 13586 } 13587 13588 int copyApk(IMediaContainerService imcs, boolean temp) { 13589 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13590 + move.fromUuid + " to " + move.toUuid); 13591 synchronized (mInstaller) { 13592 try { 13593 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13594 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13595 } catch (InstallerException e) { 13596 Slog.w(TAG, "Failed to move app", e); 13597 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13598 } 13599 } 13600 13601 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13602 resourceFile = codeFile; 13603 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13604 13605 return PackageManager.INSTALL_SUCCEEDED; 13606 } 13607 13608 int doPreInstall(int status) { 13609 if (status != PackageManager.INSTALL_SUCCEEDED) { 13610 cleanUp(move.toUuid); 13611 } 13612 return status; 13613 } 13614 13615 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13616 if (status != PackageManager.INSTALL_SUCCEEDED) { 13617 cleanUp(move.toUuid); 13618 return false; 13619 } 13620 13621 // Reflect the move in app info 13622 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13623 pkg.setApplicationInfoCodePath(pkg.codePath); 13624 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13625 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13626 pkg.setApplicationInfoResourcePath(pkg.codePath); 13627 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13628 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13629 13630 return true; 13631 } 13632 13633 int doPostInstall(int status, int uid) { 13634 if (status == PackageManager.INSTALL_SUCCEEDED) { 13635 cleanUp(move.fromUuid); 13636 } else { 13637 cleanUp(move.toUuid); 13638 } 13639 return status; 13640 } 13641 13642 @Override 13643 String getCodePath() { 13644 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13645 } 13646 13647 @Override 13648 String getResourcePath() { 13649 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13650 } 13651 13652 private boolean cleanUp(String volumeUuid) { 13653 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13654 move.dataAppName); 13655 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13656 final int[] userIds = sUserManager.getUserIds(); 13657 synchronized (mInstallLock) { 13658 // Clean up both app data and code 13659 // All package moves are frozen until finished 13660 for (int userId : userIds) { 13661 try { 13662 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13663 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13664 } catch (InstallerException e) { 13665 Slog.w(TAG, String.valueOf(e)); 13666 } 13667 } 13668 removeCodePathLI(codeFile); 13669 } 13670 return true; 13671 } 13672 13673 void cleanUpResourcesLI() { 13674 throw new UnsupportedOperationException(); 13675 } 13676 13677 boolean doPostDeleteLI(boolean delete) { 13678 throw new UnsupportedOperationException(); 13679 } 13680 } 13681 13682 static String getAsecPackageName(String packageCid) { 13683 int idx = packageCid.lastIndexOf("-"); 13684 if (idx == -1) { 13685 return packageCid; 13686 } 13687 return packageCid.substring(0, idx); 13688 } 13689 13690 // Utility method used to create code paths based on package name and available index. 13691 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13692 String idxStr = ""; 13693 int idx = 1; 13694 // Fall back to default value of idx=1 if prefix is not 13695 // part of oldCodePath 13696 if (oldCodePath != null) { 13697 String subStr = oldCodePath; 13698 // Drop the suffix right away 13699 if (suffix != null && subStr.endsWith(suffix)) { 13700 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13701 } 13702 // If oldCodePath already contains prefix find out the 13703 // ending index to either increment or decrement. 13704 int sidx = subStr.lastIndexOf(prefix); 13705 if (sidx != -1) { 13706 subStr = subStr.substring(sidx + prefix.length()); 13707 if (subStr != null) { 13708 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13709 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13710 } 13711 try { 13712 idx = Integer.parseInt(subStr); 13713 if (idx <= 1) { 13714 idx++; 13715 } else { 13716 idx--; 13717 } 13718 } catch(NumberFormatException e) { 13719 } 13720 } 13721 } 13722 } 13723 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13724 return prefix + idxStr; 13725 } 13726 13727 private File getNextCodePath(File targetDir, String packageName) { 13728 int suffix = 1; 13729 File result; 13730 do { 13731 result = new File(targetDir, packageName + "-" + suffix); 13732 suffix++; 13733 } while (result.exists()); 13734 return result; 13735 } 13736 13737 // Utility method that returns the relative package path with respect 13738 // to the installation directory. Like say for /data/data/com.test-1.apk 13739 // string com.test-1 is returned. 13740 static String deriveCodePathName(String codePath) { 13741 if (codePath == null) { 13742 return null; 13743 } 13744 final File codeFile = new File(codePath); 13745 final String name = codeFile.getName(); 13746 if (codeFile.isDirectory()) { 13747 return name; 13748 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13749 final int lastDot = name.lastIndexOf('.'); 13750 return name.substring(0, lastDot); 13751 } else { 13752 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13753 return null; 13754 } 13755 } 13756 13757 static class PackageInstalledInfo { 13758 String name; 13759 int uid; 13760 // The set of users that originally had this package installed. 13761 int[] origUsers; 13762 // The set of users that now have this package installed. 13763 int[] newUsers; 13764 PackageParser.Package pkg; 13765 int returnCode; 13766 String returnMsg; 13767 PackageRemovedInfo removedInfo; 13768 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13769 13770 public void setError(int code, String msg) { 13771 setReturnCode(code); 13772 setReturnMessage(msg); 13773 Slog.w(TAG, msg); 13774 } 13775 13776 public void setError(String msg, PackageParserException e) { 13777 setReturnCode(e.error); 13778 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13779 Slog.w(TAG, msg, e); 13780 } 13781 13782 public void setError(String msg, PackageManagerException e) { 13783 returnCode = e.error; 13784 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13785 Slog.w(TAG, msg, e); 13786 } 13787 13788 public void setReturnCode(int returnCode) { 13789 this.returnCode = returnCode; 13790 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13791 for (int i = 0; i < childCount; i++) { 13792 addedChildPackages.valueAt(i).returnCode = returnCode; 13793 } 13794 } 13795 13796 private void setReturnMessage(String returnMsg) { 13797 this.returnMsg = returnMsg; 13798 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13799 for (int i = 0; i < childCount; i++) { 13800 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13801 } 13802 } 13803 13804 // In some error cases we want to convey more info back to the observer 13805 String origPackage; 13806 String origPermission; 13807 } 13808 13809 /* 13810 * Install a non-existing package. 13811 */ 13812 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13813 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13814 PackageInstalledInfo res) { 13815 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13816 13817 // Remember this for later, in case we need to rollback this install 13818 String pkgName = pkg.packageName; 13819 13820 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13821 13822 synchronized(mPackages) { 13823 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13824 // A package with the same name is already installed, though 13825 // it has been renamed to an older name. The package we 13826 // are trying to install should be installed as an update to 13827 // the existing one, but that has not been requested, so bail. 13828 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13829 + " without first uninstalling package running as " 13830 + mSettings.mRenamedPackages.get(pkgName)); 13831 return; 13832 } 13833 if (mPackages.containsKey(pkgName)) { 13834 // Don't allow installation over an existing package with the same name. 13835 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13836 + " without first uninstalling."); 13837 return; 13838 } 13839 } 13840 13841 try { 13842 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13843 System.currentTimeMillis(), user); 13844 13845 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13846 13847 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13848 prepareAppDataAfterInstallLIF(newPackage); 13849 13850 } else { 13851 // Remove package from internal structures, but keep around any 13852 // data that might have already existed 13853 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13854 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13855 } 13856 } catch (PackageManagerException e) { 13857 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13858 } 13859 13860 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13861 } 13862 13863 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13864 // Can't rotate keys during boot or if sharedUser. 13865 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13866 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13867 return false; 13868 } 13869 // app is using upgradeKeySets; make sure all are valid 13870 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13871 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13872 for (int i = 0; i < upgradeKeySets.length; i++) { 13873 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13874 Slog.wtf(TAG, "Package " 13875 + (oldPs.name != null ? oldPs.name : "<null>") 13876 + " contains upgrade-key-set reference to unknown key-set: " 13877 + upgradeKeySets[i] 13878 + " reverting to signatures check."); 13879 return false; 13880 } 13881 } 13882 return true; 13883 } 13884 13885 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13886 // Upgrade keysets are being used. Determine if new package has a superset of the 13887 // required keys. 13888 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13889 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13890 for (int i = 0; i < upgradeKeySets.length; i++) { 13891 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13892 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13893 return true; 13894 } 13895 } 13896 return false; 13897 } 13898 13899 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13900 try (DigestInputStream digestStream = 13901 new DigestInputStream(new FileInputStream(file), digest)) { 13902 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13903 } 13904 } 13905 13906 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13907 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13908 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13909 13910 final PackageParser.Package oldPackage; 13911 final String pkgName = pkg.packageName; 13912 final int[] allUsers; 13913 final int[] installedUsers; 13914 13915 synchronized(mPackages) { 13916 oldPackage = mPackages.get(pkgName); 13917 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13918 13919 // don't allow upgrade to target a release SDK from a pre-release SDK 13920 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13921 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13922 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13923 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13924 if (oldTargetsPreRelease 13925 && !newTargetsPreRelease 13926 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13927 Slog.w(TAG, "Can't install package targeting released sdk"); 13928 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13929 return; 13930 } 13931 13932 // don't allow an upgrade from full to ephemeral 13933 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13934 if (isEphemeral && !oldIsEphemeral) { 13935 // can't downgrade from full to ephemeral 13936 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13937 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13938 return; 13939 } 13940 13941 // verify signatures are valid 13942 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13943 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13944 if (!checkUpgradeKeySetLP(ps, pkg)) { 13945 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13946 "New package not signed by keys specified by upgrade-keysets: " 13947 + pkgName); 13948 return; 13949 } 13950 } else { 13951 // default to original signature matching 13952 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13953 != PackageManager.SIGNATURE_MATCH) { 13954 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13955 "New package has a different signature: " + pkgName); 13956 return; 13957 } 13958 } 13959 13960 // don't allow a system upgrade unless the upgrade hash matches 13961 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13962 byte[] digestBytes = null; 13963 try { 13964 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13965 updateDigest(digest, new File(pkg.baseCodePath)); 13966 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13967 for (String path : pkg.splitCodePaths) { 13968 updateDigest(digest, new File(path)); 13969 } 13970 } 13971 digestBytes = digest.digest(); 13972 } catch (NoSuchAlgorithmException | IOException e) { 13973 res.setError(INSTALL_FAILED_INVALID_APK, 13974 "Could not compute hash: " + pkgName); 13975 return; 13976 } 13977 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13978 res.setError(INSTALL_FAILED_INVALID_APK, 13979 "New package fails restrict-update check: " + pkgName); 13980 return; 13981 } 13982 // retain upgrade restriction 13983 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13984 } 13985 13986 // Check for shared user id changes 13987 String invalidPackageName = 13988 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13989 if (invalidPackageName != null) { 13990 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13991 "Package " + invalidPackageName + " tried to change user " 13992 + oldPackage.mSharedUserId); 13993 return; 13994 } 13995 13996 // In case of rollback, remember per-user/profile install state 13997 allUsers = sUserManager.getUserIds(); 13998 installedUsers = ps.queryInstalledUsers(allUsers, true); 13999 } 14000 14001 // Update what is removed 14002 res.removedInfo = new PackageRemovedInfo(); 14003 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14004 res.removedInfo.removedPackage = oldPackage.packageName; 14005 res.removedInfo.isUpdate = true; 14006 res.removedInfo.origUsers = installedUsers; 14007 final int childCount = (oldPackage.childPackages != null) 14008 ? oldPackage.childPackages.size() : 0; 14009 for (int i = 0; i < childCount; i++) { 14010 boolean childPackageUpdated = false; 14011 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14012 if (res.addedChildPackages != null) { 14013 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14014 if (childRes != null) { 14015 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14016 childRes.removedInfo.removedPackage = childPkg.packageName; 14017 childRes.removedInfo.isUpdate = true; 14018 childPackageUpdated = true; 14019 } 14020 } 14021 if (!childPackageUpdated) { 14022 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14023 childRemovedRes.removedPackage = childPkg.packageName; 14024 childRemovedRes.isUpdate = false; 14025 childRemovedRes.dataRemoved = true; 14026 synchronized (mPackages) { 14027 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14028 if (childPs != null) { 14029 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14030 } 14031 } 14032 if (res.removedInfo.removedChildPackages == null) { 14033 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14034 } 14035 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14036 } 14037 } 14038 14039 boolean sysPkg = (isSystemApp(oldPackage)); 14040 if (sysPkg) { 14041 // Set the system/privileged flags as needed 14042 final boolean privileged = 14043 (oldPackage.applicationInfo.privateFlags 14044 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14045 final int systemPolicyFlags = policyFlags 14046 | PackageParser.PARSE_IS_SYSTEM 14047 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14048 14049 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14050 user, allUsers, installerPackageName, res); 14051 } else { 14052 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14053 user, allUsers, installerPackageName, res); 14054 } 14055 } 14056 14057 public List<String> getPreviousCodePaths(String packageName) { 14058 final PackageSetting ps = mSettings.mPackages.get(packageName); 14059 final List<String> result = new ArrayList<String>(); 14060 if (ps != null && ps.oldCodePaths != null) { 14061 result.addAll(ps.oldCodePaths); 14062 } 14063 return result; 14064 } 14065 14066 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14067 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14068 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14069 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14070 + deletedPackage); 14071 14072 String pkgName = deletedPackage.packageName; 14073 boolean deletedPkg = true; 14074 boolean addedPkg = false; 14075 boolean updatedSettings = false; 14076 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14077 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14078 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14079 14080 final long origUpdateTime = (pkg.mExtras != null) 14081 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14082 14083 // First delete the existing package while retaining the data directory 14084 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14085 res.removedInfo, true, pkg)) { 14086 // If the existing package wasn't successfully deleted 14087 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14088 deletedPkg = false; 14089 } else { 14090 // Successfully deleted the old package; proceed with replace. 14091 14092 // If deleted package lived in a container, give users a chance to 14093 // relinquish resources before killing. 14094 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14095 if (DEBUG_INSTALL) { 14096 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14097 } 14098 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14099 final ArrayList<String> pkgList = new ArrayList<String>(1); 14100 pkgList.add(deletedPackage.applicationInfo.packageName); 14101 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14102 } 14103 14104 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14105 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14106 clearAppProfilesLIF(pkg); 14107 14108 try { 14109 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14110 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14111 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14112 14113 // Update the in-memory copy of the previous code paths. 14114 PackageSetting ps = mSettings.mPackages.get(pkgName); 14115 if (!killApp) { 14116 if (ps.oldCodePaths == null) { 14117 ps.oldCodePaths = new ArraySet<>(); 14118 } 14119 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14120 if (deletedPackage.splitCodePaths != null) { 14121 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14122 } 14123 } else { 14124 ps.oldCodePaths = null; 14125 } 14126 if (ps.childPackageNames != null) { 14127 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14128 final String childPkgName = ps.childPackageNames.get(i); 14129 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14130 childPs.oldCodePaths = ps.oldCodePaths; 14131 } 14132 } 14133 prepareAppDataAfterInstallLIF(newPackage); 14134 addedPkg = true; 14135 } catch (PackageManagerException e) { 14136 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14137 } 14138 } 14139 14140 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14141 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14142 14143 // Revert all internal state mutations and added folders for the failed install 14144 if (addedPkg) { 14145 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14146 res.removedInfo, true, null); 14147 } 14148 14149 // Restore the old package 14150 if (deletedPkg) { 14151 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14152 File restoreFile = new File(deletedPackage.codePath); 14153 // Parse old package 14154 boolean oldExternal = isExternal(deletedPackage); 14155 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14156 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14157 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14158 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14159 try { 14160 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14161 null); 14162 } catch (PackageManagerException e) { 14163 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14164 + e.getMessage()); 14165 return; 14166 } 14167 14168 synchronized (mPackages) { 14169 // Ensure the installer package name up to date 14170 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14171 14172 // Update permissions for restored package 14173 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14174 14175 mSettings.writeLPr(); 14176 } 14177 14178 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14179 } 14180 } else { 14181 synchronized (mPackages) { 14182 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14183 if (ps != null) { 14184 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14185 if (res.removedInfo.removedChildPackages != null) { 14186 final int childCount = res.removedInfo.removedChildPackages.size(); 14187 // Iterate in reverse as we may modify the collection 14188 for (int i = childCount - 1; i >= 0; i--) { 14189 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14190 if (res.addedChildPackages.containsKey(childPackageName)) { 14191 res.removedInfo.removedChildPackages.removeAt(i); 14192 } else { 14193 PackageRemovedInfo childInfo = res.removedInfo 14194 .removedChildPackages.valueAt(i); 14195 childInfo.removedForAllUsers = mPackages.get( 14196 childInfo.removedPackage) == null; 14197 } 14198 } 14199 } 14200 } 14201 } 14202 } 14203 } 14204 14205 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14206 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14207 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14208 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14209 + ", old=" + deletedPackage); 14210 14211 final boolean disabledSystem; 14212 14213 // Remove existing system package 14214 removePackageLI(deletedPackage, true); 14215 14216 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14217 if (!disabledSystem) { 14218 // We didn't need to disable the .apk as a current system package, 14219 // which means we are replacing another update that is already 14220 // installed. We need to make sure to delete the older one's .apk. 14221 res.removedInfo.args = createInstallArgsForExisting(0, 14222 deletedPackage.applicationInfo.getCodePath(), 14223 deletedPackage.applicationInfo.getResourcePath(), 14224 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14225 } else { 14226 res.removedInfo.args = null; 14227 } 14228 14229 // Successfully disabled the old package. Now proceed with re-installation 14230 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14231 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14232 clearAppProfilesLIF(pkg); 14233 14234 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14235 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14236 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14237 14238 PackageParser.Package newPackage = null; 14239 try { 14240 // Add the package to the internal data structures 14241 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14242 14243 // Set the update and install times 14244 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14245 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14246 System.currentTimeMillis()); 14247 14248 // Update the package dynamic state if succeeded 14249 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14250 // Now that the install succeeded make sure we remove data 14251 // directories for any child package the update removed. 14252 final int deletedChildCount = (deletedPackage.childPackages != null) 14253 ? deletedPackage.childPackages.size() : 0; 14254 final int newChildCount = (newPackage.childPackages != null) 14255 ? newPackage.childPackages.size() : 0; 14256 for (int i = 0; i < deletedChildCount; i++) { 14257 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14258 boolean childPackageDeleted = true; 14259 for (int j = 0; j < newChildCount; j++) { 14260 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14261 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14262 childPackageDeleted = false; 14263 break; 14264 } 14265 } 14266 if (childPackageDeleted) { 14267 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14268 deletedChildPkg.packageName); 14269 if (ps != null && res.removedInfo.removedChildPackages != null) { 14270 PackageRemovedInfo removedChildRes = res.removedInfo 14271 .removedChildPackages.get(deletedChildPkg.packageName); 14272 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14273 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14274 } 14275 } 14276 } 14277 14278 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14279 prepareAppDataAfterInstallLIF(newPackage); 14280 } 14281 } catch (PackageManagerException e) { 14282 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14283 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14284 } 14285 14286 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14287 // Re installation failed. Restore old information 14288 // Remove new pkg information 14289 if (newPackage != null) { 14290 removeInstalledPackageLI(newPackage, true); 14291 } 14292 // Add back the old system package 14293 try { 14294 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14295 } catch (PackageManagerException e) { 14296 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14297 } 14298 14299 synchronized (mPackages) { 14300 if (disabledSystem) { 14301 enableSystemPackageLPw(deletedPackage); 14302 } 14303 14304 // Ensure the installer package name up to date 14305 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14306 14307 // Update permissions for restored package 14308 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14309 14310 mSettings.writeLPr(); 14311 } 14312 14313 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14314 + " after failed upgrade"); 14315 } 14316 } 14317 14318 /** 14319 * Checks whether the parent or any of the child packages have a change shared 14320 * user. For a package to be a valid update the shred users of the parent and 14321 * the children should match. We may later support changing child shared users. 14322 * @param oldPkg The updated package. 14323 * @param newPkg The update package. 14324 * @return The shared user that change between the versions. 14325 */ 14326 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14327 PackageParser.Package newPkg) { 14328 // Check parent shared user 14329 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14330 return newPkg.packageName; 14331 } 14332 // Check child shared users 14333 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14334 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14335 for (int i = 0; i < newChildCount; i++) { 14336 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14337 // If this child was present, did it have the same shared user? 14338 for (int j = 0; j < oldChildCount; j++) { 14339 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14340 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14341 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14342 return newChildPkg.packageName; 14343 } 14344 } 14345 } 14346 return null; 14347 } 14348 14349 private void removeNativeBinariesLI(PackageSetting ps) { 14350 // Remove the lib path for the parent package 14351 if (ps != null) { 14352 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14353 // Remove the lib path for the child packages 14354 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14355 for (int i = 0; i < childCount; i++) { 14356 PackageSetting childPs = null; 14357 synchronized (mPackages) { 14358 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14359 } 14360 if (childPs != null) { 14361 NativeLibraryHelper.removeNativeBinariesLI(childPs 14362 .legacyNativeLibraryPathString); 14363 } 14364 } 14365 } 14366 } 14367 14368 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14369 // Enable the parent package 14370 mSettings.enableSystemPackageLPw(pkg.packageName); 14371 // Enable the child packages 14372 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14373 for (int i = 0; i < childCount; i++) { 14374 PackageParser.Package childPkg = pkg.childPackages.get(i); 14375 mSettings.enableSystemPackageLPw(childPkg.packageName); 14376 } 14377 } 14378 14379 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14380 PackageParser.Package newPkg) { 14381 // Disable the parent package (parent always replaced) 14382 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14383 // Disable the child packages 14384 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14385 for (int i = 0; i < childCount; i++) { 14386 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14387 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14388 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14389 } 14390 return disabled; 14391 } 14392 14393 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14394 String installerPackageName) { 14395 // Enable the parent package 14396 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14397 // Enable the child packages 14398 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14399 for (int i = 0; i < childCount; i++) { 14400 PackageParser.Package childPkg = pkg.childPackages.get(i); 14401 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14402 } 14403 } 14404 14405 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14406 // Collect all used permissions in the UID 14407 ArraySet<String> usedPermissions = new ArraySet<>(); 14408 final int packageCount = su.packages.size(); 14409 for (int i = 0; i < packageCount; i++) { 14410 PackageSetting ps = su.packages.valueAt(i); 14411 if (ps.pkg == null) { 14412 continue; 14413 } 14414 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14415 for (int j = 0; j < requestedPermCount; j++) { 14416 String permission = ps.pkg.requestedPermissions.get(j); 14417 BasePermission bp = mSettings.mPermissions.get(permission); 14418 if (bp != null) { 14419 usedPermissions.add(permission); 14420 } 14421 } 14422 } 14423 14424 PermissionsState permissionsState = su.getPermissionsState(); 14425 // Prune install permissions 14426 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14427 final int installPermCount = installPermStates.size(); 14428 for (int i = installPermCount - 1; i >= 0; i--) { 14429 PermissionState permissionState = installPermStates.get(i); 14430 if (!usedPermissions.contains(permissionState.getName())) { 14431 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14432 if (bp != null) { 14433 permissionsState.revokeInstallPermission(bp); 14434 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14435 PackageManager.MASK_PERMISSION_FLAGS, 0); 14436 } 14437 } 14438 } 14439 14440 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14441 14442 // Prune runtime permissions 14443 for (int userId : allUserIds) { 14444 List<PermissionState> runtimePermStates = permissionsState 14445 .getRuntimePermissionStates(userId); 14446 final int runtimePermCount = runtimePermStates.size(); 14447 for (int i = runtimePermCount - 1; i >= 0; i--) { 14448 PermissionState permissionState = runtimePermStates.get(i); 14449 if (!usedPermissions.contains(permissionState.getName())) { 14450 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14451 if (bp != null) { 14452 permissionsState.revokeRuntimePermission(bp, userId); 14453 permissionsState.updatePermissionFlags(bp, userId, 14454 PackageManager.MASK_PERMISSION_FLAGS, 0); 14455 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14456 runtimePermissionChangedUserIds, userId); 14457 } 14458 } 14459 } 14460 } 14461 14462 return runtimePermissionChangedUserIds; 14463 } 14464 14465 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14466 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14467 // Update the parent package setting 14468 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14469 res, user); 14470 // Update the child packages setting 14471 final int childCount = (newPackage.childPackages != null) 14472 ? newPackage.childPackages.size() : 0; 14473 for (int i = 0; i < childCount; i++) { 14474 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14475 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14476 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14477 childRes.origUsers, childRes, user); 14478 } 14479 } 14480 14481 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14482 String installerPackageName, int[] allUsers, int[] installedForUsers, 14483 PackageInstalledInfo res, UserHandle user) { 14484 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14485 14486 String pkgName = newPackage.packageName; 14487 synchronized (mPackages) { 14488 //write settings. the installStatus will be incomplete at this stage. 14489 //note that the new package setting would have already been 14490 //added to mPackages. It hasn't been persisted yet. 14491 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14492 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14493 mSettings.writeLPr(); 14494 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14495 } 14496 14497 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14498 synchronized (mPackages) { 14499 updatePermissionsLPw(newPackage.packageName, newPackage, 14500 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14501 ? UPDATE_PERMISSIONS_ALL : 0)); 14502 // For system-bundled packages, we assume that installing an upgraded version 14503 // of the package implies that the user actually wants to run that new code, 14504 // so we enable the package. 14505 PackageSetting ps = mSettings.mPackages.get(pkgName); 14506 final int userId = user.getIdentifier(); 14507 if (ps != null) { 14508 if (isSystemApp(newPackage)) { 14509 if (DEBUG_INSTALL) { 14510 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14511 } 14512 // Enable system package for requested users 14513 if (res.origUsers != null) { 14514 for (int origUserId : res.origUsers) { 14515 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14516 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14517 origUserId, installerPackageName); 14518 } 14519 } 14520 } 14521 // Also convey the prior install/uninstall state 14522 if (allUsers != null && installedForUsers != null) { 14523 for (int currentUserId : allUsers) { 14524 final boolean installed = ArrayUtils.contains( 14525 installedForUsers, currentUserId); 14526 if (DEBUG_INSTALL) { 14527 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14528 } 14529 ps.setInstalled(installed, currentUserId); 14530 } 14531 // these install state changes will be persisted in the 14532 // upcoming call to mSettings.writeLPr(). 14533 } 14534 } 14535 // It's implied that when a user requests installation, they want the app to be 14536 // installed and enabled. 14537 if (userId != UserHandle.USER_ALL) { 14538 ps.setInstalled(true, userId); 14539 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14540 } 14541 } 14542 res.name = pkgName; 14543 res.uid = newPackage.applicationInfo.uid; 14544 res.pkg = newPackage; 14545 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14546 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14547 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14548 //to update install status 14549 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14550 mSettings.writeLPr(); 14551 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14552 } 14553 14554 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14555 } 14556 14557 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14558 try { 14559 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14560 installPackageLI(args, res); 14561 } finally { 14562 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14563 } 14564 } 14565 14566 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14567 final int installFlags = args.installFlags; 14568 final String installerPackageName = args.installerPackageName; 14569 final String volumeUuid = args.volumeUuid; 14570 final File tmpPackageFile = new File(args.getCodePath()); 14571 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14572 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14573 || (args.volumeUuid != null)); 14574 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14575 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14576 boolean replace = false; 14577 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14578 if (args.move != null) { 14579 // moving a complete application; perform an initial scan on the new install location 14580 scanFlags |= SCAN_INITIAL; 14581 } 14582 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14583 scanFlags |= SCAN_DONT_KILL_APP; 14584 } 14585 14586 // Result object to be returned 14587 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14588 14589 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14590 14591 // Sanity check 14592 if (ephemeral && (forwardLocked || onExternal)) { 14593 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14594 + " external=" + onExternal); 14595 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14596 return; 14597 } 14598 14599 // Retrieve PackageSettings and parse package 14600 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14601 | PackageParser.PARSE_ENFORCE_CODE 14602 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14603 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14604 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14605 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14606 PackageParser pp = new PackageParser(); 14607 pp.setSeparateProcesses(mSeparateProcesses); 14608 pp.setDisplayMetrics(mMetrics); 14609 14610 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14611 final PackageParser.Package pkg; 14612 try { 14613 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14614 } catch (PackageParserException e) { 14615 res.setError("Failed parse during installPackageLI", e); 14616 return; 14617 } finally { 14618 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14619 } 14620 14621 // If we are installing a clustered package add results for the children 14622 if (pkg.childPackages != null) { 14623 synchronized (mPackages) { 14624 final int childCount = pkg.childPackages.size(); 14625 for (int i = 0; i < childCount; i++) { 14626 PackageParser.Package childPkg = pkg.childPackages.get(i); 14627 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14628 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14629 childRes.pkg = childPkg; 14630 childRes.name = childPkg.packageName; 14631 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14632 if (childPs != null) { 14633 childRes.origUsers = childPs.queryInstalledUsers( 14634 sUserManager.getUserIds(), true); 14635 } 14636 if ((mPackages.containsKey(childPkg.packageName))) { 14637 childRes.removedInfo = new PackageRemovedInfo(); 14638 childRes.removedInfo.removedPackage = childPkg.packageName; 14639 } 14640 if (res.addedChildPackages == null) { 14641 res.addedChildPackages = new ArrayMap<>(); 14642 } 14643 res.addedChildPackages.put(childPkg.packageName, childRes); 14644 } 14645 } 14646 } 14647 14648 // If package doesn't declare API override, mark that we have an install 14649 // time CPU ABI override. 14650 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14651 pkg.cpuAbiOverride = args.abiOverride; 14652 } 14653 14654 String pkgName = res.name = pkg.packageName; 14655 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14656 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14657 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14658 return; 14659 } 14660 } 14661 14662 try { 14663 // either use what we've been given or parse directly from the APK 14664 if (args.certificates != null) { 14665 try { 14666 PackageParser.populateCertificates(pkg, args.certificates); 14667 } catch (PackageParserException e) { 14668 // there was something wrong with the certificates we were given; 14669 // try to pull them from the APK 14670 PackageParser.collectCertificates(pkg, parseFlags); 14671 } 14672 } else { 14673 PackageParser.collectCertificates(pkg, parseFlags); 14674 } 14675 } catch (PackageParserException e) { 14676 res.setError("Failed collect during installPackageLI", e); 14677 return; 14678 } 14679 14680 // Get rid of all references to package scan path via parser. 14681 pp = null; 14682 String oldCodePath = null; 14683 boolean systemApp = false; 14684 synchronized (mPackages) { 14685 // Check if installing already existing package 14686 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14687 String oldName = mSettings.mRenamedPackages.get(pkgName); 14688 if (pkg.mOriginalPackages != null 14689 && pkg.mOriginalPackages.contains(oldName) 14690 && mPackages.containsKey(oldName)) { 14691 // This package is derived from an original package, 14692 // and this device has been updating from that original 14693 // name. We must continue using the original name, so 14694 // rename the new package here. 14695 pkg.setPackageName(oldName); 14696 pkgName = pkg.packageName; 14697 replace = true; 14698 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14699 + oldName + " pkgName=" + pkgName); 14700 } else if (mPackages.containsKey(pkgName)) { 14701 // This package, under its official name, already exists 14702 // on the device; we should replace it. 14703 replace = true; 14704 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14705 } 14706 14707 // Child packages are installed through the parent package 14708 if (pkg.parentPackage != null) { 14709 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14710 "Package " + pkg.packageName + " is child of package " 14711 + pkg.parentPackage.parentPackage + ". Child packages " 14712 + "can be updated only through the parent package."); 14713 return; 14714 } 14715 14716 if (replace) { 14717 // Prevent apps opting out from runtime permissions 14718 PackageParser.Package oldPackage = mPackages.get(pkgName); 14719 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14720 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14721 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14722 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14723 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14724 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14725 + " doesn't support runtime permissions but the old" 14726 + " target SDK " + oldTargetSdk + " does."); 14727 return; 14728 } 14729 14730 // Prevent installing of child packages 14731 if (oldPackage.parentPackage != null) { 14732 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14733 "Package " + pkg.packageName + " is child of package " 14734 + oldPackage.parentPackage + ". Child packages " 14735 + "can be updated only through the parent package."); 14736 return; 14737 } 14738 } 14739 } 14740 14741 PackageSetting ps = mSettings.mPackages.get(pkgName); 14742 if (ps != null) { 14743 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14744 14745 // Quick sanity check that we're signed correctly if updating; 14746 // we'll check this again later when scanning, but we want to 14747 // bail early here before tripping over redefined permissions. 14748 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14749 if (!checkUpgradeKeySetLP(ps, pkg)) { 14750 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14751 + pkg.packageName + " upgrade keys do not match the " 14752 + "previously installed version"); 14753 return; 14754 } 14755 } else { 14756 try { 14757 verifySignaturesLP(ps, pkg); 14758 } catch (PackageManagerException e) { 14759 res.setError(e.error, e.getMessage()); 14760 return; 14761 } 14762 } 14763 14764 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14765 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14766 systemApp = (ps.pkg.applicationInfo.flags & 14767 ApplicationInfo.FLAG_SYSTEM) != 0; 14768 } 14769 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14770 } 14771 14772 // Check whether the newly-scanned package wants to define an already-defined perm 14773 int N = pkg.permissions.size(); 14774 for (int i = N-1; i >= 0; i--) { 14775 PackageParser.Permission perm = pkg.permissions.get(i); 14776 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14777 if (bp != null) { 14778 // If the defining package is signed with our cert, it's okay. This 14779 // also includes the "updating the same package" case, of course. 14780 // "updating same package" could also involve key-rotation. 14781 final boolean sigsOk; 14782 if (bp.sourcePackage.equals(pkg.packageName) 14783 && (bp.packageSetting instanceof PackageSetting) 14784 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14785 scanFlags))) { 14786 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14787 } else { 14788 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14789 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14790 } 14791 if (!sigsOk) { 14792 // If the owning package is the system itself, we log but allow 14793 // install to proceed; we fail the install on all other permission 14794 // redefinitions. 14795 if (!bp.sourcePackage.equals("android")) { 14796 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14797 + pkg.packageName + " attempting to redeclare permission " 14798 + perm.info.name + " already owned by " + bp.sourcePackage); 14799 res.origPermission = perm.info.name; 14800 res.origPackage = bp.sourcePackage; 14801 return; 14802 } else { 14803 Slog.w(TAG, "Package " + pkg.packageName 14804 + " attempting to redeclare system permission " 14805 + perm.info.name + "; ignoring new declaration"); 14806 pkg.permissions.remove(i); 14807 } 14808 } 14809 } 14810 } 14811 } 14812 14813 if (systemApp) { 14814 if (onExternal) { 14815 // Abort update; system app can't be replaced with app on sdcard 14816 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14817 "Cannot install updates to system apps on sdcard"); 14818 return; 14819 } else if (ephemeral) { 14820 // Abort update; system app can't be replaced with an ephemeral app 14821 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14822 "Cannot update a system app with an ephemeral app"); 14823 return; 14824 } 14825 } 14826 14827 if (args.move != null) { 14828 // We did an in-place move, so dex is ready to roll 14829 scanFlags |= SCAN_NO_DEX; 14830 scanFlags |= SCAN_MOVE; 14831 14832 synchronized (mPackages) { 14833 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14834 if (ps == null) { 14835 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14836 "Missing settings for moved package " + pkgName); 14837 } 14838 14839 // We moved the entire application as-is, so bring over the 14840 // previously derived ABI information. 14841 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14842 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14843 } 14844 14845 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14846 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14847 scanFlags |= SCAN_NO_DEX; 14848 14849 try { 14850 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14851 args.abiOverride : pkg.cpuAbiOverride); 14852 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14853 true /* extract libs */); 14854 } catch (PackageManagerException pme) { 14855 Slog.e(TAG, "Error deriving application ABI", pme); 14856 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14857 return; 14858 } 14859 14860 // Shared libraries for the package need to be updated. 14861 synchronized (mPackages) { 14862 try { 14863 updateSharedLibrariesLPw(pkg, null); 14864 } catch (PackageManagerException e) { 14865 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14866 } 14867 } 14868 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14869 // Do not run PackageDexOptimizer through the local performDexOpt 14870 // method because `pkg` is not in `mPackages` yet. 14871 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14872 null /* instructionSets */, false /* checkProfiles */, 14873 getCompilerFilterForReason(REASON_INSTALL)); 14874 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14875 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14876 String msg = "Extracting package failed for " + pkgName; 14877 res.setError(INSTALL_FAILED_DEXOPT, msg); 14878 return; 14879 } 14880 14881 // Notify BackgroundDexOptService that the package has been changed. 14882 // If this is an update of a package which used to fail to compile, 14883 // BDOS will remove it from its blacklist. 14884 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14885 } 14886 14887 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14888 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14889 return; 14890 } 14891 14892 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14893 14894 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14895 "installPackageLI")) { 14896 if (replace) { 14897 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14898 installerPackageName, res); 14899 } else { 14900 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14901 args.user, installerPackageName, volumeUuid, res); 14902 } 14903 } 14904 synchronized (mPackages) { 14905 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14906 if (ps != null) { 14907 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14908 } 14909 14910 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14911 for (int i = 0; i < childCount; i++) { 14912 PackageParser.Package childPkg = pkg.childPackages.get(i); 14913 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14914 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14915 if (childPs != null) { 14916 childRes.newUsers = childPs.queryInstalledUsers( 14917 sUserManager.getUserIds(), true); 14918 } 14919 } 14920 } 14921 } 14922 14923 private void startIntentFilterVerifications(int userId, boolean replacing, 14924 PackageParser.Package pkg) { 14925 if (mIntentFilterVerifierComponent == null) { 14926 Slog.w(TAG, "No IntentFilter verification will not be done as " 14927 + "there is no IntentFilterVerifier available!"); 14928 return; 14929 } 14930 14931 final int verifierUid = getPackageUid( 14932 mIntentFilterVerifierComponent.getPackageName(), 14933 MATCH_DEBUG_TRIAGED_MISSING, 14934 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14935 14936 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14937 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14938 mHandler.sendMessage(msg); 14939 14940 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14941 for (int i = 0; i < childCount; i++) { 14942 PackageParser.Package childPkg = pkg.childPackages.get(i); 14943 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14944 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14945 mHandler.sendMessage(msg); 14946 } 14947 } 14948 14949 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14950 PackageParser.Package pkg) { 14951 int size = pkg.activities.size(); 14952 if (size == 0) { 14953 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14954 "No activity, so no need to verify any IntentFilter!"); 14955 return; 14956 } 14957 14958 final boolean hasDomainURLs = hasDomainURLs(pkg); 14959 if (!hasDomainURLs) { 14960 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14961 "No domain URLs, so no need to verify any IntentFilter!"); 14962 return; 14963 } 14964 14965 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14966 + " if any IntentFilter from the " + size 14967 + " Activities needs verification ..."); 14968 14969 int count = 0; 14970 final String packageName = pkg.packageName; 14971 14972 synchronized (mPackages) { 14973 // If this is a new install and we see that we've already run verification for this 14974 // package, we have nothing to do: it means the state was restored from backup. 14975 if (!replacing) { 14976 IntentFilterVerificationInfo ivi = 14977 mSettings.getIntentFilterVerificationLPr(packageName); 14978 if (ivi != null) { 14979 if (DEBUG_DOMAIN_VERIFICATION) { 14980 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14981 + ivi.getStatusString()); 14982 } 14983 return; 14984 } 14985 } 14986 14987 // If any filters need to be verified, then all need to be. 14988 boolean needToVerify = false; 14989 for (PackageParser.Activity a : pkg.activities) { 14990 for (ActivityIntentInfo filter : a.intents) { 14991 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14992 if (DEBUG_DOMAIN_VERIFICATION) { 14993 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14994 } 14995 needToVerify = true; 14996 break; 14997 } 14998 } 14999 } 15000 15001 if (needToVerify) { 15002 final int verificationId = mIntentFilterVerificationToken++; 15003 for (PackageParser.Activity a : pkg.activities) { 15004 for (ActivityIntentInfo filter : a.intents) { 15005 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15006 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15007 "Verification needed for IntentFilter:" + filter.toString()); 15008 mIntentFilterVerifier.addOneIntentFilterVerification( 15009 verifierUid, userId, verificationId, filter, packageName); 15010 count++; 15011 } 15012 } 15013 } 15014 } 15015 } 15016 15017 if (count > 0) { 15018 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15019 + " IntentFilter verification" + (count > 1 ? "s" : "") 15020 + " for userId:" + userId); 15021 mIntentFilterVerifier.startVerifications(userId); 15022 } else { 15023 if (DEBUG_DOMAIN_VERIFICATION) { 15024 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15025 } 15026 } 15027 } 15028 15029 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15030 final ComponentName cn = filter.activity.getComponentName(); 15031 final String packageName = cn.getPackageName(); 15032 15033 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15034 packageName); 15035 if (ivi == null) { 15036 return true; 15037 } 15038 int status = ivi.getStatus(); 15039 switch (status) { 15040 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15041 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15042 return true; 15043 15044 default: 15045 // Nothing to do 15046 return false; 15047 } 15048 } 15049 15050 private static boolean isMultiArch(ApplicationInfo info) { 15051 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15052 } 15053 15054 private static boolean isExternal(PackageParser.Package pkg) { 15055 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15056 } 15057 15058 private static boolean isExternal(PackageSetting ps) { 15059 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15060 } 15061 15062 private static boolean isEphemeral(PackageParser.Package pkg) { 15063 return pkg.applicationInfo.isEphemeralApp(); 15064 } 15065 15066 private static boolean isEphemeral(PackageSetting ps) { 15067 return ps.pkg != null && isEphemeral(ps.pkg); 15068 } 15069 15070 private static boolean isSystemApp(PackageParser.Package pkg) { 15071 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15072 } 15073 15074 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15075 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15076 } 15077 15078 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15079 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15080 } 15081 15082 private static boolean isSystemApp(PackageSetting ps) { 15083 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15084 } 15085 15086 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15087 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15088 } 15089 15090 private int packageFlagsToInstallFlags(PackageSetting ps) { 15091 int installFlags = 0; 15092 if (isEphemeral(ps)) { 15093 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15094 } 15095 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15096 // This existing package was an external ASEC install when we have 15097 // the external flag without a UUID 15098 installFlags |= PackageManager.INSTALL_EXTERNAL; 15099 } 15100 if (ps.isForwardLocked()) { 15101 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15102 } 15103 return installFlags; 15104 } 15105 15106 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15107 if (isExternal(pkg)) { 15108 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15109 return StorageManager.UUID_PRIMARY_PHYSICAL; 15110 } else { 15111 return pkg.volumeUuid; 15112 } 15113 } else { 15114 return StorageManager.UUID_PRIVATE_INTERNAL; 15115 } 15116 } 15117 15118 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15119 if (isExternal(pkg)) { 15120 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15121 return mSettings.getExternalVersion(); 15122 } else { 15123 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15124 } 15125 } else { 15126 return mSettings.getInternalVersion(); 15127 } 15128 } 15129 15130 private void deleteTempPackageFiles() { 15131 final FilenameFilter filter = new FilenameFilter() { 15132 public boolean accept(File dir, String name) { 15133 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15134 } 15135 }; 15136 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15137 file.delete(); 15138 } 15139 } 15140 15141 @Override 15142 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15143 int flags) { 15144 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15145 flags); 15146 } 15147 15148 @Override 15149 public void deletePackage(final String packageName, 15150 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15151 mContext.enforceCallingOrSelfPermission( 15152 android.Manifest.permission.DELETE_PACKAGES, null); 15153 Preconditions.checkNotNull(packageName); 15154 Preconditions.checkNotNull(observer); 15155 final int uid = Binder.getCallingUid(); 15156 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15157 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15158 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15159 mContext.enforceCallingOrSelfPermission( 15160 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15161 "deletePackage for user " + userId); 15162 } 15163 15164 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15165 try { 15166 observer.onPackageDeleted(packageName, 15167 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15168 } catch (RemoteException re) { 15169 } 15170 return; 15171 } 15172 15173 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15174 try { 15175 observer.onPackageDeleted(packageName, 15176 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15177 } catch (RemoteException re) { 15178 } 15179 return; 15180 } 15181 15182 if (DEBUG_REMOVE) { 15183 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15184 + " deleteAllUsers: " + deleteAllUsers ); 15185 } 15186 // Queue up an async operation since the package deletion may take a little while. 15187 mHandler.post(new Runnable() { 15188 public void run() { 15189 mHandler.removeCallbacks(this); 15190 int returnCode; 15191 if (!deleteAllUsers) { 15192 returnCode = deletePackageX(packageName, userId, deleteFlags); 15193 } else { 15194 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15195 // If nobody is blocking uninstall, proceed with delete for all users 15196 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15197 returnCode = deletePackageX(packageName, userId, deleteFlags); 15198 } else { 15199 // Otherwise uninstall individually for users with blockUninstalls=false 15200 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15201 for (int userId : users) { 15202 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15203 returnCode = deletePackageX(packageName, userId, userFlags); 15204 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15205 Slog.w(TAG, "Package delete failed for user " + userId 15206 + ", returnCode " + returnCode); 15207 } 15208 } 15209 } 15210 // The app has only been marked uninstalled for certain users. 15211 // We still need to report that delete was blocked 15212 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15213 } 15214 } 15215 try { 15216 observer.onPackageDeleted(packageName, returnCode, null); 15217 } catch (RemoteException e) { 15218 Log.i(TAG, "Observer no longer exists."); 15219 } //end catch 15220 } //end run 15221 }); 15222 } 15223 15224 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15225 int[] result = EMPTY_INT_ARRAY; 15226 for (int userId : userIds) { 15227 if (getBlockUninstallForUser(packageName, userId)) { 15228 result = ArrayUtils.appendInt(result, userId); 15229 } 15230 } 15231 return result; 15232 } 15233 15234 @Override 15235 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15236 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15237 } 15238 15239 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15240 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15241 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15242 try { 15243 if (dpm != null) { 15244 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15245 /* callingUserOnly =*/ false); 15246 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15247 : deviceOwnerComponentName.getPackageName(); 15248 // Does the package contains the device owner? 15249 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15250 // this check is probably not needed, since DO should be registered as a device 15251 // admin on some user too. (Original bug for this: b/17657954) 15252 if (packageName.equals(deviceOwnerPackageName)) { 15253 return true; 15254 } 15255 // Does it contain a device admin for any user? 15256 int[] users; 15257 if (userId == UserHandle.USER_ALL) { 15258 users = sUserManager.getUserIds(); 15259 } else { 15260 users = new int[]{userId}; 15261 } 15262 for (int i = 0; i < users.length; ++i) { 15263 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15264 return true; 15265 } 15266 } 15267 } 15268 } catch (RemoteException e) { 15269 } 15270 return false; 15271 } 15272 15273 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15274 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15275 } 15276 15277 /** 15278 * This method is an internal method that could be get invoked either 15279 * to delete an installed package or to clean up a failed installation. 15280 * After deleting an installed package, a broadcast is sent to notify any 15281 * listeners that the package has been removed. For cleaning up a failed 15282 * installation, the broadcast is not necessary since the package's 15283 * installation wouldn't have sent the initial broadcast either 15284 * The key steps in deleting a package are 15285 * deleting the package information in internal structures like mPackages, 15286 * deleting the packages base directories through installd 15287 * updating mSettings to reflect current status 15288 * persisting settings for later use 15289 * sending a broadcast if necessary 15290 */ 15291 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15292 final PackageRemovedInfo info = new PackageRemovedInfo(); 15293 final boolean res; 15294 15295 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15296 ? UserHandle.ALL : new UserHandle(userId); 15297 15298 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15299 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15300 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15301 } 15302 15303 PackageSetting uninstalledPs = null; 15304 15305 // for the uninstall-updates case and restricted profiles, remember the per- 15306 // user handle installed state 15307 int[] allUsers; 15308 synchronized (mPackages) { 15309 uninstalledPs = mSettings.mPackages.get(packageName); 15310 if (uninstalledPs == null) { 15311 Slog.w(TAG, "Not removing non-existent package " + packageName); 15312 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15313 } 15314 allUsers = sUserManager.getUserIds(); 15315 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15316 } 15317 15318 synchronized (mInstallLock) { 15319 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15320 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15321 "deletePackageX")) { 15322 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15323 deleteFlags | REMOVE_CHATTY, info, true, null); 15324 } 15325 synchronized (mPackages) { 15326 if (res) { 15327 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15328 } 15329 } 15330 } 15331 15332 if (res) { 15333 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15334 info.sendPackageRemovedBroadcasts(killApp); 15335 info.sendSystemPackageUpdatedBroadcasts(); 15336 info.sendSystemPackageAppearedBroadcasts(); 15337 } 15338 // Force a gc here. 15339 Runtime.getRuntime().gc(); 15340 // Delete the resources here after sending the broadcast to let 15341 // other processes clean up before deleting resources. 15342 if (info.args != null) { 15343 synchronized (mInstallLock) { 15344 info.args.doPostDeleteLI(true); 15345 } 15346 } 15347 15348 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15349 } 15350 15351 class PackageRemovedInfo { 15352 String removedPackage; 15353 int uid = -1; 15354 int removedAppId = -1; 15355 int[] origUsers; 15356 int[] removedUsers = null; 15357 boolean isRemovedPackageSystemUpdate = false; 15358 boolean isUpdate; 15359 boolean dataRemoved; 15360 boolean removedForAllUsers; 15361 // Clean up resources deleted packages. 15362 InstallArgs args = null; 15363 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15364 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15365 15366 void sendPackageRemovedBroadcasts(boolean killApp) { 15367 sendPackageRemovedBroadcastInternal(killApp); 15368 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15369 for (int i = 0; i < childCount; i++) { 15370 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15371 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15372 } 15373 } 15374 15375 void sendSystemPackageUpdatedBroadcasts() { 15376 if (isRemovedPackageSystemUpdate) { 15377 sendSystemPackageUpdatedBroadcastsInternal(); 15378 final int childCount = (removedChildPackages != null) 15379 ? removedChildPackages.size() : 0; 15380 for (int i = 0; i < childCount; i++) { 15381 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15382 if (childInfo.isRemovedPackageSystemUpdate) { 15383 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15384 } 15385 } 15386 } 15387 } 15388 15389 void sendSystemPackageAppearedBroadcasts() { 15390 final int packageCount = (appearedChildPackages != null) 15391 ? appearedChildPackages.size() : 0; 15392 for (int i = 0; i < packageCount; i++) { 15393 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15394 for (int userId : installedInfo.newUsers) { 15395 sendPackageAddedForUser(installedInfo.name, true, 15396 UserHandle.getAppId(installedInfo.uid), userId); 15397 } 15398 } 15399 } 15400 15401 private void sendSystemPackageUpdatedBroadcastsInternal() { 15402 Bundle extras = new Bundle(2); 15403 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15404 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15405 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15406 extras, 0, null, null, null); 15407 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15408 extras, 0, null, null, null); 15409 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15410 null, 0, removedPackage, null, null); 15411 } 15412 15413 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15414 Bundle extras = new Bundle(2); 15415 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15416 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15417 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15418 if (isUpdate || isRemovedPackageSystemUpdate) { 15419 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15420 } 15421 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15422 if (removedPackage != null) { 15423 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15424 extras, 0, null, null, removedUsers); 15425 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15426 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15427 removedPackage, extras, 0, null, null, removedUsers); 15428 } 15429 } 15430 if (removedAppId >= 0) { 15431 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15432 removedUsers); 15433 } 15434 } 15435 } 15436 15437 /* 15438 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15439 * flag is not set, the data directory is removed as well. 15440 * make sure this flag is set for partially installed apps. If not its meaningless to 15441 * delete a partially installed application. 15442 */ 15443 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15444 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15445 String packageName = ps.name; 15446 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15447 // Retrieve object to delete permissions for shared user later on 15448 final PackageParser.Package deletedPkg; 15449 final PackageSetting deletedPs; 15450 // reader 15451 synchronized (mPackages) { 15452 deletedPkg = mPackages.get(packageName); 15453 deletedPs = mSettings.mPackages.get(packageName); 15454 if (outInfo != null) { 15455 outInfo.removedPackage = packageName; 15456 outInfo.removedUsers = deletedPs != null 15457 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15458 : null; 15459 } 15460 } 15461 15462 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15463 15464 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15465 final PackageParser.Package resolvedPkg; 15466 if (deletedPkg != null) { 15467 resolvedPkg = deletedPkg; 15468 } else { 15469 // We don't have a parsed package when it lives on an ejected 15470 // adopted storage device, so fake something together 15471 resolvedPkg = new PackageParser.Package(ps.name); 15472 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15473 } 15474 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15475 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15476 destroyAppProfilesLIF(resolvedPkg); 15477 if (outInfo != null) { 15478 outInfo.dataRemoved = true; 15479 } 15480 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15481 } 15482 15483 // writer 15484 synchronized (mPackages) { 15485 if (deletedPs != null) { 15486 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15487 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15488 clearDefaultBrowserIfNeeded(packageName); 15489 if (outInfo != null) { 15490 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15491 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15492 } 15493 updatePermissionsLPw(deletedPs.name, null, 0); 15494 if (deletedPs.sharedUser != null) { 15495 // Remove permissions associated with package. Since runtime 15496 // permissions are per user we have to kill the removed package 15497 // or packages running under the shared user of the removed 15498 // package if revoking the permissions requested only by the removed 15499 // package is successful and this causes a change in gids. 15500 for (int userId : UserManagerService.getInstance().getUserIds()) { 15501 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15502 userId); 15503 if (userIdToKill == UserHandle.USER_ALL 15504 || userIdToKill >= UserHandle.USER_SYSTEM) { 15505 // If gids changed for this user, kill all affected packages. 15506 mHandler.post(new Runnable() { 15507 @Override 15508 public void run() { 15509 // This has to happen with no lock held. 15510 killApplication(deletedPs.name, deletedPs.appId, 15511 KILL_APP_REASON_GIDS_CHANGED); 15512 } 15513 }); 15514 break; 15515 } 15516 } 15517 } 15518 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15519 } 15520 // make sure to preserve per-user disabled state if this removal was just 15521 // a downgrade of a system app to the factory package 15522 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15523 if (DEBUG_REMOVE) { 15524 Slog.d(TAG, "Propagating install state across downgrade"); 15525 } 15526 for (int userId : allUserHandles) { 15527 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15528 if (DEBUG_REMOVE) { 15529 Slog.d(TAG, " user " + userId + " => " + installed); 15530 } 15531 ps.setInstalled(installed, userId); 15532 } 15533 } 15534 } 15535 // can downgrade to reader 15536 if (writeSettings) { 15537 // Save settings now 15538 mSettings.writeLPr(); 15539 } 15540 } 15541 if (outInfo != null) { 15542 // A user ID was deleted here. Go through all users and remove it 15543 // from KeyStore. 15544 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15545 } 15546 } 15547 15548 static boolean locationIsPrivileged(File path) { 15549 try { 15550 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15551 .getCanonicalPath(); 15552 return path.getCanonicalPath().startsWith(privilegedAppDir); 15553 } catch (IOException e) { 15554 Slog.e(TAG, "Unable to access code path " + path); 15555 } 15556 return false; 15557 } 15558 15559 /* 15560 * Tries to delete system package. 15561 */ 15562 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15563 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15564 boolean writeSettings) { 15565 if (deletedPs.parentPackageName != null) { 15566 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15567 return false; 15568 } 15569 15570 final boolean applyUserRestrictions 15571 = (allUserHandles != null) && (outInfo.origUsers != null); 15572 final PackageSetting disabledPs; 15573 // Confirm if the system package has been updated 15574 // An updated system app can be deleted. This will also have to restore 15575 // the system pkg from system partition 15576 // reader 15577 synchronized (mPackages) { 15578 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15579 } 15580 15581 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15582 + " disabledPs=" + disabledPs); 15583 15584 if (disabledPs == null) { 15585 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15586 return false; 15587 } else if (DEBUG_REMOVE) { 15588 Slog.d(TAG, "Deleting system pkg from data partition"); 15589 } 15590 15591 if (DEBUG_REMOVE) { 15592 if (applyUserRestrictions) { 15593 Slog.d(TAG, "Remembering install states:"); 15594 for (int userId : allUserHandles) { 15595 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15596 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15597 } 15598 } 15599 } 15600 15601 // Delete the updated package 15602 outInfo.isRemovedPackageSystemUpdate = true; 15603 if (outInfo.removedChildPackages != null) { 15604 final int childCount = (deletedPs.childPackageNames != null) 15605 ? deletedPs.childPackageNames.size() : 0; 15606 for (int i = 0; i < childCount; i++) { 15607 String childPackageName = deletedPs.childPackageNames.get(i); 15608 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15609 .contains(childPackageName)) { 15610 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15611 childPackageName); 15612 if (childInfo != null) { 15613 childInfo.isRemovedPackageSystemUpdate = true; 15614 } 15615 } 15616 } 15617 } 15618 15619 if (disabledPs.versionCode < deletedPs.versionCode) { 15620 // Delete data for downgrades 15621 flags &= ~PackageManager.DELETE_KEEP_DATA; 15622 } else { 15623 // Preserve data by setting flag 15624 flags |= PackageManager.DELETE_KEEP_DATA; 15625 } 15626 15627 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15628 outInfo, writeSettings, disabledPs.pkg); 15629 if (!ret) { 15630 return false; 15631 } 15632 15633 // writer 15634 synchronized (mPackages) { 15635 // Reinstate the old system package 15636 enableSystemPackageLPw(disabledPs.pkg); 15637 // Remove any native libraries from the upgraded package. 15638 removeNativeBinariesLI(deletedPs); 15639 } 15640 15641 // Install the system package 15642 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15643 int parseFlags = mDefParseFlags 15644 | PackageParser.PARSE_MUST_BE_APK 15645 | PackageParser.PARSE_IS_SYSTEM 15646 | PackageParser.PARSE_IS_SYSTEM_DIR; 15647 if (locationIsPrivileged(disabledPs.codePath)) { 15648 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15649 } 15650 15651 final PackageParser.Package newPkg; 15652 try { 15653 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15654 } catch (PackageManagerException e) { 15655 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15656 + e.getMessage()); 15657 return false; 15658 } 15659 15660 prepareAppDataAfterInstallLIF(newPkg); 15661 15662 // writer 15663 synchronized (mPackages) { 15664 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15665 15666 // Propagate the permissions state as we do not want to drop on the floor 15667 // runtime permissions. The update permissions method below will take 15668 // care of removing obsolete permissions and grant install permissions. 15669 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15670 updatePermissionsLPw(newPkg.packageName, newPkg, 15671 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15672 15673 if (applyUserRestrictions) { 15674 if (DEBUG_REMOVE) { 15675 Slog.d(TAG, "Propagating install state across reinstall"); 15676 } 15677 for (int userId : allUserHandles) { 15678 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15679 if (DEBUG_REMOVE) { 15680 Slog.d(TAG, " user " + userId + " => " + installed); 15681 } 15682 ps.setInstalled(installed, userId); 15683 15684 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15685 } 15686 // Regardless of writeSettings we need to ensure that this restriction 15687 // state propagation is persisted 15688 mSettings.writeAllUsersPackageRestrictionsLPr(); 15689 } 15690 // can downgrade to reader here 15691 if (writeSettings) { 15692 mSettings.writeLPr(); 15693 } 15694 } 15695 return true; 15696 } 15697 15698 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15699 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15700 PackageRemovedInfo outInfo, boolean writeSettings, 15701 PackageParser.Package replacingPackage) { 15702 synchronized (mPackages) { 15703 if (outInfo != null) { 15704 outInfo.uid = ps.appId; 15705 } 15706 15707 if (outInfo != null && outInfo.removedChildPackages != null) { 15708 final int childCount = (ps.childPackageNames != null) 15709 ? ps.childPackageNames.size() : 0; 15710 for (int i = 0; i < childCount; i++) { 15711 String childPackageName = ps.childPackageNames.get(i); 15712 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15713 if (childPs == null) { 15714 return false; 15715 } 15716 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15717 childPackageName); 15718 if (childInfo != null) { 15719 childInfo.uid = childPs.appId; 15720 } 15721 } 15722 } 15723 } 15724 15725 // Delete package data from internal structures and also remove data if flag is set 15726 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15727 15728 // Delete the child packages data 15729 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15730 for (int i = 0; i < childCount; i++) { 15731 PackageSetting childPs; 15732 synchronized (mPackages) { 15733 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15734 } 15735 if (childPs != null) { 15736 PackageRemovedInfo childOutInfo = (outInfo != null 15737 && outInfo.removedChildPackages != null) 15738 ? outInfo.removedChildPackages.get(childPs.name) : null; 15739 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15740 && (replacingPackage != null 15741 && !replacingPackage.hasChildPackage(childPs.name)) 15742 ? flags & ~DELETE_KEEP_DATA : flags; 15743 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15744 deleteFlags, writeSettings); 15745 } 15746 } 15747 15748 // Delete application code and resources only for parent packages 15749 if (ps.parentPackageName == null) { 15750 if (deleteCodeAndResources && (outInfo != null)) { 15751 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15752 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15753 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15754 } 15755 } 15756 15757 return true; 15758 } 15759 15760 @Override 15761 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15762 int userId) { 15763 mContext.enforceCallingOrSelfPermission( 15764 android.Manifest.permission.DELETE_PACKAGES, null); 15765 synchronized (mPackages) { 15766 PackageSetting ps = mSettings.mPackages.get(packageName); 15767 if (ps == null) { 15768 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15769 return false; 15770 } 15771 if (!ps.getInstalled(userId)) { 15772 // Can't block uninstall for an app that is not installed or enabled. 15773 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15774 return false; 15775 } 15776 ps.setBlockUninstall(blockUninstall, userId); 15777 mSettings.writePackageRestrictionsLPr(userId); 15778 } 15779 return true; 15780 } 15781 15782 @Override 15783 public boolean getBlockUninstallForUser(String packageName, int userId) { 15784 synchronized (mPackages) { 15785 PackageSetting ps = mSettings.mPackages.get(packageName); 15786 if (ps == null) { 15787 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15788 return false; 15789 } 15790 return ps.getBlockUninstall(userId); 15791 } 15792 } 15793 15794 @Override 15795 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15796 int callingUid = Binder.getCallingUid(); 15797 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15798 throw new SecurityException( 15799 "setRequiredForSystemUser can only be run by the system or root"); 15800 } 15801 synchronized (mPackages) { 15802 PackageSetting ps = mSettings.mPackages.get(packageName); 15803 if (ps == null) { 15804 Log.w(TAG, "Package doesn't exist: " + packageName); 15805 return false; 15806 } 15807 if (systemUserApp) { 15808 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15809 } else { 15810 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15811 } 15812 mSettings.writeLPr(); 15813 } 15814 return true; 15815 } 15816 15817 /* 15818 * This method handles package deletion in general 15819 */ 15820 private boolean deletePackageLIF(String packageName, UserHandle user, 15821 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15822 PackageRemovedInfo outInfo, boolean writeSettings, 15823 PackageParser.Package replacingPackage) { 15824 if (packageName == null) { 15825 Slog.w(TAG, "Attempt to delete null packageName."); 15826 return false; 15827 } 15828 15829 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15830 15831 PackageSetting ps; 15832 15833 synchronized (mPackages) { 15834 ps = mSettings.mPackages.get(packageName); 15835 if (ps == null) { 15836 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15837 return false; 15838 } 15839 15840 if (ps.parentPackageName != null && (!isSystemApp(ps) 15841 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15842 if (DEBUG_REMOVE) { 15843 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15844 + ((user == null) ? UserHandle.USER_ALL : user)); 15845 } 15846 final int removedUserId = (user != null) ? user.getIdentifier() 15847 : UserHandle.USER_ALL; 15848 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15849 return false; 15850 } 15851 markPackageUninstalledForUserLPw(ps, user); 15852 scheduleWritePackageRestrictionsLocked(user); 15853 return true; 15854 } 15855 } 15856 15857 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15858 && user.getIdentifier() != UserHandle.USER_ALL)) { 15859 // The caller is asking that the package only be deleted for a single 15860 // user. To do this, we just mark its uninstalled state and delete 15861 // its data. If this is a system app, we only allow this to happen if 15862 // they have set the special DELETE_SYSTEM_APP which requests different 15863 // semantics than normal for uninstalling system apps. 15864 markPackageUninstalledForUserLPw(ps, user); 15865 15866 if (!isSystemApp(ps)) { 15867 // Do not uninstall the APK if an app should be cached 15868 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15869 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15870 // Other user still have this package installed, so all 15871 // we need to do is clear this user's data and save that 15872 // it is uninstalled. 15873 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15874 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15875 return false; 15876 } 15877 scheduleWritePackageRestrictionsLocked(user); 15878 return true; 15879 } else { 15880 // We need to set it back to 'installed' so the uninstall 15881 // broadcasts will be sent correctly. 15882 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15883 ps.setInstalled(true, user.getIdentifier()); 15884 } 15885 } else { 15886 // This is a system app, so we assume that the 15887 // other users still have this package installed, so all 15888 // we need to do is clear this user's data and save that 15889 // it is uninstalled. 15890 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15891 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15892 return false; 15893 } 15894 scheduleWritePackageRestrictionsLocked(user); 15895 return true; 15896 } 15897 } 15898 15899 // If we are deleting a composite package for all users, keep track 15900 // of result for each child. 15901 if (ps.childPackageNames != null && outInfo != null) { 15902 synchronized (mPackages) { 15903 final int childCount = ps.childPackageNames.size(); 15904 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15905 for (int i = 0; i < childCount; i++) { 15906 String childPackageName = ps.childPackageNames.get(i); 15907 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15908 childInfo.removedPackage = childPackageName; 15909 outInfo.removedChildPackages.put(childPackageName, childInfo); 15910 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15911 if (childPs != null) { 15912 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15913 } 15914 } 15915 } 15916 } 15917 15918 boolean ret = false; 15919 if (isSystemApp(ps)) { 15920 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15921 // When an updated system application is deleted we delete the existing resources 15922 // as well and fall back to existing code in system partition 15923 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15924 } else { 15925 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15926 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15927 outInfo, writeSettings, replacingPackage); 15928 } 15929 15930 // Take a note whether we deleted the package for all users 15931 if (outInfo != null) { 15932 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15933 if (outInfo.removedChildPackages != null) { 15934 synchronized (mPackages) { 15935 final int childCount = outInfo.removedChildPackages.size(); 15936 for (int i = 0; i < childCount; i++) { 15937 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15938 if (childInfo != null) { 15939 childInfo.removedForAllUsers = mPackages.get( 15940 childInfo.removedPackage) == null; 15941 } 15942 } 15943 } 15944 } 15945 // If we uninstalled an update to a system app there may be some 15946 // child packages that appeared as they are declared in the system 15947 // app but were not declared in the update. 15948 if (isSystemApp(ps)) { 15949 synchronized (mPackages) { 15950 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15951 final int childCount = (updatedPs.childPackageNames != null) 15952 ? updatedPs.childPackageNames.size() : 0; 15953 for (int i = 0; i < childCount; i++) { 15954 String childPackageName = updatedPs.childPackageNames.get(i); 15955 if (outInfo.removedChildPackages == null 15956 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15957 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15958 if (childPs == null) { 15959 continue; 15960 } 15961 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15962 installRes.name = childPackageName; 15963 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15964 installRes.pkg = mPackages.get(childPackageName); 15965 installRes.uid = childPs.pkg.applicationInfo.uid; 15966 if (outInfo.appearedChildPackages == null) { 15967 outInfo.appearedChildPackages = new ArrayMap<>(); 15968 } 15969 outInfo.appearedChildPackages.put(childPackageName, installRes); 15970 } 15971 } 15972 } 15973 } 15974 } 15975 15976 return ret; 15977 } 15978 15979 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15980 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15981 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15982 for (int nextUserId : userIds) { 15983 if (DEBUG_REMOVE) { 15984 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15985 } 15986 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15987 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15988 false /*hidden*/, false /*suspended*/, null, null, null, 15989 false /*blockUninstall*/, 15990 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15991 } 15992 } 15993 15994 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15995 PackageRemovedInfo outInfo) { 15996 final PackageParser.Package pkg; 15997 synchronized (mPackages) { 15998 pkg = mPackages.get(ps.name); 15999 } 16000 16001 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16002 : new int[] {userId}; 16003 for (int nextUserId : userIds) { 16004 if (DEBUG_REMOVE) { 16005 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16006 + nextUserId); 16007 } 16008 16009 destroyAppDataLIF(pkg, userId, 16010 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16011 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16012 schedulePackageCleaning(ps.name, nextUserId, false); 16013 synchronized (mPackages) { 16014 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16015 scheduleWritePackageRestrictionsLocked(nextUserId); 16016 } 16017 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16018 } 16019 } 16020 16021 if (outInfo != null) { 16022 outInfo.removedPackage = ps.name; 16023 outInfo.removedAppId = ps.appId; 16024 outInfo.removedUsers = userIds; 16025 } 16026 16027 return true; 16028 } 16029 16030 private final class ClearStorageConnection implements ServiceConnection { 16031 IMediaContainerService mContainerService; 16032 16033 @Override 16034 public void onServiceConnected(ComponentName name, IBinder service) { 16035 synchronized (this) { 16036 mContainerService = IMediaContainerService.Stub.asInterface(service); 16037 notifyAll(); 16038 } 16039 } 16040 16041 @Override 16042 public void onServiceDisconnected(ComponentName name) { 16043 } 16044 } 16045 16046 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16047 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16048 16049 final boolean mounted; 16050 if (Environment.isExternalStorageEmulated()) { 16051 mounted = true; 16052 } else { 16053 final String status = Environment.getExternalStorageState(); 16054 16055 mounted = status.equals(Environment.MEDIA_MOUNTED) 16056 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16057 } 16058 16059 if (!mounted) { 16060 return; 16061 } 16062 16063 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16064 int[] users; 16065 if (userId == UserHandle.USER_ALL) { 16066 users = sUserManager.getUserIds(); 16067 } else { 16068 users = new int[] { userId }; 16069 } 16070 final ClearStorageConnection conn = new ClearStorageConnection(); 16071 if (mContext.bindServiceAsUser( 16072 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16073 try { 16074 for (int curUser : users) { 16075 long timeout = SystemClock.uptimeMillis() + 5000; 16076 synchronized (conn) { 16077 long now = SystemClock.uptimeMillis(); 16078 while (conn.mContainerService == null && now < timeout) { 16079 try { 16080 conn.wait(timeout - now); 16081 } catch (InterruptedException e) { 16082 } 16083 } 16084 } 16085 if (conn.mContainerService == null) { 16086 return; 16087 } 16088 16089 final UserEnvironment userEnv = new UserEnvironment(curUser); 16090 clearDirectory(conn.mContainerService, 16091 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16092 if (allData) { 16093 clearDirectory(conn.mContainerService, 16094 userEnv.buildExternalStorageAppDataDirs(packageName)); 16095 clearDirectory(conn.mContainerService, 16096 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16097 } 16098 } 16099 } finally { 16100 mContext.unbindService(conn); 16101 } 16102 } 16103 } 16104 16105 @Override 16106 public void clearApplicationProfileData(String packageName) { 16107 enforceSystemOrRoot("Only the system can clear all profile data"); 16108 16109 final PackageParser.Package pkg; 16110 synchronized (mPackages) { 16111 pkg = mPackages.get(packageName); 16112 } 16113 16114 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16115 synchronized (mInstallLock) { 16116 clearAppProfilesLIF(pkg); 16117 } 16118 } 16119 } 16120 16121 @Override 16122 public void clearApplicationUserData(final String packageName, 16123 final IPackageDataObserver observer, final int userId) { 16124 mContext.enforceCallingOrSelfPermission( 16125 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16126 16127 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16128 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16129 16130 final DevicePolicyManagerInternal dpmi = LocalServices 16131 .getService(DevicePolicyManagerInternal.class); 16132 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16133 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16134 } 16135 // Queue up an async operation since the package deletion may take a little while. 16136 mHandler.post(new Runnable() { 16137 public void run() { 16138 mHandler.removeCallbacks(this); 16139 final boolean succeeded; 16140 try (PackageFreezer freezer = freezePackage(packageName, 16141 "clearApplicationUserData")) { 16142 synchronized (mInstallLock) { 16143 succeeded = clearApplicationUserDataLIF(packageName, userId); 16144 } 16145 clearExternalStorageDataSync(packageName, userId, true); 16146 } 16147 if (succeeded) { 16148 // invoke DeviceStorageMonitor's update method to clear any notifications 16149 DeviceStorageMonitorInternal dsm = LocalServices 16150 .getService(DeviceStorageMonitorInternal.class); 16151 if (dsm != null) { 16152 dsm.checkMemory(); 16153 } 16154 } 16155 if(observer != null) { 16156 try { 16157 observer.onRemoveCompleted(packageName, succeeded); 16158 } catch (RemoteException e) { 16159 Log.i(TAG, "Observer no longer exists."); 16160 } 16161 } //end if observer 16162 } //end run 16163 }); 16164 } 16165 16166 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16167 if (packageName == null) { 16168 Slog.w(TAG, "Attempt to delete null packageName."); 16169 return false; 16170 } 16171 16172 // Try finding details about the requested package 16173 PackageParser.Package pkg; 16174 synchronized (mPackages) { 16175 pkg = mPackages.get(packageName); 16176 if (pkg == null) { 16177 final PackageSetting ps = mSettings.mPackages.get(packageName); 16178 if (ps != null) { 16179 pkg = ps.pkg; 16180 } 16181 } 16182 16183 if (pkg == null) { 16184 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16185 return false; 16186 } 16187 16188 PackageSetting ps = (PackageSetting) pkg.mExtras; 16189 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16190 } 16191 16192 clearAppDataLIF(pkg, userId, 16193 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16194 16195 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16196 removeKeystoreDataIfNeeded(userId, appId); 16197 16198 final UserManager um = mContext.getSystemService(UserManager.class); 16199 final int flags; 16200 if (um.isUserUnlockingOrUnlocked(userId)) { 16201 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16202 } else if (um.isUserRunning(userId)) { 16203 flags = StorageManager.FLAG_STORAGE_DE; 16204 } else { 16205 flags = 0; 16206 } 16207 prepareAppDataContentsLIF(pkg, userId, flags); 16208 16209 return true; 16210 } 16211 16212 /** 16213 * Reverts user permission state changes (permissions and flags) in 16214 * all packages for a given user. 16215 * 16216 * @param userId The device user for which to do a reset. 16217 */ 16218 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16219 final int packageCount = mPackages.size(); 16220 for (int i = 0; i < packageCount; i++) { 16221 PackageParser.Package pkg = mPackages.valueAt(i); 16222 PackageSetting ps = (PackageSetting) pkg.mExtras; 16223 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16224 } 16225 } 16226 16227 private void resetNetworkPolicies(int userId) { 16228 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16229 } 16230 16231 /** 16232 * Reverts user permission state changes (permissions and flags). 16233 * 16234 * @param ps The package for which to reset. 16235 * @param userId The device user for which to do a reset. 16236 */ 16237 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16238 final PackageSetting ps, final int userId) { 16239 if (ps.pkg == null) { 16240 return; 16241 } 16242 16243 // These are flags that can change base on user actions. 16244 final int userSettableMask = FLAG_PERMISSION_USER_SET 16245 | FLAG_PERMISSION_USER_FIXED 16246 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16247 | FLAG_PERMISSION_REVIEW_REQUIRED; 16248 16249 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16250 | FLAG_PERMISSION_POLICY_FIXED; 16251 16252 boolean writeInstallPermissions = false; 16253 boolean writeRuntimePermissions = false; 16254 16255 final int permissionCount = ps.pkg.requestedPermissions.size(); 16256 for (int i = 0; i < permissionCount; i++) { 16257 String permission = ps.pkg.requestedPermissions.get(i); 16258 16259 BasePermission bp = mSettings.mPermissions.get(permission); 16260 if (bp == null) { 16261 continue; 16262 } 16263 16264 // If shared user we just reset the state to which only this app contributed. 16265 if (ps.sharedUser != null) { 16266 boolean used = false; 16267 final int packageCount = ps.sharedUser.packages.size(); 16268 for (int j = 0; j < packageCount; j++) { 16269 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16270 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16271 && pkg.pkg.requestedPermissions.contains(permission)) { 16272 used = true; 16273 break; 16274 } 16275 } 16276 if (used) { 16277 continue; 16278 } 16279 } 16280 16281 PermissionsState permissionsState = ps.getPermissionsState(); 16282 16283 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16284 16285 // Always clear the user settable flags. 16286 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16287 bp.name) != null; 16288 // If permission review is enabled and this is a legacy app, mark the 16289 // permission as requiring a review as this is the initial state. 16290 int flags = 0; 16291 if (Build.PERMISSIONS_REVIEW_REQUIRED 16292 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16293 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16294 } 16295 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16296 if (hasInstallState) { 16297 writeInstallPermissions = true; 16298 } else { 16299 writeRuntimePermissions = true; 16300 } 16301 } 16302 16303 // Below is only runtime permission handling. 16304 if (!bp.isRuntime()) { 16305 continue; 16306 } 16307 16308 // Never clobber system or policy. 16309 if ((oldFlags & policyOrSystemFlags) != 0) { 16310 continue; 16311 } 16312 16313 // If this permission was granted by default, make sure it is. 16314 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16315 if (permissionsState.grantRuntimePermission(bp, userId) 16316 != PERMISSION_OPERATION_FAILURE) { 16317 writeRuntimePermissions = true; 16318 } 16319 // If permission review is enabled the permissions for a legacy apps 16320 // are represented as constantly granted runtime ones, so don't revoke. 16321 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16322 // Otherwise, reset the permission. 16323 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16324 switch (revokeResult) { 16325 case PERMISSION_OPERATION_SUCCESS: 16326 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16327 writeRuntimePermissions = true; 16328 final int appId = ps.appId; 16329 mHandler.post(new Runnable() { 16330 @Override 16331 public void run() { 16332 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16333 } 16334 }); 16335 } break; 16336 } 16337 } 16338 } 16339 16340 // Synchronously write as we are taking permissions away. 16341 if (writeRuntimePermissions) { 16342 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16343 } 16344 16345 // Synchronously write as we are taking permissions away. 16346 if (writeInstallPermissions) { 16347 mSettings.writeLPr(); 16348 } 16349 } 16350 16351 /** 16352 * Remove entries from the keystore daemon. Will only remove it if the 16353 * {@code appId} is valid. 16354 */ 16355 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16356 if (appId < 0) { 16357 return; 16358 } 16359 16360 final KeyStore keyStore = KeyStore.getInstance(); 16361 if (keyStore != null) { 16362 if (userId == UserHandle.USER_ALL) { 16363 for (final int individual : sUserManager.getUserIds()) { 16364 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16365 } 16366 } else { 16367 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16368 } 16369 } else { 16370 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16371 } 16372 } 16373 16374 @Override 16375 public void deleteApplicationCacheFiles(final String packageName, 16376 final IPackageDataObserver observer) { 16377 final int userId = UserHandle.getCallingUserId(); 16378 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16379 } 16380 16381 @Override 16382 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16383 final IPackageDataObserver observer) { 16384 mContext.enforceCallingOrSelfPermission( 16385 android.Manifest.permission.DELETE_CACHE_FILES, null); 16386 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16387 /* requireFullPermission= */ true, /* checkShell= */ false, 16388 "delete application cache files"); 16389 16390 final PackageParser.Package pkg; 16391 synchronized (mPackages) { 16392 pkg = mPackages.get(packageName); 16393 } 16394 16395 // Queue up an async operation since the package deletion may take a little while. 16396 mHandler.post(new Runnable() { 16397 public void run() { 16398 synchronized (mInstallLock) { 16399 final int flags = StorageManager.FLAG_STORAGE_DE 16400 | StorageManager.FLAG_STORAGE_CE; 16401 // We're only clearing cache files, so we don't care if the 16402 // app is unfrozen and still able to run 16403 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16404 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16405 } 16406 clearExternalStorageDataSync(packageName, userId, false); 16407 if (observer != null) { 16408 try { 16409 observer.onRemoveCompleted(packageName, true); 16410 } catch (RemoteException e) { 16411 Log.i(TAG, "Observer no longer exists."); 16412 } 16413 } 16414 } 16415 }); 16416 } 16417 16418 @Override 16419 public void getPackageSizeInfo(final String packageName, int userHandle, 16420 final IPackageStatsObserver observer) { 16421 mContext.enforceCallingOrSelfPermission( 16422 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16423 if (packageName == null) { 16424 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16425 } 16426 16427 PackageStats stats = new PackageStats(packageName, userHandle); 16428 16429 /* 16430 * Queue up an async operation since the package measurement may take a 16431 * little while. 16432 */ 16433 Message msg = mHandler.obtainMessage(INIT_COPY); 16434 msg.obj = new MeasureParams(stats, observer); 16435 mHandler.sendMessage(msg); 16436 } 16437 16438 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16439 final PackageSetting ps; 16440 synchronized (mPackages) { 16441 ps = mSettings.mPackages.get(packageName); 16442 if (ps == null) { 16443 Slog.w(TAG, "Failed to find settings for " + packageName); 16444 return false; 16445 } 16446 } 16447 try { 16448 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16449 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16450 ps.getCeDataInode(userId), ps.codePathString, stats); 16451 } catch (InstallerException e) { 16452 Slog.w(TAG, String.valueOf(e)); 16453 return false; 16454 } 16455 16456 // For now, ignore code size of packages on system partition 16457 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16458 stats.codeSize = 0; 16459 } 16460 16461 return true; 16462 } 16463 16464 private int getUidTargetSdkVersionLockedLPr(int uid) { 16465 Object obj = mSettings.getUserIdLPr(uid); 16466 if (obj instanceof SharedUserSetting) { 16467 final SharedUserSetting sus = (SharedUserSetting) obj; 16468 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16469 final Iterator<PackageSetting> it = sus.packages.iterator(); 16470 while (it.hasNext()) { 16471 final PackageSetting ps = it.next(); 16472 if (ps.pkg != null) { 16473 int v = ps.pkg.applicationInfo.targetSdkVersion; 16474 if (v < vers) vers = v; 16475 } 16476 } 16477 return vers; 16478 } else if (obj instanceof PackageSetting) { 16479 final PackageSetting ps = (PackageSetting) obj; 16480 if (ps.pkg != null) { 16481 return ps.pkg.applicationInfo.targetSdkVersion; 16482 } 16483 } 16484 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16485 } 16486 16487 @Override 16488 public void addPreferredActivity(IntentFilter filter, int match, 16489 ComponentName[] set, ComponentName activity, int userId) { 16490 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16491 "Adding preferred"); 16492 } 16493 16494 private void addPreferredActivityInternal(IntentFilter filter, int match, 16495 ComponentName[] set, ComponentName activity, boolean always, int userId, 16496 String opname) { 16497 // writer 16498 int callingUid = Binder.getCallingUid(); 16499 enforceCrossUserPermission(callingUid, userId, 16500 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16501 if (filter.countActions() == 0) { 16502 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16503 return; 16504 } 16505 synchronized (mPackages) { 16506 if (mContext.checkCallingOrSelfPermission( 16507 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16508 != PackageManager.PERMISSION_GRANTED) { 16509 if (getUidTargetSdkVersionLockedLPr(callingUid) 16510 < Build.VERSION_CODES.FROYO) { 16511 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16512 + callingUid); 16513 return; 16514 } 16515 mContext.enforceCallingOrSelfPermission( 16516 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16517 } 16518 16519 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16520 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16521 + userId + ":"); 16522 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16523 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16524 scheduleWritePackageRestrictionsLocked(userId); 16525 } 16526 } 16527 16528 @Override 16529 public void replacePreferredActivity(IntentFilter filter, int match, 16530 ComponentName[] set, ComponentName activity, int userId) { 16531 if (filter.countActions() != 1) { 16532 throw new IllegalArgumentException( 16533 "replacePreferredActivity expects filter to have only 1 action."); 16534 } 16535 if (filter.countDataAuthorities() != 0 16536 || filter.countDataPaths() != 0 16537 || filter.countDataSchemes() > 1 16538 || filter.countDataTypes() != 0) { 16539 throw new IllegalArgumentException( 16540 "replacePreferredActivity expects filter to have no data authorities, " + 16541 "paths, or types; and at most one scheme."); 16542 } 16543 16544 final int callingUid = Binder.getCallingUid(); 16545 enforceCrossUserPermission(callingUid, userId, 16546 true /* requireFullPermission */, false /* checkShell */, 16547 "replace preferred activity"); 16548 synchronized (mPackages) { 16549 if (mContext.checkCallingOrSelfPermission( 16550 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16551 != PackageManager.PERMISSION_GRANTED) { 16552 if (getUidTargetSdkVersionLockedLPr(callingUid) 16553 < Build.VERSION_CODES.FROYO) { 16554 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16555 + Binder.getCallingUid()); 16556 return; 16557 } 16558 mContext.enforceCallingOrSelfPermission( 16559 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16560 } 16561 16562 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16563 if (pir != null) { 16564 // Get all of the existing entries that exactly match this filter. 16565 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16566 if (existing != null && existing.size() == 1) { 16567 PreferredActivity cur = existing.get(0); 16568 if (DEBUG_PREFERRED) { 16569 Slog.i(TAG, "Checking replace of preferred:"); 16570 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16571 if (!cur.mPref.mAlways) { 16572 Slog.i(TAG, " -- CUR; not mAlways!"); 16573 } else { 16574 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16575 Slog.i(TAG, " -- CUR: mSet=" 16576 + Arrays.toString(cur.mPref.mSetComponents)); 16577 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16578 Slog.i(TAG, " -- NEW: mMatch=" 16579 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16580 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16581 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16582 } 16583 } 16584 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16585 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16586 && cur.mPref.sameSet(set)) { 16587 // Setting the preferred activity to what it happens to be already 16588 if (DEBUG_PREFERRED) { 16589 Slog.i(TAG, "Replacing with same preferred activity " 16590 + cur.mPref.mShortComponent + " for user " 16591 + userId + ":"); 16592 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16593 } 16594 return; 16595 } 16596 } 16597 16598 if (existing != null) { 16599 if (DEBUG_PREFERRED) { 16600 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16601 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16602 } 16603 for (int i = 0; i < existing.size(); i++) { 16604 PreferredActivity pa = existing.get(i); 16605 if (DEBUG_PREFERRED) { 16606 Slog.i(TAG, "Removing existing preferred activity " 16607 + pa.mPref.mComponent + ":"); 16608 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16609 } 16610 pir.removeFilter(pa); 16611 } 16612 } 16613 } 16614 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16615 "Replacing preferred"); 16616 } 16617 } 16618 16619 @Override 16620 public void clearPackagePreferredActivities(String packageName) { 16621 final int uid = Binder.getCallingUid(); 16622 // writer 16623 synchronized (mPackages) { 16624 PackageParser.Package pkg = mPackages.get(packageName); 16625 if (pkg == null || pkg.applicationInfo.uid != uid) { 16626 if (mContext.checkCallingOrSelfPermission( 16627 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16628 != PackageManager.PERMISSION_GRANTED) { 16629 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16630 < Build.VERSION_CODES.FROYO) { 16631 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16632 + Binder.getCallingUid()); 16633 return; 16634 } 16635 mContext.enforceCallingOrSelfPermission( 16636 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16637 } 16638 } 16639 16640 int user = UserHandle.getCallingUserId(); 16641 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16642 scheduleWritePackageRestrictionsLocked(user); 16643 } 16644 } 16645 } 16646 16647 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16648 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16649 ArrayList<PreferredActivity> removed = null; 16650 boolean changed = false; 16651 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16652 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16653 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16654 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16655 continue; 16656 } 16657 Iterator<PreferredActivity> it = pir.filterIterator(); 16658 while (it.hasNext()) { 16659 PreferredActivity pa = it.next(); 16660 // Mark entry for removal only if it matches the package name 16661 // and the entry is of type "always". 16662 if (packageName == null || 16663 (pa.mPref.mComponent.getPackageName().equals(packageName) 16664 && pa.mPref.mAlways)) { 16665 if (removed == null) { 16666 removed = new ArrayList<PreferredActivity>(); 16667 } 16668 removed.add(pa); 16669 } 16670 } 16671 if (removed != null) { 16672 for (int j=0; j<removed.size(); j++) { 16673 PreferredActivity pa = removed.get(j); 16674 pir.removeFilter(pa); 16675 } 16676 changed = true; 16677 } 16678 } 16679 return changed; 16680 } 16681 16682 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16683 private void clearIntentFilterVerificationsLPw(int userId) { 16684 final int packageCount = mPackages.size(); 16685 for (int i = 0; i < packageCount; i++) { 16686 PackageParser.Package pkg = mPackages.valueAt(i); 16687 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16688 } 16689 } 16690 16691 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16692 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16693 if (userId == UserHandle.USER_ALL) { 16694 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16695 sUserManager.getUserIds())) { 16696 for (int oneUserId : sUserManager.getUserIds()) { 16697 scheduleWritePackageRestrictionsLocked(oneUserId); 16698 } 16699 } 16700 } else { 16701 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16702 scheduleWritePackageRestrictionsLocked(userId); 16703 } 16704 } 16705 } 16706 16707 void clearDefaultBrowserIfNeeded(String packageName) { 16708 for (int oneUserId : sUserManager.getUserIds()) { 16709 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16710 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16711 if (packageName.equals(defaultBrowserPackageName)) { 16712 setDefaultBrowserPackageName(null, oneUserId); 16713 } 16714 } 16715 } 16716 16717 @Override 16718 public void resetApplicationPreferences(int userId) { 16719 mContext.enforceCallingOrSelfPermission( 16720 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16721 final long identity = Binder.clearCallingIdentity(); 16722 // writer 16723 try { 16724 synchronized (mPackages) { 16725 clearPackagePreferredActivitiesLPw(null, userId); 16726 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16727 // TODO: We have to reset the default SMS and Phone. This requires 16728 // significant refactoring to keep all default apps in the package 16729 // manager (cleaner but more work) or have the services provide 16730 // callbacks to the package manager to request a default app reset. 16731 applyFactoryDefaultBrowserLPw(userId); 16732 clearIntentFilterVerificationsLPw(userId); 16733 primeDomainVerificationsLPw(userId); 16734 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16735 scheduleWritePackageRestrictionsLocked(userId); 16736 } 16737 resetNetworkPolicies(userId); 16738 } finally { 16739 Binder.restoreCallingIdentity(identity); 16740 } 16741 } 16742 16743 @Override 16744 public int getPreferredActivities(List<IntentFilter> outFilters, 16745 List<ComponentName> outActivities, String packageName) { 16746 16747 int num = 0; 16748 final int userId = UserHandle.getCallingUserId(); 16749 // reader 16750 synchronized (mPackages) { 16751 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16752 if (pir != null) { 16753 final Iterator<PreferredActivity> it = pir.filterIterator(); 16754 while (it.hasNext()) { 16755 final PreferredActivity pa = it.next(); 16756 if (packageName == null 16757 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16758 && pa.mPref.mAlways)) { 16759 if (outFilters != null) { 16760 outFilters.add(new IntentFilter(pa)); 16761 } 16762 if (outActivities != null) { 16763 outActivities.add(pa.mPref.mComponent); 16764 } 16765 } 16766 } 16767 } 16768 } 16769 16770 return num; 16771 } 16772 16773 @Override 16774 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16775 int userId) { 16776 int callingUid = Binder.getCallingUid(); 16777 if (callingUid != Process.SYSTEM_UID) { 16778 throw new SecurityException( 16779 "addPersistentPreferredActivity can only be run by the system"); 16780 } 16781 if (filter.countActions() == 0) { 16782 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16783 return; 16784 } 16785 synchronized (mPackages) { 16786 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16787 ":"); 16788 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16789 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16790 new PersistentPreferredActivity(filter, activity)); 16791 scheduleWritePackageRestrictionsLocked(userId); 16792 } 16793 } 16794 16795 @Override 16796 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16797 int callingUid = Binder.getCallingUid(); 16798 if (callingUid != Process.SYSTEM_UID) { 16799 throw new SecurityException( 16800 "clearPackagePersistentPreferredActivities can only be run by the system"); 16801 } 16802 ArrayList<PersistentPreferredActivity> removed = null; 16803 boolean changed = false; 16804 synchronized (mPackages) { 16805 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16806 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16807 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16808 .valueAt(i); 16809 if (userId != thisUserId) { 16810 continue; 16811 } 16812 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16813 while (it.hasNext()) { 16814 PersistentPreferredActivity ppa = it.next(); 16815 // Mark entry for removal only if it matches the package name. 16816 if (ppa.mComponent.getPackageName().equals(packageName)) { 16817 if (removed == null) { 16818 removed = new ArrayList<PersistentPreferredActivity>(); 16819 } 16820 removed.add(ppa); 16821 } 16822 } 16823 if (removed != null) { 16824 for (int j=0; j<removed.size(); j++) { 16825 PersistentPreferredActivity ppa = removed.get(j); 16826 ppir.removeFilter(ppa); 16827 } 16828 changed = true; 16829 } 16830 } 16831 16832 if (changed) { 16833 scheduleWritePackageRestrictionsLocked(userId); 16834 } 16835 } 16836 } 16837 16838 /** 16839 * Common machinery for picking apart a restored XML blob and passing 16840 * it to a caller-supplied functor to be applied to the running system. 16841 */ 16842 private void restoreFromXml(XmlPullParser parser, int userId, 16843 String expectedStartTag, BlobXmlRestorer functor) 16844 throws IOException, XmlPullParserException { 16845 int type; 16846 while ((type = parser.next()) != XmlPullParser.START_TAG 16847 && type != XmlPullParser.END_DOCUMENT) { 16848 } 16849 if (type != XmlPullParser.START_TAG) { 16850 // oops didn't find a start tag?! 16851 if (DEBUG_BACKUP) { 16852 Slog.e(TAG, "Didn't find start tag during restore"); 16853 } 16854 return; 16855 } 16856Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16857 // this is supposed to be TAG_PREFERRED_BACKUP 16858 if (!expectedStartTag.equals(parser.getName())) { 16859 if (DEBUG_BACKUP) { 16860 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16861 } 16862 return; 16863 } 16864 16865 // skip interfering stuff, then we're aligned with the backing implementation 16866 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16867Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16868 functor.apply(parser, userId); 16869 } 16870 16871 private interface BlobXmlRestorer { 16872 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16873 } 16874 16875 /** 16876 * Non-Binder method, support for the backup/restore mechanism: write the 16877 * full set of preferred activities in its canonical XML format. Returns the 16878 * XML output as a byte array, or null if there is none. 16879 */ 16880 @Override 16881 public byte[] getPreferredActivityBackup(int userId) { 16882 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16883 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16884 } 16885 16886 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16887 try { 16888 final XmlSerializer serializer = new FastXmlSerializer(); 16889 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16890 serializer.startDocument(null, true); 16891 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16892 16893 synchronized (mPackages) { 16894 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16895 } 16896 16897 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16898 serializer.endDocument(); 16899 serializer.flush(); 16900 } catch (Exception e) { 16901 if (DEBUG_BACKUP) { 16902 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16903 } 16904 return null; 16905 } 16906 16907 return dataStream.toByteArray(); 16908 } 16909 16910 @Override 16911 public void restorePreferredActivities(byte[] backup, int userId) { 16912 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16913 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16914 } 16915 16916 try { 16917 final XmlPullParser parser = Xml.newPullParser(); 16918 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16919 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16920 new BlobXmlRestorer() { 16921 @Override 16922 public void apply(XmlPullParser parser, int userId) 16923 throws XmlPullParserException, IOException { 16924 synchronized (mPackages) { 16925 mSettings.readPreferredActivitiesLPw(parser, userId); 16926 } 16927 } 16928 } ); 16929 } catch (Exception e) { 16930 if (DEBUG_BACKUP) { 16931 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16932 } 16933 } 16934 } 16935 16936 /** 16937 * Non-Binder method, support for the backup/restore mechanism: write the 16938 * default browser (etc) settings in its canonical XML format. Returns the default 16939 * browser XML representation as a byte array, or null if there is none. 16940 */ 16941 @Override 16942 public byte[] getDefaultAppsBackup(int userId) { 16943 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16944 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16945 } 16946 16947 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16948 try { 16949 final XmlSerializer serializer = new FastXmlSerializer(); 16950 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16951 serializer.startDocument(null, true); 16952 serializer.startTag(null, TAG_DEFAULT_APPS); 16953 16954 synchronized (mPackages) { 16955 mSettings.writeDefaultAppsLPr(serializer, userId); 16956 } 16957 16958 serializer.endTag(null, TAG_DEFAULT_APPS); 16959 serializer.endDocument(); 16960 serializer.flush(); 16961 } catch (Exception e) { 16962 if (DEBUG_BACKUP) { 16963 Slog.e(TAG, "Unable to write default apps for backup", e); 16964 } 16965 return null; 16966 } 16967 16968 return dataStream.toByteArray(); 16969 } 16970 16971 @Override 16972 public void restoreDefaultApps(byte[] backup, int userId) { 16973 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16974 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16975 } 16976 16977 try { 16978 final XmlPullParser parser = Xml.newPullParser(); 16979 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16980 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16981 new BlobXmlRestorer() { 16982 @Override 16983 public void apply(XmlPullParser parser, int userId) 16984 throws XmlPullParserException, IOException { 16985 synchronized (mPackages) { 16986 mSettings.readDefaultAppsLPw(parser, userId); 16987 } 16988 } 16989 } ); 16990 } catch (Exception e) { 16991 if (DEBUG_BACKUP) { 16992 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16993 } 16994 } 16995 } 16996 16997 @Override 16998 public byte[] getIntentFilterVerificationBackup(int userId) { 16999 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17000 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17001 } 17002 17003 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17004 try { 17005 final XmlSerializer serializer = new FastXmlSerializer(); 17006 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17007 serializer.startDocument(null, true); 17008 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17009 17010 synchronized (mPackages) { 17011 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17012 } 17013 17014 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17015 serializer.endDocument(); 17016 serializer.flush(); 17017 } catch (Exception e) { 17018 if (DEBUG_BACKUP) { 17019 Slog.e(TAG, "Unable to write default apps for backup", e); 17020 } 17021 return null; 17022 } 17023 17024 return dataStream.toByteArray(); 17025 } 17026 17027 @Override 17028 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17029 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17030 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17031 } 17032 17033 try { 17034 final XmlPullParser parser = Xml.newPullParser(); 17035 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17036 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17037 new BlobXmlRestorer() { 17038 @Override 17039 public void apply(XmlPullParser parser, int userId) 17040 throws XmlPullParserException, IOException { 17041 synchronized (mPackages) { 17042 mSettings.readAllDomainVerificationsLPr(parser, userId); 17043 mSettings.writeLPr(); 17044 } 17045 } 17046 } ); 17047 } catch (Exception e) { 17048 if (DEBUG_BACKUP) { 17049 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17050 } 17051 } 17052 } 17053 17054 @Override 17055 public byte[] getPermissionGrantBackup(int userId) { 17056 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17057 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17058 } 17059 17060 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17061 try { 17062 final XmlSerializer serializer = new FastXmlSerializer(); 17063 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17064 serializer.startDocument(null, true); 17065 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17066 17067 synchronized (mPackages) { 17068 serializeRuntimePermissionGrantsLPr(serializer, userId); 17069 } 17070 17071 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17072 serializer.endDocument(); 17073 serializer.flush(); 17074 } catch (Exception e) { 17075 if (DEBUG_BACKUP) { 17076 Slog.e(TAG, "Unable to write default apps for backup", e); 17077 } 17078 return null; 17079 } 17080 17081 return dataStream.toByteArray(); 17082 } 17083 17084 @Override 17085 public void restorePermissionGrants(byte[] backup, int userId) { 17086 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17087 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17088 } 17089 17090 try { 17091 final XmlPullParser parser = Xml.newPullParser(); 17092 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17093 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17094 new BlobXmlRestorer() { 17095 @Override 17096 public void apply(XmlPullParser parser, int userId) 17097 throws XmlPullParserException, IOException { 17098 synchronized (mPackages) { 17099 processRestoredPermissionGrantsLPr(parser, userId); 17100 } 17101 } 17102 } ); 17103 } catch (Exception e) { 17104 if (DEBUG_BACKUP) { 17105 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17106 } 17107 } 17108 } 17109 17110 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17111 throws IOException { 17112 serializer.startTag(null, TAG_ALL_GRANTS); 17113 17114 final int N = mSettings.mPackages.size(); 17115 for (int i = 0; i < N; i++) { 17116 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17117 boolean pkgGrantsKnown = false; 17118 17119 PermissionsState packagePerms = ps.getPermissionsState(); 17120 17121 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17122 final int grantFlags = state.getFlags(); 17123 // only look at grants that are not system/policy fixed 17124 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17125 final boolean isGranted = state.isGranted(); 17126 // And only back up the user-twiddled state bits 17127 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17128 final String packageName = mSettings.mPackages.keyAt(i); 17129 if (!pkgGrantsKnown) { 17130 serializer.startTag(null, TAG_GRANT); 17131 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17132 pkgGrantsKnown = true; 17133 } 17134 17135 final boolean userSet = 17136 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17137 final boolean userFixed = 17138 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17139 final boolean revoke = 17140 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17141 17142 serializer.startTag(null, TAG_PERMISSION); 17143 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17144 if (isGranted) { 17145 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17146 } 17147 if (userSet) { 17148 serializer.attribute(null, ATTR_USER_SET, "true"); 17149 } 17150 if (userFixed) { 17151 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17152 } 17153 if (revoke) { 17154 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17155 } 17156 serializer.endTag(null, TAG_PERMISSION); 17157 } 17158 } 17159 } 17160 17161 if (pkgGrantsKnown) { 17162 serializer.endTag(null, TAG_GRANT); 17163 } 17164 } 17165 17166 serializer.endTag(null, TAG_ALL_GRANTS); 17167 } 17168 17169 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17170 throws XmlPullParserException, IOException { 17171 String pkgName = null; 17172 int outerDepth = parser.getDepth(); 17173 int type; 17174 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17175 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17176 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17177 continue; 17178 } 17179 17180 final String tagName = parser.getName(); 17181 if (tagName.equals(TAG_GRANT)) { 17182 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17183 if (DEBUG_BACKUP) { 17184 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17185 } 17186 } else if (tagName.equals(TAG_PERMISSION)) { 17187 17188 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17189 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17190 17191 int newFlagSet = 0; 17192 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17193 newFlagSet |= FLAG_PERMISSION_USER_SET; 17194 } 17195 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17196 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17197 } 17198 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17199 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17200 } 17201 if (DEBUG_BACKUP) { 17202 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17203 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17204 } 17205 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17206 if (ps != null) { 17207 // Already installed so we apply the grant immediately 17208 if (DEBUG_BACKUP) { 17209 Slog.v(TAG, " + already installed; applying"); 17210 } 17211 PermissionsState perms = ps.getPermissionsState(); 17212 BasePermission bp = mSettings.mPermissions.get(permName); 17213 if (bp != null) { 17214 if (isGranted) { 17215 perms.grantRuntimePermission(bp, userId); 17216 } 17217 if (newFlagSet != 0) { 17218 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17219 } 17220 } 17221 } else { 17222 // Need to wait for post-restore install to apply the grant 17223 if (DEBUG_BACKUP) { 17224 Slog.v(TAG, " - not yet installed; saving for later"); 17225 } 17226 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17227 isGranted, newFlagSet, userId); 17228 } 17229 } else { 17230 PackageManagerService.reportSettingsProblem(Log.WARN, 17231 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17232 XmlUtils.skipCurrentTag(parser); 17233 } 17234 } 17235 17236 scheduleWriteSettingsLocked(); 17237 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17238 } 17239 17240 @Override 17241 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17242 int sourceUserId, int targetUserId, int flags) { 17243 mContext.enforceCallingOrSelfPermission( 17244 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17245 int callingUid = Binder.getCallingUid(); 17246 enforceOwnerRights(ownerPackage, callingUid); 17247 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17248 if (intentFilter.countActions() == 0) { 17249 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17250 return; 17251 } 17252 synchronized (mPackages) { 17253 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17254 ownerPackage, targetUserId, flags); 17255 CrossProfileIntentResolver resolver = 17256 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17257 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17258 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17259 if (existing != null) { 17260 int size = existing.size(); 17261 for (int i = 0; i < size; i++) { 17262 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17263 return; 17264 } 17265 } 17266 } 17267 resolver.addFilter(newFilter); 17268 scheduleWritePackageRestrictionsLocked(sourceUserId); 17269 } 17270 } 17271 17272 @Override 17273 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17274 mContext.enforceCallingOrSelfPermission( 17275 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17276 int callingUid = Binder.getCallingUid(); 17277 enforceOwnerRights(ownerPackage, callingUid); 17278 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17279 synchronized (mPackages) { 17280 CrossProfileIntentResolver resolver = 17281 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17282 ArraySet<CrossProfileIntentFilter> set = 17283 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17284 for (CrossProfileIntentFilter filter : set) { 17285 if (filter.getOwnerPackage().equals(ownerPackage)) { 17286 resolver.removeFilter(filter); 17287 } 17288 } 17289 scheduleWritePackageRestrictionsLocked(sourceUserId); 17290 } 17291 } 17292 17293 // Enforcing that callingUid is owning pkg on userId 17294 private void enforceOwnerRights(String pkg, int callingUid) { 17295 // The system owns everything. 17296 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17297 return; 17298 } 17299 int callingUserId = UserHandle.getUserId(callingUid); 17300 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17301 if (pi == null) { 17302 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17303 + callingUserId); 17304 } 17305 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17306 throw new SecurityException("Calling uid " + callingUid 17307 + " does not own package " + pkg); 17308 } 17309 } 17310 17311 @Override 17312 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17313 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17314 } 17315 17316 private Intent getHomeIntent() { 17317 Intent intent = new Intent(Intent.ACTION_MAIN); 17318 intent.addCategory(Intent.CATEGORY_HOME); 17319 return intent; 17320 } 17321 17322 private IntentFilter getHomeFilter() { 17323 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17324 filter.addCategory(Intent.CATEGORY_HOME); 17325 filter.addCategory(Intent.CATEGORY_DEFAULT); 17326 return filter; 17327 } 17328 17329 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17330 int userId) { 17331 Intent intent = getHomeIntent(); 17332 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17333 PackageManager.GET_META_DATA, userId); 17334 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17335 true, false, false, userId); 17336 17337 allHomeCandidates.clear(); 17338 if (list != null) { 17339 for (ResolveInfo ri : list) { 17340 allHomeCandidates.add(ri); 17341 } 17342 } 17343 return (preferred == null || preferred.activityInfo == null) 17344 ? null 17345 : new ComponentName(preferred.activityInfo.packageName, 17346 preferred.activityInfo.name); 17347 } 17348 17349 @Override 17350 public void setHomeActivity(ComponentName comp, int userId) { 17351 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17352 getHomeActivitiesAsUser(homeActivities, userId); 17353 17354 boolean found = false; 17355 17356 final int size = homeActivities.size(); 17357 final ComponentName[] set = new ComponentName[size]; 17358 for (int i = 0; i < size; i++) { 17359 final ResolveInfo candidate = homeActivities.get(i); 17360 final ActivityInfo info = candidate.activityInfo; 17361 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17362 set[i] = activityName; 17363 if (!found && activityName.equals(comp)) { 17364 found = true; 17365 } 17366 } 17367 if (!found) { 17368 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17369 + userId); 17370 } 17371 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17372 set, comp, userId); 17373 } 17374 17375 private @Nullable String getSetupWizardPackageName() { 17376 final Intent intent = new Intent(Intent.ACTION_MAIN); 17377 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17378 17379 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17380 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17381 | MATCH_DISABLED_COMPONENTS, 17382 UserHandle.myUserId()); 17383 if (matches.size() == 1) { 17384 return matches.get(0).getComponentInfo().packageName; 17385 } else { 17386 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17387 + ": matches=" + matches); 17388 return null; 17389 } 17390 } 17391 17392 @Override 17393 public void setApplicationEnabledSetting(String appPackageName, 17394 int newState, int flags, int userId, String callingPackage) { 17395 if (!sUserManager.exists(userId)) return; 17396 if (callingPackage == null) { 17397 callingPackage = Integer.toString(Binder.getCallingUid()); 17398 } 17399 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17400 } 17401 17402 @Override 17403 public void setComponentEnabledSetting(ComponentName componentName, 17404 int newState, int flags, int userId) { 17405 if (!sUserManager.exists(userId)) return; 17406 setEnabledSetting(componentName.getPackageName(), 17407 componentName.getClassName(), newState, flags, userId, null); 17408 } 17409 17410 private void setEnabledSetting(final String packageName, String className, int newState, 17411 final int flags, int userId, String callingPackage) { 17412 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17413 || newState == COMPONENT_ENABLED_STATE_ENABLED 17414 || newState == COMPONENT_ENABLED_STATE_DISABLED 17415 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17416 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17417 throw new IllegalArgumentException("Invalid new component state: " 17418 + newState); 17419 } 17420 PackageSetting pkgSetting; 17421 final int uid = Binder.getCallingUid(); 17422 final int permission; 17423 if (uid == Process.SYSTEM_UID) { 17424 permission = PackageManager.PERMISSION_GRANTED; 17425 } else { 17426 permission = mContext.checkCallingOrSelfPermission( 17427 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17428 } 17429 enforceCrossUserPermission(uid, userId, 17430 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17431 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17432 boolean sendNow = false; 17433 boolean isApp = (className == null); 17434 String componentName = isApp ? packageName : className; 17435 int packageUid = -1; 17436 ArrayList<String> components; 17437 17438 // writer 17439 synchronized (mPackages) { 17440 pkgSetting = mSettings.mPackages.get(packageName); 17441 if (pkgSetting == null) { 17442 if (className == null) { 17443 throw new IllegalArgumentException("Unknown package: " + packageName); 17444 } 17445 throw new IllegalArgumentException( 17446 "Unknown component: " + packageName + "/" + className); 17447 } 17448 // Allow root and verify that userId is not being specified by a different user 17449 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17450 throw new SecurityException( 17451 "Permission Denial: attempt to change component state from pid=" 17452 + Binder.getCallingPid() 17453 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17454 } 17455 if (className == null) { 17456 // We're dealing with an application/package level state change 17457 if (pkgSetting.getEnabled(userId) == newState) { 17458 // Nothing to do 17459 return; 17460 } 17461 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17462 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17463 // Don't care about who enables an app. 17464 callingPackage = null; 17465 } 17466 pkgSetting.setEnabled(newState, userId, callingPackage); 17467 // pkgSetting.pkg.mSetEnabled = newState; 17468 } else { 17469 // We're dealing with a component level state change 17470 // First, verify that this is a valid class name. 17471 PackageParser.Package pkg = pkgSetting.pkg; 17472 if (pkg == null || !pkg.hasComponentClassName(className)) { 17473 if (pkg != null && 17474 pkg.applicationInfo.targetSdkVersion >= 17475 Build.VERSION_CODES.JELLY_BEAN) { 17476 throw new IllegalArgumentException("Component class " + className 17477 + " does not exist in " + packageName); 17478 } else { 17479 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17480 + className + " does not exist in " + packageName); 17481 } 17482 } 17483 switch (newState) { 17484 case COMPONENT_ENABLED_STATE_ENABLED: 17485 if (!pkgSetting.enableComponentLPw(className, userId)) { 17486 return; 17487 } 17488 break; 17489 case COMPONENT_ENABLED_STATE_DISABLED: 17490 if (!pkgSetting.disableComponentLPw(className, userId)) { 17491 return; 17492 } 17493 break; 17494 case COMPONENT_ENABLED_STATE_DEFAULT: 17495 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17496 return; 17497 } 17498 break; 17499 default: 17500 Slog.e(TAG, "Invalid new component state: " + newState); 17501 return; 17502 } 17503 } 17504 scheduleWritePackageRestrictionsLocked(userId); 17505 components = mPendingBroadcasts.get(userId, packageName); 17506 final boolean newPackage = components == null; 17507 if (newPackage) { 17508 components = new ArrayList<String>(); 17509 } 17510 if (!components.contains(componentName)) { 17511 components.add(componentName); 17512 } 17513 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17514 sendNow = true; 17515 // Purge entry from pending broadcast list if another one exists already 17516 // since we are sending one right away. 17517 mPendingBroadcasts.remove(userId, packageName); 17518 } else { 17519 if (newPackage) { 17520 mPendingBroadcasts.put(userId, packageName, components); 17521 } 17522 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17523 // Schedule a message 17524 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17525 } 17526 } 17527 } 17528 17529 long callingId = Binder.clearCallingIdentity(); 17530 try { 17531 if (sendNow) { 17532 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17533 sendPackageChangedBroadcast(packageName, 17534 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17535 } 17536 } finally { 17537 Binder.restoreCallingIdentity(callingId); 17538 } 17539 } 17540 17541 @Override 17542 public void flushPackageRestrictionsAsUser(int userId) { 17543 if (!sUserManager.exists(userId)) { 17544 return; 17545 } 17546 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17547 false /* checkShell */, "flushPackageRestrictions"); 17548 synchronized (mPackages) { 17549 mSettings.writePackageRestrictionsLPr(userId); 17550 mDirtyUsers.remove(userId); 17551 if (mDirtyUsers.isEmpty()) { 17552 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17553 } 17554 } 17555 } 17556 17557 private void sendPackageChangedBroadcast(String packageName, 17558 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17559 if (DEBUG_INSTALL) 17560 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17561 + componentNames); 17562 Bundle extras = new Bundle(4); 17563 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17564 String nameList[] = new String[componentNames.size()]; 17565 componentNames.toArray(nameList); 17566 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17567 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17568 extras.putInt(Intent.EXTRA_UID, packageUid); 17569 // If this is not reporting a change of the overall package, then only send it 17570 // to registered receivers. We don't want to launch a swath of apps for every 17571 // little component state change. 17572 final int flags = !componentNames.contains(packageName) 17573 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17574 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17575 new int[] {UserHandle.getUserId(packageUid)}); 17576 } 17577 17578 @Override 17579 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17580 if (!sUserManager.exists(userId)) return; 17581 final int uid = Binder.getCallingUid(); 17582 final int permission = mContext.checkCallingOrSelfPermission( 17583 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17584 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17585 enforceCrossUserPermission(uid, userId, 17586 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17587 // writer 17588 synchronized (mPackages) { 17589 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17590 allowedByPermission, uid, userId)) { 17591 scheduleWritePackageRestrictionsLocked(userId); 17592 } 17593 } 17594 } 17595 17596 @Override 17597 public String getInstallerPackageName(String packageName) { 17598 // reader 17599 synchronized (mPackages) { 17600 return mSettings.getInstallerPackageNameLPr(packageName); 17601 } 17602 } 17603 17604 public boolean isOrphaned(String packageName) { 17605 // reader 17606 synchronized (mPackages) { 17607 return mSettings.isOrphaned(packageName); 17608 } 17609 } 17610 17611 @Override 17612 public int getApplicationEnabledSetting(String packageName, int userId) { 17613 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17614 int uid = Binder.getCallingUid(); 17615 enforceCrossUserPermission(uid, userId, 17616 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17617 // reader 17618 synchronized (mPackages) { 17619 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17620 } 17621 } 17622 17623 @Override 17624 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17625 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17626 int uid = Binder.getCallingUid(); 17627 enforceCrossUserPermission(uid, userId, 17628 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17629 // reader 17630 synchronized (mPackages) { 17631 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17632 } 17633 } 17634 17635 @Override 17636 public void enterSafeMode() { 17637 enforceSystemOrRoot("Only the system can request entering safe mode"); 17638 17639 if (!mSystemReady) { 17640 mSafeMode = true; 17641 } 17642 } 17643 17644 @Override 17645 public void systemReady() { 17646 mSystemReady = true; 17647 17648 // Read the compatibilty setting when the system is ready. 17649 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17650 mContext.getContentResolver(), 17651 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17652 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17653 if (DEBUG_SETTINGS) { 17654 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17655 } 17656 17657 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17658 17659 synchronized (mPackages) { 17660 // Verify that all of the preferred activity components actually 17661 // exist. It is possible for applications to be updated and at 17662 // that point remove a previously declared activity component that 17663 // had been set as a preferred activity. We try to clean this up 17664 // the next time we encounter that preferred activity, but it is 17665 // possible for the user flow to never be able to return to that 17666 // situation so here we do a sanity check to make sure we haven't 17667 // left any junk around. 17668 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17669 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17670 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17671 removed.clear(); 17672 for (PreferredActivity pa : pir.filterSet()) { 17673 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17674 removed.add(pa); 17675 } 17676 } 17677 if (removed.size() > 0) { 17678 for (int r=0; r<removed.size(); r++) { 17679 PreferredActivity pa = removed.get(r); 17680 Slog.w(TAG, "Removing dangling preferred activity: " 17681 + pa.mPref.mComponent); 17682 pir.removeFilter(pa); 17683 } 17684 mSettings.writePackageRestrictionsLPr( 17685 mSettings.mPreferredActivities.keyAt(i)); 17686 } 17687 } 17688 17689 for (int userId : UserManagerService.getInstance().getUserIds()) { 17690 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17691 grantPermissionsUserIds = ArrayUtils.appendInt( 17692 grantPermissionsUserIds, userId); 17693 } 17694 } 17695 } 17696 sUserManager.systemReady(); 17697 17698 // If we upgraded grant all default permissions before kicking off. 17699 for (int userId : grantPermissionsUserIds) { 17700 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17701 } 17702 17703 // Kick off any messages waiting for system ready 17704 if (mPostSystemReadyMessages != null) { 17705 for (Message msg : mPostSystemReadyMessages) { 17706 msg.sendToTarget(); 17707 } 17708 mPostSystemReadyMessages = null; 17709 } 17710 17711 // Watch for external volumes that come and go over time 17712 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17713 storage.registerListener(mStorageListener); 17714 17715 mInstallerService.systemReady(); 17716 mPackageDexOptimizer.systemReady(); 17717 17718 MountServiceInternal mountServiceInternal = LocalServices.getService( 17719 MountServiceInternal.class); 17720 mountServiceInternal.addExternalStoragePolicy( 17721 new MountServiceInternal.ExternalStorageMountPolicy() { 17722 @Override 17723 public int getMountMode(int uid, String packageName) { 17724 if (Process.isIsolated(uid)) { 17725 return Zygote.MOUNT_EXTERNAL_NONE; 17726 } 17727 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17728 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17729 } 17730 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17731 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17732 } 17733 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17734 return Zygote.MOUNT_EXTERNAL_READ; 17735 } 17736 return Zygote.MOUNT_EXTERNAL_WRITE; 17737 } 17738 17739 @Override 17740 public boolean hasExternalStorage(int uid, String packageName) { 17741 return true; 17742 } 17743 }); 17744 17745 // Now that we're mostly running, clean up stale users and apps 17746 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17747 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17748 } 17749 17750 @Override 17751 public boolean isSafeMode() { 17752 return mSafeMode; 17753 } 17754 17755 @Override 17756 public boolean hasSystemUidErrors() { 17757 return mHasSystemUidErrors; 17758 } 17759 17760 static String arrayToString(int[] array) { 17761 StringBuffer buf = new StringBuffer(128); 17762 buf.append('['); 17763 if (array != null) { 17764 for (int i=0; i<array.length; i++) { 17765 if (i > 0) buf.append(", "); 17766 buf.append(array[i]); 17767 } 17768 } 17769 buf.append(']'); 17770 return buf.toString(); 17771 } 17772 17773 static class DumpState { 17774 public static final int DUMP_LIBS = 1 << 0; 17775 public static final int DUMP_FEATURES = 1 << 1; 17776 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17777 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17778 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17779 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17780 public static final int DUMP_PERMISSIONS = 1 << 6; 17781 public static final int DUMP_PACKAGES = 1 << 7; 17782 public static final int DUMP_SHARED_USERS = 1 << 8; 17783 public static final int DUMP_MESSAGES = 1 << 9; 17784 public static final int DUMP_PROVIDERS = 1 << 10; 17785 public static final int DUMP_VERIFIERS = 1 << 11; 17786 public static final int DUMP_PREFERRED = 1 << 12; 17787 public static final int DUMP_PREFERRED_XML = 1 << 13; 17788 public static final int DUMP_KEYSETS = 1 << 14; 17789 public static final int DUMP_VERSION = 1 << 15; 17790 public static final int DUMP_INSTALLS = 1 << 16; 17791 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17792 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17793 public static final int DUMP_FROZEN = 1 << 19; 17794 public static final int DUMP_DEXOPT = 1 << 20; 17795 17796 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17797 17798 private int mTypes; 17799 17800 private int mOptions; 17801 17802 private boolean mTitlePrinted; 17803 17804 private SharedUserSetting mSharedUser; 17805 17806 public boolean isDumping(int type) { 17807 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17808 return true; 17809 } 17810 17811 return (mTypes & type) != 0; 17812 } 17813 17814 public void setDump(int type) { 17815 mTypes |= type; 17816 } 17817 17818 public boolean isOptionEnabled(int option) { 17819 return (mOptions & option) != 0; 17820 } 17821 17822 public void setOptionEnabled(int option) { 17823 mOptions |= option; 17824 } 17825 17826 public boolean onTitlePrinted() { 17827 final boolean printed = mTitlePrinted; 17828 mTitlePrinted = true; 17829 return printed; 17830 } 17831 17832 public boolean getTitlePrinted() { 17833 return mTitlePrinted; 17834 } 17835 17836 public void setTitlePrinted(boolean enabled) { 17837 mTitlePrinted = enabled; 17838 } 17839 17840 public SharedUserSetting getSharedUser() { 17841 return mSharedUser; 17842 } 17843 17844 public void setSharedUser(SharedUserSetting user) { 17845 mSharedUser = user; 17846 } 17847 } 17848 17849 @Override 17850 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17851 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17852 (new PackageManagerShellCommand(this)).exec( 17853 this, in, out, err, args, resultReceiver); 17854 } 17855 17856 @Override 17857 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17858 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17859 != PackageManager.PERMISSION_GRANTED) { 17860 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17861 + Binder.getCallingPid() 17862 + ", uid=" + Binder.getCallingUid() 17863 + " without permission " 17864 + android.Manifest.permission.DUMP); 17865 return; 17866 } 17867 17868 DumpState dumpState = new DumpState(); 17869 boolean fullPreferred = false; 17870 boolean checkin = false; 17871 17872 String packageName = null; 17873 ArraySet<String> permissionNames = null; 17874 17875 int opti = 0; 17876 while (opti < args.length) { 17877 String opt = args[opti]; 17878 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17879 break; 17880 } 17881 opti++; 17882 17883 if ("-a".equals(opt)) { 17884 // Right now we only know how to print all. 17885 } else if ("-h".equals(opt)) { 17886 pw.println("Package manager dump options:"); 17887 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17888 pw.println(" --checkin: dump for a checkin"); 17889 pw.println(" -f: print details of intent filters"); 17890 pw.println(" -h: print this help"); 17891 pw.println(" cmd may be one of:"); 17892 pw.println(" l[ibraries]: list known shared libraries"); 17893 pw.println(" f[eatures]: list device features"); 17894 pw.println(" k[eysets]: print known keysets"); 17895 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17896 pw.println(" perm[issions]: dump permissions"); 17897 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17898 pw.println(" pref[erred]: print preferred package settings"); 17899 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17900 pw.println(" prov[iders]: dump content providers"); 17901 pw.println(" p[ackages]: dump installed packages"); 17902 pw.println(" s[hared-users]: dump shared user IDs"); 17903 pw.println(" m[essages]: print collected runtime messages"); 17904 pw.println(" v[erifiers]: print package verifier info"); 17905 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17906 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17907 pw.println(" version: print database version info"); 17908 pw.println(" write: write current settings now"); 17909 pw.println(" installs: details about install sessions"); 17910 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17911 pw.println(" dexopt: dump dexopt state"); 17912 pw.println(" <package.name>: info about given package"); 17913 return; 17914 } else if ("--checkin".equals(opt)) { 17915 checkin = true; 17916 } else if ("-f".equals(opt)) { 17917 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17918 } else { 17919 pw.println("Unknown argument: " + opt + "; use -h for help"); 17920 } 17921 } 17922 17923 // Is the caller requesting to dump a particular piece of data? 17924 if (opti < args.length) { 17925 String cmd = args[opti]; 17926 opti++; 17927 // Is this a package name? 17928 if ("android".equals(cmd) || cmd.contains(".")) { 17929 packageName = cmd; 17930 // When dumping a single package, we always dump all of its 17931 // filter information since the amount of data will be reasonable. 17932 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17933 } else if ("check-permission".equals(cmd)) { 17934 if (opti >= args.length) { 17935 pw.println("Error: check-permission missing permission argument"); 17936 return; 17937 } 17938 String perm = args[opti]; 17939 opti++; 17940 if (opti >= args.length) { 17941 pw.println("Error: check-permission missing package argument"); 17942 return; 17943 } 17944 String pkg = args[opti]; 17945 opti++; 17946 int user = UserHandle.getUserId(Binder.getCallingUid()); 17947 if (opti < args.length) { 17948 try { 17949 user = Integer.parseInt(args[opti]); 17950 } catch (NumberFormatException e) { 17951 pw.println("Error: check-permission user argument is not a number: " 17952 + args[opti]); 17953 return; 17954 } 17955 } 17956 pw.println(checkPermission(perm, pkg, user)); 17957 return; 17958 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17959 dumpState.setDump(DumpState.DUMP_LIBS); 17960 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17961 dumpState.setDump(DumpState.DUMP_FEATURES); 17962 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17963 if (opti >= args.length) { 17964 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17965 | DumpState.DUMP_SERVICE_RESOLVERS 17966 | DumpState.DUMP_RECEIVER_RESOLVERS 17967 | DumpState.DUMP_CONTENT_RESOLVERS); 17968 } else { 17969 while (opti < args.length) { 17970 String name = args[opti]; 17971 if ("a".equals(name) || "activity".equals(name)) { 17972 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17973 } else if ("s".equals(name) || "service".equals(name)) { 17974 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17975 } else if ("r".equals(name) || "receiver".equals(name)) { 17976 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17977 } else if ("c".equals(name) || "content".equals(name)) { 17978 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17979 } else { 17980 pw.println("Error: unknown resolver table type: " + name); 17981 return; 17982 } 17983 opti++; 17984 } 17985 } 17986 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17987 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17988 } else if ("permission".equals(cmd)) { 17989 if (opti >= args.length) { 17990 pw.println("Error: permission requires permission name"); 17991 return; 17992 } 17993 permissionNames = new ArraySet<>(); 17994 while (opti < args.length) { 17995 permissionNames.add(args[opti]); 17996 opti++; 17997 } 17998 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17999 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18000 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18001 dumpState.setDump(DumpState.DUMP_PREFERRED); 18002 } else if ("preferred-xml".equals(cmd)) { 18003 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18004 if (opti < args.length && "--full".equals(args[opti])) { 18005 fullPreferred = true; 18006 opti++; 18007 } 18008 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18009 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18010 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18011 dumpState.setDump(DumpState.DUMP_PACKAGES); 18012 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18013 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18014 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18015 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18016 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18017 dumpState.setDump(DumpState.DUMP_MESSAGES); 18018 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18019 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18020 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18021 || "intent-filter-verifiers".equals(cmd)) { 18022 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18023 } else if ("version".equals(cmd)) { 18024 dumpState.setDump(DumpState.DUMP_VERSION); 18025 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18026 dumpState.setDump(DumpState.DUMP_KEYSETS); 18027 } else if ("installs".equals(cmd)) { 18028 dumpState.setDump(DumpState.DUMP_INSTALLS); 18029 } else if ("frozen".equals(cmd)) { 18030 dumpState.setDump(DumpState.DUMP_FROZEN); 18031 } else if ("dexopt".equals(cmd)) { 18032 dumpState.setDump(DumpState.DUMP_DEXOPT); 18033 } else if ("write".equals(cmd)) { 18034 synchronized (mPackages) { 18035 mSettings.writeLPr(); 18036 pw.println("Settings written."); 18037 return; 18038 } 18039 } 18040 } 18041 18042 if (checkin) { 18043 pw.println("vers,1"); 18044 } 18045 18046 // reader 18047 synchronized (mPackages) { 18048 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18049 if (!checkin) { 18050 if (dumpState.onTitlePrinted()) 18051 pw.println(); 18052 pw.println("Database versions:"); 18053 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18054 } 18055 } 18056 18057 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18058 if (!checkin) { 18059 if (dumpState.onTitlePrinted()) 18060 pw.println(); 18061 pw.println("Verifiers:"); 18062 pw.print(" Required: "); 18063 pw.print(mRequiredVerifierPackage); 18064 pw.print(" (uid="); 18065 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18066 UserHandle.USER_SYSTEM)); 18067 pw.println(")"); 18068 } else if (mRequiredVerifierPackage != null) { 18069 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18070 pw.print(","); 18071 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18072 UserHandle.USER_SYSTEM)); 18073 } 18074 } 18075 18076 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18077 packageName == null) { 18078 if (mIntentFilterVerifierComponent != null) { 18079 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18080 if (!checkin) { 18081 if (dumpState.onTitlePrinted()) 18082 pw.println(); 18083 pw.println("Intent Filter Verifier:"); 18084 pw.print(" Using: "); 18085 pw.print(verifierPackageName); 18086 pw.print(" (uid="); 18087 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18088 UserHandle.USER_SYSTEM)); 18089 pw.println(")"); 18090 } else if (verifierPackageName != null) { 18091 pw.print("ifv,"); pw.print(verifierPackageName); 18092 pw.print(","); 18093 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18094 UserHandle.USER_SYSTEM)); 18095 } 18096 } else { 18097 pw.println(); 18098 pw.println("No Intent Filter Verifier available!"); 18099 } 18100 } 18101 18102 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18103 boolean printedHeader = false; 18104 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18105 while (it.hasNext()) { 18106 String name = it.next(); 18107 SharedLibraryEntry ent = mSharedLibraries.get(name); 18108 if (!checkin) { 18109 if (!printedHeader) { 18110 if (dumpState.onTitlePrinted()) 18111 pw.println(); 18112 pw.println("Libraries:"); 18113 printedHeader = true; 18114 } 18115 pw.print(" "); 18116 } else { 18117 pw.print("lib,"); 18118 } 18119 pw.print(name); 18120 if (!checkin) { 18121 pw.print(" -> "); 18122 } 18123 if (ent.path != null) { 18124 if (!checkin) { 18125 pw.print("(jar) "); 18126 pw.print(ent.path); 18127 } else { 18128 pw.print(",jar,"); 18129 pw.print(ent.path); 18130 } 18131 } else { 18132 if (!checkin) { 18133 pw.print("(apk) "); 18134 pw.print(ent.apk); 18135 } else { 18136 pw.print(",apk,"); 18137 pw.print(ent.apk); 18138 } 18139 } 18140 pw.println(); 18141 } 18142 } 18143 18144 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18145 if (dumpState.onTitlePrinted()) 18146 pw.println(); 18147 if (!checkin) { 18148 pw.println("Features:"); 18149 } 18150 18151 for (FeatureInfo feat : mAvailableFeatures.values()) { 18152 if (checkin) { 18153 pw.print("feat,"); 18154 pw.print(feat.name); 18155 pw.print(","); 18156 pw.println(feat.version); 18157 } else { 18158 pw.print(" "); 18159 pw.print(feat.name); 18160 if (feat.version > 0) { 18161 pw.print(" version="); 18162 pw.print(feat.version); 18163 } 18164 pw.println(); 18165 } 18166 } 18167 } 18168 18169 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18170 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18171 : "Activity Resolver Table:", " ", packageName, 18172 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18173 dumpState.setTitlePrinted(true); 18174 } 18175 } 18176 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18177 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18178 : "Receiver Resolver Table:", " ", packageName, 18179 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18180 dumpState.setTitlePrinted(true); 18181 } 18182 } 18183 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18184 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18185 : "Service Resolver Table:", " ", packageName, 18186 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18187 dumpState.setTitlePrinted(true); 18188 } 18189 } 18190 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18191 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18192 : "Provider Resolver Table:", " ", packageName, 18193 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18194 dumpState.setTitlePrinted(true); 18195 } 18196 } 18197 18198 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18199 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18200 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18201 int user = mSettings.mPreferredActivities.keyAt(i); 18202 if (pir.dump(pw, 18203 dumpState.getTitlePrinted() 18204 ? "\nPreferred Activities User " + user + ":" 18205 : "Preferred Activities User " + user + ":", " ", 18206 packageName, true, false)) { 18207 dumpState.setTitlePrinted(true); 18208 } 18209 } 18210 } 18211 18212 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18213 pw.flush(); 18214 FileOutputStream fout = new FileOutputStream(fd); 18215 BufferedOutputStream str = new BufferedOutputStream(fout); 18216 XmlSerializer serializer = new FastXmlSerializer(); 18217 try { 18218 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18219 serializer.startDocument(null, true); 18220 serializer.setFeature( 18221 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18222 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18223 serializer.endDocument(); 18224 serializer.flush(); 18225 } catch (IllegalArgumentException e) { 18226 pw.println("Failed writing: " + e); 18227 } catch (IllegalStateException e) { 18228 pw.println("Failed writing: " + e); 18229 } catch (IOException e) { 18230 pw.println("Failed writing: " + e); 18231 } 18232 } 18233 18234 if (!checkin 18235 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18236 && packageName == null) { 18237 pw.println(); 18238 int count = mSettings.mPackages.size(); 18239 if (count == 0) { 18240 pw.println("No applications!"); 18241 pw.println(); 18242 } else { 18243 final String prefix = " "; 18244 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18245 if (allPackageSettings.size() == 0) { 18246 pw.println("No domain preferred apps!"); 18247 pw.println(); 18248 } else { 18249 pw.println("App verification status:"); 18250 pw.println(); 18251 count = 0; 18252 for (PackageSetting ps : allPackageSettings) { 18253 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18254 if (ivi == null || ivi.getPackageName() == null) continue; 18255 pw.println(prefix + "Package: " + ivi.getPackageName()); 18256 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18257 pw.println(prefix + "Status: " + ivi.getStatusString()); 18258 pw.println(); 18259 count++; 18260 } 18261 if (count == 0) { 18262 pw.println(prefix + "No app verification established."); 18263 pw.println(); 18264 } 18265 for (int userId : sUserManager.getUserIds()) { 18266 pw.println("App linkages for user " + userId + ":"); 18267 pw.println(); 18268 count = 0; 18269 for (PackageSetting ps : allPackageSettings) { 18270 final long status = ps.getDomainVerificationStatusForUser(userId); 18271 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18272 continue; 18273 } 18274 pw.println(prefix + "Package: " + ps.name); 18275 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18276 String statusStr = IntentFilterVerificationInfo. 18277 getStatusStringFromValue(status); 18278 pw.println(prefix + "Status: " + statusStr); 18279 pw.println(); 18280 count++; 18281 } 18282 if (count == 0) { 18283 pw.println(prefix + "No configured app linkages."); 18284 pw.println(); 18285 } 18286 } 18287 } 18288 } 18289 } 18290 18291 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18292 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18293 if (packageName == null && permissionNames == null) { 18294 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18295 if (iperm == 0) { 18296 if (dumpState.onTitlePrinted()) 18297 pw.println(); 18298 pw.println("AppOp Permissions:"); 18299 } 18300 pw.print(" AppOp Permission "); 18301 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18302 pw.println(":"); 18303 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18304 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18305 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18306 } 18307 } 18308 } 18309 } 18310 18311 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18312 boolean printedSomething = false; 18313 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18314 if (packageName != null && !packageName.equals(p.info.packageName)) { 18315 continue; 18316 } 18317 if (!printedSomething) { 18318 if (dumpState.onTitlePrinted()) 18319 pw.println(); 18320 pw.println("Registered ContentProviders:"); 18321 printedSomething = true; 18322 } 18323 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18324 pw.print(" "); pw.println(p.toString()); 18325 } 18326 printedSomething = false; 18327 for (Map.Entry<String, PackageParser.Provider> entry : 18328 mProvidersByAuthority.entrySet()) { 18329 PackageParser.Provider p = entry.getValue(); 18330 if (packageName != null && !packageName.equals(p.info.packageName)) { 18331 continue; 18332 } 18333 if (!printedSomething) { 18334 if (dumpState.onTitlePrinted()) 18335 pw.println(); 18336 pw.println("ContentProvider Authorities:"); 18337 printedSomething = true; 18338 } 18339 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18340 pw.print(" "); pw.println(p.toString()); 18341 if (p.info != null && p.info.applicationInfo != null) { 18342 final String appInfo = p.info.applicationInfo.toString(); 18343 pw.print(" applicationInfo="); pw.println(appInfo); 18344 } 18345 } 18346 } 18347 18348 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18349 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18350 } 18351 18352 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18353 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18354 } 18355 18356 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18357 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18358 } 18359 18360 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18361 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18362 } 18363 18364 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18365 // XXX should handle packageName != null by dumping only install data that 18366 // the given package is involved with. 18367 if (dumpState.onTitlePrinted()) pw.println(); 18368 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18369 } 18370 18371 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18372 // XXX should handle packageName != null by dumping only install data that 18373 // the given package is involved with. 18374 if (dumpState.onTitlePrinted()) pw.println(); 18375 18376 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18377 ipw.println(); 18378 ipw.println("Frozen packages:"); 18379 ipw.increaseIndent(); 18380 if (mFrozenPackages.size() == 0) { 18381 ipw.println("(none)"); 18382 } else { 18383 for (int i = 0; i < mFrozenPackages.size(); i++) { 18384 ipw.println(mFrozenPackages.valueAt(i)); 18385 } 18386 } 18387 ipw.decreaseIndent(); 18388 } 18389 18390 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18391 if (dumpState.onTitlePrinted()) pw.println(); 18392 dumpDexoptStateLPr(pw, packageName); 18393 } 18394 18395 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18396 if (dumpState.onTitlePrinted()) pw.println(); 18397 mSettings.dumpReadMessagesLPr(pw, dumpState); 18398 18399 pw.println(); 18400 pw.println("Package warning messages:"); 18401 BufferedReader in = null; 18402 String line = null; 18403 try { 18404 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18405 while ((line = in.readLine()) != null) { 18406 if (line.contains("ignored: updated version")) continue; 18407 pw.println(line); 18408 } 18409 } catch (IOException ignored) { 18410 } finally { 18411 IoUtils.closeQuietly(in); 18412 } 18413 } 18414 18415 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18416 BufferedReader in = null; 18417 String line = null; 18418 try { 18419 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18420 while ((line = in.readLine()) != null) { 18421 if (line.contains("ignored: updated version")) continue; 18422 pw.print("msg,"); 18423 pw.println(line); 18424 } 18425 } catch (IOException ignored) { 18426 } finally { 18427 IoUtils.closeQuietly(in); 18428 } 18429 } 18430 } 18431 } 18432 18433 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18434 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18435 ipw.println(); 18436 ipw.println("Dexopt state:"); 18437 ipw.increaseIndent(); 18438 Collection<PackageParser.Package> packages = null; 18439 if (packageName != null) { 18440 PackageParser.Package targetPackage = mPackages.get(packageName); 18441 if (targetPackage != null) { 18442 packages = Collections.singletonList(targetPackage); 18443 } else { 18444 ipw.println("Unable to find package: " + packageName); 18445 return; 18446 } 18447 } else { 18448 packages = mPackages.values(); 18449 } 18450 18451 for (PackageParser.Package pkg : packages) { 18452 ipw.println("[" + pkg.packageName + "]"); 18453 ipw.increaseIndent(); 18454 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18455 ipw.decreaseIndent(); 18456 } 18457 } 18458 18459 private String dumpDomainString(String packageName) { 18460 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18461 .getList(); 18462 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18463 18464 ArraySet<String> result = new ArraySet<>(); 18465 if (iviList.size() > 0) { 18466 for (IntentFilterVerificationInfo ivi : iviList) { 18467 for (String host : ivi.getDomains()) { 18468 result.add(host); 18469 } 18470 } 18471 } 18472 if (filters != null && filters.size() > 0) { 18473 for (IntentFilter filter : filters) { 18474 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18475 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18476 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18477 result.addAll(filter.getHostsList()); 18478 } 18479 } 18480 } 18481 18482 StringBuilder sb = new StringBuilder(result.size() * 16); 18483 for (String domain : result) { 18484 if (sb.length() > 0) sb.append(" "); 18485 sb.append(domain); 18486 } 18487 return sb.toString(); 18488 } 18489 18490 // ------- apps on sdcard specific code ------- 18491 static final boolean DEBUG_SD_INSTALL = false; 18492 18493 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18494 18495 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18496 18497 private boolean mMediaMounted = false; 18498 18499 static String getEncryptKey() { 18500 try { 18501 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18502 SD_ENCRYPTION_KEYSTORE_NAME); 18503 if (sdEncKey == null) { 18504 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18505 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18506 if (sdEncKey == null) { 18507 Slog.e(TAG, "Failed to create encryption keys"); 18508 return null; 18509 } 18510 } 18511 return sdEncKey; 18512 } catch (NoSuchAlgorithmException nsae) { 18513 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18514 return null; 18515 } catch (IOException ioe) { 18516 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18517 return null; 18518 } 18519 } 18520 18521 /* 18522 * Update media status on PackageManager. 18523 */ 18524 @Override 18525 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18526 int callingUid = Binder.getCallingUid(); 18527 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18528 throw new SecurityException("Media status can only be updated by the system"); 18529 } 18530 // reader; this apparently protects mMediaMounted, but should probably 18531 // be a different lock in that case. 18532 synchronized (mPackages) { 18533 Log.i(TAG, "Updating external media status from " 18534 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18535 + (mediaStatus ? "mounted" : "unmounted")); 18536 if (DEBUG_SD_INSTALL) 18537 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18538 + ", mMediaMounted=" + mMediaMounted); 18539 if (mediaStatus == mMediaMounted) { 18540 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18541 : 0, -1); 18542 mHandler.sendMessage(msg); 18543 return; 18544 } 18545 mMediaMounted = mediaStatus; 18546 } 18547 // Queue up an async operation since the package installation may take a 18548 // little while. 18549 mHandler.post(new Runnable() { 18550 public void run() { 18551 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18552 } 18553 }); 18554 } 18555 18556 /** 18557 * Called by MountService when the initial ASECs to scan are available. 18558 * Should block until all the ASEC containers are finished being scanned. 18559 */ 18560 public void scanAvailableAsecs() { 18561 updateExternalMediaStatusInner(true, false, false); 18562 } 18563 18564 /* 18565 * Collect information of applications on external media, map them against 18566 * existing containers and update information based on current mount status. 18567 * Please note that we always have to report status if reportStatus has been 18568 * set to true especially when unloading packages. 18569 */ 18570 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18571 boolean externalStorage) { 18572 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18573 int[] uidArr = EmptyArray.INT; 18574 18575 final String[] list = PackageHelper.getSecureContainerList(); 18576 if (ArrayUtils.isEmpty(list)) { 18577 Log.i(TAG, "No secure containers found"); 18578 } else { 18579 // Process list of secure containers and categorize them 18580 // as active or stale based on their package internal state. 18581 18582 // reader 18583 synchronized (mPackages) { 18584 for (String cid : list) { 18585 // Leave stages untouched for now; installer service owns them 18586 if (PackageInstallerService.isStageName(cid)) continue; 18587 18588 if (DEBUG_SD_INSTALL) 18589 Log.i(TAG, "Processing container " + cid); 18590 String pkgName = getAsecPackageName(cid); 18591 if (pkgName == null) { 18592 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18593 continue; 18594 } 18595 if (DEBUG_SD_INSTALL) 18596 Log.i(TAG, "Looking for pkg : " + pkgName); 18597 18598 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18599 if (ps == null) { 18600 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18601 continue; 18602 } 18603 18604 /* 18605 * Skip packages that are not external if we're unmounting 18606 * external storage. 18607 */ 18608 if (externalStorage && !isMounted && !isExternal(ps)) { 18609 continue; 18610 } 18611 18612 final AsecInstallArgs args = new AsecInstallArgs(cid, 18613 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18614 // The package status is changed only if the code path 18615 // matches between settings and the container id. 18616 if (ps.codePathString != null 18617 && ps.codePathString.startsWith(args.getCodePath())) { 18618 if (DEBUG_SD_INSTALL) { 18619 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18620 + " at code path: " + ps.codePathString); 18621 } 18622 18623 // We do have a valid package installed on sdcard 18624 processCids.put(args, ps.codePathString); 18625 final int uid = ps.appId; 18626 if (uid != -1) { 18627 uidArr = ArrayUtils.appendInt(uidArr, uid); 18628 } 18629 } else { 18630 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18631 + ps.codePathString); 18632 } 18633 } 18634 } 18635 18636 Arrays.sort(uidArr); 18637 } 18638 18639 // Process packages with valid entries. 18640 if (isMounted) { 18641 if (DEBUG_SD_INSTALL) 18642 Log.i(TAG, "Loading packages"); 18643 loadMediaPackages(processCids, uidArr, externalStorage); 18644 startCleaningPackages(); 18645 mInstallerService.onSecureContainersAvailable(); 18646 } else { 18647 if (DEBUG_SD_INSTALL) 18648 Log.i(TAG, "Unloading packages"); 18649 unloadMediaPackages(processCids, uidArr, reportStatus); 18650 } 18651 } 18652 18653 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18654 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18655 final int size = infos.size(); 18656 final String[] packageNames = new String[size]; 18657 final int[] packageUids = new int[size]; 18658 for (int i = 0; i < size; i++) { 18659 final ApplicationInfo info = infos.get(i); 18660 packageNames[i] = info.packageName; 18661 packageUids[i] = info.uid; 18662 } 18663 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18664 finishedReceiver); 18665 } 18666 18667 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18668 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18669 sendResourcesChangedBroadcast(mediaStatus, replacing, 18670 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18671 } 18672 18673 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18674 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18675 int size = pkgList.length; 18676 if (size > 0) { 18677 // Send broadcasts here 18678 Bundle extras = new Bundle(); 18679 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18680 if (uidArr != null) { 18681 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18682 } 18683 if (replacing) { 18684 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18685 } 18686 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18687 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18688 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18689 } 18690 } 18691 18692 /* 18693 * Look at potentially valid container ids from processCids If package 18694 * information doesn't match the one on record or package scanning fails, 18695 * the cid is added to list of removeCids. We currently don't delete stale 18696 * containers. 18697 */ 18698 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18699 boolean externalStorage) { 18700 ArrayList<String> pkgList = new ArrayList<String>(); 18701 Set<AsecInstallArgs> keys = processCids.keySet(); 18702 18703 for (AsecInstallArgs args : keys) { 18704 String codePath = processCids.get(args); 18705 if (DEBUG_SD_INSTALL) 18706 Log.i(TAG, "Loading container : " + args.cid); 18707 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18708 try { 18709 // Make sure there are no container errors first. 18710 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18711 Slog.e(TAG, "Failed to mount cid : " + args.cid 18712 + " when installing from sdcard"); 18713 continue; 18714 } 18715 // Check code path here. 18716 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18717 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18718 + " does not match one in settings " + codePath); 18719 continue; 18720 } 18721 // Parse package 18722 int parseFlags = mDefParseFlags; 18723 if (args.isExternalAsec()) { 18724 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18725 } 18726 if (args.isFwdLocked()) { 18727 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18728 } 18729 18730 synchronized (mInstallLock) { 18731 PackageParser.Package pkg = null; 18732 try { 18733 // Sadly we don't know the package name yet to freeze it 18734 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18735 SCAN_IGNORE_FROZEN, 0, null); 18736 } catch (PackageManagerException e) { 18737 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18738 } 18739 // Scan the package 18740 if (pkg != null) { 18741 /* 18742 * TODO why is the lock being held? doPostInstall is 18743 * called in other places without the lock. This needs 18744 * to be straightened out. 18745 */ 18746 // writer 18747 synchronized (mPackages) { 18748 retCode = PackageManager.INSTALL_SUCCEEDED; 18749 pkgList.add(pkg.packageName); 18750 // Post process args 18751 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18752 pkg.applicationInfo.uid); 18753 } 18754 } else { 18755 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18756 } 18757 } 18758 18759 } finally { 18760 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18761 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18762 } 18763 } 18764 } 18765 // writer 18766 synchronized (mPackages) { 18767 // If the platform SDK has changed since the last time we booted, 18768 // we need to re-grant app permission to catch any new ones that 18769 // appear. This is really a hack, and means that apps can in some 18770 // cases get permissions that the user didn't initially explicitly 18771 // allow... it would be nice to have some better way to handle 18772 // this situation. 18773 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18774 : mSettings.getInternalVersion(); 18775 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18776 : StorageManager.UUID_PRIVATE_INTERNAL; 18777 18778 int updateFlags = UPDATE_PERMISSIONS_ALL; 18779 if (ver.sdkVersion != mSdkVersion) { 18780 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18781 + mSdkVersion + "; regranting permissions for external"); 18782 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18783 } 18784 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18785 18786 // Yay, everything is now upgraded 18787 ver.forceCurrent(); 18788 18789 // can downgrade to reader 18790 // Persist settings 18791 mSettings.writeLPr(); 18792 } 18793 // Send a broadcast to let everyone know we are done processing 18794 if (pkgList.size() > 0) { 18795 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18796 } 18797 } 18798 18799 /* 18800 * Utility method to unload a list of specified containers 18801 */ 18802 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18803 // Just unmount all valid containers. 18804 for (AsecInstallArgs arg : cidArgs) { 18805 synchronized (mInstallLock) { 18806 arg.doPostDeleteLI(false); 18807 } 18808 } 18809 } 18810 18811 /* 18812 * Unload packages mounted on external media. This involves deleting package 18813 * data from internal structures, sending broadcasts about disabled packages, 18814 * gc'ing to free up references, unmounting all secure containers 18815 * corresponding to packages on external media, and posting a 18816 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18817 * that we always have to post this message if status has been requested no 18818 * matter what. 18819 */ 18820 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18821 final boolean reportStatus) { 18822 if (DEBUG_SD_INSTALL) 18823 Log.i(TAG, "unloading media packages"); 18824 ArrayList<String> pkgList = new ArrayList<String>(); 18825 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18826 final Set<AsecInstallArgs> keys = processCids.keySet(); 18827 for (AsecInstallArgs args : keys) { 18828 String pkgName = args.getPackageName(); 18829 if (DEBUG_SD_INSTALL) 18830 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18831 // Delete package internally 18832 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18833 synchronized (mInstallLock) { 18834 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18835 final boolean res; 18836 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18837 "unloadMediaPackages")) { 18838 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18839 null); 18840 } 18841 if (res) { 18842 pkgList.add(pkgName); 18843 } else { 18844 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18845 failedList.add(args); 18846 } 18847 } 18848 } 18849 18850 // reader 18851 synchronized (mPackages) { 18852 // We didn't update the settings after removing each package; 18853 // write them now for all packages. 18854 mSettings.writeLPr(); 18855 } 18856 18857 // We have to absolutely send UPDATED_MEDIA_STATUS only 18858 // after confirming that all the receivers processed the ordered 18859 // broadcast when packages get disabled, force a gc to clean things up. 18860 // and unload all the containers. 18861 if (pkgList.size() > 0) { 18862 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18863 new IIntentReceiver.Stub() { 18864 public void performReceive(Intent intent, int resultCode, String data, 18865 Bundle extras, boolean ordered, boolean sticky, 18866 int sendingUser) throws RemoteException { 18867 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18868 reportStatus ? 1 : 0, 1, keys); 18869 mHandler.sendMessage(msg); 18870 } 18871 }); 18872 } else { 18873 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18874 keys); 18875 mHandler.sendMessage(msg); 18876 } 18877 } 18878 18879 private void loadPrivatePackages(final VolumeInfo vol) { 18880 mHandler.post(new Runnable() { 18881 @Override 18882 public void run() { 18883 loadPrivatePackagesInner(vol); 18884 } 18885 }); 18886 } 18887 18888 private void loadPrivatePackagesInner(VolumeInfo vol) { 18889 final String volumeUuid = vol.fsUuid; 18890 if (TextUtils.isEmpty(volumeUuid)) { 18891 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18892 return; 18893 } 18894 18895 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18896 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18897 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18898 18899 final VersionInfo ver; 18900 final List<PackageSetting> packages; 18901 synchronized (mPackages) { 18902 ver = mSettings.findOrCreateVersion(volumeUuid); 18903 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18904 } 18905 18906 for (PackageSetting ps : packages) { 18907 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18908 synchronized (mInstallLock) { 18909 final PackageParser.Package pkg; 18910 try { 18911 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18912 loaded.add(pkg.applicationInfo); 18913 18914 } catch (PackageManagerException e) { 18915 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18916 } 18917 18918 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18919 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18920 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18921 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18922 } 18923 } 18924 } 18925 18926 // Reconcile app data for all started/unlocked users 18927 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18928 final UserManager um = mContext.getSystemService(UserManager.class); 18929 for (UserInfo user : um.getUsers()) { 18930 final int flags; 18931 if (um.isUserUnlockingOrUnlocked(user.id)) { 18932 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18933 } else if (um.isUserRunning(user.id)) { 18934 flags = StorageManager.FLAG_STORAGE_DE; 18935 } else { 18936 continue; 18937 } 18938 18939 try { 18940 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18941 synchronized (mInstallLock) { 18942 reconcileAppsDataLI(volumeUuid, user.id, flags); 18943 } 18944 } catch (IllegalStateException e) { 18945 // Device was probably ejected, and we'll process that event momentarily 18946 Slog.w(TAG, "Failed to prepare storage: " + e); 18947 } 18948 } 18949 18950 synchronized (mPackages) { 18951 int updateFlags = UPDATE_PERMISSIONS_ALL; 18952 if (ver.sdkVersion != mSdkVersion) { 18953 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18954 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18955 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18956 } 18957 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18958 18959 // Yay, everything is now upgraded 18960 ver.forceCurrent(); 18961 18962 mSettings.writeLPr(); 18963 } 18964 18965 for (PackageFreezer freezer : freezers) { 18966 freezer.close(); 18967 } 18968 18969 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18970 sendResourcesChangedBroadcast(true, false, loaded, null); 18971 } 18972 18973 private void unloadPrivatePackages(final VolumeInfo vol) { 18974 mHandler.post(new Runnable() { 18975 @Override 18976 public void run() { 18977 unloadPrivatePackagesInner(vol); 18978 } 18979 }); 18980 } 18981 18982 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18983 final String volumeUuid = vol.fsUuid; 18984 if (TextUtils.isEmpty(volumeUuid)) { 18985 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18986 return; 18987 } 18988 18989 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18990 synchronized (mInstallLock) { 18991 synchronized (mPackages) { 18992 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18993 for (PackageSetting ps : packages) { 18994 if (ps.pkg == null) continue; 18995 18996 final ApplicationInfo info = ps.pkg.applicationInfo; 18997 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18998 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18999 19000 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19001 "unloadPrivatePackagesInner")) { 19002 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19003 false, null)) { 19004 unloaded.add(info); 19005 } else { 19006 Slog.w(TAG, "Failed to unload " + ps.codePath); 19007 } 19008 } 19009 } 19010 19011 mSettings.writeLPr(); 19012 } 19013 } 19014 19015 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19016 sendResourcesChangedBroadcast(false, false, unloaded, null); 19017 } 19018 19019 /** 19020 * Prepare storage areas for given user on all mounted devices. 19021 */ 19022 void prepareUserData(int userId, int userSerial, int flags) { 19023 synchronized (mInstallLock) { 19024 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19025 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19026 final String volumeUuid = vol.getFsUuid(); 19027 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19028 } 19029 } 19030 } 19031 19032 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19033 boolean allowRecover) { 19034 // Prepare storage and verify that serial numbers are consistent; if 19035 // there's a mismatch we need to destroy to avoid leaking data 19036 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19037 try { 19038 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19039 19040 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19041 UserManagerService.enforceSerialNumber( 19042 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19043 } 19044 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19045 UserManagerService.enforceSerialNumber( 19046 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19047 } 19048 19049 synchronized (mInstallLock) { 19050 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19051 } 19052 } catch (Exception e) { 19053 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19054 + " because we failed to prepare: " + e); 19055 destroyUserDataLI(volumeUuid, userId, 19056 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19057 19058 if (allowRecover) { 19059 // Try one last time; if we fail again we're really in trouble 19060 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19061 } 19062 } 19063 } 19064 19065 /** 19066 * Destroy storage areas for given user on all mounted devices. 19067 */ 19068 void destroyUserData(int userId, int flags) { 19069 synchronized (mInstallLock) { 19070 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19071 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19072 final String volumeUuid = vol.getFsUuid(); 19073 destroyUserDataLI(volumeUuid, userId, flags); 19074 } 19075 } 19076 } 19077 19078 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19079 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19080 try { 19081 // Clean up app data, profile data, and media data 19082 mInstaller.destroyUserData(volumeUuid, userId, flags); 19083 19084 // Clean up system data 19085 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19086 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19087 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19088 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19089 } 19090 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19091 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19092 } 19093 } 19094 19095 // Data with special labels is now gone, so finish the job 19096 storage.destroyUserStorage(volumeUuid, userId, flags); 19097 19098 } catch (Exception e) { 19099 logCriticalInfo(Log.WARN, 19100 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19101 } 19102 } 19103 19104 /** 19105 * Examine all users present on given mounted volume, and destroy data 19106 * belonging to users that are no longer valid, or whose user ID has been 19107 * recycled. 19108 */ 19109 private void reconcileUsers(String volumeUuid) { 19110 final List<File> files = new ArrayList<>(); 19111 Collections.addAll(files, FileUtils 19112 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19113 Collections.addAll(files, FileUtils 19114 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19115 for (File file : files) { 19116 if (!file.isDirectory()) continue; 19117 19118 final int userId; 19119 final UserInfo info; 19120 try { 19121 userId = Integer.parseInt(file.getName()); 19122 info = sUserManager.getUserInfo(userId); 19123 } catch (NumberFormatException e) { 19124 Slog.w(TAG, "Invalid user directory " + file); 19125 continue; 19126 } 19127 19128 boolean destroyUser = false; 19129 if (info == null) { 19130 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19131 + " because no matching user was found"); 19132 destroyUser = true; 19133 } else if (!mOnlyCore) { 19134 try { 19135 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19136 } catch (IOException e) { 19137 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19138 + " because we failed to enforce serial number: " + e); 19139 destroyUser = true; 19140 } 19141 } 19142 19143 if (destroyUser) { 19144 synchronized (mInstallLock) { 19145 destroyUserDataLI(volumeUuid, userId, 19146 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19147 } 19148 } 19149 } 19150 } 19151 19152 private void assertPackageKnown(String volumeUuid, String packageName) 19153 throws PackageManagerException { 19154 synchronized (mPackages) { 19155 final PackageSetting ps = mSettings.mPackages.get(packageName); 19156 if (ps == null) { 19157 throw new PackageManagerException("Package " + packageName + " is unknown"); 19158 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19159 throw new PackageManagerException( 19160 "Package " + packageName + " found on unknown volume " + volumeUuid 19161 + "; expected volume " + ps.volumeUuid); 19162 } 19163 } 19164 } 19165 19166 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19167 throws PackageManagerException { 19168 synchronized (mPackages) { 19169 final PackageSetting ps = mSettings.mPackages.get(packageName); 19170 if (ps == null) { 19171 throw new PackageManagerException("Package " + packageName + " is unknown"); 19172 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19173 throw new PackageManagerException( 19174 "Package " + packageName + " found on unknown volume " + volumeUuid 19175 + "; expected volume " + ps.volumeUuid); 19176 } else if (!ps.getInstalled(userId)) { 19177 throw new PackageManagerException( 19178 "Package " + packageName + " not installed for user " + userId); 19179 } 19180 } 19181 } 19182 19183 /** 19184 * Examine all apps present on given mounted volume, and destroy apps that 19185 * aren't expected, either due to uninstallation or reinstallation on 19186 * another volume. 19187 */ 19188 private void reconcileApps(String volumeUuid) { 19189 final File[] files = FileUtils 19190 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19191 for (File file : files) { 19192 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19193 && !PackageInstallerService.isStageName(file.getName()); 19194 if (!isPackage) { 19195 // Ignore entries which are not packages 19196 continue; 19197 } 19198 19199 try { 19200 final PackageLite pkg = PackageParser.parsePackageLite(file, 19201 PackageParser.PARSE_MUST_BE_APK); 19202 assertPackageKnown(volumeUuid, pkg.packageName); 19203 19204 } catch (PackageParserException | PackageManagerException e) { 19205 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19206 synchronized (mInstallLock) { 19207 removeCodePathLI(file); 19208 } 19209 } 19210 } 19211 } 19212 19213 /** 19214 * Reconcile all app data for the given user. 19215 * <p> 19216 * Verifies that directories exist and that ownership and labeling is 19217 * correct for all installed apps on all mounted volumes. 19218 */ 19219 void reconcileAppsData(int userId, int flags) { 19220 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19221 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19222 final String volumeUuid = vol.getFsUuid(); 19223 synchronized (mInstallLock) { 19224 reconcileAppsDataLI(volumeUuid, userId, flags); 19225 } 19226 } 19227 } 19228 19229 /** 19230 * Reconcile all app data on given mounted volume. 19231 * <p> 19232 * Destroys app data that isn't expected, either due to uninstallation or 19233 * reinstallation on another volume. 19234 * <p> 19235 * Verifies that directories exist and that ownership and labeling is 19236 * correct for all installed apps. 19237 */ 19238 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19239 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19240 + Integer.toHexString(flags)); 19241 19242 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19243 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19244 19245 boolean restoreconNeeded = false; 19246 19247 // First look for stale data that doesn't belong, and check if things 19248 // have changed since we did our last restorecon 19249 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19250 if (StorageManager.isFileEncryptedNativeOrEmulated() 19251 && !StorageManager.isUserKeyUnlocked(userId)) { 19252 throw new RuntimeException( 19253 "Yikes, someone asked us to reconcile CE storage while " + userId 19254 + " was still locked; this would have caused massive data loss!"); 19255 } 19256 19257 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19258 19259 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19260 for (File file : files) { 19261 final String packageName = file.getName(); 19262 try { 19263 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19264 } catch (PackageManagerException e) { 19265 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19266 try { 19267 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19268 StorageManager.FLAG_STORAGE_CE, 0); 19269 } catch (InstallerException e2) { 19270 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19271 } 19272 } 19273 } 19274 } 19275 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19276 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19277 19278 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19279 for (File file : files) { 19280 final String packageName = file.getName(); 19281 try { 19282 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19283 } catch (PackageManagerException e) { 19284 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19285 try { 19286 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19287 StorageManager.FLAG_STORAGE_DE, 0); 19288 } catch (InstallerException e2) { 19289 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19290 } 19291 } 19292 } 19293 } 19294 19295 // Ensure that data directories are ready to roll for all packages 19296 // installed for this volume and user 19297 final List<PackageSetting> packages; 19298 synchronized (mPackages) { 19299 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19300 } 19301 int preparedCount = 0; 19302 for (PackageSetting ps : packages) { 19303 final String packageName = ps.name; 19304 if (ps.pkg == null) { 19305 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19306 // TODO: might be due to legacy ASEC apps; we should circle back 19307 // and reconcile again once they're scanned 19308 continue; 19309 } 19310 19311 if (ps.getInstalled(userId)) { 19312 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19313 19314 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19315 // We may have just shuffled around app data directories, so 19316 // prepare them one more time 19317 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19318 } 19319 19320 preparedCount++; 19321 } 19322 } 19323 19324 if (restoreconNeeded) { 19325 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19326 SELinuxMMAC.setRestoreconDone(ceDir); 19327 } 19328 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19329 SELinuxMMAC.setRestoreconDone(deDir); 19330 } 19331 } 19332 19333 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19334 + " packages; restoreconNeeded was " + restoreconNeeded); 19335 } 19336 19337 /** 19338 * Prepare app data for the given app just after it was installed or 19339 * upgraded. This method carefully only touches users that it's installed 19340 * for, and it forces a restorecon to handle any seinfo changes. 19341 * <p> 19342 * Verifies that directories exist and that ownership and labeling is 19343 * correct for all installed apps. If there is an ownership mismatch, it 19344 * will try recovering system apps by wiping data; third-party app data is 19345 * left intact. 19346 * <p> 19347 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19348 */ 19349 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19350 final PackageSetting ps; 19351 synchronized (mPackages) { 19352 ps = mSettings.mPackages.get(pkg.packageName); 19353 mSettings.writeKernelMappingLPr(ps); 19354 } 19355 19356 final UserManager um = mContext.getSystemService(UserManager.class); 19357 for (UserInfo user : um.getUsers()) { 19358 final int flags; 19359 if (um.isUserUnlockingOrUnlocked(user.id)) { 19360 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19361 } else if (um.isUserRunning(user.id)) { 19362 flags = StorageManager.FLAG_STORAGE_DE; 19363 } else { 19364 continue; 19365 } 19366 19367 if (ps.getInstalled(user.id)) { 19368 // Whenever an app changes, force a restorecon of its data 19369 // TODO: when user data is locked, mark that we're still dirty 19370 prepareAppDataLIF(pkg, user.id, flags, true); 19371 } 19372 } 19373 } 19374 19375 /** 19376 * Prepare app data for the given app. 19377 * <p> 19378 * Verifies that directories exist and that ownership and labeling is 19379 * correct for all installed apps. If there is an ownership mismatch, this 19380 * will try recovering system apps by wiping data; third-party app data is 19381 * left intact. 19382 */ 19383 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19384 boolean restoreconNeeded) { 19385 if (pkg == null) { 19386 Slog.wtf(TAG, "Package was null!", new Throwable()); 19387 return; 19388 } 19389 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19390 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19391 for (int i = 0; i < childCount; i++) { 19392 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19393 } 19394 } 19395 19396 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19397 boolean restoreconNeeded) { 19398 if (DEBUG_APP_DATA) { 19399 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19400 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19401 } 19402 19403 final String volumeUuid = pkg.volumeUuid; 19404 final String packageName = pkg.packageName; 19405 final ApplicationInfo app = pkg.applicationInfo; 19406 final int appId = UserHandle.getAppId(app.uid); 19407 19408 Preconditions.checkNotNull(app.seinfo); 19409 19410 try { 19411 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19412 appId, app.seinfo, app.targetSdkVersion); 19413 } catch (InstallerException e) { 19414 if (app.isSystemApp()) { 19415 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19416 + ", but trying to recover: " + e); 19417 destroyAppDataLeafLIF(pkg, userId, flags); 19418 try { 19419 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19420 appId, app.seinfo, app.targetSdkVersion); 19421 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19422 } catch (InstallerException e2) { 19423 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19424 } 19425 } else { 19426 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19427 } 19428 } 19429 19430 if (restoreconNeeded) { 19431 try { 19432 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19433 app.seinfo); 19434 } catch (InstallerException e) { 19435 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19436 } 19437 } 19438 19439 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19440 try { 19441 // CE storage is unlocked right now, so read out the inode and 19442 // remember for use later when it's locked 19443 // TODO: mark this structure as dirty so we persist it! 19444 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19445 StorageManager.FLAG_STORAGE_CE); 19446 synchronized (mPackages) { 19447 final PackageSetting ps = mSettings.mPackages.get(packageName); 19448 if (ps != null) { 19449 ps.setCeDataInode(ceDataInode, userId); 19450 } 19451 } 19452 } catch (InstallerException e) { 19453 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19454 } 19455 } 19456 19457 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19458 } 19459 19460 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19461 if (pkg == null) { 19462 Slog.wtf(TAG, "Package was null!", new Throwable()); 19463 return; 19464 } 19465 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19466 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19467 for (int i = 0; i < childCount; i++) { 19468 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19469 } 19470 } 19471 19472 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19473 final String volumeUuid = pkg.volumeUuid; 19474 final String packageName = pkg.packageName; 19475 final ApplicationInfo app = pkg.applicationInfo; 19476 19477 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19478 // Create a native library symlink only if we have native libraries 19479 // and if the native libraries are 32 bit libraries. We do not provide 19480 // this symlink for 64 bit libraries. 19481 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19482 final String nativeLibPath = app.nativeLibraryDir; 19483 try { 19484 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19485 nativeLibPath, userId); 19486 } catch (InstallerException e) { 19487 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19488 } 19489 } 19490 } 19491 } 19492 19493 /** 19494 * For system apps on non-FBE devices, this method migrates any existing 19495 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19496 * requested by the app. 19497 */ 19498 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19499 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19500 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19501 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19502 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19503 try { 19504 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19505 storageTarget); 19506 } catch (InstallerException e) { 19507 logCriticalInfo(Log.WARN, 19508 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19509 } 19510 return true; 19511 } else { 19512 return false; 19513 } 19514 } 19515 19516 public PackageFreezer freezePackage(String packageName, String killReason) { 19517 return new PackageFreezer(packageName, killReason); 19518 } 19519 19520 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19521 String killReason) { 19522 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19523 return new PackageFreezer(); 19524 } else { 19525 return freezePackage(packageName, killReason); 19526 } 19527 } 19528 19529 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19530 String killReason) { 19531 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19532 return new PackageFreezer(); 19533 } else { 19534 return freezePackage(packageName, killReason); 19535 } 19536 } 19537 19538 /** 19539 * Class that freezes and kills the given package upon creation, and 19540 * unfreezes it upon closing. This is typically used when doing surgery on 19541 * app code/data to prevent the app from running while you're working. 19542 */ 19543 private class PackageFreezer implements AutoCloseable { 19544 private final String mPackageName; 19545 private final PackageFreezer[] mChildren; 19546 19547 private final boolean mWeFroze; 19548 19549 private final AtomicBoolean mClosed = new AtomicBoolean(); 19550 private final CloseGuard mCloseGuard = CloseGuard.get(); 19551 19552 /** 19553 * Create and return a stub freezer that doesn't actually do anything, 19554 * typically used when someone requested 19555 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19556 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19557 */ 19558 public PackageFreezer() { 19559 mPackageName = null; 19560 mChildren = null; 19561 mWeFroze = false; 19562 mCloseGuard.open("close"); 19563 } 19564 19565 public PackageFreezer(String packageName, String killReason) { 19566 synchronized (mPackages) { 19567 mPackageName = packageName; 19568 mWeFroze = mFrozenPackages.add(mPackageName); 19569 19570 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19571 if (ps != null) { 19572 killApplication(ps.name, ps.appId, killReason); 19573 } 19574 19575 final PackageParser.Package p = mPackages.get(packageName); 19576 if (p != null && p.childPackages != null) { 19577 final int N = p.childPackages.size(); 19578 mChildren = new PackageFreezer[N]; 19579 for (int i = 0; i < N; i++) { 19580 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19581 killReason); 19582 } 19583 } else { 19584 mChildren = null; 19585 } 19586 } 19587 mCloseGuard.open("close"); 19588 } 19589 19590 @Override 19591 protected void finalize() throws Throwable { 19592 try { 19593 mCloseGuard.warnIfOpen(); 19594 close(); 19595 } finally { 19596 super.finalize(); 19597 } 19598 } 19599 19600 @Override 19601 public void close() { 19602 mCloseGuard.close(); 19603 if (mClosed.compareAndSet(false, true)) { 19604 synchronized (mPackages) { 19605 if (mWeFroze) { 19606 mFrozenPackages.remove(mPackageName); 19607 } 19608 19609 if (mChildren != null) { 19610 for (PackageFreezer freezer : mChildren) { 19611 freezer.close(); 19612 } 19613 } 19614 } 19615 } 19616 } 19617 } 19618 19619 /** 19620 * Verify that given package is currently frozen. 19621 */ 19622 private void checkPackageFrozen(String packageName) { 19623 synchronized (mPackages) { 19624 if (!mFrozenPackages.contains(packageName)) { 19625 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19626 } 19627 } 19628 } 19629 19630 @Override 19631 public int movePackage(final String packageName, final String volumeUuid) { 19632 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19633 19634 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19635 final int moveId = mNextMoveId.getAndIncrement(); 19636 mHandler.post(new Runnable() { 19637 @Override 19638 public void run() { 19639 try { 19640 movePackageInternal(packageName, volumeUuid, moveId, user); 19641 } catch (PackageManagerException e) { 19642 Slog.w(TAG, "Failed to move " + packageName, e); 19643 mMoveCallbacks.notifyStatusChanged(moveId, 19644 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19645 } 19646 } 19647 }); 19648 return moveId; 19649 } 19650 19651 private void movePackageInternal(final String packageName, final String volumeUuid, 19652 final int moveId, UserHandle user) throws PackageManagerException { 19653 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19654 final PackageManager pm = mContext.getPackageManager(); 19655 19656 final boolean currentAsec; 19657 final String currentVolumeUuid; 19658 final File codeFile; 19659 final String installerPackageName; 19660 final String packageAbiOverride; 19661 final int appId; 19662 final String seinfo; 19663 final String label; 19664 final int targetSdkVersion; 19665 final PackageFreezer freezer; 19666 final int[] installedUserIds; 19667 19668 // reader 19669 synchronized (mPackages) { 19670 final PackageParser.Package pkg = mPackages.get(packageName); 19671 final PackageSetting ps = mSettings.mPackages.get(packageName); 19672 if (pkg == null || ps == null) { 19673 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19674 } 19675 19676 if (pkg.applicationInfo.isSystemApp()) { 19677 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19678 "Cannot move system application"); 19679 } 19680 19681 if (pkg.applicationInfo.isExternalAsec()) { 19682 currentAsec = true; 19683 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19684 } else if (pkg.applicationInfo.isForwardLocked()) { 19685 currentAsec = true; 19686 currentVolumeUuid = "forward_locked"; 19687 } else { 19688 currentAsec = false; 19689 currentVolumeUuid = ps.volumeUuid; 19690 19691 final File probe = new File(pkg.codePath); 19692 final File probeOat = new File(probe, "oat"); 19693 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19694 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19695 "Move only supported for modern cluster style installs"); 19696 } 19697 } 19698 19699 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19700 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19701 "Package already moved to " + volumeUuid); 19702 } 19703 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19704 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19705 "Device admin cannot be moved"); 19706 } 19707 19708 if (mFrozenPackages.contains(packageName)) { 19709 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19710 "Failed to move already frozen package"); 19711 } 19712 19713 codeFile = new File(pkg.codePath); 19714 installerPackageName = ps.installerPackageName; 19715 packageAbiOverride = ps.cpuAbiOverrideString; 19716 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19717 seinfo = pkg.applicationInfo.seinfo; 19718 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19719 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19720 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19721 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19722 } 19723 19724 final Bundle extras = new Bundle(); 19725 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19726 extras.putString(Intent.EXTRA_TITLE, label); 19727 mMoveCallbacks.notifyCreated(moveId, extras); 19728 19729 int installFlags; 19730 final boolean moveCompleteApp; 19731 final File measurePath; 19732 19733 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19734 installFlags = INSTALL_INTERNAL; 19735 moveCompleteApp = !currentAsec; 19736 measurePath = Environment.getDataAppDirectory(volumeUuid); 19737 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19738 installFlags = INSTALL_EXTERNAL; 19739 moveCompleteApp = false; 19740 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19741 } else { 19742 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19743 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19744 || !volume.isMountedWritable()) { 19745 freezer.close(); 19746 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19747 "Move location not mounted private volume"); 19748 } 19749 19750 Preconditions.checkState(!currentAsec); 19751 19752 installFlags = INSTALL_INTERNAL; 19753 moveCompleteApp = true; 19754 measurePath = Environment.getDataAppDirectory(volumeUuid); 19755 } 19756 19757 final PackageStats stats = new PackageStats(null, -1); 19758 synchronized (mInstaller) { 19759 for (int userId : installedUserIds) { 19760 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19761 freezer.close(); 19762 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19763 "Failed to measure package size"); 19764 } 19765 } 19766 } 19767 19768 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19769 + stats.dataSize); 19770 19771 final long startFreeBytes = measurePath.getFreeSpace(); 19772 final long sizeBytes; 19773 if (moveCompleteApp) { 19774 sizeBytes = stats.codeSize + stats.dataSize; 19775 } else { 19776 sizeBytes = stats.codeSize; 19777 } 19778 19779 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19780 freezer.close(); 19781 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19782 "Not enough free space to move"); 19783 } 19784 19785 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19786 19787 final CountDownLatch installedLatch = new CountDownLatch(1); 19788 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19789 @Override 19790 public void onUserActionRequired(Intent intent) throws RemoteException { 19791 throw new IllegalStateException(); 19792 } 19793 19794 @Override 19795 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19796 Bundle extras) throws RemoteException { 19797 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19798 + PackageManager.installStatusToString(returnCode, msg)); 19799 19800 installedLatch.countDown(); 19801 freezer.close(); 19802 19803 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19804 switch (status) { 19805 case PackageInstaller.STATUS_SUCCESS: 19806 mMoveCallbacks.notifyStatusChanged(moveId, 19807 PackageManager.MOVE_SUCCEEDED); 19808 break; 19809 case PackageInstaller.STATUS_FAILURE_STORAGE: 19810 mMoveCallbacks.notifyStatusChanged(moveId, 19811 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19812 break; 19813 default: 19814 mMoveCallbacks.notifyStatusChanged(moveId, 19815 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19816 break; 19817 } 19818 } 19819 }; 19820 19821 final MoveInfo move; 19822 if (moveCompleteApp) { 19823 // Kick off a thread to report progress estimates 19824 new Thread() { 19825 @Override 19826 public void run() { 19827 while (true) { 19828 try { 19829 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19830 break; 19831 } 19832 } catch (InterruptedException ignored) { 19833 } 19834 19835 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19836 final int progress = 10 + (int) MathUtils.constrain( 19837 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19838 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19839 } 19840 } 19841 }.start(); 19842 19843 final String dataAppName = codeFile.getName(); 19844 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19845 dataAppName, appId, seinfo, targetSdkVersion); 19846 } else { 19847 move = null; 19848 } 19849 19850 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19851 19852 final Message msg = mHandler.obtainMessage(INIT_COPY); 19853 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19854 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19855 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19856 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19857 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19858 msg.obj = params; 19859 19860 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19861 System.identityHashCode(msg.obj)); 19862 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19863 System.identityHashCode(msg.obj)); 19864 19865 mHandler.sendMessage(msg); 19866 } 19867 19868 @Override 19869 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19870 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19871 19872 final int realMoveId = mNextMoveId.getAndIncrement(); 19873 final Bundle extras = new Bundle(); 19874 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19875 mMoveCallbacks.notifyCreated(realMoveId, extras); 19876 19877 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19878 @Override 19879 public void onCreated(int moveId, Bundle extras) { 19880 // Ignored 19881 } 19882 19883 @Override 19884 public void onStatusChanged(int moveId, int status, long estMillis) { 19885 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19886 } 19887 }; 19888 19889 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19890 storage.setPrimaryStorageUuid(volumeUuid, callback); 19891 return realMoveId; 19892 } 19893 19894 @Override 19895 public int getMoveStatus(int moveId) { 19896 mContext.enforceCallingOrSelfPermission( 19897 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19898 return mMoveCallbacks.mLastStatus.get(moveId); 19899 } 19900 19901 @Override 19902 public void registerMoveCallback(IPackageMoveObserver callback) { 19903 mContext.enforceCallingOrSelfPermission( 19904 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19905 mMoveCallbacks.register(callback); 19906 } 19907 19908 @Override 19909 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19910 mContext.enforceCallingOrSelfPermission( 19911 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19912 mMoveCallbacks.unregister(callback); 19913 } 19914 19915 @Override 19916 public boolean setInstallLocation(int loc) { 19917 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19918 null); 19919 if (getInstallLocation() == loc) { 19920 return true; 19921 } 19922 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19923 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19924 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19925 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19926 return true; 19927 } 19928 return false; 19929 } 19930 19931 @Override 19932 public int getInstallLocation() { 19933 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19934 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19935 PackageHelper.APP_INSTALL_AUTO); 19936 } 19937 19938 /** Called by UserManagerService */ 19939 void cleanUpUser(UserManagerService userManager, int userHandle) { 19940 synchronized (mPackages) { 19941 mDirtyUsers.remove(userHandle); 19942 mUserNeedsBadging.delete(userHandle); 19943 mSettings.removeUserLPw(userHandle); 19944 mPendingBroadcasts.remove(userHandle); 19945 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19946 removeUnusedPackagesLPw(userManager, userHandle); 19947 } 19948 } 19949 19950 /** 19951 * We're removing userHandle and would like to remove any downloaded packages 19952 * that are no longer in use by any other user. 19953 * @param userHandle the user being removed 19954 */ 19955 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19956 final boolean DEBUG_CLEAN_APKS = false; 19957 int [] users = userManager.getUserIds(); 19958 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19959 while (psit.hasNext()) { 19960 PackageSetting ps = psit.next(); 19961 if (ps.pkg == null) { 19962 continue; 19963 } 19964 final String packageName = ps.pkg.packageName; 19965 // Skip over if system app 19966 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19967 continue; 19968 } 19969 if (DEBUG_CLEAN_APKS) { 19970 Slog.i(TAG, "Checking package " + packageName); 19971 } 19972 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19973 if (keep) { 19974 if (DEBUG_CLEAN_APKS) { 19975 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19976 } 19977 } else { 19978 for (int i = 0; i < users.length; i++) { 19979 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19980 keep = true; 19981 if (DEBUG_CLEAN_APKS) { 19982 Slog.i(TAG, " Keeping package " + packageName + " for user " 19983 + users[i]); 19984 } 19985 break; 19986 } 19987 } 19988 } 19989 if (!keep) { 19990 if (DEBUG_CLEAN_APKS) { 19991 Slog.i(TAG, " Removing package " + packageName); 19992 } 19993 mHandler.post(new Runnable() { 19994 public void run() { 19995 deletePackageX(packageName, userHandle, 0); 19996 } //end run 19997 }); 19998 } 19999 } 20000 } 20001 20002 /** Called by UserManagerService */ 20003 void createNewUser(int userHandle) { 20004 synchronized (mInstallLock) { 20005 mSettings.createNewUserLI(this, mInstaller, userHandle); 20006 } 20007 synchronized (mPackages) { 20008 applyFactoryDefaultBrowserLPw(userHandle); 20009 primeDomainVerificationsLPw(userHandle); 20010 } 20011 } 20012 20013 void newUserCreated(final int userHandle) { 20014 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 20015 // If permission review for legacy apps is required, we represent 20016 // dagerous permissions for such apps as always granted runtime 20017 // permissions to keep per user flag state whether review is needed. 20018 // Hence, if a new user is added we have to propagate dangerous 20019 // permission grants for these legacy apps. 20020 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20021 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20022 | UPDATE_PERMISSIONS_REPLACE_ALL); 20023 } 20024 } 20025 20026 @Override 20027 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20028 mContext.enforceCallingOrSelfPermission( 20029 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20030 "Only package verification agents can read the verifier device identity"); 20031 20032 synchronized (mPackages) { 20033 return mSettings.getVerifierDeviceIdentityLPw(); 20034 } 20035 } 20036 20037 @Override 20038 public void setPermissionEnforced(String permission, boolean enforced) { 20039 // TODO: Now that we no longer change GID for storage, this should to away. 20040 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20041 "setPermissionEnforced"); 20042 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20043 synchronized (mPackages) { 20044 if (mSettings.mReadExternalStorageEnforced == null 20045 || mSettings.mReadExternalStorageEnforced != enforced) { 20046 mSettings.mReadExternalStorageEnforced = enforced; 20047 mSettings.writeLPr(); 20048 } 20049 } 20050 // kill any non-foreground processes so we restart them and 20051 // grant/revoke the GID. 20052 final IActivityManager am = ActivityManagerNative.getDefault(); 20053 if (am != null) { 20054 final long token = Binder.clearCallingIdentity(); 20055 try { 20056 am.killProcessesBelowForeground("setPermissionEnforcement"); 20057 } catch (RemoteException e) { 20058 } finally { 20059 Binder.restoreCallingIdentity(token); 20060 } 20061 } 20062 } else { 20063 throw new IllegalArgumentException("No selective enforcement for " + permission); 20064 } 20065 } 20066 20067 @Override 20068 @Deprecated 20069 public boolean isPermissionEnforced(String permission) { 20070 return true; 20071 } 20072 20073 @Override 20074 public boolean isStorageLow() { 20075 final long token = Binder.clearCallingIdentity(); 20076 try { 20077 final DeviceStorageMonitorInternal 20078 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20079 if (dsm != null) { 20080 return dsm.isMemoryLow(); 20081 } else { 20082 return false; 20083 } 20084 } finally { 20085 Binder.restoreCallingIdentity(token); 20086 } 20087 } 20088 20089 @Override 20090 public IPackageInstaller getPackageInstaller() { 20091 return mInstallerService; 20092 } 20093 20094 private boolean userNeedsBadging(int userId) { 20095 int index = mUserNeedsBadging.indexOfKey(userId); 20096 if (index < 0) { 20097 final UserInfo userInfo; 20098 final long token = Binder.clearCallingIdentity(); 20099 try { 20100 userInfo = sUserManager.getUserInfo(userId); 20101 } finally { 20102 Binder.restoreCallingIdentity(token); 20103 } 20104 final boolean b; 20105 if (userInfo != null && userInfo.isManagedProfile()) { 20106 b = true; 20107 } else { 20108 b = false; 20109 } 20110 mUserNeedsBadging.put(userId, b); 20111 return b; 20112 } 20113 return mUserNeedsBadging.valueAt(index); 20114 } 20115 20116 @Override 20117 public KeySet getKeySetByAlias(String packageName, String alias) { 20118 if (packageName == null || alias == null) { 20119 return null; 20120 } 20121 synchronized(mPackages) { 20122 final PackageParser.Package pkg = mPackages.get(packageName); 20123 if (pkg == null) { 20124 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20125 throw new IllegalArgumentException("Unknown package: " + packageName); 20126 } 20127 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20128 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20129 } 20130 } 20131 20132 @Override 20133 public KeySet getSigningKeySet(String packageName) { 20134 if (packageName == null) { 20135 return null; 20136 } 20137 synchronized(mPackages) { 20138 final PackageParser.Package pkg = mPackages.get(packageName); 20139 if (pkg == null) { 20140 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20141 throw new IllegalArgumentException("Unknown package: " + packageName); 20142 } 20143 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20144 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20145 throw new SecurityException("May not access signing KeySet of other apps."); 20146 } 20147 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20148 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20149 } 20150 } 20151 20152 @Override 20153 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20154 if (packageName == null || ks == null) { 20155 return false; 20156 } 20157 synchronized(mPackages) { 20158 final PackageParser.Package pkg = mPackages.get(packageName); 20159 if (pkg == null) { 20160 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20161 throw new IllegalArgumentException("Unknown package: " + packageName); 20162 } 20163 IBinder ksh = ks.getToken(); 20164 if (ksh instanceof KeySetHandle) { 20165 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20166 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20167 } 20168 return false; 20169 } 20170 } 20171 20172 @Override 20173 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20174 if (packageName == null || ks == null) { 20175 return false; 20176 } 20177 synchronized(mPackages) { 20178 final PackageParser.Package pkg = mPackages.get(packageName); 20179 if (pkg == null) { 20180 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20181 throw new IllegalArgumentException("Unknown package: " + packageName); 20182 } 20183 IBinder ksh = ks.getToken(); 20184 if (ksh instanceof KeySetHandle) { 20185 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20186 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20187 } 20188 return false; 20189 } 20190 } 20191 20192 private void deletePackageIfUnusedLPr(final String packageName) { 20193 PackageSetting ps = mSettings.mPackages.get(packageName); 20194 if (ps == null) { 20195 return; 20196 } 20197 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20198 // TODO Implement atomic delete if package is unused 20199 // It is currently possible that the package will be deleted even if it is installed 20200 // after this method returns. 20201 mHandler.post(new Runnable() { 20202 public void run() { 20203 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20204 } 20205 }); 20206 } 20207 } 20208 20209 /** 20210 * Check and throw if the given before/after packages would be considered a 20211 * downgrade. 20212 */ 20213 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20214 throws PackageManagerException { 20215 if (after.versionCode < before.mVersionCode) { 20216 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20217 "Update version code " + after.versionCode + " is older than current " 20218 + before.mVersionCode); 20219 } else if (after.versionCode == before.mVersionCode) { 20220 if (after.baseRevisionCode < before.baseRevisionCode) { 20221 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20222 "Update base revision code " + after.baseRevisionCode 20223 + " is older than current " + before.baseRevisionCode); 20224 } 20225 20226 if (!ArrayUtils.isEmpty(after.splitNames)) { 20227 for (int i = 0; i < after.splitNames.length; i++) { 20228 final String splitName = after.splitNames[i]; 20229 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20230 if (j != -1) { 20231 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20232 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20233 "Update split " + splitName + " revision code " 20234 + after.splitRevisionCodes[i] + " is older than current " 20235 + before.splitRevisionCodes[j]); 20236 } 20237 } 20238 } 20239 } 20240 } 20241 } 20242 20243 private static class MoveCallbacks extends Handler { 20244 private static final int MSG_CREATED = 1; 20245 private static final int MSG_STATUS_CHANGED = 2; 20246 20247 private final RemoteCallbackList<IPackageMoveObserver> 20248 mCallbacks = new RemoteCallbackList<>(); 20249 20250 private final SparseIntArray mLastStatus = new SparseIntArray(); 20251 20252 public MoveCallbacks(Looper looper) { 20253 super(looper); 20254 } 20255 20256 public void register(IPackageMoveObserver callback) { 20257 mCallbacks.register(callback); 20258 } 20259 20260 public void unregister(IPackageMoveObserver callback) { 20261 mCallbacks.unregister(callback); 20262 } 20263 20264 @Override 20265 public void handleMessage(Message msg) { 20266 final SomeArgs args = (SomeArgs) msg.obj; 20267 final int n = mCallbacks.beginBroadcast(); 20268 for (int i = 0; i < n; i++) { 20269 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20270 try { 20271 invokeCallback(callback, msg.what, args); 20272 } catch (RemoteException ignored) { 20273 } 20274 } 20275 mCallbacks.finishBroadcast(); 20276 args.recycle(); 20277 } 20278 20279 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20280 throws RemoteException { 20281 switch (what) { 20282 case MSG_CREATED: { 20283 callback.onCreated(args.argi1, (Bundle) args.arg2); 20284 break; 20285 } 20286 case MSG_STATUS_CHANGED: { 20287 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20288 break; 20289 } 20290 } 20291 } 20292 20293 private void notifyCreated(int moveId, Bundle extras) { 20294 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20295 20296 final SomeArgs args = SomeArgs.obtain(); 20297 args.argi1 = moveId; 20298 args.arg2 = extras; 20299 obtainMessage(MSG_CREATED, args).sendToTarget(); 20300 } 20301 20302 private void notifyStatusChanged(int moveId, int status) { 20303 notifyStatusChanged(moveId, status, -1); 20304 } 20305 20306 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20307 Slog.v(TAG, "Move " + moveId + " status " + status); 20308 20309 final SomeArgs args = SomeArgs.obtain(); 20310 args.argi1 = moveId; 20311 args.argi2 = status; 20312 args.arg3 = estMillis; 20313 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20314 20315 synchronized (mLastStatus) { 20316 mLastStatus.put(moveId, status); 20317 } 20318 } 20319 } 20320 20321 private final static class OnPermissionChangeListeners extends Handler { 20322 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20323 20324 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20325 new RemoteCallbackList<>(); 20326 20327 public OnPermissionChangeListeners(Looper looper) { 20328 super(looper); 20329 } 20330 20331 @Override 20332 public void handleMessage(Message msg) { 20333 switch (msg.what) { 20334 case MSG_ON_PERMISSIONS_CHANGED: { 20335 final int uid = msg.arg1; 20336 handleOnPermissionsChanged(uid); 20337 } break; 20338 } 20339 } 20340 20341 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20342 mPermissionListeners.register(listener); 20343 20344 } 20345 20346 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20347 mPermissionListeners.unregister(listener); 20348 } 20349 20350 public void onPermissionsChanged(int uid) { 20351 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20352 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20353 } 20354 } 20355 20356 private void handleOnPermissionsChanged(int uid) { 20357 final int count = mPermissionListeners.beginBroadcast(); 20358 try { 20359 for (int i = 0; i < count; i++) { 20360 IOnPermissionsChangeListener callback = mPermissionListeners 20361 .getBroadcastItem(i); 20362 try { 20363 callback.onPermissionsChanged(uid); 20364 } catch (RemoteException e) { 20365 Log.e(TAG, "Permission listener is dead", e); 20366 } 20367 } 20368 } finally { 20369 mPermissionListeners.finishBroadcast(); 20370 } 20371 } 20372 } 20373 20374 private class PackageManagerInternalImpl extends PackageManagerInternal { 20375 @Override 20376 public void setLocationPackagesProvider(PackagesProvider provider) { 20377 synchronized (mPackages) { 20378 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20379 } 20380 } 20381 20382 @Override 20383 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20384 synchronized (mPackages) { 20385 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20386 } 20387 } 20388 20389 @Override 20390 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20391 synchronized (mPackages) { 20392 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20393 } 20394 } 20395 20396 @Override 20397 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20398 synchronized (mPackages) { 20399 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20400 } 20401 } 20402 20403 @Override 20404 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20405 synchronized (mPackages) { 20406 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20407 } 20408 } 20409 20410 @Override 20411 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20412 synchronized (mPackages) { 20413 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20414 } 20415 } 20416 20417 @Override 20418 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20419 synchronized (mPackages) { 20420 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20421 packageName, userId); 20422 } 20423 } 20424 20425 @Override 20426 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20427 synchronized (mPackages) { 20428 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20429 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20430 packageName, userId); 20431 } 20432 } 20433 20434 @Override 20435 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20436 synchronized (mPackages) { 20437 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20438 packageName, userId); 20439 } 20440 } 20441 20442 @Override 20443 public void setKeepUninstalledPackages(final List<String> packageList) { 20444 Preconditions.checkNotNull(packageList); 20445 List<String> removedFromList = null; 20446 synchronized (mPackages) { 20447 if (mKeepUninstalledPackages != null) { 20448 final int packagesCount = mKeepUninstalledPackages.size(); 20449 for (int i = 0; i < packagesCount; i++) { 20450 String oldPackage = mKeepUninstalledPackages.get(i); 20451 if (packageList != null && packageList.contains(oldPackage)) { 20452 continue; 20453 } 20454 if (removedFromList == null) { 20455 removedFromList = new ArrayList<>(); 20456 } 20457 removedFromList.add(oldPackage); 20458 } 20459 } 20460 mKeepUninstalledPackages = new ArrayList<>(packageList); 20461 if (removedFromList != null) { 20462 final int removedCount = removedFromList.size(); 20463 for (int i = 0; i < removedCount; i++) { 20464 deletePackageIfUnusedLPr(removedFromList.get(i)); 20465 } 20466 } 20467 } 20468 } 20469 20470 @Override 20471 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20472 synchronized (mPackages) { 20473 // If we do not support permission review, done. 20474 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20475 return false; 20476 } 20477 20478 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20479 if (packageSetting == null) { 20480 return false; 20481 } 20482 20483 // Permission review applies only to apps not supporting the new permission model. 20484 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20485 return false; 20486 } 20487 20488 // Legacy apps have the permission and get user consent on launch. 20489 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20490 return permissionsState.isPermissionReviewRequired(userId); 20491 } 20492 } 20493 20494 @Override 20495 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20496 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20497 } 20498 20499 @Override 20500 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20501 int userId) { 20502 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20503 } 20504 } 20505 20506 @Override 20507 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20508 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20509 synchronized (mPackages) { 20510 final long identity = Binder.clearCallingIdentity(); 20511 try { 20512 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20513 packageNames, userId); 20514 } finally { 20515 Binder.restoreCallingIdentity(identity); 20516 } 20517 } 20518 } 20519 20520 private static void enforceSystemOrPhoneCaller(String tag) { 20521 int callingUid = Binder.getCallingUid(); 20522 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20523 throw new SecurityException( 20524 "Cannot call " + tag + " from UID " + callingUid); 20525 } 20526 } 20527 20528 boolean isHistoricalPackageUsageAvailable() { 20529 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20530 } 20531 20532 /** 20533 * Return a <b>copy</b> of the collection of packages known to the package manager. 20534 * @return A copy of the values of mPackages. 20535 */ 20536 Collection<PackageParser.Package> getPackages() { 20537 synchronized (mPackages) { 20538 return new ArrayList<>(mPackages.values()); 20539 } 20540 } 20541 20542 /** 20543 * Logs process start information (including base APK hash) to the security log. 20544 * @hide 20545 */ 20546 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20547 String apkFile, int pid) { 20548 if (!SecurityLog.isLoggingEnabled()) { 20549 return; 20550 } 20551 Bundle data = new Bundle(); 20552 data.putLong("startTimestamp", System.currentTimeMillis()); 20553 data.putString("processName", processName); 20554 data.putInt("uid", uid); 20555 data.putString("seinfo", seinfo); 20556 data.putString("apkFile", apkFile); 20557 data.putInt("pid", pid); 20558 Message msg = mProcessLoggingHandler.obtainMessage( 20559 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20560 msg.setData(data); 20561 mProcessLoggingHandler.sendMessage(msg); 20562 } 20563} 20564