PackageManagerService.java revision 4ec026930bfbbb5d8923f359c80b465d4b0ccda2
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.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.util.jar.StrictJarFile; 221import android.view.Display; 222 223import com.android.internal.R; 224import com.android.internal.annotations.GuardedBy; 225import com.android.internal.app.IMediaContainerService; 226import com.android.internal.app.ResolverActivity; 227import com.android.internal.content.NativeLibraryHelper; 228import com.android.internal.content.PackageHelper; 229import com.android.internal.logging.MetricsLogger; 230import com.android.internal.logging.MetricsProto.MetricsEvent; 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 static class IFVerificationParams { 743 PackageParser.Package pkg; 744 boolean replacing; 745 int userId; 746 int verifierUid; 747 748 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 749 int _userId, int _verifierUid) { 750 pkg = _pkg; 751 replacing = _replacing; 752 userId = _userId; 753 replacing = _replacing; 754 verifierUid = _verifierUid; 755 } 756 } 757 758 private interface IntentFilterVerifier<T extends IntentFilter> { 759 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 760 T filter, String packageName); 761 void startVerifications(int userId); 762 void receiveVerificationResponse(int verificationId); 763 } 764 765 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 766 private Context mContext; 767 private ComponentName mIntentFilterVerifierComponent; 768 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 769 770 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 771 mContext = context; 772 mIntentFilterVerifierComponent = verifierComponent; 773 } 774 775 private String getDefaultScheme() { 776 return IntentFilter.SCHEME_HTTPS; 777 } 778 779 @Override 780 public void startVerifications(int userId) { 781 // Launch verifications requests 782 int count = mCurrentIntentFilterVerifications.size(); 783 for (int n=0; n<count; n++) { 784 int verificationId = mCurrentIntentFilterVerifications.get(n); 785 final IntentFilterVerificationState ivs = 786 mIntentFilterVerificationStates.get(verificationId); 787 788 String packageName = ivs.getPackageName(); 789 790 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 791 final int filterCount = filters.size(); 792 ArraySet<String> domainsSet = new ArraySet<>(); 793 for (int m=0; m<filterCount; m++) { 794 PackageParser.ActivityIntentInfo filter = filters.get(m); 795 domainsSet.addAll(filter.getHostsList()); 796 } 797 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 798 synchronized (mPackages) { 799 if (mSettings.createIntentFilterVerificationIfNeededLPw( 800 packageName, domainsList) != null) { 801 scheduleWriteSettingsLocked(); 802 } 803 } 804 sendVerificationRequest(userId, verificationId, ivs); 805 } 806 mCurrentIntentFilterVerifications.clear(); 807 } 808 809 private void sendVerificationRequest(int userId, int verificationId, 810 IntentFilterVerificationState ivs) { 811 812 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 813 verificationIntent.putExtra( 814 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 815 verificationId); 816 verificationIntent.putExtra( 817 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 818 getDefaultScheme()); 819 verificationIntent.putExtra( 820 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 821 ivs.getHostsString()); 822 verificationIntent.putExtra( 823 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 824 ivs.getPackageName()); 825 verificationIntent.setComponent(mIntentFilterVerifierComponent); 826 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 827 828 UserHandle user = new UserHandle(userId); 829 mContext.sendBroadcastAsUser(verificationIntent, user); 830 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 831 "Sending IntentFilter verification broadcast"); 832 } 833 834 public void receiveVerificationResponse(int verificationId) { 835 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 836 837 final boolean verified = ivs.isVerified(); 838 839 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 840 final int count = filters.size(); 841 if (DEBUG_DOMAIN_VERIFICATION) { 842 Slog.i(TAG, "Received verification response " + verificationId 843 + " for " + count + " filters, verified=" + verified); 844 } 845 for (int n=0; n<count; n++) { 846 PackageParser.ActivityIntentInfo filter = filters.get(n); 847 filter.setVerified(verified); 848 849 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 850 + " verified with result:" + verified + " and hosts:" 851 + ivs.getHostsString()); 852 } 853 854 mIntentFilterVerificationStates.remove(verificationId); 855 856 final String packageName = ivs.getPackageName(); 857 IntentFilterVerificationInfo ivi = null; 858 859 synchronized (mPackages) { 860 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 861 } 862 if (ivi == null) { 863 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 864 + verificationId + " packageName:" + packageName); 865 return; 866 } 867 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 868 "Updating IntentFilterVerificationInfo for package " + packageName 869 +" verificationId:" + verificationId); 870 871 synchronized (mPackages) { 872 if (verified) { 873 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 874 } else { 875 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 876 } 877 scheduleWriteSettingsLocked(); 878 879 final int userId = ivs.getUserId(); 880 if (userId != UserHandle.USER_ALL) { 881 final int userStatus = 882 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 883 884 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 885 boolean needUpdate = false; 886 887 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 888 // already been set by the User thru the Disambiguation dialog 889 switch (userStatus) { 890 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 891 if (verified) { 892 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 893 } else { 894 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 895 } 896 needUpdate = true; 897 break; 898 899 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 900 if (verified) { 901 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 902 needUpdate = true; 903 } 904 break; 905 906 default: 907 // Nothing to do 908 } 909 910 if (needUpdate) { 911 mSettings.updateIntentFilterVerificationStatusLPw( 912 packageName, updatedStatus, userId); 913 scheduleWritePackageRestrictionsLocked(userId); 914 } 915 } 916 } 917 } 918 919 @Override 920 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 921 ActivityIntentInfo filter, String packageName) { 922 if (!hasValidDomains(filter)) { 923 return false; 924 } 925 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 926 if (ivs == null) { 927 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 928 packageName); 929 } 930 if (DEBUG_DOMAIN_VERIFICATION) { 931 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 932 } 933 ivs.addFilter(filter); 934 return true; 935 } 936 937 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 938 int userId, int verificationId, String packageName) { 939 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 940 verifierUid, userId, packageName); 941 ivs.setPendingState(); 942 synchronized (mPackages) { 943 mIntentFilterVerificationStates.append(verificationId, ivs); 944 mCurrentIntentFilterVerifications.add(verificationId); 945 } 946 return ivs; 947 } 948 } 949 950 private static boolean hasValidDomains(ActivityIntentInfo filter) { 951 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 952 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 953 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 954 } 955 956 // Set of pending broadcasts for aggregating enable/disable of components. 957 static class PendingPackageBroadcasts { 958 // for each user id, a map of <package name -> components within that package> 959 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 960 961 public PendingPackageBroadcasts() { 962 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 963 } 964 965 public ArrayList<String> get(int userId, String packageName) { 966 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 967 return packages.get(packageName); 968 } 969 970 public void put(int userId, String packageName, ArrayList<String> components) { 971 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 972 packages.put(packageName, components); 973 } 974 975 public void remove(int userId, String packageName) { 976 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 977 if (packages != null) { 978 packages.remove(packageName); 979 } 980 } 981 982 public void remove(int userId) { 983 mUidMap.remove(userId); 984 } 985 986 public int userIdCount() { 987 return mUidMap.size(); 988 } 989 990 public int userIdAt(int n) { 991 return mUidMap.keyAt(n); 992 } 993 994 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 995 return mUidMap.get(userId); 996 } 997 998 public int size() { 999 // total number of pending broadcast entries across all userIds 1000 int num = 0; 1001 for (int i = 0; i< mUidMap.size(); i++) { 1002 num += mUidMap.valueAt(i).size(); 1003 } 1004 return num; 1005 } 1006 1007 public void clear() { 1008 mUidMap.clear(); 1009 } 1010 1011 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1012 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1013 if (map == null) { 1014 map = new ArrayMap<String, ArrayList<String>>(); 1015 mUidMap.put(userId, map); 1016 } 1017 return map; 1018 } 1019 } 1020 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1021 1022 // Service Connection to remote media container service to copy 1023 // package uri's from external media onto secure containers 1024 // or internal storage. 1025 private IMediaContainerService mContainerService = null; 1026 1027 static final int SEND_PENDING_BROADCAST = 1; 1028 static final int MCS_BOUND = 3; 1029 static final int END_COPY = 4; 1030 static final int INIT_COPY = 5; 1031 static final int MCS_UNBIND = 6; 1032 static final int START_CLEANING_PACKAGE = 7; 1033 static final int FIND_INSTALL_LOC = 8; 1034 static final int POST_INSTALL = 9; 1035 static final int MCS_RECONNECT = 10; 1036 static final int MCS_GIVE_UP = 11; 1037 static final int UPDATED_MEDIA_STATUS = 12; 1038 static final int WRITE_SETTINGS = 13; 1039 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1040 static final int PACKAGE_VERIFIED = 15; 1041 static final int CHECK_PENDING_VERIFICATION = 16; 1042 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1043 static final int INTENT_FILTER_VERIFIED = 18; 1044 1045 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1046 1047 // Delay time in millisecs 1048 static final int BROADCAST_DELAY = 10 * 1000; 1049 1050 static UserManagerService sUserManager; 1051 1052 // Stores a list of users whose package restrictions file needs to be updated 1053 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1054 1055 final private DefaultContainerConnection mDefContainerConn = 1056 new DefaultContainerConnection(); 1057 class DefaultContainerConnection implements ServiceConnection { 1058 public void onServiceConnected(ComponentName name, IBinder service) { 1059 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1060 IMediaContainerService imcs = 1061 IMediaContainerService.Stub.asInterface(service); 1062 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1063 } 1064 1065 public void onServiceDisconnected(ComponentName name) { 1066 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1067 } 1068 } 1069 1070 // Recordkeeping of restore-after-install operations that are currently in flight 1071 // between the Package Manager and the Backup Manager 1072 static class PostInstallData { 1073 public InstallArgs args; 1074 public PackageInstalledInfo res; 1075 1076 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1077 args = _a; 1078 res = _r; 1079 } 1080 } 1081 1082 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1083 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1084 1085 // XML tags for backup/restore of various bits of state 1086 private static final String TAG_PREFERRED_BACKUP = "pa"; 1087 private static final String TAG_DEFAULT_APPS = "da"; 1088 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1089 1090 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1091 private static final String TAG_ALL_GRANTS = "rt-grants"; 1092 private static final String TAG_GRANT = "grant"; 1093 private static final String ATTR_PACKAGE_NAME = "pkg"; 1094 1095 private static final String TAG_PERMISSION = "perm"; 1096 private static final String ATTR_PERMISSION_NAME = "name"; 1097 private static final String ATTR_IS_GRANTED = "g"; 1098 private static final String ATTR_USER_SET = "set"; 1099 private static final String ATTR_USER_FIXED = "fixed"; 1100 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1101 1102 // System/policy permission grants are not backed up 1103 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1104 FLAG_PERMISSION_POLICY_FIXED 1105 | FLAG_PERMISSION_SYSTEM_FIXED 1106 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1107 1108 // And we back up these user-adjusted states 1109 private static final int USER_RUNTIME_GRANT_MASK = 1110 FLAG_PERMISSION_USER_SET 1111 | FLAG_PERMISSION_USER_FIXED 1112 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1113 1114 final @Nullable String mRequiredVerifierPackage; 1115 final @NonNull String mRequiredInstallerPackage; 1116 final @Nullable String mSetupWizardPackage; 1117 final @NonNull String mServicesSystemSharedLibraryPackageName; 1118 final @NonNull String mSharedSystemSharedLibraryPackageName; 1119 1120 private final PackageUsage mPackageUsage = new PackageUsage(); 1121 1122 private class PackageUsage { 1123 private static final int WRITE_INTERVAL 1124 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1125 1126 private final Object mFileLock = new Object(); 1127 private final AtomicLong mLastWritten = new AtomicLong(0); 1128 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1129 1130 private boolean mIsHistoricalPackageUsageAvailable = true; 1131 1132 boolean isHistoricalPackageUsageAvailable() { 1133 return mIsHistoricalPackageUsageAvailable; 1134 } 1135 1136 void write(boolean force) { 1137 if (force) { 1138 writeInternal(); 1139 return; 1140 } 1141 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1142 && !DEBUG_DEXOPT) { 1143 return; 1144 } 1145 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1146 new Thread("PackageUsage_DiskWriter") { 1147 @Override 1148 public void run() { 1149 try { 1150 writeInternal(); 1151 } finally { 1152 mBackgroundWriteRunning.set(false); 1153 } 1154 } 1155 }.start(); 1156 } 1157 } 1158 1159 private void writeInternal() { 1160 synchronized (mPackages) { 1161 synchronized (mFileLock) { 1162 AtomicFile file = getFile(); 1163 FileOutputStream f = null; 1164 try { 1165 f = file.startWrite(); 1166 BufferedOutputStream out = new BufferedOutputStream(f); 1167 FileUtils.setPermissions(file.getBaseFile().getPath(), 1168 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1169 StringBuilder sb = new StringBuilder(); 1170 1171 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1172 sb.append('\n'); 1173 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1174 1175 for (PackageParser.Package pkg : mPackages.values()) { 1176 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1177 continue; 1178 } 1179 sb.setLength(0); 1180 sb.append(pkg.packageName); 1181 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1182 sb.append(' '); 1183 sb.append(usageTimeInMillis); 1184 } 1185 sb.append('\n'); 1186 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1187 } 1188 out.flush(); 1189 file.finishWrite(f); 1190 } catch (IOException e) { 1191 if (f != null) { 1192 file.failWrite(f); 1193 } 1194 Log.e(TAG, "Failed to write package usage times", e); 1195 } 1196 } 1197 } 1198 mLastWritten.set(SystemClock.elapsedRealtime()); 1199 } 1200 1201 void readLP() { 1202 synchronized (mFileLock) { 1203 AtomicFile file = getFile(); 1204 BufferedInputStream in = null; 1205 try { 1206 in = new BufferedInputStream(file.openRead()); 1207 StringBuffer sb = new StringBuffer(); 1208 1209 String firstLine = readLine(in, sb); 1210 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1211 readVersion1LP(in, sb); 1212 } else { 1213 readVersion0LP(in, sb, firstLine); 1214 } 1215 } catch (FileNotFoundException expected) { 1216 mIsHistoricalPackageUsageAvailable = false; 1217 } catch (IOException e) { 1218 Log.w(TAG, "Failed to read package usage times", e); 1219 } finally { 1220 IoUtils.closeQuietly(in); 1221 } 1222 } 1223 mLastWritten.set(SystemClock.elapsedRealtime()); 1224 } 1225 1226 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1227 throws IOException { 1228 // Initial version of the file had no version number and stored one 1229 // package-timestamp pair per line. 1230 // Note that the first line has already been read from the InputStream. 1231 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1232 String[] tokens = line.split(" "); 1233 if (tokens.length != 2) { 1234 throw new IOException("Failed to parse " + line + 1235 " as package-timestamp pair."); 1236 } 1237 1238 String packageName = tokens[0]; 1239 PackageParser.Package pkg = mPackages.get(packageName); 1240 if (pkg == null) { 1241 continue; 1242 } 1243 1244 long timestamp = parseAsLong(tokens[1]); 1245 for (int reason = 0; 1246 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1247 reason++) { 1248 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1249 } 1250 } 1251 } 1252 1253 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1254 // Version 1 of the file started with the corresponding version 1255 // number and then stored a package name and eight timestamps per line. 1256 String line; 1257 while ((line = readLine(in, sb)) != null) { 1258 String[] tokens = line.split(" "); 1259 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1260 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1261 } 1262 1263 String packageName = tokens[0]; 1264 PackageParser.Package pkg = mPackages.get(packageName); 1265 if (pkg == null) { 1266 continue; 1267 } 1268 1269 for (int reason = 0; 1270 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1271 reason++) { 1272 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1273 } 1274 } 1275 } 1276 1277 private long parseAsLong(String token) throws IOException { 1278 try { 1279 return Long.parseLong(token); 1280 } catch (NumberFormatException e) { 1281 throw new IOException("Failed to parse " + token + " as a long.", e); 1282 } 1283 } 1284 1285 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1286 return readToken(in, sb, '\n'); 1287 } 1288 1289 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1290 throws IOException { 1291 sb.setLength(0); 1292 while (true) { 1293 int ch = in.read(); 1294 if (ch == -1) { 1295 if (sb.length() == 0) { 1296 return null; 1297 } 1298 throw new IOException("Unexpected EOF"); 1299 } 1300 if (ch == endOfToken) { 1301 return sb.toString(); 1302 } 1303 sb.append((char)ch); 1304 } 1305 } 1306 1307 private AtomicFile getFile() { 1308 File dataDir = Environment.getDataDirectory(); 1309 File systemDir = new File(dataDir, "system"); 1310 File fname = new File(systemDir, "package-usage.list"); 1311 return new AtomicFile(fname); 1312 } 1313 1314 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1315 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1316 } 1317 1318 class PackageHandler extends Handler { 1319 private boolean mBound = false; 1320 final ArrayList<HandlerParams> mPendingInstalls = 1321 new ArrayList<HandlerParams>(); 1322 1323 private boolean connectToService() { 1324 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1325 " DefaultContainerService"); 1326 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1327 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1328 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1329 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1330 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1331 mBound = true; 1332 return true; 1333 } 1334 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1335 return false; 1336 } 1337 1338 private void disconnectService() { 1339 mContainerService = null; 1340 mBound = false; 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1342 mContext.unbindService(mDefContainerConn); 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1344 } 1345 1346 PackageHandler(Looper looper) { 1347 super(looper); 1348 } 1349 1350 public void handleMessage(Message msg) { 1351 try { 1352 doHandleMessage(msg); 1353 } finally { 1354 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1355 } 1356 } 1357 1358 void doHandleMessage(Message msg) { 1359 switch (msg.what) { 1360 case INIT_COPY: { 1361 HandlerParams params = (HandlerParams) msg.obj; 1362 int idx = mPendingInstalls.size(); 1363 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1364 // If a bind was already initiated we dont really 1365 // need to do anything. The pending install 1366 // will be processed later on. 1367 if (!mBound) { 1368 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1369 System.identityHashCode(mHandler)); 1370 // If this is the only one pending we might 1371 // have to bind to the service again. 1372 if (!connectToService()) { 1373 Slog.e(TAG, "Failed to bind to media container service"); 1374 params.serviceError(); 1375 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1376 System.identityHashCode(mHandler)); 1377 if (params.traceMethod != null) { 1378 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1379 params.traceCookie); 1380 } 1381 return; 1382 } else { 1383 // Once we bind to the service, the first 1384 // pending request will be processed. 1385 mPendingInstalls.add(idx, params); 1386 } 1387 } else { 1388 mPendingInstalls.add(idx, params); 1389 // Already bound to the service. Just make 1390 // sure we trigger off processing the first request. 1391 if (idx == 0) { 1392 mHandler.sendEmptyMessage(MCS_BOUND); 1393 } 1394 } 1395 break; 1396 } 1397 case MCS_BOUND: { 1398 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1399 if (msg.obj != null) { 1400 mContainerService = (IMediaContainerService) msg.obj; 1401 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1402 System.identityHashCode(mHandler)); 1403 } 1404 if (mContainerService == null) { 1405 if (!mBound) { 1406 // Something seriously wrong since we are not bound and we are not 1407 // waiting for connection. Bail out. 1408 Slog.e(TAG, "Cannot bind to media container service"); 1409 for (HandlerParams params : mPendingInstalls) { 1410 // Indicate service bind error 1411 params.serviceError(); 1412 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1413 System.identityHashCode(params)); 1414 if (params.traceMethod != null) { 1415 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1416 params.traceMethod, params.traceCookie); 1417 } 1418 return; 1419 } 1420 mPendingInstalls.clear(); 1421 } else { 1422 Slog.w(TAG, "Waiting to connect to media container service"); 1423 } 1424 } else if (mPendingInstalls.size() > 0) { 1425 HandlerParams params = mPendingInstalls.get(0); 1426 if (params != null) { 1427 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1428 System.identityHashCode(params)); 1429 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1430 if (params.startCopy()) { 1431 // We are done... look for more work or to 1432 // go idle. 1433 if (DEBUG_SD_INSTALL) Log.i(TAG, 1434 "Checking for more work or unbind..."); 1435 // Delete pending install 1436 if (mPendingInstalls.size() > 0) { 1437 mPendingInstalls.remove(0); 1438 } 1439 if (mPendingInstalls.size() == 0) { 1440 if (mBound) { 1441 if (DEBUG_SD_INSTALL) Log.i(TAG, 1442 "Posting delayed MCS_UNBIND"); 1443 removeMessages(MCS_UNBIND); 1444 Message ubmsg = obtainMessage(MCS_UNBIND); 1445 // Unbind after a little delay, to avoid 1446 // continual thrashing. 1447 sendMessageDelayed(ubmsg, 10000); 1448 } 1449 } else { 1450 // There are more pending requests in queue. 1451 // Just post MCS_BOUND message to trigger processing 1452 // of next pending install. 1453 if (DEBUG_SD_INSTALL) Log.i(TAG, 1454 "Posting MCS_BOUND for next work"); 1455 mHandler.sendEmptyMessage(MCS_BOUND); 1456 } 1457 } 1458 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1459 } 1460 } else { 1461 // Should never happen ideally. 1462 Slog.w(TAG, "Empty queue"); 1463 } 1464 break; 1465 } 1466 case MCS_RECONNECT: { 1467 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1468 if (mPendingInstalls.size() > 0) { 1469 if (mBound) { 1470 disconnectService(); 1471 } 1472 if (!connectToService()) { 1473 Slog.e(TAG, "Failed to bind to media container service"); 1474 for (HandlerParams params : mPendingInstalls) { 1475 // Indicate service bind error 1476 params.serviceError(); 1477 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1478 System.identityHashCode(params)); 1479 } 1480 mPendingInstalls.clear(); 1481 } 1482 } 1483 break; 1484 } 1485 case MCS_UNBIND: { 1486 // If there is no actual work left, then time to unbind. 1487 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1488 1489 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1490 if (mBound) { 1491 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1492 1493 disconnectService(); 1494 } 1495 } else if (mPendingInstalls.size() > 0) { 1496 // There are more pending requests in queue. 1497 // Just post MCS_BOUND message to trigger processing 1498 // of next pending install. 1499 mHandler.sendEmptyMessage(MCS_BOUND); 1500 } 1501 1502 break; 1503 } 1504 case MCS_GIVE_UP: { 1505 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1506 HandlerParams params = mPendingInstalls.remove(0); 1507 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1508 System.identityHashCode(params)); 1509 break; 1510 } 1511 case SEND_PENDING_BROADCAST: { 1512 String packages[]; 1513 ArrayList<String> components[]; 1514 int size = 0; 1515 int uids[]; 1516 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1517 synchronized (mPackages) { 1518 if (mPendingBroadcasts == null) { 1519 return; 1520 } 1521 size = mPendingBroadcasts.size(); 1522 if (size <= 0) { 1523 // Nothing to be done. Just return 1524 return; 1525 } 1526 packages = new String[size]; 1527 components = new ArrayList[size]; 1528 uids = new int[size]; 1529 int i = 0; // filling out the above arrays 1530 1531 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1532 int packageUserId = mPendingBroadcasts.userIdAt(n); 1533 Iterator<Map.Entry<String, ArrayList<String>>> it 1534 = mPendingBroadcasts.packagesForUserId(packageUserId) 1535 .entrySet().iterator(); 1536 while (it.hasNext() && i < size) { 1537 Map.Entry<String, ArrayList<String>> ent = it.next(); 1538 packages[i] = ent.getKey(); 1539 components[i] = ent.getValue(); 1540 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1541 uids[i] = (ps != null) 1542 ? UserHandle.getUid(packageUserId, ps.appId) 1543 : -1; 1544 i++; 1545 } 1546 } 1547 size = i; 1548 mPendingBroadcasts.clear(); 1549 } 1550 // Send broadcasts 1551 for (int i = 0; i < size; i++) { 1552 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1553 } 1554 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1555 break; 1556 } 1557 case START_CLEANING_PACKAGE: { 1558 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1559 final String packageName = (String)msg.obj; 1560 final int userId = msg.arg1; 1561 final boolean andCode = msg.arg2 != 0; 1562 synchronized (mPackages) { 1563 if (userId == UserHandle.USER_ALL) { 1564 int[] users = sUserManager.getUserIds(); 1565 for (int user : users) { 1566 mSettings.addPackageToCleanLPw( 1567 new PackageCleanItem(user, packageName, andCode)); 1568 } 1569 } else { 1570 mSettings.addPackageToCleanLPw( 1571 new PackageCleanItem(userId, packageName, andCode)); 1572 } 1573 } 1574 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1575 startCleaningPackages(); 1576 } break; 1577 case POST_INSTALL: { 1578 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1579 1580 PostInstallData data = mRunningInstalls.get(msg.arg1); 1581 final boolean didRestore = (msg.arg2 != 0); 1582 mRunningInstalls.delete(msg.arg1); 1583 1584 if (data != null) { 1585 InstallArgs args = data.args; 1586 PackageInstalledInfo parentRes = data.res; 1587 1588 final boolean grantPermissions = (args.installFlags 1589 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1590 final boolean killApp = (args.installFlags 1591 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1592 final String[] grantedPermissions = args.installGrantPermissions; 1593 1594 // Handle the parent package 1595 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1596 grantedPermissions, didRestore, args.installerPackageName, 1597 args.observer); 1598 1599 // Handle the child packages 1600 final int childCount = (parentRes.addedChildPackages != null) 1601 ? parentRes.addedChildPackages.size() : 0; 1602 for (int i = 0; i < childCount; i++) { 1603 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1604 handlePackagePostInstall(childRes, grantPermissions, killApp, 1605 grantedPermissions, false, args.installerPackageName, 1606 args.observer); 1607 } 1608 1609 // Log tracing if needed 1610 if (args.traceMethod != null) { 1611 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1612 args.traceCookie); 1613 } 1614 } else { 1615 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1616 } 1617 1618 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1619 } break; 1620 case UPDATED_MEDIA_STATUS: { 1621 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1622 boolean reportStatus = msg.arg1 == 1; 1623 boolean doGc = msg.arg2 == 1; 1624 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1625 if (doGc) { 1626 // Force a gc to clear up stale containers. 1627 Runtime.getRuntime().gc(); 1628 } 1629 if (msg.obj != null) { 1630 @SuppressWarnings("unchecked") 1631 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1632 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1633 // Unload containers 1634 unloadAllContainers(args); 1635 } 1636 if (reportStatus) { 1637 try { 1638 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1639 PackageHelper.getMountService().finishMediaUpdate(); 1640 } catch (RemoteException e) { 1641 Log.e(TAG, "MountService not running?"); 1642 } 1643 } 1644 } break; 1645 case WRITE_SETTINGS: { 1646 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1647 synchronized (mPackages) { 1648 removeMessages(WRITE_SETTINGS); 1649 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1650 mSettings.writeLPr(); 1651 mDirtyUsers.clear(); 1652 } 1653 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1654 } break; 1655 case WRITE_PACKAGE_RESTRICTIONS: { 1656 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1657 synchronized (mPackages) { 1658 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1659 for (int userId : mDirtyUsers) { 1660 mSettings.writePackageRestrictionsLPr(userId); 1661 } 1662 mDirtyUsers.clear(); 1663 } 1664 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1665 } break; 1666 case CHECK_PENDING_VERIFICATION: { 1667 final int verificationId = msg.arg1; 1668 final PackageVerificationState state = mPendingVerification.get(verificationId); 1669 1670 if ((state != null) && !state.timeoutExtended()) { 1671 final InstallArgs args = state.getInstallArgs(); 1672 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1673 1674 Slog.i(TAG, "Verification timed out for " + originUri); 1675 mPendingVerification.remove(verificationId); 1676 1677 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1678 1679 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1680 Slog.i(TAG, "Continuing with installation of " + originUri); 1681 state.setVerifierResponse(Binder.getCallingUid(), 1682 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1683 broadcastPackageVerified(verificationId, originUri, 1684 PackageManager.VERIFICATION_ALLOW, 1685 state.getInstallArgs().getUser()); 1686 try { 1687 ret = args.copyApk(mContainerService, true); 1688 } catch (RemoteException e) { 1689 Slog.e(TAG, "Could not contact the ContainerService"); 1690 } 1691 } else { 1692 broadcastPackageVerified(verificationId, originUri, 1693 PackageManager.VERIFICATION_REJECT, 1694 state.getInstallArgs().getUser()); 1695 } 1696 1697 Trace.asyncTraceEnd( 1698 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1699 1700 processPendingInstall(args, ret); 1701 mHandler.sendEmptyMessage(MCS_UNBIND); 1702 } 1703 break; 1704 } 1705 case PACKAGE_VERIFIED: { 1706 final int verificationId = msg.arg1; 1707 1708 final PackageVerificationState state = mPendingVerification.get(verificationId); 1709 if (state == null) { 1710 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1711 break; 1712 } 1713 1714 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1715 1716 state.setVerifierResponse(response.callerUid, response.code); 1717 1718 if (state.isVerificationComplete()) { 1719 mPendingVerification.remove(verificationId); 1720 1721 final InstallArgs args = state.getInstallArgs(); 1722 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1723 1724 int ret; 1725 if (state.isInstallAllowed()) { 1726 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1727 broadcastPackageVerified(verificationId, originUri, 1728 response.code, state.getInstallArgs().getUser()); 1729 try { 1730 ret = args.copyApk(mContainerService, true); 1731 } catch (RemoteException e) { 1732 Slog.e(TAG, "Could not contact the ContainerService"); 1733 } 1734 } else { 1735 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1736 } 1737 1738 Trace.asyncTraceEnd( 1739 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1740 1741 processPendingInstall(args, ret); 1742 mHandler.sendEmptyMessage(MCS_UNBIND); 1743 } 1744 1745 break; 1746 } 1747 case START_INTENT_FILTER_VERIFICATIONS: { 1748 IFVerificationParams params = (IFVerificationParams) msg.obj; 1749 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1750 params.replacing, params.pkg); 1751 break; 1752 } 1753 case INTENT_FILTER_VERIFIED: { 1754 final int verificationId = msg.arg1; 1755 1756 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1757 verificationId); 1758 if (state == null) { 1759 Slog.w(TAG, "Invalid IntentFilter verification token " 1760 + verificationId + " received"); 1761 break; 1762 } 1763 1764 final int userId = state.getUserId(); 1765 1766 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1767 "Processing IntentFilter verification with token:" 1768 + verificationId + " and userId:" + userId); 1769 1770 final IntentFilterVerificationResponse response = 1771 (IntentFilterVerificationResponse) msg.obj; 1772 1773 state.setVerifierResponse(response.callerUid, response.code); 1774 1775 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1776 "IntentFilter verification with token:" + verificationId 1777 + " and userId:" + userId 1778 + " is settings verifier response with response code:" 1779 + response.code); 1780 1781 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1782 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1783 + response.getFailedDomainsString()); 1784 } 1785 1786 if (state.isVerificationComplete()) { 1787 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1788 } else { 1789 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1790 "IntentFilter verification with token:" + verificationId 1791 + " was not said to be complete"); 1792 } 1793 1794 break; 1795 } 1796 } 1797 } 1798 } 1799 1800 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1801 boolean killApp, String[] grantedPermissions, 1802 boolean launchedForRestore, String installerPackage, 1803 IPackageInstallObserver2 installObserver) { 1804 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1805 // Send the removed broadcasts 1806 if (res.removedInfo != null) { 1807 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1808 } 1809 1810 // Now that we successfully installed the package, grant runtime 1811 // permissions if requested before broadcasting the install. 1812 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1813 >= Build.VERSION_CODES.M) { 1814 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1815 } 1816 1817 final boolean update = res.removedInfo != null 1818 && res.removedInfo.removedPackage != null; 1819 1820 // If this is the first time we have child packages for a disabled privileged 1821 // app that had no children, we grant requested runtime permissions to the new 1822 // children if the parent on the system image had them already granted. 1823 if (res.pkg.parentPackage != null) { 1824 synchronized (mPackages) { 1825 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1826 } 1827 } 1828 1829 synchronized (mPackages) { 1830 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1831 } 1832 1833 final String packageName = res.pkg.applicationInfo.packageName; 1834 Bundle extras = new Bundle(1); 1835 extras.putInt(Intent.EXTRA_UID, res.uid); 1836 1837 // Determine the set of users who are adding this package for 1838 // the first time vs. those who are seeing an update. 1839 int[] firstUsers = EMPTY_INT_ARRAY; 1840 int[] updateUsers = EMPTY_INT_ARRAY; 1841 if (res.origUsers == null || res.origUsers.length == 0) { 1842 firstUsers = res.newUsers; 1843 } else { 1844 for (int newUser : res.newUsers) { 1845 boolean isNew = true; 1846 for (int origUser : res.origUsers) { 1847 if (origUser == newUser) { 1848 isNew = false; 1849 break; 1850 } 1851 } 1852 if (isNew) { 1853 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1854 } else { 1855 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1856 } 1857 } 1858 } 1859 1860 // Send installed broadcasts if the install/update is not ephemeral 1861 if (!isEphemeral(res.pkg)) { 1862 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1863 1864 // Send added for users that see the package for the first time 1865 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1866 extras, 0 /*flags*/, null /*targetPackage*/, 1867 null /*finishedReceiver*/, firstUsers); 1868 1869 // Send added for users that don't see the package for the first time 1870 if (update) { 1871 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1872 } 1873 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1874 extras, 0 /*flags*/, null /*targetPackage*/, 1875 null /*finishedReceiver*/, updateUsers); 1876 1877 // Send replaced for users that don't see the package for the first time 1878 if (update) { 1879 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1880 packageName, extras, 0 /*flags*/, 1881 null /*targetPackage*/, null /*finishedReceiver*/, 1882 updateUsers); 1883 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1884 null /*package*/, null /*extras*/, 0 /*flags*/, 1885 packageName /*targetPackage*/, 1886 null /*finishedReceiver*/, updateUsers); 1887 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1888 // First-install and we did a restore, so we're responsible for the 1889 // first-launch broadcast. 1890 if (DEBUG_BACKUP) { 1891 Slog.i(TAG, "Post-restore of " + packageName 1892 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1893 } 1894 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1895 } 1896 1897 // Send broadcast package appeared if forward locked/external for all users 1898 // treat asec-hosted packages like removable media on upgrade 1899 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1900 if (DEBUG_INSTALL) { 1901 Slog.i(TAG, "upgrading pkg " + res.pkg 1902 + " is ASEC-hosted -> AVAILABLE"); 1903 } 1904 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1905 ArrayList<String> pkgList = new ArrayList<>(1); 1906 pkgList.add(packageName); 1907 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1908 } 1909 } 1910 1911 // Work that needs to happen on first install within each user 1912 if (firstUsers != null && firstUsers.length > 0) { 1913 synchronized (mPackages) { 1914 for (int userId : firstUsers) { 1915 // If this app is a browser and it's newly-installed for some 1916 // users, clear any default-browser state in those users. The 1917 // app's nature doesn't depend on the user, so we can just check 1918 // its browser nature in any user and generalize. 1919 if (packageIsBrowser(packageName, userId)) { 1920 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1921 } 1922 1923 // We may also need to apply pending (restored) runtime 1924 // permission grants within these users. 1925 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1926 } 1927 } 1928 } 1929 1930 // Log current value of "unknown sources" setting 1931 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1932 getUnknownSourcesSettings()); 1933 1934 // Force a gc to clear up things 1935 Runtime.getRuntime().gc(); 1936 1937 // Remove the replaced package's older resources safely now 1938 // We delete after a gc for applications on sdcard. 1939 if (res.removedInfo != null && res.removedInfo.args != null) { 1940 synchronized (mInstallLock) { 1941 res.removedInfo.args.doPostDeleteLI(true); 1942 } 1943 } 1944 } 1945 1946 // If someone is watching installs - notify them 1947 if (installObserver != null) { 1948 try { 1949 Bundle extras = extrasForInstallResult(res); 1950 installObserver.onPackageInstalled(res.name, res.returnCode, 1951 res.returnMsg, extras); 1952 } catch (RemoteException e) { 1953 Slog.i(TAG, "Observer no longer exists."); 1954 } 1955 } 1956 } 1957 1958 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1959 PackageParser.Package pkg) { 1960 if (pkg.parentPackage == null) { 1961 return; 1962 } 1963 if (pkg.requestedPermissions == null) { 1964 return; 1965 } 1966 final PackageSetting disabledSysParentPs = mSettings 1967 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1968 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1969 || !disabledSysParentPs.isPrivileged() 1970 || (disabledSysParentPs.childPackageNames != null 1971 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1972 return; 1973 } 1974 final int[] allUserIds = sUserManager.getUserIds(); 1975 final int permCount = pkg.requestedPermissions.size(); 1976 for (int i = 0; i < permCount; i++) { 1977 String permission = pkg.requestedPermissions.get(i); 1978 BasePermission bp = mSettings.mPermissions.get(permission); 1979 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1980 continue; 1981 } 1982 for (int userId : allUserIds) { 1983 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1984 permission, userId)) { 1985 grantRuntimePermission(pkg.packageName, permission, userId); 1986 } 1987 } 1988 } 1989 } 1990 1991 private StorageEventListener mStorageListener = new StorageEventListener() { 1992 @Override 1993 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1994 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1995 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1996 final String volumeUuid = vol.getFsUuid(); 1997 1998 // Clean up any users or apps that were removed or recreated 1999 // while this volume was missing 2000 reconcileUsers(volumeUuid); 2001 reconcileApps(volumeUuid); 2002 2003 // Clean up any install sessions that expired or were 2004 // cancelled while this volume was missing 2005 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2006 2007 loadPrivatePackages(vol); 2008 2009 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2010 unloadPrivatePackages(vol); 2011 } 2012 } 2013 2014 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2015 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2016 updateExternalMediaStatus(true, false); 2017 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2018 updateExternalMediaStatus(false, false); 2019 } 2020 } 2021 } 2022 2023 @Override 2024 public void onVolumeForgotten(String fsUuid) { 2025 if (TextUtils.isEmpty(fsUuid)) { 2026 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2027 return; 2028 } 2029 2030 // Remove any apps installed on the forgotten volume 2031 synchronized (mPackages) { 2032 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2033 for (PackageSetting ps : packages) { 2034 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2035 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2036 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2037 } 2038 2039 mSettings.onVolumeForgotten(fsUuid); 2040 mSettings.writeLPr(); 2041 } 2042 } 2043 }; 2044 2045 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2046 String[] grantedPermissions) { 2047 for (int userId : userIds) { 2048 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2049 } 2050 2051 // We could have touched GID membership, so flush out packages.list 2052 synchronized (mPackages) { 2053 mSettings.writePackageListLPr(); 2054 } 2055 } 2056 2057 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2058 String[] grantedPermissions) { 2059 SettingBase sb = (SettingBase) pkg.mExtras; 2060 if (sb == null) { 2061 return; 2062 } 2063 2064 PermissionsState permissionsState = sb.getPermissionsState(); 2065 2066 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2067 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2068 2069 for (String permission : pkg.requestedPermissions) { 2070 final BasePermission bp; 2071 synchronized (mPackages) { 2072 bp = mSettings.mPermissions.get(permission); 2073 } 2074 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2075 && (grantedPermissions == null 2076 || ArrayUtils.contains(grantedPermissions, permission))) { 2077 final int flags = permissionsState.getPermissionFlags(permission, userId); 2078 // Installer cannot change immutable permissions. 2079 if ((flags & immutableFlags) == 0) { 2080 grantRuntimePermission(pkg.packageName, permission, userId); 2081 } 2082 } 2083 } 2084 } 2085 2086 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2087 Bundle extras = null; 2088 switch (res.returnCode) { 2089 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2090 extras = new Bundle(); 2091 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2092 res.origPermission); 2093 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2094 res.origPackage); 2095 break; 2096 } 2097 case PackageManager.INSTALL_SUCCEEDED: { 2098 extras = new Bundle(); 2099 extras.putBoolean(Intent.EXTRA_REPLACING, 2100 res.removedInfo != null && res.removedInfo.removedPackage != null); 2101 break; 2102 } 2103 } 2104 return extras; 2105 } 2106 2107 void scheduleWriteSettingsLocked() { 2108 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2109 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2110 } 2111 } 2112 2113 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2114 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2115 scheduleWritePackageRestrictionsLocked(userId); 2116 } 2117 2118 void scheduleWritePackageRestrictionsLocked(int userId) { 2119 final int[] userIds = (userId == UserHandle.USER_ALL) 2120 ? sUserManager.getUserIds() : new int[]{userId}; 2121 for (int nextUserId : userIds) { 2122 if (!sUserManager.exists(nextUserId)) return; 2123 mDirtyUsers.add(nextUserId); 2124 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2125 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2126 } 2127 } 2128 } 2129 2130 public static PackageManagerService main(Context context, Installer installer, 2131 boolean factoryTest, boolean onlyCore) { 2132 // Self-check for initial settings. 2133 PackageManagerServiceCompilerMapping.checkProperties(); 2134 2135 PackageManagerService m = new PackageManagerService(context, installer, 2136 factoryTest, onlyCore); 2137 m.enableSystemUserPackages(); 2138 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2139 // disabled after already being started. 2140 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2141 UserHandle.USER_SYSTEM); 2142 ServiceManager.addService("package", m); 2143 return m; 2144 } 2145 2146 private void enableSystemUserPackages() { 2147 if (!UserManager.isSplitSystemUser()) { 2148 return; 2149 } 2150 // For system user, enable apps based on the following conditions: 2151 // - app is whitelisted or belong to one of these groups: 2152 // -- system app which has no launcher icons 2153 // -- system app which has INTERACT_ACROSS_USERS permission 2154 // -- system IME app 2155 // - app is not in the blacklist 2156 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2157 Set<String> enableApps = new ArraySet<>(); 2158 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2159 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2160 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2161 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2162 enableApps.addAll(wlApps); 2163 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2164 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2165 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2166 enableApps.removeAll(blApps); 2167 Log.i(TAG, "Applications installed for system user: " + enableApps); 2168 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2169 UserHandle.SYSTEM); 2170 final int allAppsSize = allAps.size(); 2171 synchronized (mPackages) { 2172 for (int i = 0; i < allAppsSize; i++) { 2173 String pName = allAps.get(i); 2174 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2175 // Should not happen, but we shouldn't be failing if it does 2176 if (pkgSetting == null) { 2177 continue; 2178 } 2179 boolean install = enableApps.contains(pName); 2180 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2181 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2182 + " for system user"); 2183 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2184 } 2185 } 2186 } 2187 } 2188 2189 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2190 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2191 Context.DISPLAY_SERVICE); 2192 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2193 } 2194 2195 public PackageManagerService(Context context, Installer installer, 2196 boolean factoryTest, boolean onlyCore) { 2197 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2198 SystemClock.uptimeMillis()); 2199 2200 if (mSdkVersion <= 0) { 2201 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2202 } 2203 2204 mContext = context; 2205 mFactoryTest = factoryTest; 2206 mOnlyCore = onlyCore; 2207 mMetrics = new DisplayMetrics(); 2208 mSettings = new Settings(mPackages); 2209 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2210 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2211 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2214 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2215 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2216 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2217 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2218 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2219 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2220 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2221 2222 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2223 if (separateProcesses != null && separateProcesses.length() > 0) { 2224 if ("*".equals(separateProcesses)) { 2225 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2226 mSeparateProcesses = null; 2227 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2228 } else { 2229 mDefParseFlags = 0; 2230 mSeparateProcesses = separateProcesses.split(","); 2231 Slog.w(TAG, "Running with debug.separate_processes: " 2232 + separateProcesses); 2233 } 2234 } else { 2235 mDefParseFlags = 0; 2236 mSeparateProcesses = null; 2237 } 2238 2239 mInstaller = installer; 2240 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2241 "*dexopt*"); 2242 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2243 2244 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2245 FgThread.get().getLooper()); 2246 2247 getDefaultDisplayMetrics(context, mMetrics); 2248 2249 SystemConfig systemConfig = SystemConfig.getInstance(); 2250 mGlobalGids = systemConfig.getGlobalGids(); 2251 mSystemPermissions = systemConfig.getSystemPermissions(); 2252 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2253 2254 synchronized (mInstallLock) { 2255 // writer 2256 synchronized (mPackages) { 2257 mHandlerThread = new ServiceThread(TAG, 2258 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2259 mHandlerThread.start(); 2260 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2261 mProcessLoggingHandler = new ProcessLoggingHandler(); 2262 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2263 2264 File dataDir = Environment.getDataDirectory(); 2265 mAppInstallDir = new File(dataDir, "app"); 2266 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2267 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2268 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2269 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2270 2271 sUserManager = new UserManagerService(context, this, mPackages); 2272 2273 // Propagate permission configuration in to package manager. 2274 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2275 = systemConfig.getPermissions(); 2276 for (int i=0; i<permConfig.size(); i++) { 2277 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2278 BasePermission bp = mSettings.mPermissions.get(perm.name); 2279 if (bp == null) { 2280 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2281 mSettings.mPermissions.put(perm.name, bp); 2282 } 2283 if (perm.gids != null) { 2284 bp.setGids(perm.gids, perm.perUser); 2285 } 2286 } 2287 2288 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2289 for (int i=0; i<libConfig.size(); i++) { 2290 mSharedLibraries.put(libConfig.keyAt(i), 2291 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2292 } 2293 2294 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2295 2296 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2297 2298 String customResolverActivity = Resources.getSystem().getString( 2299 R.string.config_customResolverActivity); 2300 if (TextUtils.isEmpty(customResolverActivity)) { 2301 customResolverActivity = null; 2302 } else { 2303 mCustomResolverComponentName = ComponentName.unflattenFromString( 2304 customResolverActivity); 2305 } 2306 2307 long startTime = SystemClock.uptimeMillis(); 2308 2309 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2310 startTime); 2311 2312 // Set flag to monitor and not change apk file paths when 2313 // scanning install directories. 2314 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2315 2316 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2317 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2318 2319 if (bootClassPath == null) { 2320 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2321 } 2322 2323 if (systemServerClassPath == null) { 2324 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2325 } 2326 2327 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2328 final String[] dexCodeInstructionSets = 2329 getDexCodeInstructionSets( 2330 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2331 2332 /** 2333 * Ensure all external libraries have had dexopt run on them. 2334 */ 2335 if (mSharedLibraries.size() > 0) { 2336 // NOTE: For now, we're compiling these system "shared libraries" 2337 // (and framework jars) into all available architectures. It's possible 2338 // to compile them only when we come across an app that uses them (there's 2339 // already logic for that in scanPackageLI) but that adds some complexity. 2340 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2341 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2342 final String lib = libEntry.path; 2343 if (lib == null) { 2344 continue; 2345 } 2346 2347 try { 2348 // Shared libraries do not have profiles so we perform a full 2349 // AOT compilation (if needed). 2350 int dexoptNeeded = DexFile.getDexOptNeeded( 2351 lib, dexCodeInstructionSet, 2352 getCompilerFilterForReason(REASON_SHARED_APK), 2353 false /* newProfile */); 2354 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2355 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2356 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2357 getCompilerFilterForReason(REASON_SHARED_APK), 2358 StorageManager.UUID_PRIVATE_INTERNAL, 2359 SKIP_SHARED_LIBRARY_CHECK); 2360 } 2361 } catch (FileNotFoundException e) { 2362 Slog.w(TAG, "Library not found: " + lib); 2363 } catch (IOException | InstallerException e) { 2364 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2365 + e.getMessage()); 2366 } 2367 } 2368 } 2369 } 2370 2371 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2372 2373 final VersionInfo ver = mSettings.getInternalVersion(); 2374 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2375 2376 // when upgrading from pre-M, promote system app permissions from install to runtime 2377 mPromoteSystemApps = 2378 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2379 2380 // save off the names of pre-existing system packages prior to scanning; we don't 2381 // want to automatically grant runtime permissions for new system apps 2382 if (mPromoteSystemApps) { 2383 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2384 while (pkgSettingIter.hasNext()) { 2385 PackageSetting ps = pkgSettingIter.next(); 2386 if (isSystemApp(ps)) { 2387 mExistingSystemPackages.add(ps.name); 2388 } 2389 } 2390 } 2391 2392 // When upgrading from pre-N, we need to handle package extraction like first boot, 2393 // as there is no profiling data available. 2394 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2395 mSettings.setNWorkDone(); 2396 2397 // Collect vendor overlay packages. 2398 // (Do this before scanning any apps.) 2399 // For security and version matching reason, only consider 2400 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2401 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2402 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2403 | PackageParser.PARSE_IS_SYSTEM 2404 | PackageParser.PARSE_IS_SYSTEM_DIR 2405 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2406 2407 // Find base frameworks (resource packages without code). 2408 scanDirTracedLI(frameworkDir, mDefParseFlags 2409 | PackageParser.PARSE_IS_SYSTEM 2410 | PackageParser.PARSE_IS_SYSTEM_DIR 2411 | PackageParser.PARSE_IS_PRIVILEGED, 2412 scanFlags | SCAN_NO_DEX, 0); 2413 2414 // Collected privileged system packages. 2415 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2416 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2417 | PackageParser.PARSE_IS_SYSTEM 2418 | PackageParser.PARSE_IS_SYSTEM_DIR 2419 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2420 2421 // Collect ordinary system packages. 2422 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2423 scanDirTracedLI(systemAppDir, mDefParseFlags 2424 | PackageParser.PARSE_IS_SYSTEM 2425 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2426 2427 // Collect all vendor packages. 2428 File vendorAppDir = new File("/vendor/app"); 2429 try { 2430 vendorAppDir = vendorAppDir.getCanonicalFile(); 2431 } catch (IOException e) { 2432 // failed to look up canonical path, continue with original one 2433 } 2434 scanDirTracedLI(vendorAppDir, mDefParseFlags 2435 | PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2437 2438 // Collect all OEM packages. 2439 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2440 scanDirTracedLI(oemAppDir, mDefParseFlags 2441 | PackageParser.PARSE_IS_SYSTEM 2442 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2443 2444 // Prune any system packages that no longer exist. 2445 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2446 if (!mOnlyCore) { 2447 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2448 while (psit.hasNext()) { 2449 PackageSetting ps = psit.next(); 2450 2451 /* 2452 * If this is not a system app, it can't be a 2453 * disable system app. 2454 */ 2455 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2456 continue; 2457 } 2458 2459 /* 2460 * If the package is scanned, it's not erased. 2461 */ 2462 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2463 if (scannedPkg != null) { 2464 /* 2465 * If the system app is both scanned and in the 2466 * disabled packages list, then it must have been 2467 * added via OTA. Remove it from the currently 2468 * scanned package so the previously user-installed 2469 * application can be scanned. 2470 */ 2471 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2472 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2473 + ps.name + "; removing system app. Last known codePath=" 2474 + ps.codePathString + ", installStatus=" + ps.installStatus 2475 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2476 + scannedPkg.mVersionCode); 2477 removePackageLI(scannedPkg, true); 2478 mExpectingBetter.put(ps.name, ps.codePath); 2479 } 2480 2481 continue; 2482 } 2483 2484 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2485 psit.remove(); 2486 logCriticalInfo(Log.WARN, "System package " + ps.name 2487 + " no longer exists; it's data will be wiped"); 2488 // Actual deletion of code and data will be handled by later 2489 // reconciliation step 2490 } else { 2491 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2492 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2493 possiblyDeletedUpdatedSystemApps.add(ps.name); 2494 } 2495 } 2496 } 2497 } 2498 2499 //look for any incomplete package installations 2500 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2501 for (int i = 0; i < deletePkgsList.size(); i++) { 2502 // Actual deletion of code and data will be handled by later 2503 // reconciliation step 2504 final String packageName = deletePkgsList.get(i).name; 2505 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2506 synchronized (mPackages) { 2507 mSettings.removePackageLPw(packageName); 2508 } 2509 } 2510 2511 //delete tmp files 2512 deleteTempPackageFiles(); 2513 2514 // Remove any shared userIDs that have no associated packages 2515 mSettings.pruneSharedUsersLPw(); 2516 2517 if (!mOnlyCore) { 2518 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2519 SystemClock.uptimeMillis()); 2520 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2521 2522 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2523 | PackageParser.PARSE_FORWARD_LOCK, 2524 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2525 2526 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2527 | PackageParser.PARSE_IS_EPHEMERAL, 2528 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2529 2530 /** 2531 * Remove disable package settings for any updated system 2532 * apps that were removed via an OTA. If they're not a 2533 * previously-updated app, remove them completely. 2534 * Otherwise, just revoke their system-level permissions. 2535 */ 2536 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2537 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2538 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2539 2540 String msg; 2541 if (deletedPkg == null) { 2542 msg = "Updated system package " + deletedAppName 2543 + " no longer exists; it's data will be wiped"; 2544 // Actual deletion of code and data will be handled by later 2545 // reconciliation step 2546 } else { 2547 msg = "Updated system app + " + deletedAppName 2548 + " no longer present; removing system privileges for " 2549 + deletedAppName; 2550 2551 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2552 2553 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2554 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2555 } 2556 logCriticalInfo(Log.WARN, msg); 2557 } 2558 2559 /** 2560 * Make sure all system apps that we expected to appear on 2561 * the userdata partition actually showed up. If they never 2562 * appeared, crawl back and revive the system version. 2563 */ 2564 for (int i = 0; i < mExpectingBetter.size(); i++) { 2565 final String packageName = mExpectingBetter.keyAt(i); 2566 if (!mPackages.containsKey(packageName)) { 2567 final File scanFile = mExpectingBetter.valueAt(i); 2568 2569 logCriticalInfo(Log.WARN, "Expected better " + packageName 2570 + " but never showed up; reverting to system"); 2571 2572 int reparseFlags = mDefParseFlags; 2573 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2574 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2575 | PackageParser.PARSE_IS_SYSTEM_DIR 2576 | PackageParser.PARSE_IS_PRIVILEGED; 2577 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2578 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2579 | PackageParser.PARSE_IS_SYSTEM_DIR; 2580 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2581 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2582 | PackageParser.PARSE_IS_SYSTEM_DIR; 2583 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2584 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2585 | PackageParser.PARSE_IS_SYSTEM_DIR; 2586 } else { 2587 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2588 continue; 2589 } 2590 2591 mSettings.enableSystemPackageLPw(packageName); 2592 2593 try { 2594 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2595 } catch (PackageManagerException e) { 2596 Slog.e(TAG, "Failed to parse original system package: " 2597 + e.getMessage()); 2598 } 2599 } 2600 } 2601 } 2602 mExpectingBetter.clear(); 2603 2604 // Resolve protected action filters. Only the setup wizard is allowed to 2605 // have a high priority filter for these actions. 2606 mSetupWizardPackage = getSetupWizardPackageName(); 2607 if (mProtectedFilters.size() > 0) { 2608 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2609 Slog.i(TAG, "No setup wizard;" 2610 + " All protected intents capped to priority 0"); 2611 } 2612 for (ActivityIntentInfo filter : mProtectedFilters) { 2613 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2614 if (DEBUG_FILTERS) { 2615 Slog.i(TAG, "Found setup wizard;" 2616 + " allow priority " + filter.getPriority() + ";" 2617 + " package: " + filter.activity.info.packageName 2618 + " activity: " + filter.activity.className 2619 + " priority: " + filter.getPriority()); 2620 } 2621 // skip setup wizard; allow it to keep the high priority filter 2622 continue; 2623 } 2624 Slog.w(TAG, "Protected action; cap priority to 0;" 2625 + " package: " + filter.activity.info.packageName 2626 + " activity: " + filter.activity.className 2627 + " origPrio: " + filter.getPriority()); 2628 filter.setPriority(0); 2629 } 2630 } 2631 mDeferProtectedFilters = false; 2632 mProtectedFilters.clear(); 2633 2634 // Now that we know all of the shared libraries, update all clients to have 2635 // the correct library paths. 2636 updateAllSharedLibrariesLPw(); 2637 2638 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2639 // NOTE: We ignore potential failures here during a system scan (like 2640 // the rest of the commands above) because there's precious little we 2641 // can do about it. A settings error is reported, though. 2642 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2643 false /* boot complete */); 2644 } 2645 2646 // Now that we know all the packages we are keeping, 2647 // read and update their last usage times. 2648 mPackageUsage.readLP(); 2649 2650 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2651 SystemClock.uptimeMillis()); 2652 Slog.i(TAG, "Time to scan packages: " 2653 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2654 + " seconds"); 2655 2656 // If the platform SDK has changed since the last time we booted, 2657 // we need to re-grant app permission to catch any new ones that 2658 // appear. This is really a hack, and means that apps can in some 2659 // cases get permissions that the user didn't initially explicitly 2660 // allow... it would be nice to have some better way to handle 2661 // this situation. 2662 int updateFlags = UPDATE_PERMISSIONS_ALL; 2663 if (ver.sdkVersion != mSdkVersion) { 2664 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2665 + mSdkVersion + "; regranting permissions for internal storage"); 2666 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2667 } 2668 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2669 ver.sdkVersion = mSdkVersion; 2670 2671 // If this is the first boot or an update from pre-M, and it is a normal 2672 // boot, then we need to initialize the default preferred apps across 2673 // all defined users. 2674 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2675 for (UserInfo user : sUserManager.getUsers(true)) { 2676 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2677 applyFactoryDefaultBrowserLPw(user.id); 2678 primeDomainVerificationsLPw(user.id); 2679 } 2680 } 2681 2682 // Prepare storage for system user really early during boot, 2683 // since core system apps like SettingsProvider and SystemUI 2684 // can't wait for user to start 2685 final int storageFlags; 2686 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2687 storageFlags = StorageManager.FLAG_STORAGE_DE; 2688 } else { 2689 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2690 } 2691 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2692 storageFlags); 2693 2694 // If this is first boot after an OTA, and a normal boot, then 2695 // we need to clear code cache directories. 2696 if (mIsUpgrade && !onlyCore) { 2697 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2698 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2699 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2700 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2701 // No apps are running this early, so no need to freeze 2702 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2703 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2704 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2705 } 2706 clearAppProfilesLIF(ps.pkg); 2707 } 2708 ver.fingerprint = Build.FINGERPRINT; 2709 } 2710 2711 checkDefaultBrowser(); 2712 2713 // clear only after permissions and other defaults have been updated 2714 mExistingSystemPackages.clear(); 2715 mPromoteSystemApps = false; 2716 2717 // All the changes are done during package scanning. 2718 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2719 2720 // can downgrade to reader 2721 mSettings.writeLPr(); 2722 2723 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2724 SystemClock.uptimeMillis()); 2725 2726 if (!mOnlyCore) { 2727 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2728 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2729 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2730 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2731 mIntentFilterVerifierComponent); 2732 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2733 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2734 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2735 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2736 } else { 2737 mRequiredVerifierPackage = null; 2738 mRequiredInstallerPackage = null; 2739 mIntentFilterVerifierComponent = null; 2740 mIntentFilterVerifier = null; 2741 mServicesSystemSharedLibraryPackageName = null; 2742 mSharedSystemSharedLibraryPackageName = null; 2743 } 2744 2745 mInstallerService = new PackageInstallerService(context, this); 2746 2747 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2748 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2749 // both the installer and resolver must be present to enable ephemeral 2750 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2751 if (DEBUG_EPHEMERAL) { 2752 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2753 + " installer:" + ephemeralInstallerComponent); 2754 } 2755 mEphemeralResolverComponent = ephemeralResolverComponent; 2756 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2757 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2758 mEphemeralResolverConnection = 2759 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2760 } else { 2761 if (DEBUG_EPHEMERAL) { 2762 final String missingComponent = 2763 (ephemeralResolverComponent == null) 2764 ? (ephemeralInstallerComponent == null) 2765 ? "resolver and installer" 2766 : "resolver" 2767 : "installer"; 2768 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2769 } 2770 mEphemeralResolverComponent = null; 2771 mEphemeralInstallerComponent = null; 2772 mEphemeralResolverConnection = null; 2773 } 2774 2775 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2776 } // synchronized (mPackages) 2777 } // synchronized (mInstallLock) 2778 2779 // Now after opening every single application zip, make sure they 2780 // are all flushed. Not really needed, but keeps things nice and 2781 // tidy. 2782 Runtime.getRuntime().gc(); 2783 2784 // The initial scanning above does many calls into installd while 2785 // holding the mPackages lock, but we're mostly interested in yelling 2786 // once we have a booted system. 2787 mInstaller.setWarnIfHeld(mPackages); 2788 2789 // Expose private service for system components to use. 2790 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2791 } 2792 2793 @Override 2794 public boolean isFirstBoot() { 2795 return !mRestoredSettings; 2796 } 2797 2798 @Override 2799 public boolean isOnlyCoreApps() { 2800 return mOnlyCore; 2801 } 2802 2803 @Override 2804 public boolean isUpgrade() { 2805 return mIsUpgrade; 2806 } 2807 2808 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2809 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2810 2811 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2812 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2813 UserHandle.USER_SYSTEM); 2814 if (matches.size() == 1) { 2815 return matches.get(0).getComponentInfo().packageName; 2816 } else { 2817 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2818 return null; 2819 } 2820 } 2821 2822 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2823 synchronized (mPackages) { 2824 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2825 if (libraryEntry == null) { 2826 throw new IllegalStateException("Missing required shared library:" + libraryName); 2827 } 2828 return libraryEntry.apk; 2829 } 2830 } 2831 2832 private @NonNull String getRequiredInstallerLPr() { 2833 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2834 intent.addCategory(Intent.CATEGORY_DEFAULT); 2835 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2836 2837 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2838 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2839 UserHandle.USER_SYSTEM); 2840 if (matches.size() == 1) { 2841 ResolveInfo resolveInfo = matches.get(0); 2842 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2843 throw new RuntimeException("The installer must be a privileged app"); 2844 } 2845 return matches.get(0).getComponentInfo().packageName; 2846 } else { 2847 throw new RuntimeException("There must be exactly one installer; found " + matches); 2848 } 2849 } 2850 2851 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2852 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2853 2854 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2855 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2856 UserHandle.USER_SYSTEM); 2857 ResolveInfo best = null; 2858 final int N = matches.size(); 2859 for (int i = 0; i < N; i++) { 2860 final ResolveInfo cur = matches.get(i); 2861 final String packageName = cur.getComponentInfo().packageName; 2862 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2863 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2864 continue; 2865 } 2866 2867 if (best == null || cur.priority > best.priority) { 2868 best = cur; 2869 } 2870 } 2871 2872 if (best != null) { 2873 return best.getComponentInfo().getComponentName(); 2874 } else { 2875 throw new RuntimeException("There must be at least one intent filter verifier"); 2876 } 2877 } 2878 2879 private @Nullable ComponentName getEphemeralResolverLPr() { 2880 final String[] packageArray = 2881 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2882 if (packageArray.length == 0) { 2883 if (DEBUG_EPHEMERAL) { 2884 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2885 } 2886 return null; 2887 } 2888 2889 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2890 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2891 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2892 UserHandle.USER_SYSTEM); 2893 2894 final int N = resolvers.size(); 2895 if (N == 0) { 2896 if (DEBUG_EPHEMERAL) { 2897 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2898 } 2899 return null; 2900 } 2901 2902 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2903 for (int i = 0; i < N; i++) { 2904 final ResolveInfo info = resolvers.get(i); 2905 2906 if (info.serviceInfo == null) { 2907 continue; 2908 } 2909 2910 final String packageName = info.serviceInfo.packageName; 2911 if (!possiblePackages.contains(packageName)) { 2912 if (DEBUG_EPHEMERAL) { 2913 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2914 + " pkg: " + packageName + ", info:" + info); 2915 } 2916 continue; 2917 } 2918 2919 if (DEBUG_EPHEMERAL) { 2920 Slog.v(TAG, "Ephemeral resolver found;" 2921 + " pkg: " + packageName + ", info:" + info); 2922 } 2923 return new ComponentName(packageName, info.serviceInfo.name); 2924 } 2925 if (DEBUG_EPHEMERAL) { 2926 Slog.v(TAG, "Ephemeral resolver NOT found"); 2927 } 2928 return null; 2929 } 2930 2931 private @Nullable ComponentName getEphemeralInstallerLPr() { 2932 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2933 intent.addCategory(Intent.CATEGORY_DEFAULT); 2934 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2935 2936 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2937 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2938 UserHandle.USER_SYSTEM); 2939 if (matches.size() == 0) { 2940 return null; 2941 } else if (matches.size() == 1) { 2942 return matches.get(0).getComponentInfo().getComponentName(); 2943 } else { 2944 throw new RuntimeException( 2945 "There must be at most one ephemeral installer; found " + matches); 2946 } 2947 } 2948 2949 private void primeDomainVerificationsLPw(int userId) { 2950 if (DEBUG_DOMAIN_VERIFICATION) { 2951 Slog.d(TAG, "Priming domain verifications in user " + userId); 2952 } 2953 2954 SystemConfig systemConfig = SystemConfig.getInstance(); 2955 ArraySet<String> packages = systemConfig.getLinkedApps(); 2956 ArraySet<String> domains = new ArraySet<String>(); 2957 2958 for (String packageName : packages) { 2959 PackageParser.Package pkg = mPackages.get(packageName); 2960 if (pkg != null) { 2961 if (!pkg.isSystemApp()) { 2962 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2963 continue; 2964 } 2965 2966 domains.clear(); 2967 for (PackageParser.Activity a : pkg.activities) { 2968 for (ActivityIntentInfo filter : a.intents) { 2969 if (hasValidDomains(filter)) { 2970 domains.addAll(filter.getHostsList()); 2971 } 2972 } 2973 } 2974 2975 if (domains.size() > 0) { 2976 if (DEBUG_DOMAIN_VERIFICATION) { 2977 Slog.v(TAG, " + " + packageName); 2978 } 2979 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2980 // state w.r.t. the formal app-linkage "no verification attempted" state; 2981 // and then 'always' in the per-user state actually used for intent resolution. 2982 final IntentFilterVerificationInfo ivi; 2983 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2984 new ArrayList<String>(domains)); 2985 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2986 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2987 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2988 } else { 2989 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2990 + "' does not handle web links"); 2991 } 2992 } else { 2993 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2994 } 2995 } 2996 2997 scheduleWritePackageRestrictionsLocked(userId); 2998 scheduleWriteSettingsLocked(); 2999 } 3000 3001 private void applyFactoryDefaultBrowserLPw(int userId) { 3002 // The default browser app's package name is stored in a string resource, 3003 // with a product-specific overlay used for vendor customization. 3004 String browserPkg = mContext.getResources().getString( 3005 com.android.internal.R.string.default_browser); 3006 if (!TextUtils.isEmpty(browserPkg)) { 3007 // non-empty string => required to be a known package 3008 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3009 if (ps == null) { 3010 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3011 browserPkg = null; 3012 } else { 3013 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3014 } 3015 } 3016 3017 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3018 // default. If there's more than one, just leave everything alone. 3019 if (browserPkg == null) { 3020 calculateDefaultBrowserLPw(userId); 3021 } 3022 } 3023 3024 private void calculateDefaultBrowserLPw(int userId) { 3025 List<String> allBrowsers = resolveAllBrowserApps(userId); 3026 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3027 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3028 } 3029 3030 private List<String> resolveAllBrowserApps(int userId) { 3031 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3032 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3033 PackageManager.MATCH_ALL, userId); 3034 3035 final int count = list.size(); 3036 List<String> result = new ArrayList<String>(count); 3037 for (int i=0; i<count; i++) { 3038 ResolveInfo info = list.get(i); 3039 if (info.activityInfo == null 3040 || !info.handleAllWebDataURI 3041 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3042 || result.contains(info.activityInfo.packageName)) { 3043 continue; 3044 } 3045 result.add(info.activityInfo.packageName); 3046 } 3047 3048 return result; 3049 } 3050 3051 private boolean packageIsBrowser(String packageName, int userId) { 3052 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3053 PackageManager.MATCH_ALL, userId); 3054 final int N = list.size(); 3055 for (int i = 0; i < N; i++) { 3056 ResolveInfo info = list.get(i); 3057 if (packageName.equals(info.activityInfo.packageName)) { 3058 return true; 3059 } 3060 } 3061 return false; 3062 } 3063 3064 private void checkDefaultBrowser() { 3065 final int myUserId = UserHandle.myUserId(); 3066 final String packageName = getDefaultBrowserPackageName(myUserId); 3067 if (packageName != null) { 3068 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3069 if (info == null) { 3070 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3071 synchronized (mPackages) { 3072 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3073 } 3074 } 3075 } 3076 } 3077 3078 @Override 3079 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3080 throws RemoteException { 3081 try { 3082 return super.onTransact(code, data, reply, flags); 3083 } catch (RuntimeException e) { 3084 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3085 Slog.wtf(TAG, "Package Manager Crash", e); 3086 } 3087 throw e; 3088 } 3089 } 3090 3091 static int[] appendInts(int[] cur, int[] add) { 3092 if (add == null) return cur; 3093 if (cur == null) return add; 3094 final int N = add.length; 3095 for (int i=0; i<N; i++) { 3096 cur = appendInt(cur, add[i]); 3097 } 3098 return cur; 3099 } 3100 3101 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3102 if (!sUserManager.exists(userId)) return null; 3103 if (ps == null) { 3104 return null; 3105 } 3106 final PackageParser.Package p = ps.pkg; 3107 if (p == null) { 3108 return null; 3109 } 3110 3111 final PermissionsState permissionsState = ps.getPermissionsState(); 3112 3113 final int[] gids = permissionsState.computeGids(userId); 3114 final Set<String> permissions = permissionsState.getPermissions(userId); 3115 final PackageUserState state = ps.readUserState(userId); 3116 3117 return PackageParser.generatePackageInfo(p, gids, flags, 3118 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3119 } 3120 3121 @Override 3122 public void checkPackageStartable(String packageName, int userId) { 3123 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3124 3125 synchronized (mPackages) { 3126 final PackageSetting ps = mSettings.mPackages.get(packageName); 3127 if (ps == null) { 3128 throw new SecurityException("Package " + packageName + " was not found!"); 3129 } 3130 3131 if (!ps.getInstalled(userId)) { 3132 throw new SecurityException( 3133 "Package " + packageName + " was not installed for user " + userId + "!"); 3134 } 3135 3136 if (mSafeMode && !ps.isSystem()) { 3137 throw new SecurityException("Package " + packageName + " not a system app!"); 3138 } 3139 3140 if (mFrozenPackages.contains(packageName)) { 3141 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3142 } 3143 3144 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3145 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3146 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3147 } 3148 } 3149 } 3150 3151 @Override 3152 public boolean isPackageAvailable(String packageName, int userId) { 3153 if (!sUserManager.exists(userId)) return false; 3154 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3155 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3156 synchronized (mPackages) { 3157 PackageParser.Package p = mPackages.get(packageName); 3158 if (p != null) { 3159 final PackageSetting ps = (PackageSetting) p.mExtras; 3160 if (ps != null) { 3161 final PackageUserState state = ps.readUserState(userId); 3162 if (state != null) { 3163 return PackageParser.isAvailable(state); 3164 } 3165 } 3166 } 3167 } 3168 return false; 3169 } 3170 3171 @Override 3172 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3173 if (!sUserManager.exists(userId)) return null; 3174 flags = updateFlagsForPackage(flags, userId, packageName); 3175 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3176 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3177 // reader 3178 synchronized (mPackages) { 3179 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3180 PackageParser.Package p = null; 3181 if (matchFactoryOnly) { 3182 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3183 if (ps != null) { 3184 return generatePackageInfo(ps, flags, userId); 3185 } 3186 } 3187 if (p == null) { 3188 p = mPackages.get(packageName); 3189 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3190 return null; 3191 } 3192 } 3193 if (DEBUG_PACKAGE_INFO) 3194 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3195 if (p != null) { 3196 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3197 } 3198 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3199 final PackageSetting ps = mSettings.mPackages.get(packageName); 3200 return generatePackageInfo(ps, flags, userId); 3201 } 3202 } 3203 return null; 3204 } 3205 3206 @Override 3207 public String[] currentToCanonicalPackageNames(String[] names) { 3208 String[] out = new String[names.length]; 3209 // reader 3210 synchronized (mPackages) { 3211 for (int i=names.length-1; i>=0; i--) { 3212 PackageSetting ps = mSettings.mPackages.get(names[i]); 3213 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3214 } 3215 } 3216 return out; 3217 } 3218 3219 @Override 3220 public String[] canonicalToCurrentPackageNames(String[] names) { 3221 String[] out = new String[names.length]; 3222 // reader 3223 synchronized (mPackages) { 3224 for (int i=names.length-1; i>=0; i--) { 3225 String cur = mSettings.mRenamedPackages.get(names[i]); 3226 out[i] = cur != null ? cur : names[i]; 3227 } 3228 } 3229 return out; 3230 } 3231 3232 @Override 3233 public int getPackageUid(String packageName, int flags, int userId) { 3234 if (!sUserManager.exists(userId)) return -1; 3235 flags = updateFlagsForPackage(flags, userId, packageName); 3236 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3237 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3238 3239 // reader 3240 synchronized (mPackages) { 3241 final PackageParser.Package p = mPackages.get(packageName); 3242 if (p != null && p.isMatch(flags)) { 3243 return UserHandle.getUid(userId, p.applicationInfo.uid); 3244 } 3245 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3246 final PackageSetting ps = mSettings.mPackages.get(packageName); 3247 if (ps != null && ps.isMatch(flags)) { 3248 return UserHandle.getUid(userId, ps.appId); 3249 } 3250 } 3251 } 3252 3253 return -1; 3254 } 3255 3256 @Override 3257 public int[] getPackageGids(String packageName, int flags, int userId) { 3258 if (!sUserManager.exists(userId)) return null; 3259 flags = updateFlagsForPackage(flags, userId, packageName); 3260 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3261 false /* requireFullPermission */, false /* checkShell */, 3262 "getPackageGids"); 3263 3264 // reader 3265 synchronized (mPackages) { 3266 final PackageParser.Package p = mPackages.get(packageName); 3267 if (p != null && p.isMatch(flags)) { 3268 PackageSetting ps = (PackageSetting) p.mExtras; 3269 return ps.getPermissionsState().computeGids(userId); 3270 } 3271 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3272 final PackageSetting ps = mSettings.mPackages.get(packageName); 3273 if (ps != null && ps.isMatch(flags)) { 3274 return ps.getPermissionsState().computeGids(userId); 3275 } 3276 } 3277 } 3278 3279 return null; 3280 } 3281 3282 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3283 if (bp.perm != null) { 3284 return PackageParser.generatePermissionInfo(bp.perm, flags); 3285 } 3286 PermissionInfo pi = new PermissionInfo(); 3287 pi.name = bp.name; 3288 pi.packageName = bp.sourcePackage; 3289 pi.nonLocalizedLabel = bp.name; 3290 pi.protectionLevel = bp.protectionLevel; 3291 return pi; 3292 } 3293 3294 @Override 3295 public PermissionInfo getPermissionInfo(String name, int flags) { 3296 // reader 3297 synchronized (mPackages) { 3298 final BasePermission p = mSettings.mPermissions.get(name); 3299 if (p != null) { 3300 return generatePermissionInfo(p, flags); 3301 } 3302 return null; 3303 } 3304 } 3305 3306 @Override 3307 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3308 int flags) { 3309 // reader 3310 synchronized (mPackages) { 3311 if (group != null && !mPermissionGroups.containsKey(group)) { 3312 // This is thrown as NameNotFoundException 3313 return null; 3314 } 3315 3316 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3317 for (BasePermission p : mSettings.mPermissions.values()) { 3318 if (group == null) { 3319 if (p.perm == null || p.perm.info.group == null) { 3320 out.add(generatePermissionInfo(p, flags)); 3321 } 3322 } else { 3323 if (p.perm != null && group.equals(p.perm.info.group)) { 3324 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3325 } 3326 } 3327 } 3328 return new ParceledListSlice<>(out); 3329 } 3330 } 3331 3332 @Override 3333 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3334 // reader 3335 synchronized (mPackages) { 3336 return PackageParser.generatePermissionGroupInfo( 3337 mPermissionGroups.get(name), flags); 3338 } 3339 } 3340 3341 @Override 3342 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3343 // reader 3344 synchronized (mPackages) { 3345 final int N = mPermissionGroups.size(); 3346 ArrayList<PermissionGroupInfo> out 3347 = new ArrayList<PermissionGroupInfo>(N); 3348 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3349 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3350 } 3351 return new ParceledListSlice<>(out); 3352 } 3353 } 3354 3355 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3356 int userId) { 3357 if (!sUserManager.exists(userId)) return null; 3358 PackageSetting ps = mSettings.mPackages.get(packageName); 3359 if (ps != null) { 3360 if (ps.pkg == null) { 3361 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3362 if (pInfo != null) { 3363 return pInfo.applicationInfo; 3364 } 3365 return null; 3366 } 3367 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3368 ps.readUserState(userId), userId); 3369 } 3370 return null; 3371 } 3372 3373 @Override 3374 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3375 if (!sUserManager.exists(userId)) return null; 3376 flags = updateFlagsForApplication(flags, userId, packageName); 3377 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3378 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3379 // writer 3380 synchronized (mPackages) { 3381 PackageParser.Package p = mPackages.get(packageName); 3382 if (DEBUG_PACKAGE_INFO) Log.v( 3383 TAG, "getApplicationInfo " + packageName 3384 + ": " + p); 3385 if (p != null) { 3386 PackageSetting ps = mSettings.mPackages.get(packageName); 3387 if (ps == null) return null; 3388 // Note: isEnabledLP() does not apply here - always return info 3389 return PackageParser.generateApplicationInfo( 3390 p, flags, ps.readUserState(userId), userId); 3391 } 3392 if ("android".equals(packageName)||"system".equals(packageName)) { 3393 return mAndroidApplication; 3394 } 3395 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3396 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3397 } 3398 } 3399 return null; 3400 } 3401 3402 @Override 3403 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3404 final IPackageDataObserver observer) { 3405 mContext.enforceCallingOrSelfPermission( 3406 android.Manifest.permission.CLEAR_APP_CACHE, null); 3407 // Queue up an async operation since clearing cache may take a little while. 3408 mHandler.post(new Runnable() { 3409 public void run() { 3410 mHandler.removeCallbacks(this); 3411 boolean success = true; 3412 synchronized (mInstallLock) { 3413 try { 3414 mInstaller.freeCache(volumeUuid, freeStorageSize); 3415 } catch (InstallerException e) { 3416 Slog.w(TAG, "Couldn't clear application caches: " + e); 3417 success = false; 3418 } 3419 } 3420 if (observer != null) { 3421 try { 3422 observer.onRemoveCompleted(null, success); 3423 } catch (RemoteException e) { 3424 Slog.w(TAG, "RemoveException when invoking call back"); 3425 } 3426 } 3427 } 3428 }); 3429 } 3430 3431 @Override 3432 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3433 final IntentSender pi) { 3434 mContext.enforceCallingOrSelfPermission( 3435 android.Manifest.permission.CLEAR_APP_CACHE, null); 3436 // Queue up an async operation since clearing cache may take a little while. 3437 mHandler.post(new Runnable() { 3438 public void run() { 3439 mHandler.removeCallbacks(this); 3440 boolean success = true; 3441 synchronized (mInstallLock) { 3442 try { 3443 mInstaller.freeCache(volumeUuid, freeStorageSize); 3444 } catch (InstallerException e) { 3445 Slog.w(TAG, "Couldn't clear application caches: " + e); 3446 success = false; 3447 } 3448 } 3449 if(pi != null) { 3450 try { 3451 // Callback via pending intent 3452 int code = success ? 1 : 0; 3453 pi.sendIntent(null, code, null, 3454 null, null); 3455 } catch (SendIntentException e1) { 3456 Slog.i(TAG, "Failed to send pending intent"); 3457 } 3458 } 3459 } 3460 }); 3461 } 3462 3463 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3464 synchronized (mInstallLock) { 3465 try { 3466 mInstaller.freeCache(volumeUuid, freeStorageSize); 3467 } catch (InstallerException e) { 3468 throw new IOException("Failed to free enough space", e); 3469 } 3470 } 3471 } 3472 3473 /** 3474 * Update given flags based on encryption status of current user. 3475 */ 3476 private int updateFlags(int flags, int userId) { 3477 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3478 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3479 // Caller expressed an explicit opinion about what encryption 3480 // aware/unaware components they want to see, so fall through and 3481 // give them what they want 3482 } else { 3483 // Caller expressed no opinion, so match based on user state 3484 if (StorageManager.isUserKeyUnlocked(userId)) { 3485 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3486 } else { 3487 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3488 } 3489 } 3490 return flags; 3491 } 3492 3493 /** 3494 * Update given flags when being used to request {@link PackageInfo}. 3495 */ 3496 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3497 boolean triaged = true; 3498 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3499 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3500 // Caller is asking for component details, so they'd better be 3501 // asking for specific encryption matching behavior, or be triaged 3502 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3503 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3504 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3505 triaged = false; 3506 } 3507 } 3508 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3509 | PackageManager.MATCH_SYSTEM_ONLY 3510 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3511 triaged = false; 3512 } 3513 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3514 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3515 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3516 } 3517 return updateFlags(flags, userId); 3518 } 3519 3520 /** 3521 * Update given flags when being used to request {@link ApplicationInfo}. 3522 */ 3523 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3524 return updateFlagsForPackage(flags, userId, cookie); 3525 } 3526 3527 /** 3528 * Update given flags when being used to request {@link ComponentInfo}. 3529 */ 3530 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3531 if (cookie instanceof Intent) { 3532 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3533 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3534 } 3535 } 3536 3537 boolean triaged = true; 3538 // Caller is asking for component details, so they'd better be 3539 // asking for specific encryption matching behavior, or be triaged 3540 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3541 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3542 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3543 triaged = false; 3544 } 3545 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3546 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3547 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3548 } 3549 3550 return updateFlags(flags, userId); 3551 } 3552 3553 /** 3554 * Update given flags when being used to request {@link ResolveInfo}. 3555 */ 3556 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3557 // Safe mode means we shouldn't match any third-party components 3558 if (mSafeMode) { 3559 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3560 } 3561 3562 return updateFlagsForComponent(flags, userId, cookie); 3563 } 3564 3565 @Override 3566 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3567 if (!sUserManager.exists(userId)) return null; 3568 flags = updateFlagsForComponent(flags, userId, component); 3569 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3570 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3571 synchronized (mPackages) { 3572 PackageParser.Activity a = mActivities.mActivities.get(component); 3573 3574 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3575 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3576 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3577 if (ps == null) return null; 3578 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3579 userId); 3580 } 3581 if (mResolveComponentName.equals(component)) { 3582 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3583 new PackageUserState(), userId); 3584 } 3585 } 3586 return null; 3587 } 3588 3589 @Override 3590 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3591 String resolvedType) { 3592 synchronized (mPackages) { 3593 if (component.equals(mResolveComponentName)) { 3594 // The resolver supports EVERYTHING! 3595 return true; 3596 } 3597 PackageParser.Activity a = mActivities.mActivities.get(component); 3598 if (a == null) { 3599 return false; 3600 } 3601 for (int i=0; i<a.intents.size(); i++) { 3602 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3603 intent.getData(), intent.getCategories(), TAG) >= 0) { 3604 return true; 3605 } 3606 } 3607 return false; 3608 } 3609 } 3610 3611 @Override 3612 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3613 if (!sUserManager.exists(userId)) return null; 3614 flags = updateFlagsForComponent(flags, userId, component); 3615 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3616 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3617 synchronized (mPackages) { 3618 PackageParser.Activity a = mReceivers.mActivities.get(component); 3619 if (DEBUG_PACKAGE_INFO) Log.v( 3620 TAG, "getReceiverInfo " + component + ": " + a); 3621 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3622 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3623 if (ps == null) return null; 3624 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3625 userId); 3626 } 3627 } 3628 return null; 3629 } 3630 3631 @Override 3632 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3633 if (!sUserManager.exists(userId)) return null; 3634 flags = updateFlagsForComponent(flags, userId, component); 3635 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3636 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3637 synchronized (mPackages) { 3638 PackageParser.Service s = mServices.mServices.get(component); 3639 if (DEBUG_PACKAGE_INFO) Log.v( 3640 TAG, "getServiceInfo " + component + ": " + s); 3641 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3642 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3643 if (ps == null) return null; 3644 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3645 userId); 3646 } 3647 } 3648 return null; 3649 } 3650 3651 @Override 3652 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3653 if (!sUserManager.exists(userId)) return null; 3654 flags = updateFlagsForComponent(flags, userId, component); 3655 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3656 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3657 synchronized (mPackages) { 3658 PackageParser.Provider p = mProviders.mProviders.get(component); 3659 if (DEBUG_PACKAGE_INFO) Log.v( 3660 TAG, "getProviderInfo " + component + ": " + p); 3661 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3662 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3663 if (ps == null) return null; 3664 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3665 userId); 3666 } 3667 } 3668 return null; 3669 } 3670 3671 @Override 3672 public String[] getSystemSharedLibraryNames() { 3673 Set<String> libSet; 3674 synchronized (mPackages) { 3675 libSet = mSharedLibraries.keySet(); 3676 int size = libSet.size(); 3677 if (size > 0) { 3678 String[] libs = new String[size]; 3679 libSet.toArray(libs); 3680 return libs; 3681 } 3682 } 3683 return null; 3684 } 3685 3686 @Override 3687 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3688 synchronized (mPackages) { 3689 return mServicesSystemSharedLibraryPackageName; 3690 } 3691 } 3692 3693 @Override 3694 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3695 synchronized (mPackages) { 3696 return mSharedSystemSharedLibraryPackageName; 3697 } 3698 } 3699 3700 @Override 3701 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3702 synchronized (mPackages) { 3703 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3704 3705 final FeatureInfo fi = new FeatureInfo(); 3706 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3707 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3708 res.add(fi); 3709 3710 return new ParceledListSlice<>(res); 3711 } 3712 } 3713 3714 @Override 3715 public boolean hasSystemFeature(String name, int version) { 3716 synchronized (mPackages) { 3717 final FeatureInfo feat = mAvailableFeatures.get(name); 3718 if (feat == null) { 3719 return false; 3720 } else { 3721 return feat.version >= version; 3722 } 3723 } 3724 } 3725 3726 @Override 3727 public int checkPermission(String permName, String pkgName, int userId) { 3728 if (!sUserManager.exists(userId)) { 3729 return PackageManager.PERMISSION_DENIED; 3730 } 3731 3732 synchronized (mPackages) { 3733 final PackageParser.Package p = mPackages.get(pkgName); 3734 if (p != null && p.mExtras != null) { 3735 final PackageSetting ps = (PackageSetting) p.mExtras; 3736 final PermissionsState permissionsState = ps.getPermissionsState(); 3737 if (permissionsState.hasPermission(permName, userId)) { 3738 return PackageManager.PERMISSION_GRANTED; 3739 } 3740 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3741 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3742 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3743 return PackageManager.PERMISSION_GRANTED; 3744 } 3745 } 3746 } 3747 3748 return PackageManager.PERMISSION_DENIED; 3749 } 3750 3751 @Override 3752 public int checkUidPermission(String permName, int uid) { 3753 final int userId = UserHandle.getUserId(uid); 3754 3755 if (!sUserManager.exists(userId)) { 3756 return PackageManager.PERMISSION_DENIED; 3757 } 3758 3759 synchronized (mPackages) { 3760 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3761 if (obj != null) { 3762 final SettingBase ps = (SettingBase) obj; 3763 final PermissionsState permissionsState = ps.getPermissionsState(); 3764 if (permissionsState.hasPermission(permName, userId)) { 3765 return PackageManager.PERMISSION_GRANTED; 3766 } 3767 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3768 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3769 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3770 return PackageManager.PERMISSION_GRANTED; 3771 } 3772 } else { 3773 ArraySet<String> perms = mSystemPermissions.get(uid); 3774 if (perms != null) { 3775 if (perms.contains(permName)) { 3776 return PackageManager.PERMISSION_GRANTED; 3777 } 3778 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3779 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3780 return PackageManager.PERMISSION_GRANTED; 3781 } 3782 } 3783 } 3784 } 3785 3786 return PackageManager.PERMISSION_DENIED; 3787 } 3788 3789 @Override 3790 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3791 if (UserHandle.getCallingUserId() != userId) { 3792 mContext.enforceCallingPermission( 3793 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3794 "isPermissionRevokedByPolicy for user " + userId); 3795 } 3796 3797 if (checkPermission(permission, packageName, userId) 3798 == PackageManager.PERMISSION_GRANTED) { 3799 return false; 3800 } 3801 3802 final long identity = Binder.clearCallingIdentity(); 3803 try { 3804 final int flags = getPermissionFlags(permission, packageName, userId); 3805 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3806 } finally { 3807 Binder.restoreCallingIdentity(identity); 3808 } 3809 } 3810 3811 @Override 3812 public String getPermissionControllerPackageName() { 3813 synchronized (mPackages) { 3814 return mRequiredInstallerPackage; 3815 } 3816 } 3817 3818 /** 3819 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3820 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3821 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3822 * @param message the message to log on security exception 3823 */ 3824 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3825 boolean checkShell, String message) { 3826 if (userId < 0) { 3827 throw new IllegalArgumentException("Invalid userId " + userId); 3828 } 3829 if (checkShell) { 3830 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3831 } 3832 if (userId == UserHandle.getUserId(callingUid)) return; 3833 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3834 if (requireFullPermission) { 3835 mContext.enforceCallingOrSelfPermission( 3836 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3837 } else { 3838 try { 3839 mContext.enforceCallingOrSelfPermission( 3840 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3841 } catch (SecurityException se) { 3842 mContext.enforceCallingOrSelfPermission( 3843 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3844 } 3845 } 3846 } 3847 } 3848 3849 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3850 if (callingUid == Process.SHELL_UID) { 3851 if (userHandle >= 0 3852 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3853 throw new SecurityException("Shell does not have permission to access user " 3854 + userHandle); 3855 } else if (userHandle < 0) { 3856 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3857 + Debug.getCallers(3)); 3858 } 3859 } 3860 } 3861 3862 private BasePermission findPermissionTreeLP(String permName) { 3863 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3864 if (permName.startsWith(bp.name) && 3865 permName.length() > bp.name.length() && 3866 permName.charAt(bp.name.length()) == '.') { 3867 return bp; 3868 } 3869 } 3870 return null; 3871 } 3872 3873 private BasePermission checkPermissionTreeLP(String permName) { 3874 if (permName != null) { 3875 BasePermission bp = findPermissionTreeLP(permName); 3876 if (bp != null) { 3877 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3878 return bp; 3879 } 3880 throw new SecurityException("Calling uid " 3881 + Binder.getCallingUid() 3882 + " is not allowed to add to permission tree " 3883 + bp.name + " owned by uid " + bp.uid); 3884 } 3885 } 3886 throw new SecurityException("No permission tree found for " + permName); 3887 } 3888 3889 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3890 if (s1 == null) { 3891 return s2 == null; 3892 } 3893 if (s2 == null) { 3894 return false; 3895 } 3896 if (s1.getClass() != s2.getClass()) { 3897 return false; 3898 } 3899 return s1.equals(s2); 3900 } 3901 3902 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3903 if (pi1.icon != pi2.icon) return false; 3904 if (pi1.logo != pi2.logo) return false; 3905 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3906 if (!compareStrings(pi1.name, pi2.name)) return false; 3907 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3908 // We'll take care of setting this one. 3909 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3910 // These are not currently stored in settings. 3911 //if (!compareStrings(pi1.group, pi2.group)) return false; 3912 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3913 //if (pi1.labelRes != pi2.labelRes) return false; 3914 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3915 return true; 3916 } 3917 3918 int permissionInfoFootprint(PermissionInfo info) { 3919 int size = info.name.length(); 3920 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3921 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3922 return size; 3923 } 3924 3925 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3926 int size = 0; 3927 for (BasePermission perm : mSettings.mPermissions.values()) { 3928 if (perm.uid == tree.uid) { 3929 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3930 } 3931 } 3932 return size; 3933 } 3934 3935 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3936 // We calculate the max size of permissions defined by this uid and throw 3937 // if that plus the size of 'info' would exceed our stated maximum. 3938 if (tree.uid != Process.SYSTEM_UID) { 3939 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3940 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3941 throw new SecurityException("Permission tree size cap exceeded"); 3942 } 3943 } 3944 } 3945 3946 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3947 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3948 throw new SecurityException("Label must be specified in permission"); 3949 } 3950 BasePermission tree = checkPermissionTreeLP(info.name); 3951 BasePermission bp = mSettings.mPermissions.get(info.name); 3952 boolean added = bp == null; 3953 boolean changed = true; 3954 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3955 if (added) { 3956 enforcePermissionCapLocked(info, tree); 3957 bp = new BasePermission(info.name, tree.sourcePackage, 3958 BasePermission.TYPE_DYNAMIC); 3959 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3960 throw new SecurityException( 3961 "Not allowed to modify non-dynamic permission " 3962 + info.name); 3963 } else { 3964 if (bp.protectionLevel == fixedLevel 3965 && bp.perm.owner.equals(tree.perm.owner) 3966 && bp.uid == tree.uid 3967 && comparePermissionInfos(bp.perm.info, info)) { 3968 changed = false; 3969 } 3970 } 3971 bp.protectionLevel = fixedLevel; 3972 info = new PermissionInfo(info); 3973 info.protectionLevel = fixedLevel; 3974 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3975 bp.perm.info.packageName = tree.perm.info.packageName; 3976 bp.uid = tree.uid; 3977 if (added) { 3978 mSettings.mPermissions.put(info.name, bp); 3979 } 3980 if (changed) { 3981 if (!async) { 3982 mSettings.writeLPr(); 3983 } else { 3984 scheduleWriteSettingsLocked(); 3985 } 3986 } 3987 return added; 3988 } 3989 3990 @Override 3991 public boolean addPermission(PermissionInfo info) { 3992 synchronized (mPackages) { 3993 return addPermissionLocked(info, false); 3994 } 3995 } 3996 3997 @Override 3998 public boolean addPermissionAsync(PermissionInfo info) { 3999 synchronized (mPackages) { 4000 return addPermissionLocked(info, true); 4001 } 4002 } 4003 4004 @Override 4005 public void removePermission(String name) { 4006 synchronized (mPackages) { 4007 checkPermissionTreeLP(name); 4008 BasePermission bp = mSettings.mPermissions.get(name); 4009 if (bp != null) { 4010 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4011 throw new SecurityException( 4012 "Not allowed to modify non-dynamic permission " 4013 + name); 4014 } 4015 mSettings.mPermissions.remove(name); 4016 mSettings.writeLPr(); 4017 } 4018 } 4019 } 4020 4021 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4022 BasePermission bp) { 4023 int index = pkg.requestedPermissions.indexOf(bp.name); 4024 if (index == -1) { 4025 throw new SecurityException("Package " + pkg.packageName 4026 + " has not requested permission " + bp.name); 4027 } 4028 if (!bp.isRuntime() && !bp.isDevelopment()) { 4029 throw new SecurityException("Permission " + bp.name 4030 + " is not a changeable permission type"); 4031 } 4032 } 4033 4034 @Override 4035 public void grantRuntimePermission(String packageName, String name, final int userId) { 4036 if (!sUserManager.exists(userId)) { 4037 Log.e(TAG, "No such user:" + userId); 4038 return; 4039 } 4040 4041 mContext.enforceCallingOrSelfPermission( 4042 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4043 "grantRuntimePermission"); 4044 4045 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4046 true /* requireFullPermission */, true /* checkShell */, 4047 "grantRuntimePermission"); 4048 4049 final int uid; 4050 final SettingBase sb; 4051 4052 synchronized (mPackages) { 4053 final PackageParser.Package pkg = mPackages.get(packageName); 4054 if (pkg == null) { 4055 throw new IllegalArgumentException("Unknown package: " + packageName); 4056 } 4057 4058 final BasePermission bp = mSettings.mPermissions.get(name); 4059 if (bp == null) { 4060 throw new IllegalArgumentException("Unknown permission: " + name); 4061 } 4062 4063 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4064 4065 // If a permission review is required for legacy apps we represent 4066 // their permissions as always granted runtime ones since we need 4067 // to keep the review required permission flag per user while an 4068 // install permission's state is shared across all users. 4069 if (Build.PERMISSIONS_REVIEW_REQUIRED 4070 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4071 && bp.isRuntime()) { 4072 return; 4073 } 4074 4075 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4076 sb = (SettingBase) pkg.mExtras; 4077 if (sb == null) { 4078 throw new IllegalArgumentException("Unknown package: " + packageName); 4079 } 4080 4081 final PermissionsState permissionsState = sb.getPermissionsState(); 4082 4083 final int flags = permissionsState.getPermissionFlags(name, userId); 4084 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4085 throw new SecurityException("Cannot grant system fixed permission " 4086 + name + " for package " + packageName); 4087 } 4088 4089 if (bp.isDevelopment()) { 4090 // Development permissions must be handled specially, since they are not 4091 // normal runtime permissions. For now they apply to all users. 4092 if (permissionsState.grantInstallPermission(bp) != 4093 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4094 scheduleWriteSettingsLocked(); 4095 } 4096 return; 4097 } 4098 4099 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4100 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4101 return; 4102 } 4103 4104 final int result = permissionsState.grantRuntimePermission(bp, userId); 4105 switch (result) { 4106 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4107 return; 4108 } 4109 4110 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4111 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4112 mHandler.post(new Runnable() { 4113 @Override 4114 public void run() { 4115 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4116 } 4117 }); 4118 } 4119 break; 4120 } 4121 4122 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4123 4124 // Not critical if that is lost - app has to request again. 4125 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4126 } 4127 4128 // Only need to do this if user is initialized. Otherwise it's a new user 4129 // and there are no processes running as the user yet and there's no need 4130 // to make an expensive call to remount processes for the changed permissions. 4131 if (READ_EXTERNAL_STORAGE.equals(name) 4132 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4133 final long token = Binder.clearCallingIdentity(); 4134 try { 4135 if (sUserManager.isInitialized(userId)) { 4136 MountServiceInternal mountServiceInternal = LocalServices.getService( 4137 MountServiceInternal.class); 4138 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4139 } 4140 } finally { 4141 Binder.restoreCallingIdentity(token); 4142 } 4143 } 4144 } 4145 4146 @Override 4147 public void revokeRuntimePermission(String packageName, String name, int userId) { 4148 if (!sUserManager.exists(userId)) { 4149 Log.e(TAG, "No such user:" + userId); 4150 return; 4151 } 4152 4153 mContext.enforceCallingOrSelfPermission( 4154 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4155 "revokeRuntimePermission"); 4156 4157 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4158 true /* requireFullPermission */, true /* checkShell */, 4159 "revokeRuntimePermission"); 4160 4161 final int appId; 4162 4163 synchronized (mPackages) { 4164 final PackageParser.Package pkg = mPackages.get(packageName); 4165 if (pkg == null) { 4166 throw new IllegalArgumentException("Unknown package: " + packageName); 4167 } 4168 4169 final BasePermission bp = mSettings.mPermissions.get(name); 4170 if (bp == null) { 4171 throw new IllegalArgumentException("Unknown permission: " + name); 4172 } 4173 4174 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4175 4176 // If a permission review is required for legacy apps we represent 4177 // their permissions as always granted runtime ones since we need 4178 // to keep the review required permission flag per user while an 4179 // install permission's state is shared across all users. 4180 if (Build.PERMISSIONS_REVIEW_REQUIRED 4181 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4182 && bp.isRuntime()) { 4183 return; 4184 } 4185 4186 SettingBase sb = (SettingBase) pkg.mExtras; 4187 if (sb == null) { 4188 throw new IllegalArgumentException("Unknown package: " + packageName); 4189 } 4190 4191 final PermissionsState permissionsState = sb.getPermissionsState(); 4192 4193 final int flags = permissionsState.getPermissionFlags(name, userId); 4194 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4195 throw new SecurityException("Cannot revoke system fixed permission " 4196 + name + " for package " + packageName); 4197 } 4198 4199 if (bp.isDevelopment()) { 4200 // Development permissions must be handled specially, since they are not 4201 // normal runtime permissions. For now they apply to all users. 4202 if (permissionsState.revokeInstallPermission(bp) != 4203 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4204 scheduleWriteSettingsLocked(); 4205 } 4206 return; 4207 } 4208 4209 if (permissionsState.revokeRuntimePermission(bp, userId) == 4210 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4211 return; 4212 } 4213 4214 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4215 4216 // Critical, after this call app should never have the permission. 4217 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4218 4219 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4220 } 4221 4222 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4223 } 4224 4225 @Override 4226 public void resetRuntimePermissions() { 4227 mContext.enforceCallingOrSelfPermission( 4228 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4229 "revokeRuntimePermission"); 4230 4231 int callingUid = Binder.getCallingUid(); 4232 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4233 mContext.enforceCallingOrSelfPermission( 4234 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4235 "resetRuntimePermissions"); 4236 } 4237 4238 synchronized (mPackages) { 4239 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4240 for (int userId : UserManagerService.getInstance().getUserIds()) { 4241 final int packageCount = mPackages.size(); 4242 for (int i = 0; i < packageCount; i++) { 4243 PackageParser.Package pkg = mPackages.valueAt(i); 4244 if (!(pkg.mExtras instanceof PackageSetting)) { 4245 continue; 4246 } 4247 PackageSetting ps = (PackageSetting) pkg.mExtras; 4248 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4249 } 4250 } 4251 } 4252 } 4253 4254 @Override 4255 public int getPermissionFlags(String name, String packageName, int userId) { 4256 if (!sUserManager.exists(userId)) { 4257 return 0; 4258 } 4259 4260 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4261 4262 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4263 true /* requireFullPermission */, false /* checkShell */, 4264 "getPermissionFlags"); 4265 4266 synchronized (mPackages) { 4267 final PackageParser.Package pkg = mPackages.get(packageName); 4268 if (pkg == null) { 4269 throw new IllegalArgumentException("Unknown package: " + packageName); 4270 } 4271 4272 final BasePermission bp = mSettings.mPermissions.get(name); 4273 if (bp == null) { 4274 throw new IllegalArgumentException("Unknown permission: " + name); 4275 } 4276 4277 SettingBase sb = (SettingBase) pkg.mExtras; 4278 if (sb == null) { 4279 throw new IllegalArgumentException("Unknown package: " + packageName); 4280 } 4281 4282 PermissionsState permissionsState = sb.getPermissionsState(); 4283 return permissionsState.getPermissionFlags(name, userId); 4284 } 4285 } 4286 4287 @Override 4288 public void updatePermissionFlags(String name, String packageName, int flagMask, 4289 int flagValues, int userId) { 4290 if (!sUserManager.exists(userId)) { 4291 return; 4292 } 4293 4294 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4295 4296 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4297 true /* requireFullPermission */, true /* checkShell */, 4298 "updatePermissionFlags"); 4299 4300 // Only the system can change these flags and nothing else. 4301 if (getCallingUid() != Process.SYSTEM_UID) { 4302 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4303 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4304 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4305 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4306 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4307 } 4308 4309 synchronized (mPackages) { 4310 final PackageParser.Package pkg = mPackages.get(packageName); 4311 if (pkg == null) { 4312 throw new IllegalArgumentException("Unknown package: " + packageName); 4313 } 4314 4315 final BasePermission bp = mSettings.mPermissions.get(name); 4316 if (bp == null) { 4317 throw new IllegalArgumentException("Unknown permission: " + name); 4318 } 4319 4320 SettingBase sb = (SettingBase) pkg.mExtras; 4321 if (sb == null) { 4322 throw new IllegalArgumentException("Unknown package: " + packageName); 4323 } 4324 4325 PermissionsState permissionsState = sb.getPermissionsState(); 4326 4327 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4328 4329 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4330 // Install and runtime permissions are stored in different places, 4331 // so figure out what permission changed and persist the change. 4332 if (permissionsState.getInstallPermissionState(name) != null) { 4333 scheduleWriteSettingsLocked(); 4334 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4335 || hadState) { 4336 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4337 } 4338 } 4339 } 4340 } 4341 4342 /** 4343 * Update the permission flags for all packages and runtime permissions of a user in order 4344 * to allow device or profile owner to remove POLICY_FIXED. 4345 */ 4346 @Override 4347 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4348 if (!sUserManager.exists(userId)) { 4349 return; 4350 } 4351 4352 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4353 4354 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4355 true /* requireFullPermission */, true /* checkShell */, 4356 "updatePermissionFlagsForAllApps"); 4357 4358 // Only the system can change system fixed flags. 4359 if (getCallingUid() != Process.SYSTEM_UID) { 4360 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4361 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4362 } 4363 4364 synchronized (mPackages) { 4365 boolean changed = false; 4366 final int packageCount = mPackages.size(); 4367 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4368 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4369 SettingBase sb = (SettingBase) pkg.mExtras; 4370 if (sb == null) { 4371 continue; 4372 } 4373 PermissionsState permissionsState = sb.getPermissionsState(); 4374 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4375 userId, flagMask, flagValues); 4376 } 4377 if (changed) { 4378 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4379 } 4380 } 4381 } 4382 4383 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4384 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4385 != PackageManager.PERMISSION_GRANTED 4386 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4387 != PackageManager.PERMISSION_GRANTED) { 4388 throw new SecurityException(message + " requires " 4389 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4390 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4391 } 4392 } 4393 4394 @Override 4395 public boolean shouldShowRequestPermissionRationale(String permissionName, 4396 String packageName, int userId) { 4397 if (UserHandle.getCallingUserId() != userId) { 4398 mContext.enforceCallingPermission( 4399 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4400 "canShowRequestPermissionRationale for user " + userId); 4401 } 4402 4403 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4404 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4405 return false; 4406 } 4407 4408 if (checkPermission(permissionName, packageName, userId) 4409 == PackageManager.PERMISSION_GRANTED) { 4410 return false; 4411 } 4412 4413 final int flags; 4414 4415 final long identity = Binder.clearCallingIdentity(); 4416 try { 4417 flags = getPermissionFlags(permissionName, 4418 packageName, userId); 4419 } finally { 4420 Binder.restoreCallingIdentity(identity); 4421 } 4422 4423 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4424 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4425 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4426 4427 if ((flags & fixedFlags) != 0) { 4428 return false; 4429 } 4430 4431 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4432 } 4433 4434 @Override 4435 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4436 mContext.enforceCallingOrSelfPermission( 4437 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4438 "addOnPermissionsChangeListener"); 4439 4440 synchronized (mPackages) { 4441 mOnPermissionChangeListeners.addListenerLocked(listener); 4442 } 4443 } 4444 4445 @Override 4446 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4447 synchronized (mPackages) { 4448 mOnPermissionChangeListeners.removeListenerLocked(listener); 4449 } 4450 } 4451 4452 @Override 4453 public boolean isProtectedBroadcast(String actionName) { 4454 synchronized (mPackages) { 4455 if (mProtectedBroadcasts.contains(actionName)) { 4456 return true; 4457 } else if (actionName != null) { 4458 // TODO: remove these terrible hacks 4459 if (actionName.startsWith("android.net.netmon.lingerExpired") 4460 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4461 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4462 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4463 return true; 4464 } 4465 } 4466 } 4467 return false; 4468 } 4469 4470 @Override 4471 public int checkSignatures(String pkg1, String pkg2) { 4472 synchronized (mPackages) { 4473 final PackageParser.Package p1 = mPackages.get(pkg1); 4474 final PackageParser.Package p2 = mPackages.get(pkg2); 4475 if (p1 == null || p1.mExtras == null 4476 || p2 == null || p2.mExtras == null) { 4477 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4478 } 4479 return compareSignatures(p1.mSignatures, p2.mSignatures); 4480 } 4481 } 4482 4483 @Override 4484 public int checkUidSignatures(int uid1, int uid2) { 4485 // Map to base uids. 4486 uid1 = UserHandle.getAppId(uid1); 4487 uid2 = UserHandle.getAppId(uid2); 4488 // reader 4489 synchronized (mPackages) { 4490 Signature[] s1; 4491 Signature[] s2; 4492 Object obj = mSettings.getUserIdLPr(uid1); 4493 if (obj != null) { 4494 if (obj instanceof SharedUserSetting) { 4495 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4496 } else if (obj instanceof PackageSetting) { 4497 s1 = ((PackageSetting)obj).signatures.mSignatures; 4498 } else { 4499 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4500 } 4501 } else { 4502 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4503 } 4504 obj = mSettings.getUserIdLPr(uid2); 4505 if (obj != null) { 4506 if (obj instanceof SharedUserSetting) { 4507 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4508 } else if (obj instanceof PackageSetting) { 4509 s2 = ((PackageSetting)obj).signatures.mSignatures; 4510 } else { 4511 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4512 } 4513 } else { 4514 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4515 } 4516 return compareSignatures(s1, s2); 4517 } 4518 } 4519 4520 /** 4521 * This method should typically only be used when granting or revoking 4522 * permissions, since the app may immediately restart after this call. 4523 * <p> 4524 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4525 * guard your work against the app being relaunched. 4526 */ 4527 private void killUid(int appId, int userId, String reason) { 4528 final long identity = Binder.clearCallingIdentity(); 4529 try { 4530 IActivityManager am = ActivityManagerNative.getDefault(); 4531 if (am != null) { 4532 try { 4533 am.killUid(appId, userId, reason); 4534 } catch (RemoteException e) { 4535 /* ignore - same process */ 4536 } 4537 } 4538 } finally { 4539 Binder.restoreCallingIdentity(identity); 4540 } 4541 } 4542 4543 /** 4544 * Compares two sets of signatures. Returns: 4545 * <br /> 4546 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4547 * <br /> 4548 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4549 * <br /> 4550 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4551 * <br /> 4552 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4553 * <br /> 4554 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4555 */ 4556 static int compareSignatures(Signature[] s1, Signature[] s2) { 4557 if (s1 == null) { 4558 return s2 == null 4559 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4560 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4561 } 4562 4563 if (s2 == null) { 4564 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4565 } 4566 4567 if (s1.length != s2.length) { 4568 return PackageManager.SIGNATURE_NO_MATCH; 4569 } 4570 4571 // Since both signature sets are of size 1, we can compare without HashSets. 4572 if (s1.length == 1) { 4573 return s1[0].equals(s2[0]) ? 4574 PackageManager.SIGNATURE_MATCH : 4575 PackageManager.SIGNATURE_NO_MATCH; 4576 } 4577 4578 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4579 for (Signature sig : s1) { 4580 set1.add(sig); 4581 } 4582 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4583 for (Signature sig : s2) { 4584 set2.add(sig); 4585 } 4586 // Make sure s2 contains all signatures in s1. 4587 if (set1.equals(set2)) { 4588 return PackageManager.SIGNATURE_MATCH; 4589 } 4590 return PackageManager.SIGNATURE_NO_MATCH; 4591 } 4592 4593 /** 4594 * If the database version for this type of package (internal storage or 4595 * external storage) is less than the version where package signatures 4596 * were updated, return true. 4597 */ 4598 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4599 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4600 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4601 } 4602 4603 /** 4604 * Used for backward compatibility to make sure any packages with 4605 * certificate chains get upgraded to the new style. {@code existingSigs} 4606 * will be in the old format (since they were stored on disk from before the 4607 * system upgrade) and {@code scannedSigs} will be in the newer format. 4608 */ 4609 private int compareSignaturesCompat(PackageSignatures existingSigs, 4610 PackageParser.Package scannedPkg) { 4611 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4612 return PackageManager.SIGNATURE_NO_MATCH; 4613 } 4614 4615 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4616 for (Signature sig : existingSigs.mSignatures) { 4617 existingSet.add(sig); 4618 } 4619 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4620 for (Signature sig : scannedPkg.mSignatures) { 4621 try { 4622 Signature[] chainSignatures = sig.getChainSignatures(); 4623 for (Signature chainSig : chainSignatures) { 4624 scannedCompatSet.add(chainSig); 4625 } 4626 } catch (CertificateEncodingException e) { 4627 scannedCompatSet.add(sig); 4628 } 4629 } 4630 /* 4631 * Make sure the expanded scanned set contains all signatures in the 4632 * existing one. 4633 */ 4634 if (scannedCompatSet.equals(existingSet)) { 4635 // Migrate the old signatures to the new scheme. 4636 existingSigs.assignSignatures(scannedPkg.mSignatures); 4637 // The new KeySets will be re-added later in the scanning process. 4638 synchronized (mPackages) { 4639 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4640 } 4641 return PackageManager.SIGNATURE_MATCH; 4642 } 4643 return PackageManager.SIGNATURE_NO_MATCH; 4644 } 4645 4646 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4647 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4648 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4649 } 4650 4651 private int compareSignaturesRecover(PackageSignatures existingSigs, 4652 PackageParser.Package scannedPkg) { 4653 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4654 return PackageManager.SIGNATURE_NO_MATCH; 4655 } 4656 4657 String msg = null; 4658 try { 4659 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4660 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4661 + scannedPkg.packageName); 4662 return PackageManager.SIGNATURE_MATCH; 4663 } 4664 } catch (CertificateException e) { 4665 msg = e.getMessage(); 4666 } 4667 4668 logCriticalInfo(Log.INFO, 4669 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4670 return PackageManager.SIGNATURE_NO_MATCH; 4671 } 4672 4673 @Override 4674 public List<String> getAllPackages() { 4675 synchronized (mPackages) { 4676 return new ArrayList<String>(mPackages.keySet()); 4677 } 4678 } 4679 4680 @Override 4681 public String[] getPackagesForUid(int uid) { 4682 uid = UserHandle.getAppId(uid); 4683 // reader 4684 synchronized (mPackages) { 4685 Object obj = mSettings.getUserIdLPr(uid); 4686 if (obj instanceof SharedUserSetting) { 4687 final SharedUserSetting sus = (SharedUserSetting) obj; 4688 final int N = sus.packages.size(); 4689 final String[] res = new String[N]; 4690 final Iterator<PackageSetting> it = sus.packages.iterator(); 4691 int i = 0; 4692 while (it.hasNext()) { 4693 res[i++] = it.next().name; 4694 } 4695 return res; 4696 } else if (obj instanceof PackageSetting) { 4697 final PackageSetting ps = (PackageSetting) obj; 4698 return new String[] { ps.name }; 4699 } 4700 } 4701 return null; 4702 } 4703 4704 @Override 4705 public String getNameForUid(int uid) { 4706 // reader 4707 synchronized (mPackages) { 4708 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4709 if (obj instanceof SharedUserSetting) { 4710 final SharedUserSetting sus = (SharedUserSetting) obj; 4711 return sus.name + ":" + sus.userId; 4712 } else if (obj instanceof PackageSetting) { 4713 final PackageSetting ps = (PackageSetting) obj; 4714 return ps.name; 4715 } 4716 } 4717 return null; 4718 } 4719 4720 @Override 4721 public int getUidForSharedUser(String sharedUserName) { 4722 if(sharedUserName == null) { 4723 return -1; 4724 } 4725 // reader 4726 synchronized (mPackages) { 4727 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4728 if (suid == null) { 4729 return -1; 4730 } 4731 return suid.userId; 4732 } 4733 } 4734 4735 @Override 4736 public int getFlagsForUid(int uid) { 4737 synchronized (mPackages) { 4738 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4739 if (obj instanceof SharedUserSetting) { 4740 final SharedUserSetting sus = (SharedUserSetting) obj; 4741 return sus.pkgFlags; 4742 } else if (obj instanceof PackageSetting) { 4743 final PackageSetting ps = (PackageSetting) obj; 4744 return ps.pkgFlags; 4745 } 4746 } 4747 return 0; 4748 } 4749 4750 @Override 4751 public int getPrivateFlagsForUid(int uid) { 4752 synchronized (mPackages) { 4753 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4754 if (obj instanceof SharedUserSetting) { 4755 final SharedUserSetting sus = (SharedUserSetting) obj; 4756 return sus.pkgPrivateFlags; 4757 } else if (obj instanceof PackageSetting) { 4758 final PackageSetting ps = (PackageSetting) obj; 4759 return ps.pkgPrivateFlags; 4760 } 4761 } 4762 return 0; 4763 } 4764 4765 @Override 4766 public boolean isUidPrivileged(int uid) { 4767 uid = UserHandle.getAppId(uid); 4768 // reader 4769 synchronized (mPackages) { 4770 Object obj = mSettings.getUserIdLPr(uid); 4771 if (obj instanceof SharedUserSetting) { 4772 final SharedUserSetting sus = (SharedUserSetting) obj; 4773 final Iterator<PackageSetting> it = sus.packages.iterator(); 4774 while (it.hasNext()) { 4775 if (it.next().isPrivileged()) { 4776 return true; 4777 } 4778 } 4779 } else if (obj instanceof PackageSetting) { 4780 final PackageSetting ps = (PackageSetting) obj; 4781 return ps.isPrivileged(); 4782 } 4783 } 4784 return false; 4785 } 4786 4787 @Override 4788 public String[] getAppOpPermissionPackages(String permissionName) { 4789 synchronized (mPackages) { 4790 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4791 if (pkgs == null) { 4792 return null; 4793 } 4794 return pkgs.toArray(new String[pkgs.size()]); 4795 } 4796 } 4797 4798 @Override 4799 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4800 int flags, int userId) { 4801 try { 4802 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4803 4804 if (!sUserManager.exists(userId)) return null; 4805 flags = updateFlagsForResolve(flags, userId, intent); 4806 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4807 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4808 4809 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4810 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4811 flags, userId); 4812 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4813 4814 final ResolveInfo bestChoice = 4815 chooseBestActivity(intent, resolvedType, flags, query, userId); 4816 4817 if (isEphemeralAllowed(intent, query, userId)) { 4818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4819 final EphemeralResolveInfo ai = 4820 getEphemeralResolveInfo(intent, resolvedType, userId); 4821 if (ai != null) { 4822 if (DEBUG_EPHEMERAL) { 4823 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4824 } 4825 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4826 bestChoice.ephemeralResolveInfo = ai; 4827 } 4828 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4829 } 4830 return bestChoice; 4831 } finally { 4832 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4833 } 4834 } 4835 4836 @Override 4837 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4838 IntentFilter filter, int match, ComponentName activity) { 4839 final int userId = UserHandle.getCallingUserId(); 4840 if (DEBUG_PREFERRED) { 4841 Log.v(TAG, "setLastChosenActivity intent=" + intent 4842 + " resolvedType=" + resolvedType 4843 + " flags=" + flags 4844 + " filter=" + filter 4845 + " match=" + match 4846 + " activity=" + activity); 4847 filter.dump(new PrintStreamPrinter(System.out), " "); 4848 } 4849 intent.setComponent(null); 4850 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4851 userId); 4852 // Find any earlier preferred or last chosen entries and nuke them 4853 findPreferredActivity(intent, resolvedType, 4854 flags, query, 0, false, true, false, userId); 4855 // Add the new activity as the last chosen for this filter 4856 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4857 "Setting last chosen"); 4858 } 4859 4860 @Override 4861 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4862 final int userId = UserHandle.getCallingUserId(); 4863 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4864 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4865 userId); 4866 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4867 false, false, false, userId); 4868 } 4869 4870 4871 private boolean isEphemeralAllowed( 4872 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4873 // Short circuit and return early if possible. 4874 if (DISABLE_EPHEMERAL_APPS) { 4875 return false; 4876 } 4877 final int callingUser = UserHandle.getCallingUserId(); 4878 if (callingUser != UserHandle.USER_SYSTEM) { 4879 return false; 4880 } 4881 if (mEphemeralResolverConnection == null) { 4882 return false; 4883 } 4884 if (intent.getComponent() != null) { 4885 return false; 4886 } 4887 if (intent.getPackage() != null) { 4888 return false; 4889 } 4890 final boolean isWebUri = hasWebURI(intent); 4891 if (!isWebUri) { 4892 return false; 4893 } 4894 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4895 synchronized (mPackages) { 4896 final int count = resolvedActivites.size(); 4897 for (int n = 0; n < count; n++) { 4898 ResolveInfo info = resolvedActivites.get(n); 4899 String packageName = info.activityInfo.packageName; 4900 PackageSetting ps = mSettings.mPackages.get(packageName); 4901 if (ps != null) { 4902 // Try to get the status from User settings first 4903 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4904 int status = (int) (packedStatus >> 32); 4905 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4906 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4907 if (DEBUG_EPHEMERAL) { 4908 Slog.v(TAG, "DENY ephemeral apps;" 4909 + " pkg: " + packageName + ", status: " + status); 4910 } 4911 return false; 4912 } 4913 } 4914 } 4915 } 4916 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4917 return true; 4918 } 4919 4920 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4921 int userId) { 4922 MessageDigest digest = null; 4923 try { 4924 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4925 } catch (NoSuchAlgorithmException e) { 4926 // If we can't create a digest, ignore ephemeral apps. 4927 return null; 4928 } 4929 4930 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4931 final byte[] digestBytes = digest.digest(hostBytes); 4932 int shaPrefix = 4933 digestBytes[0] << 24 4934 | digestBytes[1] << 16 4935 | digestBytes[2] << 8 4936 | digestBytes[3] << 0; 4937 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4938 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4939 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4940 // No hash prefix match; there are no ephemeral apps for this domain. 4941 return null; 4942 } 4943 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4944 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4945 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4946 continue; 4947 } 4948 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4949 // No filters; this should never happen. 4950 if (filters.isEmpty()) { 4951 continue; 4952 } 4953 // We have a domain match; resolve the filters to see if anything matches. 4954 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4955 for (int j = filters.size() - 1; j >= 0; --j) { 4956 final EphemeralResolveIntentInfo intentInfo = 4957 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4958 ephemeralResolver.addFilter(intentInfo); 4959 } 4960 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4961 intent, resolvedType, false /*defaultOnly*/, userId); 4962 if (!matchedResolveInfoList.isEmpty()) { 4963 return matchedResolveInfoList.get(0); 4964 } 4965 } 4966 // Hash or filter mis-match; no ephemeral apps for this domain. 4967 return null; 4968 } 4969 4970 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4971 int flags, List<ResolveInfo> query, int userId) { 4972 if (query != null) { 4973 final int N = query.size(); 4974 if (N == 1) { 4975 return query.get(0); 4976 } else if (N > 1) { 4977 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4978 // If there is more than one activity with the same priority, 4979 // then let the user decide between them. 4980 ResolveInfo r0 = query.get(0); 4981 ResolveInfo r1 = query.get(1); 4982 if (DEBUG_INTENT_MATCHING || debug) { 4983 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4984 + r1.activityInfo.name + "=" + r1.priority); 4985 } 4986 // If the first activity has a higher priority, or a different 4987 // default, then it is always desirable to pick it. 4988 if (r0.priority != r1.priority 4989 || r0.preferredOrder != r1.preferredOrder 4990 || r0.isDefault != r1.isDefault) { 4991 return query.get(0); 4992 } 4993 // If we have saved a preference for a preferred activity for 4994 // this Intent, use that. 4995 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4996 flags, query, r0.priority, true, false, debug, userId); 4997 if (ri != null) { 4998 return ri; 4999 } 5000 ri = new ResolveInfo(mResolveInfo); 5001 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5002 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5003 ri.activityInfo.applicationInfo = new ApplicationInfo( 5004 ri.activityInfo.applicationInfo); 5005 if (userId != 0) { 5006 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5007 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5008 } 5009 // Make sure that the resolver is displayable in car mode 5010 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5011 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5012 return ri; 5013 } 5014 } 5015 return null; 5016 } 5017 5018 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5019 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5020 final int N = query.size(); 5021 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5022 .get(userId); 5023 // Get the list of persistent preferred activities that handle the intent 5024 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5025 List<PersistentPreferredActivity> pprefs = ppir != null 5026 ? ppir.queryIntent(intent, resolvedType, 5027 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5028 : null; 5029 if (pprefs != null && pprefs.size() > 0) { 5030 final int M = pprefs.size(); 5031 for (int i=0; i<M; i++) { 5032 final PersistentPreferredActivity ppa = pprefs.get(i); 5033 if (DEBUG_PREFERRED || debug) { 5034 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5035 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5036 + "\n component=" + ppa.mComponent); 5037 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5038 } 5039 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5040 flags | MATCH_DISABLED_COMPONENTS, userId); 5041 if (DEBUG_PREFERRED || debug) { 5042 Slog.v(TAG, "Found persistent preferred activity:"); 5043 if (ai != null) { 5044 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5045 } else { 5046 Slog.v(TAG, " null"); 5047 } 5048 } 5049 if (ai == null) { 5050 // This previously registered persistent preferred activity 5051 // component is no longer known. Ignore it and do NOT remove it. 5052 continue; 5053 } 5054 for (int j=0; j<N; j++) { 5055 final ResolveInfo ri = query.get(j); 5056 if (!ri.activityInfo.applicationInfo.packageName 5057 .equals(ai.applicationInfo.packageName)) { 5058 continue; 5059 } 5060 if (!ri.activityInfo.name.equals(ai.name)) { 5061 continue; 5062 } 5063 // Found a persistent preference that can handle the intent. 5064 if (DEBUG_PREFERRED || debug) { 5065 Slog.v(TAG, "Returning persistent preferred activity: " + 5066 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5067 } 5068 return ri; 5069 } 5070 } 5071 } 5072 return null; 5073 } 5074 5075 // TODO: handle preferred activities missing while user has amnesia 5076 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5077 List<ResolveInfo> query, int priority, boolean always, 5078 boolean removeMatches, boolean debug, int userId) { 5079 if (!sUserManager.exists(userId)) return null; 5080 flags = updateFlagsForResolve(flags, userId, intent); 5081 // writer 5082 synchronized (mPackages) { 5083 if (intent.getSelector() != null) { 5084 intent = intent.getSelector(); 5085 } 5086 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5087 5088 // Try to find a matching persistent preferred activity. 5089 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5090 debug, userId); 5091 5092 // If a persistent preferred activity matched, use it. 5093 if (pri != null) { 5094 return pri; 5095 } 5096 5097 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5098 // Get the list of preferred activities that handle the intent 5099 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5100 List<PreferredActivity> prefs = pir != null 5101 ? pir.queryIntent(intent, resolvedType, 5102 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5103 : null; 5104 if (prefs != null && prefs.size() > 0) { 5105 boolean changed = false; 5106 try { 5107 // First figure out how good the original match set is. 5108 // We will only allow preferred activities that came 5109 // from the same match quality. 5110 int match = 0; 5111 5112 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5113 5114 final int N = query.size(); 5115 for (int j=0; j<N; j++) { 5116 final ResolveInfo ri = query.get(j); 5117 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5118 + ": 0x" + Integer.toHexString(match)); 5119 if (ri.match > match) { 5120 match = ri.match; 5121 } 5122 } 5123 5124 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5125 + Integer.toHexString(match)); 5126 5127 match &= IntentFilter.MATCH_CATEGORY_MASK; 5128 final int M = prefs.size(); 5129 for (int i=0; i<M; i++) { 5130 final PreferredActivity pa = prefs.get(i); 5131 if (DEBUG_PREFERRED || debug) { 5132 Slog.v(TAG, "Checking PreferredActivity ds=" 5133 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5134 + "\n component=" + pa.mPref.mComponent); 5135 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5136 } 5137 if (pa.mPref.mMatch != match) { 5138 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5139 + Integer.toHexString(pa.mPref.mMatch)); 5140 continue; 5141 } 5142 // If it's not an "always" type preferred activity and that's what we're 5143 // looking for, skip it. 5144 if (always && !pa.mPref.mAlways) { 5145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5146 continue; 5147 } 5148 final ActivityInfo ai = getActivityInfo( 5149 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5150 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5151 userId); 5152 if (DEBUG_PREFERRED || debug) { 5153 Slog.v(TAG, "Found preferred activity:"); 5154 if (ai != null) { 5155 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5156 } else { 5157 Slog.v(TAG, " null"); 5158 } 5159 } 5160 if (ai == null) { 5161 // This previously registered preferred activity 5162 // component is no longer known. Most likely an update 5163 // to the app was installed and in the new version this 5164 // component no longer exists. Clean it up by removing 5165 // it from the preferred activities list, and skip it. 5166 Slog.w(TAG, "Removing dangling preferred activity: " 5167 + pa.mPref.mComponent); 5168 pir.removeFilter(pa); 5169 changed = true; 5170 continue; 5171 } 5172 for (int j=0; j<N; j++) { 5173 final ResolveInfo ri = query.get(j); 5174 if (!ri.activityInfo.applicationInfo.packageName 5175 .equals(ai.applicationInfo.packageName)) { 5176 continue; 5177 } 5178 if (!ri.activityInfo.name.equals(ai.name)) { 5179 continue; 5180 } 5181 5182 if (removeMatches) { 5183 pir.removeFilter(pa); 5184 changed = true; 5185 if (DEBUG_PREFERRED) { 5186 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5187 } 5188 break; 5189 } 5190 5191 // Okay we found a previously set preferred or last chosen app. 5192 // If the result set is different from when this 5193 // was created, we need to clear it and re-ask the 5194 // user their preference, if we're looking for an "always" type entry. 5195 if (always && !pa.mPref.sameSet(query)) { 5196 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5197 + intent + " type " + resolvedType); 5198 if (DEBUG_PREFERRED) { 5199 Slog.v(TAG, "Removing preferred activity since set changed " 5200 + pa.mPref.mComponent); 5201 } 5202 pir.removeFilter(pa); 5203 // Re-add the filter as a "last chosen" entry (!always) 5204 PreferredActivity lastChosen = new PreferredActivity( 5205 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5206 pir.addFilter(lastChosen); 5207 changed = true; 5208 return null; 5209 } 5210 5211 // Yay! Either the set matched or we're looking for the last chosen 5212 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5213 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5214 return ri; 5215 } 5216 } 5217 } finally { 5218 if (changed) { 5219 if (DEBUG_PREFERRED) { 5220 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5221 } 5222 scheduleWritePackageRestrictionsLocked(userId); 5223 } 5224 } 5225 } 5226 } 5227 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5228 return null; 5229 } 5230 5231 /* 5232 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5233 */ 5234 @Override 5235 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5236 int targetUserId) { 5237 mContext.enforceCallingOrSelfPermission( 5238 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5239 List<CrossProfileIntentFilter> matches = 5240 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5241 if (matches != null) { 5242 int size = matches.size(); 5243 for (int i = 0; i < size; i++) { 5244 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5245 } 5246 } 5247 if (hasWebURI(intent)) { 5248 // cross-profile app linking works only towards the parent. 5249 final UserInfo parent = getProfileParent(sourceUserId); 5250 synchronized(mPackages) { 5251 int flags = updateFlagsForResolve(0, parent.id, intent); 5252 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5253 intent, resolvedType, flags, sourceUserId, parent.id); 5254 return xpDomainInfo != null; 5255 } 5256 } 5257 return false; 5258 } 5259 5260 private UserInfo getProfileParent(int userId) { 5261 final long identity = Binder.clearCallingIdentity(); 5262 try { 5263 return sUserManager.getProfileParent(userId); 5264 } finally { 5265 Binder.restoreCallingIdentity(identity); 5266 } 5267 } 5268 5269 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5270 String resolvedType, int userId) { 5271 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5272 if (resolver != null) { 5273 return resolver.queryIntent(intent, resolvedType, false, userId); 5274 } 5275 return null; 5276 } 5277 5278 @Override 5279 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5280 String resolvedType, int flags, int userId) { 5281 try { 5282 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5283 5284 return new ParceledListSlice<>( 5285 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5286 } finally { 5287 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5288 } 5289 } 5290 5291 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5292 String resolvedType, int flags, int userId) { 5293 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5294 flags = updateFlagsForResolve(flags, userId, intent); 5295 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5296 false /* requireFullPermission */, false /* checkShell */, 5297 "query intent activities"); 5298 ComponentName comp = intent.getComponent(); 5299 if (comp == null) { 5300 if (intent.getSelector() != null) { 5301 intent = intent.getSelector(); 5302 comp = intent.getComponent(); 5303 } 5304 } 5305 5306 if (comp != null) { 5307 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5308 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5309 if (ai != null) { 5310 final ResolveInfo ri = new ResolveInfo(); 5311 ri.activityInfo = ai; 5312 list.add(ri); 5313 } 5314 return list; 5315 } 5316 5317 // reader 5318 synchronized (mPackages) { 5319 final String pkgName = intent.getPackage(); 5320 if (pkgName == null) { 5321 List<CrossProfileIntentFilter> matchingFilters = 5322 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5323 // Check for results that need to skip the current profile. 5324 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5325 resolvedType, flags, userId); 5326 if (xpResolveInfo != null) { 5327 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5328 result.add(xpResolveInfo); 5329 return filterIfNotSystemUser(result, userId); 5330 } 5331 5332 // Check for results in the current profile. 5333 List<ResolveInfo> result = mActivities.queryIntent( 5334 intent, resolvedType, flags, userId); 5335 result = filterIfNotSystemUser(result, userId); 5336 5337 // Check for cross profile results. 5338 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5339 xpResolveInfo = queryCrossProfileIntents( 5340 matchingFilters, intent, resolvedType, flags, userId, 5341 hasNonNegativePriorityResult); 5342 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5343 boolean isVisibleToUser = filterIfNotSystemUser( 5344 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5345 if (isVisibleToUser) { 5346 result.add(xpResolveInfo); 5347 Collections.sort(result, mResolvePrioritySorter); 5348 } 5349 } 5350 if (hasWebURI(intent)) { 5351 CrossProfileDomainInfo xpDomainInfo = null; 5352 final UserInfo parent = getProfileParent(userId); 5353 if (parent != null) { 5354 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5355 flags, userId, parent.id); 5356 } 5357 if (xpDomainInfo != null) { 5358 if (xpResolveInfo != null) { 5359 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5360 // in the result. 5361 result.remove(xpResolveInfo); 5362 } 5363 if (result.size() == 0) { 5364 result.add(xpDomainInfo.resolveInfo); 5365 return result; 5366 } 5367 } else if (result.size() <= 1) { 5368 return result; 5369 } 5370 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5371 xpDomainInfo, userId); 5372 Collections.sort(result, mResolvePrioritySorter); 5373 } 5374 return result; 5375 } 5376 final PackageParser.Package pkg = mPackages.get(pkgName); 5377 if (pkg != null) { 5378 return filterIfNotSystemUser( 5379 mActivities.queryIntentForPackage( 5380 intent, resolvedType, flags, pkg.activities, userId), 5381 userId); 5382 } 5383 return new ArrayList<ResolveInfo>(); 5384 } 5385 } 5386 5387 private static class CrossProfileDomainInfo { 5388 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5389 ResolveInfo resolveInfo; 5390 /* Best domain verification status of the activities found in the other profile */ 5391 int bestDomainVerificationStatus; 5392 } 5393 5394 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5395 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5396 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5397 sourceUserId)) { 5398 return null; 5399 } 5400 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5401 resolvedType, flags, parentUserId); 5402 5403 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5404 return null; 5405 } 5406 CrossProfileDomainInfo result = null; 5407 int size = resultTargetUser.size(); 5408 for (int i = 0; i < size; i++) { 5409 ResolveInfo riTargetUser = resultTargetUser.get(i); 5410 // Intent filter verification is only for filters that specify a host. So don't return 5411 // those that handle all web uris. 5412 if (riTargetUser.handleAllWebDataURI) { 5413 continue; 5414 } 5415 String packageName = riTargetUser.activityInfo.packageName; 5416 PackageSetting ps = mSettings.mPackages.get(packageName); 5417 if (ps == null) { 5418 continue; 5419 } 5420 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5421 int status = (int)(verificationState >> 32); 5422 if (result == null) { 5423 result = new CrossProfileDomainInfo(); 5424 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5425 sourceUserId, parentUserId); 5426 result.bestDomainVerificationStatus = status; 5427 } else { 5428 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5429 result.bestDomainVerificationStatus); 5430 } 5431 } 5432 // Don't consider matches with status NEVER across profiles. 5433 if (result != null && result.bestDomainVerificationStatus 5434 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5435 return null; 5436 } 5437 return result; 5438 } 5439 5440 /** 5441 * Verification statuses are ordered from the worse to the best, except for 5442 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5443 */ 5444 private int bestDomainVerificationStatus(int status1, int status2) { 5445 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5446 return status2; 5447 } 5448 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5449 return status1; 5450 } 5451 return (int) MathUtils.max(status1, status2); 5452 } 5453 5454 private boolean isUserEnabled(int userId) { 5455 long callingId = Binder.clearCallingIdentity(); 5456 try { 5457 UserInfo userInfo = sUserManager.getUserInfo(userId); 5458 return userInfo != null && userInfo.isEnabled(); 5459 } finally { 5460 Binder.restoreCallingIdentity(callingId); 5461 } 5462 } 5463 5464 /** 5465 * Filter out activities with systemUserOnly flag set, when current user is not System. 5466 * 5467 * @return filtered list 5468 */ 5469 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5470 if (userId == UserHandle.USER_SYSTEM) { 5471 return resolveInfos; 5472 } 5473 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5474 ResolveInfo info = resolveInfos.get(i); 5475 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5476 resolveInfos.remove(i); 5477 } 5478 } 5479 return resolveInfos; 5480 } 5481 5482 /** 5483 * @param resolveInfos list of resolve infos in descending priority order 5484 * @return if the list contains a resolve info with non-negative priority 5485 */ 5486 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5487 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5488 } 5489 5490 private static boolean hasWebURI(Intent intent) { 5491 if (intent.getData() == null) { 5492 return false; 5493 } 5494 final String scheme = intent.getScheme(); 5495 if (TextUtils.isEmpty(scheme)) { 5496 return false; 5497 } 5498 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5499 } 5500 5501 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5502 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5503 int userId) { 5504 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5505 5506 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5507 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5508 candidates.size()); 5509 } 5510 5511 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5512 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5513 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5514 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5515 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5516 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5517 5518 synchronized (mPackages) { 5519 final int count = candidates.size(); 5520 // First, try to use linked apps. Partition the candidates into four lists: 5521 // one for the final results, one for the "do not use ever", one for "undefined status" 5522 // and finally one for "browser app type". 5523 for (int n=0; n<count; n++) { 5524 ResolveInfo info = candidates.get(n); 5525 String packageName = info.activityInfo.packageName; 5526 PackageSetting ps = mSettings.mPackages.get(packageName); 5527 if (ps != null) { 5528 // Add to the special match all list (Browser use case) 5529 if (info.handleAllWebDataURI) { 5530 matchAllList.add(info); 5531 continue; 5532 } 5533 // Try to get the status from User settings first 5534 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5535 int status = (int)(packedStatus >> 32); 5536 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5537 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5538 if (DEBUG_DOMAIN_VERIFICATION) { 5539 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5540 + " : linkgen=" + linkGeneration); 5541 } 5542 // Use link-enabled generation as preferredOrder, i.e. 5543 // prefer newly-enabled over earlier-enabled. 5544 info.preferredOrder = linkGeneration; 5545 alwaysList.add(info); 5546 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5547 if (DEBUG_DOMAIN_VERIFICATION) { 5548 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5549 } 5550 neverList.add(info); 5551 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5552 if (DEBUG_DOMAIN_VERIFICATION) { 5553 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5554 } 5555 alwaysAskList.add(info); 5556 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5557 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5558 if (DEBUG_DOMAIN_VERIFICATION) { 5559 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5560 } 5561 undefinedList.add(info); 5562 } 5563 } 5564 } 5565 5566 // We'll want to include browser possibilities in a few cases 5567 boolean includeBrowser = false; 5568 5569 // First try to add the "always" resolution(s) for the current user, if any 5570 if (alwaysList.size() > 0) { 5571 result.addAll(alwaysList); 5572 } else { 5573 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5574 result.addAll(undefinedList); 5575 // Maybe add one for the other profile. 5576 if (xpDomainInfo != null && ( 5577 xpDomainInfo.bestDomainVerificationStatus 5578 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5579 result.add(xpDomainInfo.resolveInfo); 5580 } 5581 includeBrowser = true; 5582 } 5583 5584 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5585 // If there were 'always' entries their preferred order has been set, so we also 5586 // back that off to make the alternatives equivalent 5587 if (alwaysAskList.size() > 0) { 5588 for (ResolveInfo i : result) { 5589 i.preferredOrder = 0; 5590 } 5591 result.addAll(alwaysAskList); 5592 includeBrowser = true; 5593 } 5594 5595 if (includeBrowser) { 5596 // Also add browsers (all of them or only the default one) 5597 if (DEBUG_DOMAIN_VERIFICATION) { 5598 Slog.v(TAG, " ...including browsers in candidate set"); 5599 } 5600 if ((matchFlags & MATCH_ALL) != 0) { 5601 result.addAll(matchAllList); 5602 } else { 5603 // Browser/generic handling case. If there's a default browser, go straight 5604 // to that (but only if there is no other higher-priority match). 5605 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5606 int maxMatchPrio = 0; 5607 ResolveInfo defaultBrowserMatch = null; 5608 final int numCandidates = matchAllList.size(); 5609 for (int n = 0; n < numCandidates; n++) { 5610 ResolveInfo info = matchAllList.get(n); 5611 // track the highest overall match priority... 5612 if (info.priority > maxMatchPrio) { 5613 maxMatchPrio = info.priority; 5614 } 5615 // ...and the highest-priority default browser match 5616 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5617 if (defaultBrowserMatch == null 5618 || (defaultBrowserMatch.priority < info.priority)) { 5619 if (debug) { 5620 Slog.v(TAG, "Considering default browser match " + info); 5621 } 5622 defaultBrowserMatch = info; 5623 } 5624 } 5625 } 5626 if (defaultBrowserMatch != null 5627 && defaultBrowserMatch.priority >= maxMatchPrio 5628 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5629 { 5630 if (debug) { 5631 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5632 } 5633 result.add(defaultBrowserMatch); 5634 } else { 5635 result.addAll(matchAllList); 5636 } 5637 } 5638 5639 // If there is nothing selected, add all candidates and remove the ones that the user 5640 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5641 if (result.size() == 0) { 5642 result.addAll(candidates); 5643 result.removeAll(neverList); 5644 } 5645 } 5646 } 5647 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5648 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5649 result.size()); 5650 for (ResolveInfo info : result) { 5651 Slog.v(TAG, " + " + info.activityInfo); 5652 } 5653 } 5654 return result; 5655 } 5656 5657 // Returns a packed value as a long: 5658 // 5659 // high 'int'-sized word: link status: undefined/ask/never/always. 5660 // low 'int'-sized word: relative priority among 'always' results. 5661 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5662 long result = ps.getDomainVerificationStatusForUser(userId); 5663 // if none available, get the master status 5664 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5665 if (ps.getIntentFilterVerificationInfo() != null) { 5666 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5667 } 5668 } 5669 return result; 5670 } 5671 5672 private ResolveInfo querySkipCurrentProfileIntents( 5673 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5674 int flags, int sourceUserId) { 5675 if (matchingFilters != null) { 5676 int size = matchingFilters.size(); 5677 for (int i = 0; i < size; i ++) { 5678 CrossProfileIntentFilter filter = matchingFilters.get(i); 5679 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5680 // Checking if there are activities in the target user that can handle the 5681 // intent. 5682 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5683 resolvedType, flags, sourceUserId); 5684 if (resolveInfo != null) { 5685 return resolveInfo; 5686 } 5687 } 5688 } 5689 } 5690 return null; 5691 } 5692 5693 // Return matching ResolveInfo in target user if any. 5694 private ResolveInfo queryCrossProfileIntents( 5695 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5696 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5697 if (matchingFilters != null) { 5698 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5699 // match the same intent. For performance reasons, it is better not to 5700 // run queryIntent twice for the same userId 5701 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5702 int size = matchingFilters.size(); 5703 for (int i = 0; i < size; i++) { 5704 CrossProfileIntentFilter filter = matchingFilters.get(i); 5705 int targetUserId = filter.getTargetUserId(); 5706 boolean skipCurrentProfile = 5707 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5708 boolean skipCurrentProfileIfNoMatchFound = 5709 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5710 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5711 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5712 // Checking if there are activities in the target user that can handle the 5713 // intent. 5714 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5715 resolvedType, flags, sourceUserId); 5716 if (resolveInfo != null) return resolveInfo; 5717 alreadyTriedUserIds.put(targetUserId, true); 5718 } 5719 } 5720 } 5721 return null; 5722 } 5723 5724 /** 5725 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5726 * will forward the intent to the filter's target user. 5727 * Otherwise, returns null. 5728 */ 5729 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5730 String resolvedType, int flags, int sourceUserId) { 5731 int targetUserId = filter.getTargetUserId(); 5732 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5733 resolvedType, flags, targetUserId); 5734 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5735 // If all the matches in the target profile are suspended, return null. 5736 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5737 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5738 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5739 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5740 targetUserId); 5741 } 5742 } 5743 } 5744 return null; 5745 } 5746 5747 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5748 int sourceUserId, int targetUserId) { 5749 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5750 long ident = Binder.clearCallingIdentity(); 5751 boolean targetIsProfile; 5752 try { 5753 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5754 } finally { 5755 Binder.restoreCallingIdentity(ident); 5756 } 5757 String className; 5758 if (targetIsProfile) { 5759 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5760 } else { 5761 className = FORWARD_INTENT_TO_PARENT; 5762 } 5763 ComponentName forwardingActivityComponentName = new ComponentName( 5764 mAndroidApplication.packageName, className); 5765 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5766 sourceUserId); 5767 if (!targetIsProfile) { 5768 forwardingActivityInfo.showUserIcon = targetUserId; 5769 forwardingResolveInfo.noResourceId = true; 5770 } 5771 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5772 forwardingResolveInfo.priority = 0; 5773 forwardingResolveInfo.preferredOrder = 0; 5774 forwardingResolveInfo.match = 0; 5775 forwardingResolveInfo.isDefault = true; 5776 forwardingResolveInfo.filter = filter; 5777 forwardingResolveInfo.targetUserId = targetUserId; 5778 return forwardingResolveInfo; 5779 } 5780 5781 @Override 5782 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5783 Intent[] specifics, String[] specificTypes, Intent intent, 5784 String resolvedType, int flags, int userId) { 5785 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5786 specificTypes, intent, resolvedType, flags, userId)); 5787 } 5788 5789 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5790 Intent[] specifics, String[] specificTypes, Intent intent, 5791 String resolvedType, int flags, int userId) { 5792 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5793 flags = updateFlagsForResolve(flags, userId, intent); 5794 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5795 false /* requireFullPermission */, false /* checkShell */, 5796 "query intent activity options"); 5797 final String resultsAction = intent.getAction(); 5798 5799 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5800 | PackageManager.GET_RESOLVED_FILTER, userId); 5801 5802 if (DEBUG_INTENT_MATCHING) { 5803 Log.v(TAG, "Query " + intent + ": " + results); 5804 } 5805 5806 int specificsPos = 0; 5807 int N; 5808 5809 // todo: note that the algorithm used here is O(N^2). This 5810 // isn't a problem in our current environment, but if we start running 5811 // into situations where we have more than 5 or 10 matches then this 5812 // should probably be changed to something smarter... 5813 5814 // First we go through and resolve each of the specific items 5815 // that were supplied, taking care of removing any corresponding 5816 // duplicate items in the generic resolve list. 5817 if (specifics != null) { 5818 for (int i=0; i<specifics.length; i++) { 5819 final Intent sintent = specifics[i]; 5820 if (sintent == null) { 5821 continue; 5822 } 5823 5824 if (DEBUG_INTENT_MATCHING) { 5825 Log.v(TAG, "Specific #" + i + ": " + sintent); 5826 } 5827 5828 String action = sintent.getAction(); 5829 if (resultsAction != null && resultsAction.equals(action)) { 5830 // If this action was explicitly requested, then don't 5831 // remove things that have it. 5832 action = null; 5833 } 5834 5835 ResolveInfo ri = null; 5836 ActivityInfo ai = null; 5837 5838 ComponentName comp = sintent.getComponent(); 5839 if (comp == null) { 5840 ri = resolveIntent( 5841 sintent, 5842 specificTypes != null ? specificTypes[i] : null, 5843 flags, userId); 5844 if (ri == null) { 5845 continue; 5846 } 5847 if (ri == mResolveInfo) { 5848 // ACK! Must do something better with this. 5849 } 5850 ai = ri.activityInfo; 5851 comp = new ComponentName(ai.applicationInfo.packageName, 5852 ai.name); 5853 } else { 5854 ai = getActivityInfo(comp, flags, userId); 5855 if (ai == null) { 5856 continue; 5857 } 5858 } 5859 5860 // Look for any generic query activities that are duplicates 5861 // of this specific one, and remove them from the results. 5862 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5863 N = results.size(); 5864 int j; 5865 for (j=specificsPos; j<N; j++) { 5866 ResolveInfo sri = results.get(j); 5867 if ((sri.activityInfo.name.equals(comp.getClassName()) 5868 && sri.activityInfo.applicationInfo.packageName.equals( 5869 comp.getPackageName())) 5870 || (action != null && sri.filter.matchAction(action))) { 5871 results.remove(j); 5872 if (DEBUG_INTENT_MATCHING) Log.v( 5873 TAG, "Removing duplicate item from " + j 5874 + " due to specific " + specificsPos); 5875 if (ri == null) { 5876 ri = sri; 5877 } 5878 j--; 5879 N--; 5880 } 5881 } 5882 5883 // Add this specific item to its proper place. 5884 if (ri == null) { 5885 ri = new ResolveInfo(); 5886 ri.activityInfo = ai; 5887 } 5888 results.add(specificsPos, ri); 5889 ri.specificIndex = i; 5890 specificsPos++; 5891 } 5892 } 5893 5894 // Now we go through the remaining generic results and remove any 5895 // duplicate actions that are found here. 5896 N = results.size(); 5897 for (int i=specificsPos; i<N-1; i++) { 5898 final ResolveInfo rii = results.get(i); 5899 if (rii.filter == null) { 5900 continue; 5901 } 5902 5903 // Iterate over all of the actions of this result's intent 5904 // filter... typically this should be just one. 5905 final Iterator<String> it = rii.filter.actionsIterator(); 5906 if (it == null) { 5907 continue; 5908 } 5909 while (it.hasNext()) { 5910 final String action = it.next(); 5911 if (resultsAction != null && resultsAction.equals(action)) { 5912 // If this action was explicitly requested, then don't 5913 // remove things that have it. 5914 continue; 5915 } 5916 for (int j=i+1; j<N; j++) { 5917 final ResolveInfo rij = results.get(j); 5918 if (rij.filter != null && rij.filter.hasAction(action)) { 5919 results.remove(j); 5920 if (DEBUG_INTENT_MATCHING) Log.v( 5921 TAG, "Removing duplicate item from " + j 5922 + " due to action " + action + " at " + i); 5923 j--; 5924 N--; 5925 } 5926 } 5927 } 5928 5929 // If the caller didn't request filter information, drop it now 5930 // so we don't have to marshall/unmarshall it. 5931 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5932 rii.filter = null; 5933 } 5934 } 5935 5936 // Filter out the caller activity if so requested. 5937 if (caller != null) { 5938 N = results.size(); 5939 for (int i=0; i<N; i++) { 5940 ActivityInfo ainfo = results.get(i).activityInfo; 5941 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5942 && caller.getClassName().equals(ainfo.name)) { 5943 results.remove(i); 5944 break; 5945 } 5946 } 5947 } 5948 5949 // If the caller didn't request filter information, 5950 // drop them now so we don't have to 5951 // marshall/unmarshall it. 5952 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5953 N = results.size(); 5954 for (int i=0; i<N; i++) { 5955 results.get(i).filter = null; 5956 } 5957 } 5958 5959 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5960 return results; 5961 } 5962 5963 @Override 5964 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5965 String resolvedType, int flags, int userId) { 5966 return new ParceledListSlice<>( 5967 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5968 } 5969 5970 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5971 String resolvedType, int flags, int userId) { 5972 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5973 flags = updateFlagsForResolve(flags, userId, intent); 5974 ComponentName comp = intent.getComponent(); 5975 if (comp == null) { 5976 if (intent.getSelector() != null) { 5977 intent = intent.getSelector(); 5978 comp = intent.getComponent(); 5979 } 5980 } 5981 if (comp != null) { 5982 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5983 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5984 if (ai != null) { 5985 ResolveInfo ri = new ResolveInfo(); 5986 ri.activityInfo = ai; 5987 list.add(ri); 5988 } 5989 return list; 5990 } 5991 5992 // reader 5993 synchronized (mPackages) { 5994 String pkgName = intent.getPackage(); 5995 if (pkgName == null) { 5996 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5997 } 5998 final PackageParser.Package pkg = mPackages.get(pkgName); 5999 if (pkg != null) { 6000 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6001 userId); 6002 } 6003 return Collections.emptyList(); 6004 } 6005 } 6006 6007 @Override 6008 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6009 if (!sUserManager.exists(userId)) return null; 6010 flags = updateFlagsForResolve(flags, userId, intent); 6011 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6012 if (query != null) { 6013 if (query.size() >= 1) { 6014 // If there is more than one service with the same priority, 6015 // just arbitrarily pick the first one. 6016 return query.get(0); 6017 } 6018 } 6019 return null; 6020 } 6021 6022 @Override 6023 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6024 String resolvedType, int flags, int userId) { 6025 return new ParceledListSlice<>( 6026 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6027 } 6028 6029 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6030 String resolvedType, int flags, int userId) { 6031 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6032 flags = updateFlagsForResolve(flags, userId, intent); 6033 ComponentName comp = intent.getComponent(); 6034 if (comp == null) { 6035 if (intent.getSelector() != null) { 6036 intent = intent.getSelector(); 6037 comp = intent.getComponent(); 6038 } 6039 } 6040 if (comp != null) { 6041 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6042 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6043 if (si != null) { 6044 final ResolveInfo ri = new ResolveInfo(); 6045 ri.serviceInfo = si; 6046 list.add(ri); 6047 } 6048 return list; 6049 } 6050 6051 // reader 6052 synchronized (mPackages) { 6053 String pkgName = intent.getPackage(); 6054 if (pkgName == null) { 6055 return mServices.queryIntent(intent, resolvedType, flags, userId); 6056 } 6057 final PackageParser.Package pkg = mPackages.get(pkgName); 6058 if (pkg != null) { 6059 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6060 userId); 6061 } 6062 return Collections.emptyList(); 6063 } 6064 } 6065 6066 @Override 6067 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6068 String resolvedType, int flags, int userId) { 6069 return new ParceledListSlice<>( 6070 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6071 } 6072 6073 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6074 Intent intent, String resolvedType, int flags, int userId) { 6075 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6076 flags = updateFlagsForResolve(flags, userId, intent); 6077 ComponentName comp = intent.getComponent(); 6078 if (comp == null) { 6079 if (intent.getSelector() != null) { 6080 intent = intent.getSelector(); 6081 comp = intent.getComponent(); 6082 } 6083 } 6084 if (comp != null) { 6085 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6086 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6087 if (pi != null) { 6088 final ResolveInfo ri = new ResolveInfo(); 6089 ri.providerInfo = pi; 6090 list.add(ri); 6091 } 6092 return list; 6093 } 6094 6095 // reader 6096 synchronized (mPackages) { 6097 String pkgName = intent.getPackage(); 6098 if (pkgName == null) { 6099 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6100 } 6101 final PackageParser.Package pkg = mPackages.get(pkgName); 6102 if (pkg != null) { 6103 return mProviders.queryIntentForPackage( 6104 intent, resolvedType, flags, pkg.providers, userId); 6105 } 6106 return Collections.emptyList(); 6107 } 6108 } 6109 6110 @Override 6111 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6112 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6113 flags = updateFlagsForPackage(flags, userId, null); 6114 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6115 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6116 true /* requireFullPermission */, false /* checkShell */, 6117 "get installed packages"); 6118 6119 // writer 6120 synchronized (mPackages) { 6121 ArrayList<PackageInfo> list; 6122 if (listUninstalled) { 6123 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6124 for (PackageSetting ps : mSettings.mPackages.values()) { 6125 final PackageInfo pi; 6126 if (ps.pkg != null) { 6127 pi = generatePackageInfo(ps, flags, userId); 6128 } else { 6129 pi = generatePackageInfo(ps, flags, userId); 6130 } 6131 if (pi != null) { 6132 list.add(pi); 6133 } 6134 } 6135 } else { 6136 list = new ArrayList<PackageInfo>(mPackages.size()); 6137 for (PackageParser.Package p : mPackages.values()) { 6138 final PackageInfo pi = 6139 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6140 if (pi != null) { 6141 list.add(pi); 6142 } 6143 } 6144 } 6145 6146 return new ParceledListSlice<PackageInfo>(list); 6147 } 6148 } 6149 6150 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6151 String[] permissions, boolean[] tmp, int flags, int userId) { 6152 int numMatch = 0; 6153 final PermissionsState permissionsState = ps.getPermissionsState(); 6154 for (int i=0; i<permissions.length; i++) { 6155 final String permission = permissions[i]; 6156 if (permissionsState.hasPermission(permission, userId)) { 6157 tmp[i] = true; 6158 numMatch++; 6159 } else { 6160 tmp[i] = false; 6161 } 6162 } 6163 if (numMatch == 0) { 6164 return; 6165 } 6166 final PackageInfo pi; 6167 if (ps.pkg != null) { 6168 pi = generatePackageInfo(ps, flags, userId); 6169 } else { 6170 pi = generatePackageInfo(ps, flags, userId); 6171 } 6172 // The above might return null in cases of uninstalled apps or install-state 6173 // skew across users/profiles. 6174 if (pi != null) { 6175 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6176 if (numMatch == permissions.length) { 6177 pi.requestedPermissions = permissions; 6178 } else { 6179 pi.requestedPermissions = new String[numMatch]; 6180 numMatch = 0; 6181 for (int i=0; i<permissions.length; i++) { 6182 if (tmp[i]) { 6183 pi.requestedPermissions[numMatch] = permissions[i]; 6184 numMatch++; 6185 } 6186 } 6187 } 6188 } 6189 list.add(pi); 6190 } 6191 } 6192 6193 @Override 6194 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6195 String[] permissions, int flags, int userId) { 6196 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6197 flags = updateFlagsForPackage(flags, userId, permissions); 6198 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6199 6200 // writer 6201 synchronized (mPackages) { 6202 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6203 boolean[] tmpBools = new boolean[permissions.length]; 6204 if (listUninstalled) { 6205 for (PackageSetting ps : mSettings.mPackages.values()) { 6206 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6207 } 6208 } else { 6209 for (PackageParser.Package pkg : mPackages.values()) { 6210 PackageSetting ps = (PackageSetting)pkg.mExtras; 6211 if (ps != null) { 6212 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6213 userId); 6214 } 6215 } 6216 } 6217 6218 return new ParceledListSlice<PackageInfo>(list); 6219 } 6220 } 6221 6222 @Override 6223 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6224 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6225 flags = updateFlagsForApplication(flags, userId, null); 6226 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6227 6228 // writer 6229 synchronized (mPackages) { 6230 ArrayList<ApplicationInfo> list; 6231 if (listUninstalled) { 6232 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6233 for (PackageSetting ps : mSettings.mPackages.values()) { 6234 ApplicationInfo ai; 6235 if (ps.pkg != null) { 6236 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6237 ps.readUserState(userId), userId); 6238 } else { 6239 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6240 } 6241 if (ai != null) { 6242 list.add(ai); 6243 } 6244 } 6245 } else { 6246 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6247 for (PackageParser.Package p : mPackages.values()) { 6248 if (p.mExtras != null) { 6249 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6250 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6251 if (ai != null) { 6252 list.add(ai); 6253 } 6254 } 6255 } 6256 } 6257 6258 return new ParceledListSlice<ApplicationInfo>(list); 6259 } 6260 } 6261 6262 @Override 6263 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6264 if (DISABLE_EPHEMERAL_APPS) { 6265 return null; 6266 } 6267 6268 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6269 "getEphemeralApplications"); 6270 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6271 true /* requireFullPermission */, false /* checkShell */, 6272 "getEphemeralApplications"); 6273 synchronized (mPackages) { 6274 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6275 .getEphemeralApplicationsLPw(userId); 6276 if (ephemeralApps != null) { 6277 return new ParceledListSlice<>(ephemeralApps); 6278 } 6279 } 6280 return null; 6281 } 6282 6283 @Override 6284 public boolean isEphemeralApplication(String packageName, int userId) { 6285 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6286 true /* requireFullPermission */, false /* checkShell */, 6287 "isEphemeral"); 6288 if (DISABLE_EPHEMERAL_APPS) { 6289 return false; 6290 } 6291 6292 if (!isCallerSameApp(packageName)) { 6293 return false; 6294 } 6295 synchronized (mPackages) { 6296 PackageParser.Package pkg = mPackages.get(packageName); 6297 if (pkg != null) { 6298 return pkg.applicationInfo.isEphemeralApp(); 6299 } 6300 } 6301 return false; 6302 } 6303 6304 @Override 6305 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6306 if (DISABLE_EPHEMERAL_APPS) { 6307 return null; 6308 } 6309 6310 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6311 true /* requireFullPermission */, false /* checkShell */, 6312 "getCookie"); 6313 if (!isCallerSameApp(packageName)) { 6314 return null; 6315 } 6316 synchronized (mPackages) { 6317 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6318 packageName, userId); 6319 } 6320 } 6321 6322 @Override 6323 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6324 if (DISABLE_EPHEMERAL_APPS) { 6325 return true; 6326 } 6327 6328 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6329 true /* requireFullPermission */, true /* checkShell */, 6330 "setCookie"); 6331 if (!isCallerSameApp(packageName)) { 6332 return false; 6333 } 6334 synchronized (mPackages) { 6335 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6336 packageName, cookie, userId); 6337 } 6338 } 6339 6340 @Override 6341 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6342 if (DISABLE_EPHEMERAL_APPS) { 6343 return null; 6344 } 6345 6346 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6347 "getEphemeralApplicationIcon"); 6348 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6349 true /* requireFullPermission */, false /* checkShell */, 6350 "getEphemeralApplicationIcon"); 6351 synchronized (mPackages) { 6352 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6353 packageName, userId); 6354 } 6355 } 6356 6357 private boolean isCallerSameApp(String packageName) { 6358 PackageParser.Package pkg = mPackages.get(packageName); 6359 return pkg != null 6360 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6361 } 6362 6363 @Override 6364 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6365 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6366 } 6367 6368 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6369 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6370 6371 // reader 6372 synchronized (mPackages) { 6373 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6374 final int userId = UserHandle.getCallingUserId(); 6375 while (i.hasNext()) { 6376 final PackageParser.Package p = i.next(); 6377 if (p.applicationInfo == null) continue; 6378 6379 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6380 && !p.applicationInfo.isDirectBootAware(); 6381 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6382 && p.applicationInfo.isDirectBootAware(); 6383 6384 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6385 && (!mSafeMode || isSystemApp(p)) 6386 && (matchesUnaware || matchesAware)) { 6387 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6388 if (ps != null) { 6389 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6390 ps.readUserState(userId), userId); 6391 if (ai != null) { 6392 finalList.add(ai); 6393 } 6394 } 6395 } 6396 } 6397 } 6398 6399 return finalList; 6400 } 6401 6402 @Override 6403 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6404 if (!sUserManager.exists(userId)) return null; 6405 flags = updateFlagsForComponent(flags, userId, name); 6406 // reader 6407 synchronized (mPackages) { 6408 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6409 PackageSetting ps = provider != null 6410 ? mSettings.mPackages.get(provider.owner.packageName) 6411 : null; 6412 return ps != null 6413 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6414 ? PackageParser.generateProviderInfo(provider, flags, 6415 ps.readUserState(userId), userId) 6416 : null; 6417 } 6418 } 6419 6420 /** 6421 * @deprecated 6422 */ 6423 @Deprecated 6424 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6425 // reader 6426 synchronized (mPackages) { 6427 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6428 .entrySet().iterator(); 6429 final int userId = UserHandle.getCallingUserId(); 6430 while (i.hasNext()) { 6431 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6432 PackageParser.Provider p = entry.getValue(); 6433 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6434 6435 if (ps != null && p.syncable 6436 && (!mSafeMode || (p.info.applicationInfo.flags 6437 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6438 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6439 ps.readUserState(userId), userId); 6440 if (info != null) { 6441 outNames.add(entry.getKey()); 6442 outInfo.add(info); 6443 } 6444 } 6445 } 6446 } 6447 } 6448 6449 @Override 6450 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6451 int uid, int flags) { 6452 final int userId = processName != null ? UserHandle.getUserId(uid) 6453 : UserHandle.getCallingUserId(); 6454 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6455 flags = updateFlagsForComponent(flags, userId, processName); 6456 6457 ArrayList<ProviderInfo> finalList = null; 6458 // reader 6459 synchronized (mPackages) { 6460 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6461 while (i.hasNext()) { 6462 final PackageParser.Provider p = i.next(); 6463 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6464 if (ps != null && p.info.authority != null 6465 && (processName == null 6466 || (p.info.processName.equals(processName) 6467 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6468 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6469 if (finalList == null) { 6470 finalList = new ArrayList<ProviderInfo>(3); 6471 } 6472 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6473 ps.readUserState(userId), userId); 6474 if (info != null) { 6475 finalList.add(info); 6476 } 6477 } 6478 } 6479 } 6480 6481 if (finalList != null) { 6482 Collections.sort(finalList, mProviderInitOrderSorter); 6483 return new ParceledListSlice<ProviderInfo>(finalList); 6484 } 6485 6486 return ParceledListSlice.emptyList(); 6487 } 6488 6489 @Override 6490 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6491 // reader 6492 synchronized (mPackages) { 6493 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6494 return PackageParser.generateInstrumentationInfo(i, flags); 6495 } 6496 } 6497 6498 @Override 6499 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6500 String targetPackage, int flags) { 6501 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6502 } 6503 6504 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6505 int flags) { 6506 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6507 6508 // reader 6509 synchronized (mPackages) { 6510 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6511 while (i.hasNext()) { 6512 final PackageParser.Instrumentation p = i.next(); 6513 if (targetPackage == null 6514 || targetPackage.equals(p.info.targetPackage)) { 6515 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6516 flags); 6517 if (ii != null) { 6518 finalList.add(ii); 6519 } 6520 } 6521 } 6522 } 6523 6524 return finalList; 6525 } 6526 6527 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6528 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6529 if (overlays == null) { 6530 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6531 return; 6532 } 6533 for (PackageParser.Package opkg : overlays.values()) { 6534 // Not much to do if idmap fails: we already logged the error 6535 // and we certainly don't want to abort installation of pkg simply 6536 // because an overlay didn't fit properly. For these reasons, 6537 // ignore the return value of createIdmapForPackagePairLI. 6538 createIdmapForPackagePairLI(pkg, opkg); 6539 } 6540 } 6541 6542 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6543 PackageParser.Package opkg) { 6544 if (!opkg.mTrustedOverlay) { 6545 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6546 opkg.baseCodePath + ": overlay not trusted"); 6547 return false; 6548 } 6549 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6550 if (overlaySet == null) { 6551 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6552 opkg.baseCodePath + " but target package has no known overlays"); 6553 return false; 6554 } 6555 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6556 // TODO: generate idmap for split APKs 6557 try { 6558 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6559 } catch (InstallerException e) { 6560 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6561 + opkg.baseCodePath); 6562 return false; 6563 } 6564 PackageParser.Package[] overlayArray = 6565 overlaySet.values().toArray(new PackageParser.Package[0]); 6566 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6567 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6568 return p1.mOverlayPriority - p2.mOverlayPriority; 6569 } 6570 }; 6571 Arrays.sort(overlayArray, cmp); 6572 6573 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6574 int i = 0; 6575 for (PackageParser.Package p : overlayArray) { 6576 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6577 } 6578 return true; 6579 } 6580 6581 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6582 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6583 try { 6584 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6585 } finally { 6586 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6587 } 6588 } 6589 6590 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6591 final File[] files = dir.listFiles(); 6592 if (ArrayUtils.isEmpty(files)) { 6593 Log.d(TAG, "No files in app dir " + dir); 6594 return; 6595 } 6596 6597 if (DEBUG_PACKAGE_SCANNING) { 6598 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6599 + " flags=0x" + Integer.toHexString(parseFlags)); 6600 } 6601 6602 for (File file : files) { 6603 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6604 && !PackageInstallerService.isStageName(file.getName()); 6605 if (!isPackage) { 6606 // Ignore entries which are not packages 6607 continue; 6608 } 6609 try { 6610 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6611 scanFlags, currentTime, null); 6612 } catch (PackageManagerException e) { 6613 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6614 6615 // Delete invalid userdata apps 6616 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6617 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6618 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6619 removeCodePathLI(file); 6620 } 6621 } 6622 } 6623 } 6624 6625 private static File getSettingsProblemFile() { 6626 File dataDir = Environment.getDataDirectory(); 6627 File systemDir = new File(dataDir, "system"); 6628 File fname = new File(systemDir, "uiderrors.txt"); 6629 return fname; 6630 } 6631 6632 static void reportSettingsProblem(int priority, String msg) { 6633 logCriticalInfo(priority, msg); 6634 } 6635 6636 static void logCriticalInfo(int priority, String msg) { 6637 Slog.println(priority, TAG, msg); 6638 EventLogTags.writePmCriticalInfo(msg); 6639 try { 6640 File fname = getSettingsProblemFile(); 6641 FileOutputStream out = new FileOutputStream(fname, true); 6642 PrintWriter pw = new FastPrintWriter(out); 6643 SimpleDateFormat formatter = new SimpleDateFormat(); 6644 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6645 pw.println(dateString + ": " + msg); 6646 pw.close(); 6647 FileUtils.setPermissions( 6648 fname.toString(), 6649 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6650 -1, -1); 6651 } catch (java.io.IOException e) { 6652 } 6653 } 6654 6655 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6656 final int policyFlags) throws PackageManagerException { 6657 if (ps != null 6658 && ps.codePath.equals(srcFile) 6659 && ps.timeStamp == srcFile.lastModified() 6660 && !isCompatSignatureUpdateNeeded(pkg) 6661 && !isRecoverSignatureUpdateNeeded(pkg)) { 6662 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6663 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6664 ArraySet<PublicKey> signingKs; 6665 synchronized (mPackages) { 6666 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6667 } 6668 if (ps.signatures.mSignatures != null 6669 && ps.signatures.mSignatures.length != 0 6670 && signingKs != null) { 6671 // Optimization: reuse the existing cached certificates 6672 // if the package appears to be unchanged. 6673 pkg.mSignatures = ps.signatures.mSignatures; 6674 pkg.mSigningKeys = signingKs; 6675 return; 6676 } 6677 6678 Slog.w(TAG, "PackageSetting for " + ps.name 6679 + " is missing signatures. Collecting certs again to recover them."); 6680 } else { 6681 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6682 } 6683 6684 try { 6685 PackageParser.collectCertificates(pkg, policyFlags); 6686 } catch (PackageParserException e) { 6687 throw PackageManagerException.from(e); 6688 } 6689 } 6690 6691 /** 6692 * Traces a package scan. 6693 * @see #scanPackageLI(File, int, int, long, UserHandle) 6694 */ 6695 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6696 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6697 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6698 try { 6699 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6700 } finally { 6701 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6702 } 6703 } 6704 6705 /** 6706 * Scans a package and returns the newly parsed package. 6707 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6708 */ 6709 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6710 long currentTime, UserHandle user) throws PackageManagerException { 6711 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6712 PackageParser pp = new PackageParser(); 6713 pp.setSeparateProcesses(mSeparateProcesses); 6714 pp.setOnlyCoreApps(mOnlyCore); 6715 pp.setDisplayMetrics(mMetrics); 6716 6717 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6718 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6719 } 6720 6721 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6722 final PackageParser.Package pkg; 6723 try { 6724 pkg = pp.parsePackage(scanFile, parseFlags); 6725 } catch (PackageParserException e) { 6726 throw PackageManagerException.from(e); 6727 } finally { 6728 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6729 } 6730 6731 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6732 } 6733 6734 /** 6735 * Scans a package and returns the newly parsed package. 6736 * @throws PackageManagerException on a parse error. 6737 */ 6738 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6739 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6740 throws PackageManagerException { 6741 // If the package has children and this is the first dive in the function 6742 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6743 // packages (parent and children) would be successfully scanned before the 6744 // actual scan since scanning mutates internal state and we want to atomically 6745 // install the package and its children. 6746 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6747 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6748 scanFlags |= SCAN_CHECK_ONLY; 6749 } 6750 } else { 6751 scanFlags &= ~SCAN_CHECK_ONLY; 6752 } 6753 6754 // Scan the parent 6755 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6756 scanFlags, currentTime, user); 6757 6758 // Scan the children 6759 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6760 for (int i = 0; i < childCount; i++) { 6761 PackageParser.Package childPackage = pkg.childPackages.get(i); 6762 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6763 currentTime, user); 6764 } 6765 6766 6767 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6768 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6769 } 6770 6771 return scannedPkg; 6772 } 6773 6774 /** 6775 * Scans a package and returns the newly parsed package. 6776 * @throws PackageManagerException on a parse error. 6777 */ 6778 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6779 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6780 throws PackageManagerException { 6781 PackageSetting ps = null; 6782 PackageSetting updatedPkg; 6783 // reader 6784 synchronized (mPackages) { 6785 // Look to see if we already know about this package. 6786 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6787 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6788 // This package has been renamed to its original name. Let's 6789 // use that. 6790 ps = mSettings.peekPackageLPr(oldName); 6791 } 6792 // If there was no original package, see one for the real package name. 6793 if (ps == null) { 6794 ps = mSettings.peekPackageLPr(pkg.packageName); 6795 } 6796 // Check to see if this package could be hiding/updating a system 6797 // package. Must look for it either under the original or real 6798 // package name depending on our state. 6799 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6800 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6801 6802 // If this is a package we don't know about on the system partition, we 6803 // may need to remove disabled child packages on the system partition 6804 // or may need to not add child packages if the parent apk is updated 6805 // on the data partition and no longer defines this child package. 6806 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6807 // If this is a parent package for an updated system app and this system 6808 // app got an OTA update which no longer defines some of the child packages 6809 // we have to prune them from the disabled system packages. 6810 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6811 if (disabledPs != null) { 6812 final int scannedChildCount = (pkg.childPackages != null) 6813 ? pkg.childPackages.size() : 0; 6814 final int disabledChildCount = disabledPs.childPackageNames != null 6815 ? disabledPs.childPackageNames.size() : 0; 6816 for (int i = 0; i < disabledChildCount; i++) { 6817 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6818 boolean disabledPackageAvailable = false; 6819 for (int j = 0; j < scannedChildCount; j++) { 6820 PackageParser.Package childPkg = pkg.childPackages.get(j); 6821 if (childPkg.packageName.equals(disabledChildPackageName)) { 6822 disabledPackageAvailable = true; 6823 break; 6824 } 6825 } 6826 if (!disabledPackageAvailable) { 6827 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6828 } 6829 } 6830 } 6831 } 6832 } 6833 6834 boolean updatedPkgBetter = false; 6835 // First check if this is a system package that may involve an update 6836 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6837 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6838 // it needs to drop FLAG_PRIVILEGED. 6839 if (locationIsPrivileged(scanFile)) { 6840 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6841 } else { 6842 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6843 } 6844 6845 if (ps != null && !ps.codePath.equals(scanFile)) { 6846 // The path has changed from what was last scanned... check the 6847 // version of the new path against what we have stored to determine 6848 // what to do. 6849 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6850 if (pkg.mVersionCode <= ps.versionCode) { 6851 // The system package has been updated and the code path does not match 6852 // Ignore entry. Skip it. 6853 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6854 + " ignored: updated version " + ps.versionCode 6855 + " better than this " + pkg.mVersionCode); 6856 if (!updatedPkg.codePath.equals(scanFile)) { 6857 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6858 + ps.name + " changing from " + updatedPkg.codePathString 6859 + " to " + scanFile); 6860 updatedPkg.codePath = scanFile; 6861 updatedPkg.codePathString = scanFile.toString(); 6862 updatedPkg.resourcePath = scanFile; 6863 updatedPkg.resourcePathString = scanFile.toString(); 6864 } 6865 updatedPkg.pkg = pkg; 6866 updatedPkg.versionCode = pkg.mVersionCode; 6867 6868 // Update the disabled system child packages to point to the package too. 6869 final int childCount = updatedPkg.childPackageNames != null 6870 ? updatedPkg.childPackageNames.size() : 0; 6871 for (int i = 0; i < childCount; i++) { 6872 String childPackageName = updatedPkg.childPackageNames.get(i); 6873 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6874 childPackageName); 6875 if (updatedChildPkg != null) { 6876 updatedChildPkg.pkg = pkg; 6877 updatedChildPkg.versionCode = pkg.mVersionCode; 6878 } 6879 } 6880 6881 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6882 + scanFile + " ignored: updated version " + ps.versionCode 6883 + " better than this " + pkg.mVersionCode); 6884 } else { 6885 // The current app on the system partition is better than 6886 // what we have updated to on the data partition; switch 6887 // back to the system partition version. 6888 // At this point, its safely assumed that package installation for 6889 // apps in system partition will go through. If not there won't be a working 6890 // version of the app 6891 // writer 6892 synchronized (mPackages) { 6893 // Just remove the loaded entries from package lists. 6894 mPackages.remove(ps.name); 6895 } 6896 6897 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6898 + " reverting from " + ps.codePathString 6899 + ": new version " + pkg.mVersionCode 6900 + " better than installed " + ps.versionCode); 6901 6902 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6903 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6904 synchronized (mInstallLock) { 6905 args.cleanUpResourcesLI(); 6906 } 6907 synchronized (mPackages) { 6908 mSettings.enableSystemPackageLPw(ps.name); 6909 } 6910 updatedPkgBetter = true; 6911 } 6912 } 6913 } 6914 6915 if (updatedPkg != null) { 6916 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6917 // initially 6918 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6919 6920 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6921 // flag set initially 6922 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6923 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6924 } 6925 } 6926 6927 // Verify certificates against what was last scanned 6928 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6929 6930 /* 6931 * A new system app appeared, but we already had a non-system one of the 6932 * same name installed earlier. 6933 */ 6934 boolean shouldHideSystemApp = false; 6935 if (updatedPkg == null && ps != null 6936 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6937 /* 6938 * Check to make sure the signatures match first. If they don't, 6939 * wipe the installed application and its data. 6940 */ 6941 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6942 != PackageManager.SIGNATURE_MATCH) { 6943 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6944 + " signatures don't match existing userdata copy; removing"); 6945 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6946 "scanPackageInternalLI")) { 6947 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6948 } 6949 ps = null; 6950 } else { 6951 /* 6952 * If the newly-added system app is an older version than the 6953 * already installed version, hide it. It will be scanned later 6954 * and re-added like an update. 6955 */ 6956 if (pkg.mVersionCode <= ps.versionCode) { 6957 shouldHideSystemApp = true; 6958 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6959 + " but new version " + pkg.mVersionCode + " better than installed " 6960 + ps.versionCode + "; hiding system"); 6961 } else { 6962 /* 6963 * The newly found system app is a newer version that the 6964 * one previously installed. Simply remove the 6965 * already-installed application and replace it with our own 6966 * while keeping the application data. 6967 */ 6968 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6969 + " reverting from " + ps.codePathString + ": new version " 6970 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6971 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6972 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6973 synchronized (mInstallLock) { 6974 args.cleanUpResourcesLI(); 6975 } 6976 } 6977 } 6978 } 6979 6980 // The apk is forward locked (not public) if its code and resources 6981 // are kept in different files. (except for app in either system or 6982 // vendor path). 6983 // TODO grab this value from PackageSettings 6984 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6985 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6986 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6987 } 6988 } 6989 6990 // TODO: extend to support forward-locked splits 6991 String resourcePath = null; 6992 String baseResourcePath = null; 6993 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6994 if (ps != null && ps.resourcePathString != null) { 6995 resourcePath = ps.resourcePathString; 6996 baseResourcePath = ps.resourcePathString; 6997 } else { 6998 // Should not happen at all. Just log an error. 6999 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7000 } 7001 } else { 7002 resourcePath = pkg.codePath; 7003 baseResourcePath = pkg.baseCodePath; 7004 } 7005 7006 // Set application objects path explicitly. 7007 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7008 pkg.setApplicationInfoCodePath(pkg.codePath); 7009 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7010 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7011 pkg.setApplicationInfoResourcePath(resourcePath); 7012 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7013 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7014 7015 // Note that we invoke the following method only if we are about to unpack an application 7016 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7017 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7018 7019 /* 7020 * If the system app should be overridden by a previously installed 7021 * data, hide the system app now and let the /data/app scan pick it up 7022 * again. 7023 */ 7024 if (shouldHideSystemApp) { 7025 synchronized (mPackages) { 7026 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7027 } 7028 } 7029 7030 return scannedPkg; 7031 } 7032 7033 private static String fixProcessName(String defProcessName, 7034 String processName, int uid) { 7035 if (processName == null) { 7036 return defProcessName; 7037 } 7038 return processName; 7039 } 7040 7041 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7042 throws PackageManagerException { 7043 if (pkgSetting.signatures.mSignatures != null) { 7044 // Already existing package. Make sure signatures match 7045 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7046 == PackageManager.SIGNATURE_MATCH; 7047 if (!match) { 7048 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7049 == PackageManager.SIGNATURE_MATCH; 7050 } 7051 if (!match) { 7052 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7053 == PackageManager.SIGNATURE_MATCH; 7054 } 7055 if (!match) { 7056 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7057 + pkg.packageName + " signatures do not match the " 7058 + "previously installed version; ignoring!"); 7059 } 7060 } 7061 7062 // Check for shared user signatures 7063 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7064 // Already existing package. Make sure signatures match 7065 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7066 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7067 if (!match) { 7068 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7069 == PackageManager.SIGNATURE_MATCH; 7070 } 7071 if (!match) { 7072 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7073 == PackageManager.SIGNATURE_MATCH; 7074 } 7075 if (!match) { 7076 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7077 "Package " + pkg.packageName 7078 + " has no signatures that match those in shared user " 7079 + pkgSetting.sharedUser.name + "; ignoring!"); 7080 } 7081 } 7082 } 7083 7084 /** 7085 * Enforces that only the system UID or root's UID can call a method exposed 7086 * via Binder. 7087 * 7088 * @param message used as message if SecurityException is thrown 7089 * @throws SecurityException if the caller is not system or root 7090 */ 7091 private static final void enforceSystemOrRoot(String message) { 7092 final int uid = Binder.getCallingUid(); 7093 if (uid != Process.SYSTEM_UID && uid != 0) { 7094 throw new SecurityException(message); 7095 } 7096 } 7097 7098 @Override 7099 public void performFstrimIfNeeded() { 7100 enforceSystemOrRoot("Only the system can request fstrim"); 7101 7102 // Before everything else, see whether we need to fstrim. 7103 try { 7104 IMountService ms = PackageHelper.getMountService(); 7105 if (ms != null) { 7106 final boolean isUpgrade = isUpgrade(); 7107 boolean doTrim = isUpgrade; 7108 if (doTrim) { 7109 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7110 } else { 7111 final long interval = android.provider.Settings.Global.getLong( 7112 mContext.getContentResolver(), 7113 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7114 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7115 if (interval > 0) { 7116 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7117 if (timeSinceLast > interval) { 7118 doTrim = true; 7119 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7120 + "; running immediately"); 7121 } 7122 } 7123 } 7124 if (doTrim) { 7125 if (!isFirstBoot()) { 7126 try { 7127 ActivityManagerNative.getDefault().showBootMessage( 7128 mContext.getResources().getString( 7129 R.string.android_upgrading_fstrim), true); 7130 } catch (RemoteException e) { 7131 } 7132 } 7133 ms.runMaintenance(); 7134 } 7135 } else { 7136 Slog.e(TAG, "Mount service unavailable!"); 7137 } 7138 } catch (RemoteException e) { 7139 // Can't happen; MountService is local 7140 } 7141 } 7142 7143 @Override 7144 public void updatePackagesIfNeeded() { 7145 enforceSystemOrRoot("Only the system can request package update"); 7146 7147 // We need to re-extract after an OTA. 7148 boolean causeUpgrade = isUpgrade(); 7149 7150 // First boot or factory reset. 7151 // Note: we also handle devices that are upgrading to N right now as if it is their 7152 // first boot, as they do not have profile data. 7153 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7154 7155 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7156 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7157 7158 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7159 return; 7160 } 7161 7162 List<PackageParser.Package> pkgs; 7163 synchronized (mPackages) { 7164 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7165 } 7166 7167 int numberOfPackagesVisited = 0; 7168 int numberOfPackagesOptimized = 0; 7169 int numberOfPackagesSkipped = 0; 7170 int numberOfPackagesFailed = 0; 7171 final int numberOfPackagesToDexopt = pkgs.size(); 7172 final long startTime = System.nanoTime(); 7173 7174 for (PackageParser.Package pkg : pkgs) { 7175 numberOfPackagesVisited++; 7176 7177 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7178 if (DEBUG_DEXOPT) { 7179 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7180 } 7181 numberOfPackagesSkipped++; 7182 continue; 7183 } 7184 7185 if (DEBUG_DEXOPT) { 7186 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7187 numberOfPackagesToDexopt + ": " + pkg.packageName); 7188 } 7189 7190 if (!isFirstBoot()) { 7191 try { 7192 ActivityManagerNative.getDefault().showBootMessage( 7193 mContext.getResources().getString(R.string.android_upgrading_apk, 7194 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7195 } catch (RemoteException e) { 7196 } 7197 } 7198 7199 int dexOptStatus = performDexOptTraced(pkg.packageName, 7200 null /* instructionSet */, 7201 true /* checkProfiles */, 7202 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7203 false /* force */); 7204 switch (dexOptStatus) { 7205 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7206 numberOfPackagesOptimized++; 7207 break; 7208 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7209 numberOfPackagesSkipped++; 7210 break; 7211 case PackageDexOptimizer.DEX_OPT_FAILED: 7212 numberOfPackagesFailed++; 7213 break; 7214 default: 7215 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7216 break; 7217 } 7218 } 7219 7220 final int elapsedTime = (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); 7221 MetricsLogger.action(mContext, 7222 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_DEXOPTED, numberOfPackagesOptimized); 7223 MetricsLogger.action(mContext, 7224 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_SKIPPED, numberOfPackagesSkipped); 7225 MetricsLogger.action(mContext, 7226 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_FAILED, numberOfPackagesFailed); 7227 MetricsLogger.action(mContext, 7228 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_TOTAL, getOptimizablePackages().size()); 7229 MetricsLogger.action(mContext, 7230 MetricsEvent.OPTIMIZING_APPS_TOTAL_TIME_MS, elapsedTime); 7231 } 7232 7233 @Override 7234 public void notifyPackageUse(String packageName, int reason) { 7235 synchronized (mPackages) { 7236 PackageParser.Package p = mPackages.get(packageName); 7237 if (p == null) { 7238 return; 7239 } 7240 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7241 } 7242 } 7243 7244 // TODO: this is not used nor needed. Delete it. 7245 @Override 7246 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7247 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7248 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7249 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7250 } 7251 7252 @Override 7253 public boolean performDexOpt(String packageName, String instructionSet, 7254 boolean checkProfiles, int compileReason, boolean force) { 7255 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7256 getCompilerFilterForReason(compileReason), force); 7257 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7258 } 7259 7260 @Override 7261 public boolean performDexOptMode(String packageName, String instructionSet, 7262 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7263 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7264 targetCompilerFilter, force); 7265 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7266 } 7267 7268 private int performDexOptTraced(String packageName, String instructionSet, 7269 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7270 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7271 try { 7272 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7273 targetCompilerFilter, force); 7274 } finally { 7275 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7276 } 7277 } 7278 7279 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7280 // if the package can now be considered up to date for the given filter. 7281 private int performDexOptInternal(String packageName, String instructionSet, 7282 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7283 PackageParser.Package p; 7284 final String targetInstructionSet; 7285 synchronized (mPackages) { 7286 p = mPackages.get(packageName); 7287 if (p == null) { 7288 // Package could not be found. Report failure. 7289 return PackageDexOptimizer.DEX_OPT_FAILED; 7290 } 7291 mPackageUsage.write(false); 7292 7293 targetInstructionSet = instructionSet != null ? instructionSet : 7294 getPrimaryInstructionSet(p.applicationInfo); 7295 } 7296 long callingId = Binder.clearCallingIdentity(); 7297 try { 7298 synchronized (mInstallLock) { 7299 final String[] instructionSets = new String[] { targetInstructionSet }; 7300 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7301 targetCompilerFilter, force); 7302 } 7303 } finally { 7304 Binder.restoreCallingIdentity(callingId); 7305 } 7306 } 7307 7308 public ArraySet<String> getOptimizablePackages() { 7309 ArraySet<String> pkgs = new ArraySet<String>(); 7310 synchronized (mPackages) { 7311 for (PackageParser.Package p : mPackages.values()) { 7312 if (PackageDexOptimizer.canOptimizePackage(p)) { 7313 pkgs.add(p.packageName); 7314 } 7315 } 7316 } 7317 return pkgs; 7318 } 7319 7320 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7321 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7322 boolean force) { 7323 // Select the dex optimizer based on the force parameter. 7324 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7325 // allocate an object here. 7326 PackageDexOptimizer pdo = force 7327 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7328 : mPackageDexOptimizer; 7329 7330 // Optimize all dependencies first. Note: we ignore the return value and march on 7331 // on errors. 7332 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7333 if (!deps.isEmpty()) { 7334 for (PackageParser.Package depPackage : deps) { 7335 // TODO: Analyze and investigate if we (should) profile libraries. 7336 // Currently this will do a full compilation of the library by default. 7337 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7338 false /* checkProfiles */, 7339 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7340 } 7341 } 7342 7343 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7344 targetCompilerFilter); 7345 } 7346 7347 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7348 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7349 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7350 Set<String> collectedNames = new HashSet<>(); 7351 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7352 7353 retValue.remove(p); 7354 7355 return retValue; 7356 } else { 7357 return Collections.emptyList(); 7358 } 7359 } 7360 7361 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7362 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7363 if (!collectedNames.contains(p.packageName)) { 7364 collectedNames.add(p.packageName); 7365 collected.add(p); 7366 7367 if (p.usesLibraries != null) { 7368 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7369 } 7370 if (p.usesOptionalLibraries != null) { 7371 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7372 collectedNames); 7373 } 7374 } 7375 } 7376 7377 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7378 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7379 for (String libName : libs) { 7380 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7381 if (libPkg != null) { 7382 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7383 } 7384 } 7385 } 7386 7387 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7388 synchronized (mPackages) { 7389 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7390 if (lib != null && lib.apk != null) { 7391 return mPackages.get(lib.apk); 7392 } 7393 } 7394 return null; 7395 } 7396 7397 public void shutdown() { 7398 mPackageUsage.write(true); 7399 } 7400 7401 @Override 7402 public void forceDexOpt(String packageName) { 7403 enforceSystemOrRoot("forceDexOpt"); 7404 7405 PackageParser.Package pkg; 7406 synchronized (mPackages) { 7407 pkg = mPackages.get(packageName); 7408 if (pkg == null) { 7409 throw new IllegalArgumentException("Unknown package: " + packageName); 7410 } 7411 } 7412 7413 synchronized (mInstallLock) { 7414 final String[] instructionSets = new String[] { 7415 getPrimaryInstructionSet(pkg.applicationInfo) }; 7416 7417 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7418 7419 // Whoever is calling forceDexOpt wants a fully compiled package. 7420 // Don't use profiles since that may cause compilation to be skipped. 7421 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7422 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7423 true /* force */); 7424 7425 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7426 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7427 throw new IllegalStateException("Failed to dexopt: " + res); 7428 } 7429 } 7430 } 7431 7432 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7433 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7434 Slog.w(TAG, "Unable to update from " + oldPkg.name 7435 + " to " + newPkg.packageName 7436 + ": old package not in system partition"); 7437 return false; 7438 } else if (mPackages.get(oldPkg.name) != null) { 7439 Slog.w(TAG, "Unable to update from " + oldPkg.name 7440 + " to " + newPkg.packageName 7441 + ": old package still exists"); 7442 return false; 7443 } 7444 return true; 7445 } 7446 7447 void removeCodePathLI(File codePath) { 7448 if (codePath.isDirectory()) { 7449 try { 7450 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7451 } catch (InstallerException e) { 7452 Slog.w(TAG, "Failed to remove code path", e); 7453 } 7454 } else { 7455 codePath.delete(); 7456 } 7457 } 7458 7459 private int[] resolveUserIds(int userId) { 7460 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7461 } 7462 7463 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7464 if (pkg == null) { 7465 Slog.wtf(TAG, "Package was null!", new Throwable()); 7466 return; 7467 } 7468 clearAppDataLeafLIF(pkg, userId, flags); 7469 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7470 for (int i = 0; i < childCount; i++) { 7471 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7472 } 7473 } 7474 7475 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7476 final PackageSetting ps; 7477 synchronized (mPackages) { 7478 ps = mSettings.mPackages.get(pkg.packageName); 7479 } 7480 for (int realUserId : resolveUserIds(userId)) { 7481 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7482 try { 7483 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7484 ceDataInode); 7485 } catch (InstallerException e) { 7486 Slog.w(TAG, String.valueOf(e)); 7487 } 7488 } 7489 } 7490 7491 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7492 if (pkg == null) { 7493 Slog.wtf(TAG, "Package was null!", new Throwable()); 7494 return; 7495 } 7496 destroyAppDataLeafLIF(pkg, userId, flags); 7497 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7498 for (int i = 0; i < childCount; i++) { 7499 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7500 } 7501 } 7502 7503 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7504 final PackageSetting ps; 7505 synchronized (mPackages) { 7506 ps = mSettings.mPackages.get(pkg.packageName); 7507 } 7508 for (int realUserId : resolveUserIds(userId)) { 7509 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7510 try { 7511 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7512 ceDataInode); 7513 } catch (InstallerException e) { 7514 Slog.w(TAG, String.valueOf(e)); 7515 } 7516 } 7517 } 7518 7519 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7520 if (pkg == null) { 7521 Slog.wtf(TAG, "Package was null!", new Throwable()); 7522 return; 7523 } 7524 destroyAppProfilesLeafLIF(pkg); 7525 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7526 for (int i = 0; i < childCount; i++) { 7527 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7528 } 7529 } 7530 7531 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7532 try { 7533 mInstaller.destroyAppProfiles(pkg.packageName); 7534 } catch (InstallerException e) { 7535 Slog.w(TAG, String.valueOf(e)); 7536 } 7537 } 7538 7539 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7540 if (pkg == null) { 7541 Slog.wtf(TAG, "Package was null!", new Throwable()); 7542 return; 7543 } 7544 clearAppProfilesLeafLIF(pkg); 7545 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7546 for (int i = 0; i < childCount; i++) { 7547 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7548 } 7549 } 7550 7551 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7552 try { 7553 mInstaller.clearAppProfiles(pkg.packageName); 7554 } catch (InstallerException e) { 7555 Slog.w(TAG, String.valueOf(e)); 7556 } 7557 } 7558 7559 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7560 long lastUpdateTime) { 7561 // Set parent install/update time 7562 PackageSetting ps = (PackageSetting) pkg.mExtras; 7563 if (ps != null) { 7564 ps.firstInstallTime = firstInstallTime; 7565 ps.lastUpdateTime = lastUpdateTime; 7566 } 7567 // Set children install/update time 7568 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7569 for (int i = 0; i < childCount; i++) { 7570 PackageParser.Package childPkg = pkg.childPackages.get(i); 7571 ps = (PackageSetting) childPkg.mExtras; 7572 if (ps != null) { 7573 ps.firstInstallTime = firstInstallTime; 7574 ps.lastUpdateTime = lastUpdateTime; 7575 } 7576 } 7577 } 7578 7579 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7580 PackageParser.Package changingLib) { 7581 if (file.path != null) { 7582 usesLibraryFiles.add(file.path); 7583 return; 7584 } 7585 PackageParser.Package p = mPackages.get(file.apk); 7586 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7587 // If we are doing this while in the middle of updating a library apk, 7588 // then we need to make sure to use that new apk for determining the 7589 // dependencies here. (We haven't yet finished committing the new apk 7590 // to the package manager state.) 7591 if (p == null || p.packageName.equals(changingLib.packageName)) { 7592 p = changingLib; 7593 } 7594 } 7595 if (p != null) { 7596 usesLibraryFiles.addAll(p.getAllCodePaths()); 7597 } 7598 } 7599 7600 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7601 PackageParser.Package changingLib) throws PackageManagerException { 7602 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7603 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7604 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7605 for (int i=0; i<N; i++) { 7606 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7607 if (file == null) { 7608 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7609 "Package " + pkg.packageName + " requires unavailable shared library " 7610 + pkg.usesLibraries.get(i) + "; failing!"); 7611 } 7612 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7613 } 7614 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7615 for (int i=0; i<N; i++) { 7616 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7617 if (file == null) { 7618 Slog.w(TAG, "Package " + pkg.packageName 7619 + " desires unavailable shared library " 7620 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7621 } else { 7622 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7623 } 7624 } 7625 N = usesLibraryFiles.size(); 7626 if (N > 0) { 7627 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7628 } else { 7629 pkg.usesLibraryFiles = null; 7630 } 7631 } 7632 } 7633 7634 private static boolean hasString(List<String> list, List<String> which) { 7635 if (list == null) { 7636 return false; 7637 } 7638 for (int i=list.size()-1; i>=0; i--) { 7639 for (int j=which.size()-1; j>=0; j--) { 7640 if (which.get(j).equals(list.get(i))) { 7641 return true; 7642 } 7643 } 7644 } 7645 return false; 7646 } 7647 7648 private void updateAllSharedLibrariesLPw() { 7649 for (PackageParser.Package pkg : mPackages.values()) { 7650 try { 7651 updateSharedLibrariesLPw(pkg, null); 7652 } catch (PackageManagerException e) { 7653 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7654 } 7655 } 7656 } 7657 7658 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7659 PackageParser.Package changingPkg) { 7660 ArrayList<PackageParser.Package> res = null; 7661 for (PackageParser.Package pkg : mPackages.values()) { 7662 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7663 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7664 if (res == null) { 7665 res = new ArrayList<PackageParser.Package>(); 7666 } 7667 res.add(pkg); 7668 try { 7669 updateSharedLibrariesLPw(pkg, changingPkg); 7670 } catch (PackageManagerException e) { 7671 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7672 } 7673 } 7674 } 7675 return res; 7676 } 7677 7678 /** 7679 * Derive the value of the {@code cpuAbiOverride} based on the provided 7680 * value and an optional stored value from the package settings. 7681 */ 7682 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7683 String cpuAbiOverride = null; 7684 7685 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7686 cpuAbiOverride = null; 7687 } else if (abiOverride != null) { 7688 cpuAbiOverride = abiOverride; 7689 } else if (settings != null) { 7690 cpuAbiOverride = settings.cpuAbiOverrideString; 7691 } 7692 7693 return cpuAbiOverride; 7694 } 7695 7696 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7697 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7698 throws PackageManagerException { 7699 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7700 // If the package has children and this is the first dive in the function 7701 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7702 // whether all packages (parent and children) would be successfully scanned 7703 // before the actual scan since scanning mutates internal state and we want 7704 // to atomically install the package and its children. 7705 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7706 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7707 scanFlags |= SCAN_CHECK_ONLY; 7708 } 7709 } else { 7710 scanFlags &= ~SCAN_CHECK_ONLY; 7711 } 7712 7713 final PackageParser.Package scannedPkg; 7714 try { 7715 // Scan the parent 7716 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7717 // Scan the children 7718 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7719 for (int i = 0; i < childCount; i++) { 7720 PackageParser.Package childPkg = pkg.childPackages.get(i); 7721 scanPackageLI(childPkg, policyFlags, 7722 scanFlags, currentTime, user); 7723 } 7724 } finally { 7725 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7726 } 7727 7728 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7729 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7730 } 7731 7732 return scannedPkg; 7733 } 7734 7735 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7736 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7737 boolean success = false; 7738 try { 7739 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7740 currentTime, user); 7741 success = true; 7742 return res; 7743 } finally { 7744 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7745 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7746 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7747 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7748 destroyAppProfilesLIF(pkg); 7749 } 7750 } 7751 } 7752 7753 /** 7754 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7755 */ 7756 private static boolean apkHasCode(String fileName) { 7757 StrictJarFile jarFile = null; 7758 try { 7759 jarFile = new StrictJarFile(fileName, 7760 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7761 return jarFile.findEntry("classes.dex") != null; 7762 } catch (IOException ignore) { 7763 } finally { 7764 try { 7765 jarFile.close(); 7766 } catch (IOException ignore) {} 7767 } 7768 return false; 7769 } 7770 7771 /** 7772 * Enforces code policy for the package. This ensures that if an APK has 7773 * declared hasCode="true" in its manifest that the APK actually contains 7774 * code. 7775 * 7776 * @throws PackageManagerException If bytecode could not be found when it should exist 7777 */ 7778 private static void enforceCodePolicy(PackageParser.Package pkg) 7779 throws PackageManagerException { 7780 final boolean shouldHaveCode = 7781 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7782 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7783 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7784 "Package " + pkg.baseCodePath + " code is missing"); 7785 } 7786 7787 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7788 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7789 final boolean splitShouldHaveCode = 7790 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7791 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7792 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7793 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7794 } 7795 } 7796 } 7797 } 7798 7799 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7800 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7801 throws PackageManagerException { 7802 final File scanFile = new File(pkg.codePath); 7803 if (pkg.applicationInfo.getCodePath() == null || 7804 pkg.applicationInfo.getResourcePath() == null) { 7805 // Bail out. The resource and code paths haven't been set. 7806 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7807 "Code and resource paths haven't been set correctly"); 7808 } 7809 7810 // Apply policy 7811 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7812 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7813 if (pkg.applicationInfo.isDirectBootAware()) { 7814 // we're direct boot aware; set for all components 7815 for (PackageParser.Service s : pkg.services) { 7816 s.info.encryptionAware = s.info.directBootAware = true; 7817 } 7818 for (PackageParser.Provider p : pkg.providers) { 7819 p.info.encryptionAware = p.info.directBootAware = true; 7820 } 7821 for (PackageParser.Activity a : pkg.activities) { 7822 a.info.encryptionAware = a.info.directBootAware = true; 7823 } 7824 for (PackageParser.Activity r : pkg.receivers) { 7825 r.info.encryptionAware = r.info.directBootAware = true; 7826 } 7827 } 7828 } else { 7829 // Only allow system apps to be flagged as core apps. 7830 pkg.coreApp = false; 7831 // clear flags not applicable to regular apps 7832 pkg.applicationInfo.privateFlags &= 7833 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7834 pkg.applicationInfo.privateFlags &= 7835 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7836 } 7837 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7838 7839 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7840 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7841 } 7842 7843 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7844 enforceCodePolicy(pkg); 7845 } 7846 7847 if (mCustomResolverComponentName != null && 7848 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7849 setUpCustomResolverActivity(pkg); 7850 } 7851 7852 if (pkg.packageName.equals("android")) { 7853 synchronized (mPackages) { 7854 if (mAndroidApplication != null) { 7855 Slog.w(TAG, "*************************************************"); 7856 Slog.w(TAG, "Core android package being redefined. Skipping."); 7857 Slog.w(TAG, " file=" + scanFile); 7858 Slog.w(TAG, "*************************************************"); 7859 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7860 "Core android package being redefined. Skipping."); 7861 } 7862 7863 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7864 // Set up information for our fall-back user intent resolution activity. 7865 mPlatformPackage = pkg; 7866 pkg.mVersionCode = mSdkVersion; 7867 mAndroidApplication = pkg.applicationInfo; 7868 7869 if (!mResolverReplaced) { 7870 mResolveActivity.applicationInfo = mAndroidApplication; 7871 mResolveActivity.name = ResolverActivity.class.getName(); 7872 mResolveActivity.packageName = mAndroidApplication.packageName; 7873 mResolveActivity.processName = "system:ui"; 7874 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7875 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7876 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7877 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7878 mResolveActivity.exported = true; 7879 mResolveActivity.enabled = true; 7880 mResolveInfo.activityInfo = mResolveActivity; 7881 mResolveInfo.priority = 0; 7882 mResolveInfo.preferredOrder = 0; 7883 mResolveInfo.match = 0; 7884 mResolveComponentName = new ComponentName( 7885 mAndroidApplication.packageName, mResolveActivity.name); 7886 } 7887 } 7888 } 7889 } 7890 7891 if (DEBUG_PACKAGE_SCANNING) { 7892 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7893 Log.d(TAG, "Scanning package " + pkg.packageName); 7894 } 7895 7896 synchronized (mPackages) { 7897 if (mPackages.containsKey(pkg.packageName) 7898 || mSharedLibraries.containsKey(pkg.packageName)) { 7899 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7900 "Application package " + pkg.packageName 7901 + " already installed. Skipping duplicate."); 7902 } 7903 7904 // If we're only installing presumed-existing packages, require that the 7905 // scanned APK is both already known and at the path previously established 7906 // for it. Previously unknown packages we pick up normally, but if we have an 7907 // a priori expectation about this package's install presence, enforce it. 7908 // With a singular exception for new system packages. When an OTA contains 7909 // a new system package, we allow the codepath to change from a system location 7910 // to the user-installed location. If we don't allow this change, any newer, 7911 // user-installed version of the application will be ignored. 7912 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7913 if (mExpectingBetter.containsKey(pkg.packageName)) { 7914 logCriticalInfo(Log.WARN, 7915 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7916 } else { 7917 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7918 if (known != null) { 7919 if (DEBUG_PACKAGE_SCANNING) { 7920 Log.d(TAG, "Examining " + pkg.codePath 7921 + " and requiring known paths " + known.codePathString 7922 + " & " + known.resourcePathString); 7923 } 7924 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7925 || !pkg.applicationInfo.getResourcePath().equals( 7926 known.resourcePathString)) { 7927 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7928 "Application package " + pkg.packageName 7929 + " found at " + pkg.applicationInfo.getCodePath() 7930 + " but expected at " + known.codePathString 7931 + "; ignoring."); 7932 } 7933 } 7934 } 7935 } 7936 } 7937 7938 // Initialize package source and resource directories 7939 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7940 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7941 7942 SharedUserSetting suid = null; 7943 PackageSetting pkgSetting = null; 7944 7945 if (!isSystemApp(pkg)) { 7946 // Only system apps can use these features. 7947 pkg.mOriginalPackages = null; 7948 pkg.mRealPackage = null; 7949 pkg.mAdoptPermissions = null; 7950 } 7951 7952 // Getting the package setting may have a side-effect, so if we 7953 // are only checking if scan would succeed, stash a copy of the 7954 // old setting to restore at the end. 7955 PackageSetting nonMutatedPs = null; 7956 7957 // writer 7958 synchronized (mPackages) { 7959 if (pkg.mSharedUserId != null) { 7960 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7961 if (suid == null) { 7962 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7963 "Creating application package " + pkg.packageName 7964 + " for shared user failed"); 7965 } 7966 if (DEBUG_PACKAGE_SCANNING) { 7967 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7968 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7969 + "): packages=" + suid.packages); 7970 } 7971 } 7972 7973 // Check if we are renaming from an original package name. 7974 PackageSetting origPackage = null; 7975 String realName = null; 7976 if (pkg.mOriginalPackages != null) { 7977 // This package may need to be renamed to a previously 7978 // installed name. Let's check on that... 7979 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7980 if (pkg.mOriginalPackages.contains(renamed)) { 7981 // This package had originally been installed as the 7982 // original name, and we have already taken care of 7983 // transitioning to the new one. Just update the new 7984 // one to continue using the old name. 7985 realName = pkg.mRealPackage; 7986 if (!pkg.packageName.equals(renamed)) { 7987 // Callers into this function may have already taken 7988 // care of renaming the package; only do it here if 7989 // it is not already done. 7990 pkg.setPackageName(renamed); 7991 } 7992 7993 } else { 7994 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7995 if ((origPackage = mSettings.peekPackageLPr( 7996 pkg.mOriginalPackages.get(i))) != null) { 7997 // We do have the package already installed under its 7998 // original name... should we use it? 7999 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8000 // New package is not compatible with original. 8001 origPackage = null; 8002 continue; 8003 } else if (origPackage.sharedUser != null) { 8004 // Make sure uid is compatible between packages. 8005 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8006 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8007 + " to " + pkg.packageName + ": old uid " 8008 + origPackage.sharedUser.name 8009 + " differs from " + pkg.mSharedUserId); 8010 origPackage = null; 8011 continue; 8012 } 8013 // TODO: Add case when shared user id is added [b/28144775] 8014 } else { 8015 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8016 + pkg.packageName + " to old name " + origPackage.name); 8017 } 8018 break; 8019 } 8020 } 8021 } 8022 } 8023 8024 if (mTransferedPackages.contains(pkg.packageName)) { 8025 Slog.w(TAG, "Package " + pkg.packageName 8026 + " was transferred to another, but its .apk remains"); 8027 } 8028 8029 // See comments in nonMutatedPs declaration 8030 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8031 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8032 if (foundPs != null) { 8033 nonMutatedPs = new PackageSetting(foundPs); 8034 } 8035 } 8036 8037 // Just create the setting, don't add it yet. For already existing packages 8038 // the PkgSetting exists already and doesn't have to be created. 8039 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8040 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8041 pkg.applicationInfo.primaryCpuAbi, 8042 pkg.applicationInfo.secondaryCpuAbi, 8043 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8044 user, false); 8045 if (pkgSetting == null) { 8046 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8047 "Creating application package " + pkg.packageName + " failed"); 8048 } 8049 8050 if (pkgSetting.origPackage != null) { 8051 // If we are first transitioning from an original package, 8052 // fix up the new package's name now. We need to do this after 8053 // looking up the package under its new name, so getPackageLP 8054 // can take care of fiddling things correctly. 8055 pkg.setPackageName(origPackage.name); 8056 8057 // File a report about this. 8058 String msg = "New package " + pkgSetting.realName 8059 + " renamed to replace old package " + pkgSetting.name; 8060 reportSettingsProblem(Log.WARN, msg); 8061 8062 // Make a note of it. 8063 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8064 mTransferedPackages.add(origPackage.name); 8065 } 8066 8067 // No longer need to retain this. 8068 pkgSetting.origPackage = null; 8069 } 8070 8071 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8072 // Make a note of it. 8073 mTransferedPackages.add(pkg.packageName); 8074 } 8075 8076 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8077 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8078 } 8079 8080 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8081 // Check all shared libraries and map to their actual file path. 8082 // We only do this here for apps not on a system dir, because those 8083 // are the only ones that can fail an install due to this. We 8084 // will take care of the system apps by updating all of their 8085 // library paths after the scan is done. 8086 updateSharedLibrariesLPw(pkg, null); 8087 } 8088 8089 if (mFoundPolicyFile) { 8090 SELinuxMMAC.assignSeinfoValue(pkg); 8091 } 8092 8093 pkg.applicationInfo.uid = pkgSetting.appId; 8094 pkg.mExtras = pkgSetting; 8095 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8096 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8097 // We just determined the app is signed correctly, so bring 8098 // over the latest parsed certs. 8099 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8100 } else { 8101 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8102 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8103 "Package " + pkg.packageName + " upgrade keys do not match the " 8104 + "previously installed version"); 8105 } else { 8106 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8107 String msg = "System package " + pkg.packageName 8108 + " signature changed; retaining data."; 8109 reportSettingsProblem(Log.WARN, msg); 8110 } 8111 } 8112 } else { 8113 try { 8114 verifySignaturesLP(pkgSetting, pkg); 8115 // We just determined the app is signed correctly, so bring 8116 // over the latest parsed certs. 8117 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8118 } catch (PackageManagerException e) { 8119 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8120 throw e; 8121 } 8122 // The signature has changed, but this package is in the system 8123 // image... let's recover! 8124 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8125 // However... if this package is part of a shared user, but it 8126 // doesn't match the signature of the shared user, let's fail. 8127 // What this means is that you can't change the signatures 8128 // associated with an overall shared user, which doesn't seem all 8129 // that unreasonable. 8130 if (pkgSetting.sharedUser != null) { 8131 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8132 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8133 throw new PackageManagerException( 8134 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8135 "Signature mismatch for shared user: " 8136 + pkgSetting.sharedUser); 8137 } 8138 } 8139 // File a report about this. 8140 String msg = "System package " + pkg.packageName 8141 + " signature changed; retaining data."; 8142 reportSettingsProblem(Log.WARN, msg); 8143 } 8144 } 8145 // Verify that this new package doesn't have any content providers 8146 // that conflict with existing packages. Only do this if the 8147 // package isn't already installed, since we don't want to break 8148 // things that are installed. 8149 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8150 final int N = pkg.providers.size(); 8151 int i; 8152 for (i=0; i<N; i++) { 8153 PackageParser.Provider p = pkg.providers.get(i); 8154 if (p.info.authority != null) { 8155 String names[] = p.info.authority.split(";"); 8156 for (int j = 0; j < names.length; j++) { 8157 if (mProvidersByAuthority.containsKey(names[j])) { 8158 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8159 final String otherPackageName = 8160 ((other != null && other.getComponentName() != null) ? 8161 other.getComponentName().getPackageName() : "?"); 8162 throw new PackageManagerException( 8163 INSTALL_FAILED_CONFLICTING_PROVIDER, 8164 "Can't install because provider name " + names[j] 8165 + " (in package " + pkg.applicationInfo.packageName 8166 + ") is already used by " + otherPackageName); 8167 } 8168 } 8169 } 8170 } 8171 } 8172 8173 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8174 // This package wants to adopt ownership of permissions from 8175 // another package. 8176 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8177 final String origName = pkg.mAdoptPermissions.get(i); 8178 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8179 if (orig != null) { 8180 if (verifyPackageUpdateLPr(orig, pkg)) { 8181 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8182 + pkg.packageName); 8183 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8184 } 8185 } 8186 } 8187 } 8188 } 8189 8190 final String pkgName = pkg.packageName; 8191 8192 final long scanFileTime = scanFile.lastModified(); 8193 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8194 pkg.applicationInfo.processName = fixProcessName( 8195 pkg.applicationInfo.packageName, 8196 pkg.applicationInfo.processName, 8197 pkg.applicationInfo.uid); 8198 8199 if (pkg != mPlatformPackage) { 8200 // Get all of our default paths setup 8201 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8202 } 8203 8204 final String path = scanFile.getPath(); 8205 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8206 8207 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8208 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8209 8210 // Some system apps still use directory structure for native libraries 8211 // in which case we might end up not detecting abi solely based on apk 8212 // structure. Try to detect abi based on directory structure. 8213 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8214 pkg.applicationInfo.primaryCpuAbi == null) { 8215 setBundledAppAbisAndRoots(pkg, pkgSetting); 8216 setNativeLibraryPaths(pkg); 8217 } 8218 8219 } else { 8220 if ((scanFlags & SCAN_MOVE) != 0) { 8221 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8222 // but we already have this packages package info in the PackageSetting. We just 8223 // use that and derive the native library path based on the new codepath. 8224 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8225 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8226 } 8227 8228 // Set native library paths again. For moves, the path will be updated based on the 8229 // ABIs we've determined above. For non-moves, the path will be updated based on the 8230 // ABIs we determined during compilation, but the path will depend on the final 8231 // package path (after the rename away from the stage path). 8232 setNativeLibraryPaths(pkg); 8233 } 8234 8235 // This is a special case for the "system" package, where the ABI is 8236 // dictated by the zygote configuration (and init.rc). We should keep track 8237 // of this ABI so that we can deal with "normal" applications that run under 8238 // the same UID correctly. 8239 if (mPlatformPackage == pkg) { 8240 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8241 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8242 } 8243 8244 // If there's a mismatch between the abi-override in the package setting 8245 // and the abiOverride specified for the install. Warn about this because we 8246 // would've already compiled the app without taking the package setting into 8247 // account. 8248 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8249 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8250 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8251 " for package " + pkg.packageName); 8252 } 8253 } 8254 8255 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8256 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8257 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8258 8259 // Copy the derived override back to the parsed package, so that we can 8260 // update the package settings accordingly. 8261 pkg.cpuAbiOverride = cpuAbiOverride; 8262 8263 if (DEBUG_ABI_SELECTION) { 8264 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8265 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8266 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8267 } 8268 8269 // Push the derived path down into PackageSettings so we know what to 8270 // clean up at uninstall time. 8271 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8272 8273 if (DEBUG_ABI_SELECTION) { 8274 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8275 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8276 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8277 } 8278 8279 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8280 // We don't do this here during boot because we can do it all 8281 // at once after scanning all existing packages. 8282 // 8283 // We also do this *before* we perform dexopt on this package, so that 8284 // we can avoid redundant dexopts, and also to make sure we've got the 8285 // code and package path correct. 8286 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8287 pkg, true /* boot complete */); 8288 } 8289 8290 if (mFactoryTest && pkg.requestedPermissions.contains( 8291 android.Manifest.permission.FACTORY_TEST)) { 8292 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8293 } 8294 8295 ArrayList<PackageParser.Package> clientLibPkgs = null; 8296 8297 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8298 if (nonMutatedPs != null) { 8299 synchronized (mPackages) { 8300 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8301 } 8302 } 8303 return pkg; 8304 } 8305 8306 // Only privileged apps and updated privileged apps can add child packages. 8307 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8308 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8309 throw new PackageManagerException("Only privileged apps and updated " 8310 + "privileged apps can add child packages. Ignoring package " 8311 + pkg.packageName); 8312 } 8313 final int childCount = pkg.childPackages.size(); 8314 for (int i = 0; i < childCount; i++) { 8315 PackageParser.Package childPkg = pkg.childPackages.get(i); 8316 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8317 childPkg.packageName)) { 8318 throw new PackageManagerException("Cannot override a child package of " 8319 + "another disabled system app. Ignoring package " + pkg.packageName); 8320 } 8321 } 8322 } 8323 8324 // writer 8325 synchronized (mPackages) { 8326 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8327 // Only system apps can add new shared libraries. 8328 if (pkg.libraryNames != null) { 8329 for (int i=0; i<pkg.libraryNames.size(); i++) { 8330 String name = pkg.libraryNames.get(i); 8331 boolean allowed = false; 8332 if (pkg.isUpdatedSystemApp()) { 8333 // New library entries can only be added through the 8334 // system image. This is important to get rid of a lot 8335 // of nasty edge cases: for example if we allowed a non- 8336 // system update of the app to add a library, then uninstalling 8337 // the update would make the library go away, and assumptions 8338 // we made such as through app install filtering would now 8339 // have allowed apps on the device which aren't compatible 8340 // with it. Better to just have the restriction here, be 8341 // conservative, and create many fewer cases that can negatively 8342 // impact the user experience. 8343 final PackageSetting sysPs = mSettings 8344 .getDisabledSystemPkgLPr(pkg.packageName); 8345 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8346 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8347 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8348 allowed = true; 8349 break; 8350 } 8351 } 8352 } 8353 } else { 8354 allowed = true; 8355 } 8356 if (allowed) { 8357 if (!mSharedLibraries.containsKey(name)) { 8358 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8359 } else if (!name.equals(pkg.packageName)) { 8360 Slog.w(TAG, "Package " + pkg.packageName + " library " 8361 + name + " already exists; skipping"); 8362 } 8363 } else { 8364 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8365 + name + " that is not declared on system image; skipping"); 8366 } 8367 } 8368 if ((scanFlags & SCAN_BOOTING) == 0) { 8369 // If we are not booting, we need to update any applications 8370 // that are clients of our shared library. If we are booting, 8371 // this will all be done once the scan is complete. 8372 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8373 } 8374 } 8375 } 8376 } 8377 8378 if ((scanFlags & SCAN_BOOTING) != 0) { 8379 // No apps can run during boot scan, so they don't need to be frozen 8380 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8381 // Caller asked to not kill app, so it's probably not frozen 8382 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8383 // Caller asked us to ignore frozen check for some reason; they 8384 // probably didn't know the package name 8385 } else { 8386 // We're doing major surgery on this package, so it better be frozen 8387 // right now to keep it from launching 8388 checkPackageFrozen(pkgName); 8389 } 8390 8391 // Also need to kill any apps that are dependent on the library. 8392 if (clientLibPkgs != null) { 8393 for (int i=0; i<clientLibPkgs.size(); i++) { 8394 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8395 killApplication(clientPkg.applicationInfo.packageName, 8396 clientPkg.applicationInfo.uid, "update lib"); 8397 } 8398 } 8399 8400 // Make sure we're not adding any bogus keyset info 8401 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8402 ksms.assertScannedPackageValid(pkg); 8403 8404 // writer 8405 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8406 8407 boolean createIdmapFailed = false; 8408 synchronized (mPackages) { 8409 // We don't expect installation to fail beyond this point 8410 8411 // Add the new setting to mSettings 8412 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8413 // Add the new setting to mPackages 8414 mPackages.put(pkg.applicationInfo.packageName, pkg); 8415 // Make sure we don't accidentally delete its data. 8416 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8417 while (iter.hasNext()) { 8418 PackageCleanItem item = iter.next(); 8419 if (pkgName.equals(item.packageName)) { 8420 iter.remove(); 8421 } 8422 } 8423 8424 // Take care of first install / last update times. 8425 if (currentTime != 0) { 8426 if (pkgSetting.firstInstallTime == 0) { 8427 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8428 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8429 pkgSetting.lastUpdateTime = currentTime; 8430 } 8431 } else if (pkgSetting.firstInstallTime == 0) { 8432 // We need *something*. Take time time stamp of the file. 8433 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8434 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8435 if (scanFileTime != pkgSetting.timeStamp) { 8436 // A package on the system image has changed; consider this 8437 // to be an update. 8438 pkgSetting.lastUpdateTime = scanFileTime; 8439 } 8440 } 8441 8442 // Add the package's KeySets to the global KeySetManagerService 8443 ksms.addScannedPackageLPw(pkg); 8444 8445 int N = pkg.providers.size(); 8446 StringBuilder r = null; 8447 int i; 8448 for (i=0; i<N; i++) { 8449 PackageParser.Provider p = pkg.providers.get(i); 8450 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8451 p.info.processName, pkg.applicationInfo.uid); 8452 mProviders.addProvider(p); 8453 p.syncable = p.info.isSyncable; 8454 if (p.info.authority != null) { 8455 String names[] = p.info.authority.split(";"); 8456 p.info.authority = null; 8457 for (int j = 0; j < names.length; j++) { 8458 if (j == 1 && p.syncable) { 8459 // We only want the first authority for a provider to possibly be 8460 // syncable, so if we already added this provider using a different 8461 // authority clear the syncable flag. We copy the provider before 8462 // changing it because the mProviders object contains a reference 8463 // to a provider that we don't want to change. 8464 // Only do this for the second authority since the resulting provider 8465 // object can be the same for all future authorities for this provider. 8466 p = new PackageParser.Provider(p); 8467 p.syncable = false; 8468 } 8469 if (!mProvidersByAuthority.containsKey(names[j])) { 8470 mProvidersByAuthority.put(names[j], p); 8471 if (p.info.authority == null) { 8472 p.info.authority = names[j]; 8473 } else { 8474 p.info.authority = p.info.authority + ";" + names[j]; 8475 } 8476 if (DEBUG_PACKAGE_SCANNING) { 8477 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8478 Log.d(TAG, "Registered content provider: " + names[j] 8479 + ", className = " + p.info.name + ", isSyncable = " 8480 + p.info.isSyncable); 8481 } 8482 } else { 8483 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8484 Slog.w(TAG, "Skipping provider name " + names[j] + 8485 " (in package " + pkg.applicationInfo.packageName + 8486 "): name already used by " 8487 + ((other != null && other.getComponentName() != null) 8488 ? other.getComponentName().getPackageName() : "?")); 8489 } 8490 } 8491 } 8492 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8493 if (r == null) { 8494 r = new StringBuilder(256); 8495 } else { 8496 r.append(' '); 8497 } 8498 r.append(p.info.name); 8499 } 8500 } 8501 if (r != null) { 8502 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8503 } 8504 8505 N = pkg.services.size(); 8506 r = null; 8507 for (i=0; i<N; i++) { 8508 PackageParser.Service s = pkg.services.get(i); 8509 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8510 s.info.processName, pkg.applicationInfo.uid); 8511 mServices.addService(s); 8512 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8513 if (r == null) { 8514 r = new StringBuilder(256); 8515 } else { 8516 r.append(' '); 8517 } 8518 r.append(s.info.name); 8519 } 8520 } 8521 if (r != null) { 8522 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8523 } 8524 8525 N = pkg.receivers.size(); 8526 r = null; 8527 for (i=0; i<N; i++) { 8528 PackageParser.Activity a = pkg.receivers.get(i); 8529 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8530 a.info.processName, pkg.applicationInfo.uid); 8531 mReceivers.addActivity(a, "receiver"); 8532 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8533 if (r == null) { 8534 r = new StringBuilder(256); 8535 } else { 8536 r.append(' '); 8537 } 8538 r.append(a.info.name); 8539 } 8540 } 8541 if (r != null) { 8542 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8543 } 8544 8545 N = pkg.activities.size(); 8546 r = null; 8547 for (i=0; i<N; i++) { 8548 PackageParser.Activity a = pkg.activities.get(i); 8549 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8550 a.info.processName, pkg.applicationInfo.uid); 8551 mActivities.addActivity(a, "activity"); 8552 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8553 if (r == null) { 8554 r = new StringBuilder(256); 8555 } else { 8556 r.append(' '); 8557 } 8558 r.append(a.info.name); 8559 } 8560 } 8561 if (r != null) { 8562 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8563 } 8564 8565 N = pkg.permissionGroups.size(); 8566 r = null; 8567 for (i=0; i<N; i++) { 8568 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8569 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8570 if (cur == null) { 8571 mPermissionGroups.put(pg.info.name, pg); 8572 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8573 if (r == null) { 8574 r = new StringBuilder(256); 8575 } else { 8576 r.append(' '); 8577 } 8578 r.append(pg.info.name); 8579 } 8580 } else { 8581 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8582 + pg.info.packageName + " ignored: original from " 8583 + cur.info.packageName); 8584 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8585 if (r == null) { 8586 r = new StringBuilder(256); 8587 } else { 8588 r.append(' '); 8589 } 8590 r.append("DUP:"); 8591 r.append(pg.info.name); 8592 } 8593 } 8594 } 8595 if (r != null) { 8596 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8597 } 8598 8599 N = pkg.permissions.size(); 8600 r = null; 8601 for (i=0; i<N; i++) { 8602 PackageParser.Permission p = pkg.permissions.get(i); 8603 8604 // Assume by default that we did not install this permission into the system. 8605 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8606 8607 // Now that permission groups have a special meaning, we ignore permission 8608 // groups for legacy apps to prevent unexpected behavior. In particular, 8609 // permissions for one app being granted to someone just becase they happen 8610 // to be in a group defined by another app (before this had no implications). 8611 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8612 p.group = mPermissionGroups.get(p.info.group); 8613 // Warn for a permission in an unknown group. 8614 if (p.info.group != null && p.group == null) { 8615 Slog.w(TAG, "Permission " + p.info.name + " from package " 8616 + p.info.packageName + " in an unknown group " + p.info.group); 8617 } 8618 } 8619 8620 ArrayMap<String, BasePermission> permissionMap = 8621 p.tree ? mSettings.mPermissionTrees 8622 : mSettings.mPermissions; 8623 BasePermission bp = permissionMap.get(p.info.name); 8624 8625 // Allow system apps to redefine non-system permissions 8626 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8627 final boolean currentOwnerIsSystem = (bp.perm != null 8628 && isSystemApp(bp.perm.owner)); 8629 if (isSystemApp(p.owner)) { 8630 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8631 // It's a built-in permission and no owner, take ownership now 8632 bp.packageSetting = pkgSetting; 8633 bp.perm = p; 8634 bp.uid = pkg.applicationInfo.uid; 8635 bp.sourcePackage = p.info.packageName; 8636 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8637 } else if (!currentOwnerIsSystem) { 8638 String msg = "New decl " + p.owner + " of permission " 8639 + p.info.name + " is system; overriding " + bp.sourcePackage; 8640 reportSettingsProblem(Log.WARN, msg); 8641 bp = null; 8642 } 8643 } 8644 } 8645 8646 if (bp == null) { 8647 bp = new BasePermission(p.info.name, p.info.packageName, 8648 BasePermission.TYPE_NORMAL); 8649 permissionMap.put(p.info.name, bp); 8650 } 8651 8652 if (bp.perm == null) { 8653 if (bp.sourcePackage == null 8654 || bp.sourcePackage.equals(p.info.packageName)) { 8655 BasePermission tree = findPermissionTreeLP(p.info.name); 8656 if (tree == null 8657 || tree.sourcePackage.equals(p.info.packageName)) { 8658 bp.packageSetting = pkgSetting; 8659 bp.perm = p; 8660 bp.uid = pkg.applicationInfo.uid; 8661 bp.sourcePackage = p.info.packageName; 8662 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8663 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8664 if (r == null) { 8665 r = new StringBuilder(256); 8666 } else { 8667 r.append(' '); 8668 } 8669 r.append(p.info.name); 8670 } 8671 } else { 8672 Slog.w(TAG, "Permission " + p.info.name + " from package " 8673 + p.info.packageName + " ignored: base tree " 8674 + tree.name + " is from package " 8675 + tree.sourcePackage); 8676 } 8677 } else { 8678 Slog.w(TAG, "Permission " + p.info.name + " from package " 8679 + p.info.packageName + " ignored: original from " 8680 + bp.sourcePackage); 8681 } 8682 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8683 if (r == null) { 8684 r = new StringBuilder(256); 8685 } else { 8686 r.append(' '); 8687 } 8688 r.append("DUP:"); 8689 r.append(p.info.name); 8690 } 8691 if (bp.perm == p) { 8692 bp.protectionLevel = p.info.protectionLevel; 8693 } 8694 } 8695 8696 if (r != null) { 8697 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8698 } 8699 8700 N = pkg.instrumentation.size(); 8701 r = null; 8702 for (i=0; i<N; i++) { 8703 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8704 a.info.packageName = pkg.applicationInfo.packageName; 8705 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8706 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8707 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8708 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8709 a.info.dataDir = pkg.applicationInfo.dataDir; 8710 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8711 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8712 8713 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8714 // need other information about the application, like the ABI and what not ? 8715 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8716 mInstrumentation.put(a.getComponentName(), a); 8717 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8718 if (r == null) { 8719 r = new StringBuilder(256); 8720 } else { 8721 r.append(' '); 8722 } 8723 r.append(a.info.name); 8724 } 8725 } 8726 if (r != null) { 8727 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8728 } 8729 8730 if (pkg.protectedBroadcasts != null) { 8731 N = pkg.protectedBroadcasts.size(); 8732 for (i=0; i<N; i++) { 8733 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8734 } 8735 } 8736 8737 pkgSetting.setTimeStamp(scanFileTime); 8738 8739 // Create idmap files for pairs of (packages, overlay packages). 8740 // Note: "android", ie framework-res.apk, is handled by native layers. 8741 if (pkg.mOverlayTarget != null) { 8742 // This is an overlay package. 8743 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8744 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8745 mOverlays.put(pkg.mOverlayTarget, 8746 new ArrayMap<String, PackageParser.Package>()); 8747 } 8748 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8749 map.put(pkg.packageName, pkg); 8750 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8751 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8752 createIdmapFailed = true; 8753 } 8754 } 8755 } else if (mOverlays.containsKey(pkg.packageName) && 8756 !pkg.packageName.equals("android")) { 8757 // This is a regular package, with one or more known overlay packages. 8758 createIdmapsForPackageLI(pkg); 8759 } 8760 } 8761 8762 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8763 8764 if (createIdmapFailed) { 8765 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8766 "scanPackageLI failed to createIdmap"); 8767 } 8768 return pkg; 8769 } 8770 8771 /** 8772 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8773 * is derived purely on the basis of the contents of {@code scanFile} and 8774 * {@code cpuAbiOverride}. 8775 * 8776 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8777 */ 8778 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8779 String cpuAbiOverride, boolean extractLibs) 8780 throws PackageManagerException { 8781 // TODO: We can probably be smarter about this stuff. For installed apps, 8782 // we can calculate this information at install time once and for all. For 8783 // system apps, we can probably assume that this information doesn't change 8784 // after the first boot scan. As things stand, we do lots of unnecessary work. 8785 8786 // Give ourselves some initial paths; we'll come back for another 8787 // pass once we've determined ABI below. 8788 setNativeLibraryPaths(pkg); 8789 8790 // We would never need to extract libs for forward-locked and external packages, 8791 // since the container service will do it for us. We shouldn't attempt to 8792 // extract libs from system app when it was not updated. 8793 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8794 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8795 extractLibs = false; 8796 } 8797 8798 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8799 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8800 8801 NativeLibraryHelper.Handle handle = null; 8802 try { 8803 handle = NativeLibraryHelper.Handle.create(pkg); 8804 // TODO(multiArch): This can be null for apps that didn't go through the 8805 // usual installation process. We can calculate it again, like we 8806 // do during install time. 8807 // 8808 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8809 // unnecessary. 8810 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8811 8812 // Null out the abis so that they can be recalculated. 8813 pkg.applicationInfo.primaryCpuAbi = null; 8814 pkg.applicationInfo.secondaryCpuAbi = null; 8815 if (isMultiArch(pkg.applicationInfo)) { 8816 // Warn if we've set an abiOverride for multi-lib packages.. 8817 // By definition, we need to copy both 32 and 64 bit libraries for 8818 // such packages. 8819 if (pkg.cpuAbiOverride != null 8820 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8821 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8822 } 8823 8824 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8825 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8826 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8827 if (extractLibs) { 8828 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8829 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8830 useIsaSpecificSubdirs); 8831 } else { 8832 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8833 } 8834 } 8835 8836 maybeThrowExceptionForMultiArchCopy( 8837 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8838 8839 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8840 if (extractLibs) { 8841 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8842 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8843 useIsaSpecificSubdirs); 8844 } else { 8845 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8846 } 8847 } 8848 8849 maybeThrowExceptionForMultiArchCopy( 8850 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8851 8852 if (abi64 >= 0) { 8853 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8854 } 8855 8856 if (abi32 >= 0) { 8857 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8858 if (abi64 >= 0) { 8859 if (pkg.use32bitAbi) { 8860 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8861 pkg.applicationInfo.primaryCpuAbi = abi; 8862 } else { 8863 pkg.applicationInfo.secondaryCpuAbi = abi; 8864 } 8865 } else { 8866 pkg.applicationInfo.primaryCpuAbi = abi; 8867 } 8868 } 8869 8870 } else { 8871 String[] abiList = (cpuAbiOverride != null) ? 8872 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8873 8874 // Enable gross and lame hacks for apps that are built with old 8875 // SDK tools. We must scan their APKs for renderscript bitcode and 8876 // not launch them if it's present. Don't bother checking on devices 8877 // that don't have 64 bit support. 8878 boolean needsRenderScriptOverride = false; 8879 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8880 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8881 abiList = Build.SUPPORTED_32_BIT_ABIS; 8882 needsRenderScriptOverride = true; 8883 } 8884 8885 final int copyRet; 8886 if (extractLibs) { 8887 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8888 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8889 } else { 8890 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8891 } 8892 8893 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8894 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8895 "Error unpackaging native libs for app, errorCode=" + copyRet); 8896 } 8897 8898 if (copyRet >= 0) { 8899 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8900 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8901 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8902 } else if (needsRenderScriptOverride) { 8903 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8904 } 8905 } 8906 } catch (IOException ioe) { 8907 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8908 } finally { 8909 IoUtils.closeQuietly(handle); 8910 } 8911 8912 // Now that we've calculated the ABIs and determined if it's an internal app, 8913 // we will go ahead and populate the nativeLibraryPath. 8914 setNativeLibraryPaths(pkg); 8915 } 8916 8917 /** 8918 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8919 * i.e, so that all packages can be run inside a single process if required. 8920 * 8921 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8922 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8923 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8924 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8925 * updating a package that belongs to a shared user. 8926 * 8927 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8928 * adds unnecessary complexity. 8929 */ 8930 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8931 PackageParser.Package scannedPackage, boolean bootComplete) { 8932 String requiredInstructionSet = null; 8933 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8934 requiredInstructionSet = VMRuntime.getInstructionSet( 8935 scannedPackage.applicationInfo.primaryCpuAbi); 8936 } 8937 8938 PackageSetting requirer = null; 8939 for (PackageSetting ps : packagesForUser) { 8940 // If packagesForUser contains scannedPackage, we skip it. This will happen 8941 // when scannedPackage is an update of an existing package. Without this check, 8942 // we will never be able to change the ABI of any package belonging to a shared 8943 // user, even if it's compatible with other packages. 8944 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8945 if (ps.primaryCpuAbiString == null) { 8946 continue; 8947 } 8948 8949 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8950 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8951 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8952 // this but there's not much we can do. 8953 String errorMessage = "Instruction set mismatch, " 8954 + ((requirer == null) ? "[caller]" : requirer) 8955 + " requires " + requiredInstructionSet + " whereas " + ps 8956 + " requires " + instructionSet; 8957 Slog.w(TAG, errorMessage); 8958 } 8959 8960 if (requiredInstructionSet == null) { 8961 requiredInstructionSet = instructionSet; 8962 requirer = ps; 8963 } 8964 } 8965 } 8966 8967 if (requiredInstructionSet != null) { 8968 String adjustedAbi; 8969 if (requirer != null) { 8970 // requirer != null implies that either scannedPackage was null or that scannedPackage 8971 // did not require an ABI, in which case we have to adjust scannedPackage to match 8972 // the ABI of the set (which is the same as requirer's ABI) 8973 adjustedAbi = requirer.primaryCpuAbiString; 8974 if (scannedPackage != null) { 8975 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8976 } 8977 } else { 8978 // requirer == null implies that we're updating all ABIs in the set to 8979 // match scannedPackage. 8980 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8981 } 8982 8983 for (PackageSetting ps : packagesForUser) { 8984 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8985 if (ps.primaryCpuAbiString != null) { 8986 continue; 8987 } 8988 8989 ps.primaryCpuAbiString = adjustedAbi; 8990 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8991 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8992 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8993 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8994 + " (requirer=" 8995 + (requirer == null ? "null" : requirer.pkg.packageName) 8996 + ", scannedPackage=" 8997 + (scannedPackage != null ? scannedPackage.packageName : "null") 8998 + ")"); 8999 try { 9000 mInstaller.rmdex(ps.codePathString, 9001 getDexCodeInstructionSet(getPreferredInstructionSet())); 9002 } catch (InstallerException ignored) { 9003 } 9004 } 9005 } 9006 } 9007 } 9008 } 9009 9010 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9011 synchronized (mPackages) { 9012 mResolverReplaced = true; 9013 // Set up information for custom user intent resolution activity. 9014 mResolveActivity.applicationInfo = pkg.applicationInfo; 9015 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9016 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9017 mResolveActivity.processName = pkg.applicationInfo.packageName; 9018 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9019 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9020 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9021 mResolveActivity.theme = 0; 9022 mResolveActivity.exported = true; 9023 mResolveActivity.enabled = true; 9024 mResolveInfo.activityInfo = mResolveActivity; 9025 mResolveInfo.priority = 0; 9026 mResolveInfo.preferredOrder = 0; 9027 mResolveInfo.match = 0; 9028 mResolveComponentName = mCustomResolverComponentName; 9029 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9030 mResolveComponentName); 9031 } 9032 } 9033 9034 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9035 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9036 9037 // Set up information for ephemeral installer activity 9038 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9039 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9040 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9041 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9042 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9043 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9044 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9045 mEphemeralInstallerActivity.theme = 0; 9046 mEphemeralInstallerActivity.exported = true; 9047 mEphemeralInstallerActivity.enabled = true; 9048 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9049 mEphemeralInstallerInfo.priority = 0; 9050 mEphemeralInstallerInfo.preferredOrder = 0; 9051 mEphemeralInstallerInfo.match = 0; 9052 9053 if (DEBUG_EPHEMERAL) { 9054 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9055 } 9056 } 9057 9058 private static String calculateBundledApkRoot(final String codePathString) { 9059 final File codePath = new File(codePathString); 9060 final File codeRoot; 9061 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9062 codeRoot = Environment.getRootDirectory(); 9063 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9064 codeRoot = Environment.getOemDirectory(); 9065 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9066 codeRoot = Environment.getVendorDirectory(); 9067 } else { 9068 // Unrecognized code path; take its top real segment as the apk root: 9069 // e.g. /something/app/blah.apk => /something 9070 try { 9071 File f = codePath.getCanonicalFile(); 9072 File parent = f.getParentFile(); // non-null because codePath is a file 9073 File tmp; 9074 while ((tmp = parent.getParentFile()) != null) { 9075 f = parent; 9076 parent = tmp; 9077 } 9078 codeRoot = f; 9079 Slog.w(TAG, "Unrecognized code path " 9080 + codePath + " - using " + codeRoot); 9081 } catch (IOException e) { 9082 // Can't canonicalize the code path -- shenanigans? 9083 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9084 return Environment.getRootDirectory().getPath(); 9085 } 9086 } 9087 return codeRoot.getPath(); 9088 } 9089 9090 /** 9091 * Derive and set the location of native libraries for the given package, 9092 * which varies depending on where and how the package was installed. 9093 */ 9094 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9095 final ApplicationInfo info = pkg.applicationInfo; 9096 final String codePath = pkg.codePath; 9097 final File codeFile = new File(codePath); 9098 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9099 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9100 9101 info.nativeLibraryRootDir = null; 9102 info.nativeLibraryRootRequiresIsa = false; 9103 info.nativeLibraryDir = null; 9104 info.secondaryNativeLibraryDir = null; 9105 9106 if (isApkFile(codeFile)) { 9107 // Monolithic install 9108 if (bundledApp) { 9109 // If "/system/lib64/apkname" exists, assume that is the per-package 9110 // native library directory to use; otherwise use "/system/lib/apkname". 9111 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9112 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9113 getPrimaryInstructionSet(info)); 9114 9115 // This is a bundled system app so choose the path based on the ABI. 9116 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9117 // is just the default path. 9118 final String apkName = deriveCodePathName(codePath); 9119 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9120 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9121 apkName).getAbsolutePath(); 9122 9123 if (info.secondaryCpuAbi != null) { 9124 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9125 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9126 secondaryLibDir, apkName).getAbsolutePath(); 9127 } 9128 } else if (asecApp) { 9129 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9130 .getAbsolutePath(); 9131 } else { 9132 final String apkName = deriveCodePathName(codePath); 9133 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9134 .getAbsolutePath(); 9135 } 9136 9137 info.nativeLibraryRootRequiresIsa = false; 9138 info.nativeLibraryDir = info.nativeLibraryRootDir; 9139 } else { 9140 // Cluster install 9141 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9142 info.nativeLibraryRootRequiresIsa = true; 9143 9144 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9145 getPrimaryInstructionSet(info)).getAbsolutePath(); 9146 9147 if (info.secondaryCpuAbi != null) { 9148 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9149 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9150 } 9151 } 9152 } 9153 9154 /** 9155 * Calculate the abis and roots for a bundled app. These can uniquely 9156 * be determined from the contents of the system partition, i.e whether 9157 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9158 * of this information, and instead assume that the system was built 9159 * sensibly. 9160 */ 9161 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9162 PackageSetting pkgSetting) { 9163 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9164 9165 // If "/system/lib64/apkname" exists, assume that is the per-package 9166 // native library directory to use; otherwise use "/system/lib/apkname". 9167 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9168 setBundledAppAbi(pkg, apkRoot, apkName); 9169 // pkgSetting might be null during rescan following uninstall of updates 9170 // to a bundled app, so accommodate that possibility. The settings in 9171 // that case will be established later from the parsed package. 9172 // 9173 // If the settings aren't null, sync them up with what we've just derived. 9174 // note that apkRoot isn't stored in the package settings. 9175 if (pkgSetting != null) { 9176 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9177 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9178 } 9179 } 9180 9181 /** 9182 * Deduces the ABI of a bundled app and sets the relevant fields on the 9183 * parsed pkg object. 9184 * 9185 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9186 * under which system libraries are installed. 9187 * @param apkName the name of the installed package. 9188 */ 9189 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9190 final File codeFile = new File(pkg.codePath); 9191 9192 final boolean has64BitLibs; 9193 final boolean has32BitLibs; 9194 if (isApkFile(codeFile)) { 9195 // Monolithic install 9196 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9197 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9198 } else { 9199 // Cluster install 9200 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9201 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9202 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9203 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9204 has64BitLibs = (new File(rootDir, isa)).exists(); 9205 } else { 9206 has64BitLibs = false; 9207 } 9208 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9209 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9210 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9211 has32BitLibs = (new File(rootDir, isa)).exists(); 9212 } else { 9213 has32BitLibs = false; 9214 } 9215 } 9216 9217 if (has64BitLibs && !has32BitLibs) { 9218 // The package has 64 bit libs, but not 32 bit libs. Its primary 9219 // ABI should be 64 bit. We can safely assume here that the bundled 9220 // native libraries correspond to the most preferred ABI in the list. 9221 9222 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9223 pkg.applicationInfo.secondaryCpuAbi = null; 9224 } else if (has32BitLibs && !has64BitLibs) { 9225 // The package has 32 bit libs but not 64 bit libs. Its primary 9226 // ABI should be 32 bit. 9227 9228 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9229 pkg.applicationInfo.secondaryCpuAbi = null; 9230 } else if (has32BitLibs && has64BitLibs) { 9231 // The application has both 64 and 32 bit bundled libraries. We check 9232 // here that the app declares multiArch support, and warn if it doesn't. 9233 // 9234 // We will be lenient here and record both ABIs. The primary will be the 9235 // ABI that's higher on the list, i.e, a device that's configured to prefer 9236 // 64 bit apps will see a 64 bit primary ABI, 9237 9238 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9239 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9240 } 9241 9242 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9243 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9244 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9245 } else { 9246 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9247 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9248 } 9249 } else { 9250 pkg.applicationInfo.primaryCpuAbi = null; 9251 pkg.applicationInfo.secondaryCpuAbi = null; 9252 } 9253 } 9254 9255 private void killApplication(String pkgName, int appId, String reason) { 9256 // Request the ActivityManager to kill the process(only for existing packages) 9257 // so that we do not end up in a confused state while the user is still using the older 9258 // version of the application while the new one gets installed. 9259 final long token = Binder.clearCallingIdentity(); 9260 try { 9261 IActivityManager am = ActivityManagerNative.getDefault(); 9262 if (am != null) { 9263 try { 9264 am.killApplicationWithAppId(pkgName, appId, reason); 9265 } catch (RemoteException e) { 9266 } 9267 } 9268 } finally { 9269 Binder.restoreCallingIdentity(token); 9270 } 9271 } 9272 9273 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9274 // Remove the parent package setting 9275 PackageSetting ps = (PackageSetting) pkg.mExtras; 9276 if (ps != null) { 9277 removePackageLI(ps, chatty); 9278 } 9279 // Remove the child package setting 9280 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9281 for (int i = 0; i < childCount; i++) { 9282 PackageParser.Package childPkg = pkg.childPackages.get(i); 9283 ps = (PackageSetting) childPkg.mExtras; 9284 if (ps != null) { 9285 removePackageLI(ps, chatty); 9286 } 9287 } 9288 } 9289 9290 void removePackageLI(PackageSetting ps, boolean chatty) { 9291 if (DEBUG_INSTALL) { 9292 if (chatty) 9293 Log.d(TAG, "Removing package " + ps.name); 9294 } 9295 9296 // writer 9297 synchronized (mPackages) { 9298 mPackages.remove(ps.name); 9299 final PackageParser.Package pkg = ps.pkg; 9300 if (pkg != null) { 9301 cleanPackageDataStructuresLILPw(pkg, chatty); 9302 } 9303 } 9304 } 9305 9306 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9307 if (DEBUG_INSTALL) { 9308 if (chatty) 9309 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9310 } 9311 9312 // writer 9313 synchronized (mPackages) { 9314 // Remove the parent package 9315 mPackages.remove(pkg.applicationInfo.packageName); 9316 cleanPackageDataStructuresLILPw(pkg, chatty); 9317 9318 // Remove the child packages 9319 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9320 for (int i = 0; i < childCount; i++) { 9321 PackageParser.Package childPkg = pkg.childPackages.get(i); 9322 mPackages.remove(childPkg.applicationInfo.packageName); 9323 cleanPackageDataStructuresLILPw(childPkg, chatty); 9324 } 9325 } 9326 } 9327 9328 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9329 int N = pkg.providers.size(); 9330 StringBuilder r = null; 9331 int i; 9332 for (i=0; i<N; i++) { 9333 PackageParser.Provider p = pkg.providers.get(i); 9334 mProviders.removeProvider(p); 9335 if (p.info.authority == null) { 9336 9337 /* There was another ContentProvider with this authority when 9338 * this app was installed so this authority is null, 9339 * Ignore it as we don't have to unregister the provider. 9340 */ 9341 continue; 9342 } 9343 String names[] = p.info.authority.split(";"); 9344 for (int j = 0; j < names.length; j++) { 9345 if (mProvidersByAuthority.get(names[j]) == p) { 9346 mProvidersByAuthority.remove(names[j]); 9347 if (DEBUG_REMOVE) { 9348 if (chatty) 9349 Log.d(TAG, "Unregistered content provider: " + names[j] 9350 + ", className = " + p.info.name + ", isSyncable = " 9351 + p.info.isSyncable); 9352 } 9353 } 9354 } 9355 if (DEBUG_REMOVE && chatty) { 9356 if (r == null) { 9357 r = new StringBuilder(256); 9358 } else { 9359 r.append(' '); 9360 } 9361 r.append(p.info.name); 9362 } 9363 } 9364 if (r != null) { 9365 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9366 } 9367 9368 N = pkg.services.size(); 9369 r = null; 9370 for (i=0; i<N; i++) { 9371 PackageParser.Service s = pkg.services.get(i); 9372 mServices.removeService(s); 9373 if (chatty) { 9374 if (r == null) { 9375 r = new StringBuilder(256); 9376 } else { 9377 r.append(' '); 9378 } 9379 r.append(s.info.name); 9380 } 9381 } 9382 if (r != null) { 9383 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9384 } 9385 9386 N = pkg.receivers.size(); 9387 r = null; 9388 for (i=0; i<N; i++) { 9389 PackageParser.Activity a = pkg.receivers.get(i); 9390 mReceivers.removeActivity(a, "receiver"); 9391 if (DEBUG_REMOVE && chatty) { 9392 if (r == null) { 9393 r = new StringBuilder(256); 9394 } else { 9395 r.append(' '); 9396 } 9397 r.append(a.info.name); 9398 } 9399 } 9400 if (r != null) { 9401 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9402 } 9403 9404 N = pkg.activities.size(); 9405 r = null; 9406 for (i=0; i<N; i++) { 9407 PackageParser.Activity a = pkg.activities.get(i); 9408 mActivities.removeActivity(a, "activity"); 9409 if (DEBUG_REMOVE && chatty) { 9410 if (r == null) { 9411 r = new StringBuilder(256); 9412 } else { 9413 r.append(' '); 9414 } 9415 r.append(a.info.name); 9416 } 9417 } 9418 if (r != null) { 9419 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9420 } 9421 9422 N = pkg.permissions.size(); 9423 r = null; 9424 for (i=0; i<N; i++) { 9425 PackageParser.Permission p = pkg.permissions.get(i); 9426 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9427 if (bp == null) { 9428 bp = mSettings.mPermissionTrees.get(p.info.name); 9429 } 9430 if (bp != null && bp.perm == p) { 9431 bp.perm = null; 9432 if (DEBUG_REMOVE && chatty) { 9433 if (r == null) { 9434 r = new StringBuilder(256); 9435 } else { 9436 r.append(' '); 9437 } 9438 r.append(p.info.name); 9439 } 9440 } 9441 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9442 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9443 if (appOpPkgs != null) { 9444 appOpPkgs.remove(pkg.packageName); 9445 } 9446 } 9447 } 9448 if (r != null) { 9449 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9450 } 9451 9452 N = pkg.requestedPermissions.size(); 9453 r = null; 9454 for (i=0; i<N; i++) { 9455 String perm = pkg.requestedPermissions.get(i); 9456 BasePermission bp = mSettings.mPermissions.get(perm); 9457 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9458 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9459 if (appOpPkgs != null) { 9460 appOpPkgs.remove(pkg.packageName); 9461 if (appOpPkgs.isEmpty()) { 9462 mAppOpPermissionPackages.remove(perm); 9463 } 9464 } 9465 } 9466 } 9467 if (r != null) { 9468 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9469 } 9470 9471 N = pkg.instrumentation.size(); 9472 r = null; 9473 for (i=0; i<N; i++) { 9474 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9475 mInstrumentation.remove(a.getComponentName()); 9476 if (DEBUG_REMOVE && chatty) { 9477 if (r == null) { 9478 r = new StringBuilder(256); 9479 } else { 9480 r.append(' '); 9481 } 9482 r.append(a.info.name); 9483 } 9484 } 9485 if (r != null) { 9486 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9487 } 9488 9489 r = null; 9490 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9491 // Only system apps can hold shared libraries. 9492 if (pkg.libraryNames != null) { 9493 for (i=0; i<pkg.libraryNames.size(); i++) { 9494 String name = pkg.libraryNames.get(i); 9495 SharedLibraryEntry cur = mSharedLibraries.get(name); 9496 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9497 mSharedLibraries.remove(name); 9498 if (DEBUG_REMOVE && chatty) { 9499 if (r == null) { 9500 r = new StringBuilder(256); 9501 } else { 9502 r.append(' '); 9503 } 9504 r.append(name); 9505 } 9506 } 9507 } 9508 } 9509 } 9510 if (r != null) { 9511 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9512 } 9513 } 9514 9515 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9516 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9517 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9518 return true; 9519 } 9520 } 9521 return false; 9522 } 9523 9524 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9525 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9526 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9527 9528 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9529 // Update the parent permissions 9530 updatePermissionsLPw(pkg.packageName, pkg, flags); 9531 // Update the child permissions 9532 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9533 for (int i = 0; i < childCount; i++) { 9534 PackageParser.Package childPkg = pkg.childPackages.get(i); 9535 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9536 } 9537 } 9538 9539 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9540 int flags) { 9541 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9542 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9543 } 9544 9545 private void updatePermissionsLPw(String changingPkg, 9546 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9547 // Make sure there are no dangling permission trees. 9548 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9549 while (it.hasNext()) { 9550 final BasePermission bp = it.next(); 9551 if (bp.packageSetting == null) { 9552 // We may not yet have parsed the package, so just see if 9553 // we still know about its settings. 9554 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9555 } 9556 if (bp.packageSetting == null) { 9557 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9558 + " from package " + bp.sourcePackage); 9559 it.remove(); 9560 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9561 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9562 Slog.i(TAG, "Removing old permission tree: " + bp.name 9563 + " from package " + bp.sourcePackage); 9564 flags |= UPDATE_PERMISSIONS_ALL; 9565 it.remove(); 9566 } 9567 } 9568 } 9569 9570 // Make sure all dynamic permissions have been assigned to a package, 9571 // and make sure there are no dangling permissions. 9572 it = mSettings.mPermissions.values().iterator(); 9573 while (it.hasNext()) { 9574 final BasePermission bp = it.next(); 9575 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9576 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9577 + bp.name + " pkg=" + bp.sourcePackage 9578 + " info=" + bp.pendingInfo); 9579 if (bp.packageSetting == null && bp.pendingInfo != null) { 9580 final BasePermission tree = findPermissionTreeLP(bp.name); 9581 if (tree != null && tree.perm != null) { 9582 bp.packageSetting = tree.packageSetting; 9583 bp.perm = new PackageParser.Permission(tree.perm.owner, 9584 new PermissionInfo(bp.pendingInfo)); 9585 bp.perm.info.packageName = tree.perm.info.packageName; 9586 bp.perm.info.name = bp.name; 9587 bp.uid = tree.uid; 9588 } 9589 } 9590 } 9591 if (bp.packageSetting == null) { 9592 // We may not yet have parsed the package, so just see if 9593 // we still know about its settings. 9594 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9595 } 9596 if (bp.packageSetting == null) { 9597 Slog.w(TAG, "Removing dangling permission: " + bp.name 9598 + " from package " + bp.sourcePackage); 9599 it.remove(); 9600 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9601 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9602 Slog.i(TAG, "Removing old permission: " + bp.name 9603 + " from package " + bp.sourcePackage); 9604 flags |= UPDATE_PERMISSIONS_ALL; 9605 it.remove(); 9606 } 9607 } 9608 } 9609 9610 // Now update the permissions for all packages, in particular 9611 // replace the granted permissions of the system packages. 9612 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9613 for (PackageParser.Package pkg : mPackages.values()) { 9614 if (pkg != pkgInfo) { 9615 // Only replace for packages on requested volume 9616 final String volumeUuid = getVolumeUuidForPackage(pkg); 9617 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9618 && Objects.equals(replaceVolumeUuid, volumeUuid); 9619 grantPermissionsLPw(pkg, replace, changingPkg); 9620 } 9621 } 9622 } 9623 9624 if (pkgInfo != null) { 9625 // Only replace for packages on requested volume 9626 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9627 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9628 && Objects.equals(replaceVolumeUuid, volumeUuid); 9629 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9630 } 9631 } 9632 9633 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9634 String packageOfInterest) { 9635 // IMPORTANT: There are two types of permissions: install and runtime. 9636 // Install time permissions are granted when the app is installed to 9637 // all device users and users added in the future. Runtime permissions 9638 // are granted at runtime explicitly to specific users. Normal and signature 9639 // protected permissions are install time permissions. Dangerous permissions 9640 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9641 // otherwise they are runtime permissions. This function does not manage 9642 // runtime permissions except for the case an app targeting Lollipop MR1 9643 // being upgraded to target a newer SDK, in which case dangerous permissions 9644 // are transformed from install time to runtime ones. 9645 9646 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9647 if (ps == null) { 9648 return; 9649 } 9650 9651 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9652 9653 PermissionsState permissionsState = ps.getPermissionsState(); 9654 PermissionsState origPermissions = permissionsState; 9655 9656 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9657 9658 boolean runtimePermissionsRevoked = false; 9659 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9660 9661 boolean changedInstallPermission = false; 9662 9663 if (replace) { 9664 ps.installPermissionsFixed = false; 9665 if (!ps.isSharedUser()) { 9666 origPermissions = new PermissionsState(permissionsState); 9667 permissionsState.reset(); 9668 } else { 9669 // We need to know only about runtime permission changes since the 9670 // calling code always writes the install permissions state but 9671 // the runtime ones are written only if changed. The only cases of 9672 // changed runtime permissions here are promotion of an install to 9673 // runtime and revocation of a runtime from a shared user. 9674 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9675 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9676 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9677 runtimePermissionsRevoked = true; 9678 } 9679 } 9680 } 9681 9682 permissionsState.setGlobalGids(mGlobalGids); 9683 9684 final int N = pkg.requestedPermissions.size(); 9685 for (int i=0; i<N; i++) { 9686 final String name = pkg.requestedPermissions.get(i); 9687 final BasePermission bp = mSettings.mPermissions.get(name); 9688 9689 if (DEBUG_INSTALL) { 9690 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9691 } 9692 9693 if (bp == null || bp.packageSetting == null) { 9694 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9695 Slog.w(TAG, "Unknown permission " + name 9696 + " in package " + pkg.packageName); 9697 } 9698 continue; 9699 } 9700 9701 final String perm = bp.name; 9702 boolean allowedSig = false; 9703 int grant = GRANT_DENIED; 9704 9705 // Keep track of app op permissions. 9706 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9707 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9708 if (pkgs == null) { 9709 pkgs = new ArraySet<>(); 9710 mAppOpPermissionPackages.put(bp.name, pkgs); 9711 } 9712 pkgs.add(pkg.packageName); 9713 } 9714 9715 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9716 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9717 >= Build.VERSION_CODES.M; 9718 switch (level) { 9719 case PermissionInfo.PROTECTION_NORMAL: { 9720 // For all apps normal permissions are install time ones. 9721 grant = GRANT_INSTALL; 9722 } break; 9723 9724 case PermissionInfo.PROTECTION_DANGEROUS: { 9725 // If a permission review is required for legacy apps we represent 9726 // their permissions as always granted runtime ones since we need 9727 // to keep the review required permission flag per user while an 9728 // install permission's state is shared across all users. 9729 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9730 // For legacy apps dangerous permissions are install time ones. 9731 grant = GRANT_INSTALL; 9732 } else if (origPermissions.hasInstallPermission(bp.name)) { 9733 // For legacy apps that became modern, install becomes runtime. 9734 grant = GRANT_UPGRADE; 9735 } else if (mPromoteSystemApps 9736 && isSystemApp(ps) 9737 && mExistingSystemPackages.contains(ps.name)) { 9738 // For legacy system apps, install becomes runtime. 9739 // We cannot check hasInstallPermission() for system apps since those 9740 // permissions were granted implicitly and not persisted pre-M. 9741 grant = GRANT_UPGRADE; 9742 } else { 9743 // For modern apps keep runtime permissions unchanged. 9744 grant = GRANT_RUNTIME; 9745 } 9746 } break; 9747 9748 case PermissionInfo.PROTECTION_SIGNATURE: { 9749 // For all apps signature permissions are install time ones. 9750 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9751 if (allowedSig) { 9752 grant = GRANT_INSTALL; 9753 } 9754 } break; 9755 } 9756 9757 if (DEBUG_INSTALL) { 9758 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9759 } 9760 9761 if (grant != GRANT_DENIED) { 9762 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9763 // If this is an existing, non-system package, then 9764 // we can't add any new permissions to it. 9765 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9766 // Except... if this is a permission that was added 9767 // to the platform (note: need to only do this when 9768 // updating the platform). 9769 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9770 grant = GRANT_DENIED; 9771 } 9772 } 9773 } 9774 9775 switch (grant) { 9776 case GRANT_INSTALL: { 9777 // Revoke this as runtime permission to handle the case of 9778 // a runtime permission being downgraded to an install one. 9779 // Also in permission review mode we keep dangerous permissions 9780 // for legacy apps 9781 for (int userId : UserManagerService.getInstance().getUserIds()) { 9782 if (origPermissions.getRuntimePermissionState( 9783 bp.name, userId) != null) { 9784 // Revoke the runtime permission and clear the flags. 9785 origPermissions.revokeRuntimePermission(bp, userId); 9786 origPermissions.updatePermissionFlags(bp, userId, 9787 PackageManager.MASK_PERMISSION_FLAGS, 0); 9788 // If we revoked a permission permission, we have to write. 9789 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9790 changedRuntimePermissionUserIds, userId); 9791 } 9792 } 9793 // Grant an install permission. 9794 if (permissionsState.grantInstallPermission(bp) != 9795 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9796 changedInstallPermission = true; 9797 } 9798 } break; 9799 9800 case GRANT_RUNTIME: { 9801 // Grant previously granted runtime permissions. 9802 for (int userId : UserManagerService.getInstance().getUserIds()) { 9803 PermissionState permissionState = origPermissions 9804 .getRuntimePermissionState(bp.name, userId); 9805 int flags = permissionState != null 9806 ? permissionState.getFlags() : 0; 9807 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9808 if (permissionsState.grantRuntimePermission(bp, userId) == 9809 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9810 // If we cannot put the permission as it was, we have to write. 9811 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9812 changedRuntimePermissionUserIds, userId); 9813 } 9814 // If the app supports runtime permissions no need for a review. 9815 if (Build.PERMISSIONS_REVIEW_REQUIRED 9816 && appSupportsRuntimePermissions 9817 && (flags & PackageManager 9818 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9819 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9820 // Since we changed the flags, we have to write. 9821 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9822 changedRuntimePermissionUserIds, userId); 9823 } 9824 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9825 && !appSupportsRuntimePermissions) { 9826 // For legacy apps that need a permission review, every new 9827 // runtime permission is granted but it is pending a review. 9828 // We also need to review only platform defined runtime 9829 // permissions as these are the only ones the platform knows 9830 // how to disable the API to simulate revocation as legacy 9831 // apps don't expect to run with revoked permissions. 9832 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9833 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9834 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9835 // We changed the flags, hence have to write. 9836 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9837 changedRuntimePermissionUserIds, userId); 9838 } 9839 } 9840 if (permissionsState.grantRuntimePermission(bp, userId) 9841 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9842 // We changed the permission, hence have to write. 9843 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9844 changedRuntimePermissionUserIds, userId); 9845 } 9846 } 9847 // Propagate the permission flags. 9848 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9849 } 9850 } break; 9851 9852 case GRANT_UPGRADE: { 9853 // Grant runtime permissions for a previously held install permission. 9854 PermissionState permissionState = origPermissions 9855 .getInstallPermissionState(bp.name); 9856 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9857 9858 if (origPermissions.revokeInstallPermission(bp) 9859 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9860 // We will be transferring the permission flags, so clear them. 9861 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9862 PackageManager.MASK_PERMISSION_FLAGS, 0); 9863 changedInstallPermission = true; 9864 } 9865 9866 // If the permission is not to be promoted to runtime we ignore it and 9867 // also its other flags as they are not applicable to install permissions. 9868 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9869 for (int userId : currentUserIds) { 9870 if (permissionsState.grantRuntimePermission(bp, userId) != 9871 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9872 // Transfer the permission flags. 9873 permissionsState.updatePermissionFlags(bp, userId, 9874 flags, flags); 9875 // If we granted the permission, we have to write. 9876 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9877 changedRuntimePermissionUserIds, userId); 9878 } 9879 } 9880 } 9881 } break; 9882 9883 default: { 9884 if (packageOfInterest == null 9885 || packageOfInterest.equals(pkg.packageName)) { 9886 Slog.w(TAG, "Not granting permission " + perm 9887 + " to package " + pkg.packageName 9888 + " because it was previously installed without"); 9889 } 9890 } break; 9891 } 9892 } else { 9893 if (permissionsState.revokeInstallPermission(bp) != 9894 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9895 // Also drop the permission flags. 9896 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9897 PackageManager.MASK_PERMISSION_FLAGS, 0); 9898 changedInstallPermission = true; 9899 Slog.i(TAG, "Un-granting permission " + perm 9900 + " from package " + pkg.packageName 9901 + " (protectionLevel=" + bp.protectionLevel 9902 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9903 + ")"); 9904 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9905 // Don't print warning for app op permissions, since it is fine for them 9906 // not to be granted, there is a UI for the user to decide. 9907 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9908 Slog.w(TAG, "Not granting permission " + perm 9909 + " to package " + pkg.packageName 9910 + " (protectionLevel=" + bp.protectionLevel 9911 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9912 + ")"); 9913 } 9914 } 9915 } 9916 } 9917 9918 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9919 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9920 // This is the first that we have heard about this package, so the 9921 // permissions we have now selected are fixed until explicitly 9922 // changed. 9923 ps.installPermissionsFixed = true; 9924 } 9925 9926 // Persist the runtime permissions state for users with changes. If permissions 9927 // were revoked because no app in the shared user declares them we have to 9928 // write synchronously to avoid losing runtime permissions state. 9929 for (int userId : changedRuntimePermissionUserIds) { 9930 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9931 } 9932 9933 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9934 } 9935 9936 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9937 boolean allowed = false; 9938 final int NP = PackageParser.NEW_PERMISSIONS.length; 9939 for (int ip=0; ip<NP; ip++) { 9940 final PackageParser.NewPermissionInfo npi 9941 = PackageParser.NEW_PERMISSIONS[ip]; 9942 if (npi.name.equals(perm) 9943 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9944 allowed = true; 9945 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9946 + pkg.packageName); 9947 break; 9948 } 9949 } 9950 return allowed; 9951 } 9952 9953 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9954 BasePermission bp, PermissionsState origPermissions) { 9955 boolean allowed; 9956 allowed = (compareSignatures( 9957 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9958 == PackageManager.SIGNATURE_MATCH) 9959 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9960 == PackageManager.SIGNATURE_MATCH); 9961 if (!allowed && (bp.protectionLevel 9962 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9963 if (isSystemApp(pkg)) { 9964 // For updated system applications, a system permission 9965 // is granted only if it had been defined by the original application. 9966 if (pkg.isUpdatedSystemApp()) { 9967 final PackageSetting sysPs = mSettings 9968 .getDisabledSystemPkgLPr(pkg.packageName); 9969 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9970 // If the original was granted this permission, we take 9971 // that grant decision as read and propagate it to the 9972 // update. 9973 if (sysPs.isPrivileged()) { 9974 allowed = true; 9975 } 9976 } else { 9977 // The system apk may have been updated with an older 9978 // version of the one on the data partition, but which 9979 // granted a new system permission that it didn't have 9980 // before. In this case we do want to allow the app to 9981 // now get the new permission if the ancestral apk is 9982 // privileged to get it. 9983 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9984 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9985 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9986 allowed = true; 9987 break; 9988 } 9989 } 9990 } 9991 // Also if a privileged parent package on the system image or any of 9992 // its children requested a privileged permission, the updated child 9993 // packages can also get the permission. 9994 if (pkg.parentPackage != null) { 9995 final PackageSetting disabledSysParentPs = mSettings 9996 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9997 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9998 && disabledSysParentPs.isPrivileged()) { 9999 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10000 allowed = true; 10001 } else if (disabledSysParentPs.pkg.childPackages != null) { 10002 final int count = disabledSysParentPs.pkg.childPackages.size(); 10003 for (int i = 0; i < count; i++) { 10004 PackageParser.Package disabledSysChildPkg = 10005 disabledSysParentPs.pkg.childPackages.get(i); 10006 if (isPackageRequestingPermission(disabledSysChildPkg, 10007 perm)) { 10008 allowed = true; 10009 break; 10010 } 10011 } 10012 } 10013 } 10014 } 10015 } 10016 } else { 10017 allowed = isPrivilegedApp(pkg); 10018 } 10019 } 10020 } 10021 if (!allowed) { 10022 if (!allowed && (bp.protectionLevel 10023 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10024 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10025 // If this was a previously normal/dangerous permission that got moved 10026 // to a system permission as part of the runtime permission redesign, then 10027 // we still want to blindly grant it to old apps. 10028 allowed = true; 10029 } 10030 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10031 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10032 // If this permission is to be granted to the system installer and 10033 // this app is an installer, then it gets the permission. 10034 allowed = true; 10035 } 10036 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10037 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10038 // If this permission is to be granted to the system verifier and 10039 // this app is a verifier, then it gets the permission. 10040 allowed = true; 10041 } 10042 if (!allowed && (bp.protectionLevel 10043 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10044 && isSystemApp(pkg)) { 10045 // Any pre-installed system app is allowed to get this permission. 10046 allowed = true; 10047 } 10048 if (!allowed && (bp.protectionLevel 10049 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10050 // For development permissions, a development permission 10051 // is granted only if it was already granted. 10052 allowed = origPermissions.hasInstallPermission(perm); 10053 } 10054 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10055 && pkg.packageName.equals(mSetupWizardPackage)) { 10056 // If this permission is to be granted to the system setup wizard and 10057 // this app is a setup wizard, then it gets the permission. 10058 allowed = true; 10059 } 10060 } 10061 return allowed; 10062 } 10063 10064 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10065 final int permCount = pkg.requestedPermissions.size(); 10066 for (int j = 0; j < permCount; j++) { 10067 String requestedPermission = pkg.requestedPermissions.get(j); 10068 if (permission.equals(requestedPermission)) { 10069 return true; 10070 } 10071 } 10072 return false; 10073 } 10074 10075 final class ActivityIntentResolver 10076 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10077 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10078 boolean defaultOnly, int userId) { 10079 if (!sUserManager.exists(userId)) return null; 10080 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10081 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10082 } 10083 10084 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10085 int userId) { 10086 if (!sUserManager.exists(userId)) return null; 10087 mFlags = flags; 10088 return super.queryIntent(intent, resolvedType, 10089 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10090 } 10091 10092 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10093 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10094 if (!sUserManager.exists(userId)) return null; 10095 if (packageActivities == null) { 10096 return null; 10097 } 10098 mFlags = flags; 10099 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10100 final int N = packageActivities.size(); 10101 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10102 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10103 10104 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10105 for (int i = 0; i < N; ++i) { 10106 intentFilters = packageActivities.get(i).intents; 10107 if (intentFilters != null && intentFilters.size() > 0) { 10108 PackageParser.ActivityIntentInfo[] array = 10109 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10110 intentFilters.toArray(array); 10111 listCut.add(array); 10112 } 10113 } 10114 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10115 } 10116 10117 /** 10118 * Finds a privileged activity that matches the specified activity names. 10119 */ 10120 private PackageParser.Activity findMatchingActivity( 10121 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10122 for (PackageParser.Activity sysActivity : activityList) { 10123 if (sysActivity.info.name.equals(activityInfo.name)) { 10124 return sysActivity; 10125 } 10126 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10127 return sysActivity; 10128 } 10129 if (sysActivity.info.targetActivity != null) { 10130 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10131 return sysActivity; 10132 } 10133 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10134 return sysActivity; 10135 } 10136 } 10137 } 10138 return null; 10139 } 10140 10141 public class IterGenerator<E> { 10142 public Iterator<E> generate(ActivityIntentInfo info) { 10143 return null; 10144 } 10145 } 10146 10147 public class ActionIterGenerator extends IterGenerator<String> { 10148 @Override 10149 public Iterator<String> generate(ActivityIntentInfo info) { 10150 return info.actionsIterator(); 10151 } 10152 } 10153 10154 public class CategoriesIterGenerator extends IterGenerator<String> { 10155 @Override 10156 public Iterator<String> generate(ActivityIntentInfo info) { 10157 return info.categoriesIterator(); 10158 } 10159 } 10160 10161 public class SchemesIterGenerator extends IterGenerator<String> { 10162 @Override 10163 public Iterator<String> generate(ActivityIntentInfo info) { 10164 return info.schemesIterator(); 10165 } 10166 } 10167 10168 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10169 @Override 10170 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10171 return info.authoritiesIterator(); 10172 } 10173 } 10174 10175 /** 10176 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10177 * MODIFIED. Do not pass in a list that should not be changed. 10178 */ 10179 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10180 IterGenerator<T> generator, Iterator<T> searchIterator) { 10181 // loop through the set of actions; every one must be found in the intent filter 10182 while (searchIterator.hasNext()) { 10183 // we must have at least one filter in the list to consider a match 10184 if (intentList.size() == 0) { 10185 break; 10186 } 10187 10188 final T searchAction = searchIterator.next(); 10189 10190 // loop through the set of intent filters 10191 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10192 while (intentIter.hasNext()) { 10193 final ActivityIntentInfo intentInfo = intentIter.next(); 10194 boolean selectionFound = false; 10195 10196 // loop through the intent filter's selection criteria; at least one 10197 // of them must match the searched criteria 10198 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10199 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10200 final T intentSelection = intentSelectionIter.next(); 10201 if (intentSelection != null && intentSelection.equals(searchAction)) { 10202 selectionFound = true; 10203 break; 10204 } 10205 } 10206 10207 // the selection criteria wasn't found in this filter's set; this filter 10208 // is not a potential match 10209 if (!selectionFound) { 10210 intentIter.remove(); 10211 } 10212 } 10213 } 10214 } 10215 10216 private boolean isProtectedAction(ActivityIntentInfo filter) { 10217 final Iterator<String> actionsIter = filter.actionsIterator(); 10218 while (actionsIter != null && actionsIter.hasNext()) { 10219 final String filterAction = actionsIter.next(); 10220 if (PROTECTED_ACTIONS.contains(filterAction)) { 10221 return true; 10222 } 10223 } 10224 return false; 10225 } 10226 10227 /** 10228 * Adjusts the priority of the given intent filter according to policy. 10229 * <p> 10230 * <ul> 10231 * <li>The priority for non privileged applications is capped to '0'</li> 10232 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10233 * <li>The priority for unbundled updates to privileged applications is capped to the 10234 * priority defined on the system partition</li> 10235 * </ul> 10236 * <p> 10237 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10238 * allowed to obtain any priority on any action. 10239 */ 10240 private void adjustPriority( 10241 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10242 // nothing to do; priority is fine as-is 10243 if (intent.getPriority() <= 0) { 10244 return; 10245 } 10246 10247 final ActivityInfo activityInfo = intent.activity.info; 10248 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10249 10250 final boolean privilegedApp = 10251 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10252 if (!privilegedApp) { 10253 // non-privileged applications can never define a priority >0 10254 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10255 + " package: " + applicationInfo.packageName 10256 + " activity: " + intent.activity.className 10257 + " origPrio: " + intent.getPriority()); 10258 intent.setPriority(0); 10259 return; 10260 } 10261 10262 if (systemActivities == null) { 10263 // the system package is not disabled; we're parsing the system partition 10264 if (isProtectedAction(intent)) { 10265 if (mDeferProtectedFilters) { 10266 // We can't deal with these just yet. No component should ever obtain a 10267 // >0 priority for a protected actions, with ONE exception -- the setup 10268 // wizard. The setup wizard, however, cannot be known until we're able to 10269 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10270 // until all intent filters have been processed. Chicken, meet egg. 10271 // Let the filter temporarily have a high priority and rectify the 10272 // priorities after all system packages have been scanned. 10273 mProtectedFilters.add(intent); 10274 if (DEBUG_FILTERS) { 10275 Slog.i(TAG, "Protected action; save for later;" 10276 + " package: " + applicationInfo.packageName 10277 + " activity: " + intent.activity.className 10278 + " origPrio: " + intent.getPriority()); 10279 } 10280 return; 10281 } else { 10282 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10283 Slog.i(TAG, "No setup wizard;" 10284 + " All protected intents capped to priority 0"); 10285 } 10286 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10287 if (DEBUG_FILTERS) { 10288 Slog.i(TAG, "Found setup wizard;" 10289 + " allow priority " + intent.getPriority() + ";" 10290 + " package: " + intent.activity.info.packageName 10291 + " activity: " + intent.activity.className 10292 + " priority: " + intent.getPriority()); 10293 } 10294 // setup wizard gets whatever it wants 10295 return; 10296 } 10297 Slog.w(TAG, "Protected action; cap priority to 0;" 10298 + " package: " + intent.activity.info.packageName 10299 + " activity: " + intent.activity.className 10300 + " origPrio: " + intent.getPriority()); 10301 intent.setPriority(0); 10302 return; 10303 } 10304 } 10305 // privileged apps on the system image get whatever priority they request 10306 return; 10307 } 10308 10309 // privileged app unbundled update ... try to find the same activity 10310 final PackageParser.Activity foundActivity = 10311 findMatchingActivity(systemActivities, activityInfo); 10312 if (foundActivity == null) { 10313 // this is a new activity; it cannot obtain >0 priority 10314 if (DEBUG_FILTERS) { 10315 Slog.i(TAG, "New activity; cap priority to 0;" 10316 + " package: " + applicationInfo.packageName 10317 + " activity: " + intent.activity.className 10318 + " origPrio: " + intent.getPriority()); 10319 } 10320 intent.setPriority(0); 10321 return; 10322 } 10323 10324 // found activity, now check for filter equivalence 10325 10326 // a shallow copy is enough; we modify the list, not its contents 10327 final List<ActivityIntentInfo> intentListCopy = 10328 new ArrayList<>(foundActivity.intents); 10329 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10330 10331 // find matching action subsets 10332 final Iterator<String> actionsIterator = intent.actionsIterator(); 10333 if (actionsIterator != null) { 10334 getIntentListSubset( 10335 intentListCopy, new ActionIterGenerator(), actionsIterator); 10336 if (intentListCopy.size() == 0) { 10337 // no more intents to match; we're not equivalent 10338 if (DEBUG_FILTERS) { 10339 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10340 + " package: " + applicationInfo.packageName 10341 + " activity: " + intent.activity.className 10342 + " origPrio: " + intent.getPriority()); 10343 } 10344 intent.setPriority(0); 10345 return; 10346 } 10347 } 10348 10349 // find matching category subsets 10350 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10351 if (categoriesIterator != null) { 10352 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10353 categoriesIterator); 10354 if (intentListCopy.size() == 0) { 10355 // no more intents to match; we're not equivalent 10356 if (DEBUG_FILTERS) { 10357 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10358 + " package: " + applicationInfo.packageName 10359 + " activity: " + intent.activity.className 10360 + " origPrio: " + intent.getPriority()); 10361 } 10362 intent.setPriority(0); 10363 return; 10364 } 10365 } 10366 10367 // find matching schemes subsets 10368 final Iterator<String> schemesIterator = intent.schemesIterator(); 10369 if (schemesIterator != null) { 10370 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10371 schemesIterator); 10372 if (intentListCopy.size() == 0) { 10373 // no more intents to match; we're not equivalent 10374 if (DEBUG_FILTERS) { 10375 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10376 + " package: " + applicationInfo.packageName 10377 + " activity: " + intent.activity.className 10378 + " origPrio: " + intent.getPriority()); 10379 } 10380 intent.setPriority(0); 10381 return; 10382 } 10383 } 10384 10385 // find matching authorities subsets 10386 final Iterator<IntentFilter.AuthorityEntry> 10387 authoritiesIterator = intent.authoritiesIterator(); 10388 if (authoritiesIterator != null) { 10389 getIntentListSubset(intentListCopy, 10390 new AuthoritiesIterGenerator(), 10391 authoritiesIterator); 10392 if (intentListCopy.size() == 0) { 10393 // no more intents to match; we're not equivalent 10394 if (DEBUG_FILTERS) { 10395 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10396 + " package: " + applicationInfo.packageName 10397 + " activity: " + intent.activity.className 10398 + " origPrio: " + intent.getPriority()); 10399 } 10400 intent.setPriority(0); 10401 return; 10402 } 10403 } 10404 10405 // we found matching filter(s); app gets the max priority of all intents 10406 int cappedPriority = 0; 10407 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10408 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10409 } 10410 if (intent.getPriority() > cappedPriority) { 10411 if (DEBUG_FILTERS) { 10412 Slog.i(TAG, "Found matching filter(s);" 10413 + " cap priority to " + cappedPriority + ";" 10414 + " package: " + applicationInfo.packageName 10415 + " activity: " + intent.activity.className 10416 + " origPrio: " + intent.getPriority()); 10417 } 10418 intent.setPriority(cappedPriority); 10419 return; 10420 } 10421 // all this for nothing; the requested priority was <= what was on the system 10422 } 10423 10424 public final void addActivity(PackageParser.Activity a, String type) { 10425 mActivities.put(a.getComponentName(), a); 10426 if (DEBUG_SHOW_INFO) 10427 Log.v( 10428 TAG, " " + type + " " + 10429 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10430 if (DEBUG_SHOW_INFO) 10431 Log.v(TAG, " Class=" + a.info.name); 10432 final int NI = a.intents.size(); 10433 for (int j=0; j<NI; j++) { 10434 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10435 if ("activity".equals(type)) { 10436 final PackageSetting ps = 10437 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10438 final List<PackageParser.Activity> systemActivities = 10439 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10440 adjustPriority(systemActivities, intent); 10441 } 10442 if (DEBUG_SHOW_INFO) { 10443 Log.v(TAG, " IntentFilter:"); 10444 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10445 } 10446 if (!intent.debugCheck()) { 10447 Log.w(TAG, "==> For Activity " + a.info.name); 10448 } 10449 addFilter(intent); 10450 } 10451 } 10452 10453 public final void removeActivity(PackageParser.Activity a, String type) { 10454 mActivities.remove(a.getComponentName()); 10455 if (DEBUG_SHOW_INFO) { 10456 Log.v(TAG, " " + type + " " 10457 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10458 : a.info.name) + ":"); 10459 Log.v(TAG, " Class=" + a.info.name); 10460 } 10461 final int NI = a.intents.size(); 10462 for (int j=0; j<NI; j++) { 10463 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10464 if (DEBUG_SHOW_INFO) { 10465 Log.v(TAG, " IntentFilter:"); 10466 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10467 } 10468 removeFilter(intent); 10469 } 10470 } 10471 10472 @Override 10473 protected boolean allowFilterResult( 10474 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10475 ActivityInfo filterAi = filter.activity.info; 10476 for (int i=dest.size()-1; i>=0; i--) { 10477 ActivityInfo destAi = dest.get(i).activityInfo; 10478 if (destAi.name == filterAi.name 10479 && destAi.packageName == filterAi.packageName) { 10480 return false; 10481 } 10482 } 10483 return true; 10484 } 10485 10486 @Override 10487 protected ActivityIntentInfo[] newArray(int size) { 10488 return new ActivityIntentInfo[size]; 10489 } 10490 10491 @Override 10492 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10493 if (!sUserManager.exists(userId)) return true; 10494 PackageParser.Package p = filter.activity.owner; 10495 if (p != null) { 10496 PackageSetting ps = (PackageSetting)p.mExtras; 10497 if (ps != null) { 10498 // System apps are never considered stopped for purposes of 10499 // filtering, because there may be no way for the user to 10500 // actually re-launch them. 10501 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10502 && ps.getStopped(userId); 10503 } 10504 } 10505 return false; 10506 } 10507 10508 @Override 10509 protected boolean isPackageForFilter(String packageName, 10510 PackageParser.ActivityIntentInfo info) { 10511 return packageName.equals(info.activity.owner.packageName); 10512 } 10513 10514 @Override 10515 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10516 int match, int userId) { 10517 if (!sUserManager.exists(userId)) return null; 10518 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10519 return null; 10520 } 10521 final PackageParser.Activity activity = info.activity; 10522 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10523 if (ps == null) { 10524 return null; 10525 } 10526 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10527 ps.readUserState(userId), userId); 10528 if (ai == null) { 10529 return null; 10530 } 10531 final ResolveInfo res = new ResolveInfo(); 10532 res.activityInfo = ai; 10533 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10534 res.filter = info; 10535 } 10536 if (info != null) { 10537 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10538 } 10539 res.priority = info.getPriority(); 10540 res.preferredOrder = activity.owner.mPreferredOrder; 10541 //System.out.println("Result: " + res.activityInfo.className + 10542 // " = " + res.priority); 10543 res.match = match; 10544 res.isDefault = info.hasDefault; 10545 res.labelRes = info.labelRes; 10546 res.nonLocalizedLabel = info.nonLocalizedLabel; 10547 if (userNeedsBadging(userId)) { 10548 res.noResourceId = true; 10549 } else { 10550 res.icon = info.icon; 10551 } 10552 res.iconResourceId = info.icon; 10553 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10554 return res; 10555 } 10556 10557 @Override 10558 protected void sortResults(List<ResolveInfo> results) { 10559 Collections.sort(results, mResolvePrioritySorter); 10560 } 10561 10562 @Override 10563 protected void dumpFilter(PrintWriter out, String prefix, 10564 PackageParser.ActivityIntentInfo filter) { 10565 out.print(prefix); out.print( 10566 Integer.toHexString(System.identityHashCode(filter.activity))); 10567 out.print(' '); 10568 filter.activity.printComponentShortName(out); 10569 out.print(" filter "); 10570 out.println(Integer.toHexString(System.identityHashCode(filter))); 10571 } 10572 10573 @Override 10574 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10575 return filter.activity; 10576 } 10577 10578 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10579 PackageParser.Activity activity = (PackageParser.Activity)label; 10580 out.print(prefix); out.print( 10581 Integer.toHexString(System.identityHashCode(activity))); 10582 out.print(' '); 10583 activity.printComponentShortName(out); 10584 if (count > 1) { 10585 out.print(" ("); out.print(count); out.print(" filters)"); 10586 } 10587 out.println(); 10588 } 10589 10590 // Keys are String (activity class name), values are Activity. 10591 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10592 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10593 private int mFlags; 10594 } 10595 10596 private final class ServiceIntentResolver 10597 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10598 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10599 boolean defaultOnly, int userId) { 10600 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10601 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10602 } 10603 10604 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10605 int userId) { 10606 if (!sUserManager.exists(userId)) return null; 10607 mFlags = flags; 10608 return super.queryIntent(intent, resolvedType, 10609 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10610 } 10611 10612 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10613 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10614 if (!sUserManager.exists(userId)) return null; 10615 if (packageServices == null) { 10616 return null; 10617 } 10618 mFlags = flags; 10619 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10620 final int N = packageServices.size(); 10621 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10622 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10623 10624 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10625 for (int i = 0; i < N; ++i) { 10626 intentFilters = packageServices.get(i).intents; 10627 if (intentFilters != null && intentFilters.size() > 0) { 10628 PackageParser.ServiceIntentInfo[] array = 10629 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10630 intentFilters.toArray(array); 10631 listCut.add(array); 10632 } 10633 } 10634 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10635 } 10636 10637 public final void addService(PackageParser.Service s) { 10638 mServices.put(s.getComponentName(), s); 10639 if (DEBUG_SHOW_INFO) { 10640 Log.v(TAG, " " 10641 + (s.info.nonLocalizedLabel != null 10642 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10643 Log.v(TAG, " Class=" + s.info.name); 10644 } 10645 final int NI = s.intents.size(); 10646 int j; 10647 for (j=0; j<NI; j++) { 10648 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10649 if (DEBUG_SHOW_INFO) { 10650 Log.v(TAG, " IntentFilter:"); 10651 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10652 } 10653 if (!intent.debugCheck()) { 10654 Log.w(TAG, "==> For Service " + s.info.name); 10655 } 10656 addFilter(intent); 10657 } 10658 } 10659 10660 public final void removeService(PackageParser.Service s) { 10661 mServices.remove(s.getComponentName()); 10662 if (DEBUG_SHOW_INFO) { 10663 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10664 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10665 Log.v(TAG, " Class=" + s.info.name); 10666 } 10667 final int NI = s.intents.size(); 10668 int j; 10669 for (j=0; j<NI; j++) { 10670 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10671 if (DEBUG_SHOW_INFO) { 10672 Log.v(TAG, " IntentFilter:"); 10673 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10674 } 10675 removeFilter(intent); 10676 } 10677 } 10678 10679 @Override 10680 protected boolean allowFilterResult( 10681 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10682 ServiceInfo filterSi = filter.service.info; 10683 for (int i=dest.size()-1; i>=0; i--) { 10684 ServiceInfo destAi = dest.get(i).serviceInfo; 10685 if (destAi.name == filterSi.name 10686 && destAi.packageName == filterSi.packageName) { 10687 return false; 10688 } 10689 } 10690 return true; 10691 } 10692 10693 @Override 10694 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10695 return new PackageParser.ServiceIntentInfo[size]; 10696 } 10697 10698 @Override 10699 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10700 if (!sUserManager.exists(userId)) return true; 10701 PackageParser.Package p = filter.service.owner; 10702 if (p != null) { 10703 PackageSetting ps = (PackageSetting)p.mExtras; 10704 if (ps != null) { 10705 // System apps are never considered stopped for purposes of 10706 // filtering, because there may be no way for the user to 10707 // actually re-launch them. 10708 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10709 && ps.getStopped(userId); 10710 } 10711 } 10712 return false; 10713 } 10714 10715 @Override 10716 protected boolean isPackageForFilter(String packageName, 10717 PackageParser.ServiceIntentInfo info) { 10718 return packageName.equals(info.service.owner.packageName); 10719 } 10720 10721 @Override 10722 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10723 int match, int userId) { 10724 if (!sUserManager.exists(userId)) return null; 10725 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10726 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10727 return null; 10728 } 10729 final PackageParser.Service service = info.service; 10730 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10731 if (ps == null) { 10732 return null; 10733 } 10734 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10735 ps.readUserState(userId), userId); 10736 if (si == null) { 10737 return null; 10738 } 10739 final ResolveInfo res = new ResolveInfo(); 10740 res.serviceInfo = si; 10741 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10742 res.filter = filter; 10743 } 10744 res.priority = info.getPriority(); 10745 res.preferredOrder = service.owner.mPreferredOrder; 10746 res.match = match; 10747 res.isDefault = info.hasDefault; 10748 res.labelRes = info.labelRes; 10749 res.nonLocalizedLabel = info.nonLocalizedLabel; 10750 res.icon = info.icon; 10751 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10752 return res; 10753 } 10754 10755 @Override 10756 protected void sortResults(List<ResolveInfo> results) { 10757 Collections.sort(results, mResolvePrioritySorter); 10758 } 10759 10760 @Override 10761 protected void dumpFilter(PrintWriter out, String prefix, 10762 PackageParser.ServiceIntentInfo filter) { 10763 out.print(prefix); out.print( 10764 Integer.toHexString(System.identityHashCode(filter.service))); 10765 out.print(' '); 10766 filter.service.printComponentShortName(out); 10767 out.print(" filter "); 10768 out.println(Integer.toHexString(System.identityHashCode(filter))); 10769 } 10770 10771 @Override 10772 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10773 return filter.service; 10774 } 10775 10776 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10777 PackageParser.Service service = (PackageParser.Service)label; 10778 out.print(prefix); out.print( 10779 Integer.toHexString(System.identityHashCode(service))); 10780 out.print(' '); 10781 service.printComponentShortName(out); 10782 if (count > 1) { 10783 out.print(" ("); out.print(count); out.print(" filters)"); 10784 } 10785 out.println(); 10786 } 10787 10788// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10789// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10790// final List<ResolveInfo> retList = Lists.newArrayList(); 10791// while (i.hasNext()) { 10792// final ResolveInfo resolveInfo = (ResolveInfo) i; 10793// if (isEnabledLP(resolveInfo.serviceInfo)) { 10794// retList.add(resolveInfo); 10795// } 10796// } 10797// return retList; 10798// } 10799 10800 // Keys are String (activity class name), values are Activity. 10801 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10802 = new ArrayMap<ComponentName, PackageParser.Service>(); 10803 private int mFlags; 10804 }; 10805 10806 private final class ProviderIntentResolver 10807 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10808 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10809 boolean defaultOnly, int userId) { 10810 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10811 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10812 } 10813 10814 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10815 int userId) { 10816 if (!sUserManager.exists(userId)) 10817 return null; 10818 mFlags = flags; 10819 return super.queryIntent(intent, resolvedType, 10820 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10821 } 10822 10823 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10824 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10825 if (!sUserManager.exists(userId)) 10826 return null; 10827 if (packageProviders == null) { 10828 return null; 10829 } 10830 mFlags = flags; 10831 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10832 final int N = packageProviders.size(); 10833 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10834 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10835 10836 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10837 for (int i = 0; i < N; ++i) { 10838 intentFilters = packageProviders.get(i).intents; 10839 if (intentFilters != null && intentFilters.size() > 0) { 10840 PackageParser.ProviderIntentInfo[] array = 10841 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10842 intentFilters.toArray(array); 10843 listCut.add(array); 10844 } 10845 } 10846 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10847 } 10848 10849 public final void addProvider(PackageParser.Provider p) { 10850 if (mProviders.containsKey(p.getComponentName())) { 10851 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10852 return; 10853 } 10854 10855 mProviders.put(p.getComponentName(), p); 10856 if (DEBUG_SHOW_INFO) { 10857 Log.v(TAG, " " 10858 + (p.info.nonLocalizedLabel != null 10859 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10860 Log.v(TAG, " Class=" + p.info.name); 10861 } 10862 final int NI = p.intents.size(); 10863 int j; 10864 for (j = 0; j < NI; j++) { 10865 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10866 if (DEBUG_SHOW_INFO) { 10867 Log.v(TAG, " IntentFilter:"); 10868 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10869 } 10870 if (!intent.debugCheck()) { 10871 Log.w(TAG, "==> For Provider " + p.info.name); 10872 } 10873 addFilter(intent); 10874 } 10875 } 10876 10877 public final void removeProvider(PackageParser.Provider p) { 10878 mProviders.remove(p.getComponentName()); 10879 if (DEBUG_SHOW_INFO) { 10880 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10881 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10882 Log.v(TAG, " Class=" + p.info.name); 10883 } 10884 final int NI = p.intents.size(); 10885 int j; 10886 for (j = 0; j < NI; j++) { 10887 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10888 if (DEBUG_SHOW_INFO) { 10889 Log.v(TAG, " IntentFilter:"); 10890 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10891 } 10892 removeFilter(intent); 10893 } 10894 } 10895 10896 @Override 10897 protected boolean allowFilterResult( 10898 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10899 ProviderInfo filterPi = filter.provider.info; 10900 for (int i = dest.size() - 1; i >= 0; i--) { 10901 ProviderInfo destPi = dest.get(i).providerInfo; 10902 if (destPi.name == filterPi.name 10903 && destPi.packageName == filterPi.packageName) { 10904 return false; 10905 } 10906 } 10907 return true; 10908 } 10909 10910 @Override 10911 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10912 return new PackageParser.ProviderIntentInfo[size]; 10913 } 10914 10915 @Override 10916 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10917 if (!sUserManager.exists(userId)) 10918 return true; 10919 PackageParser.Package p = filter.provider.owner; 10920 if (p != null) { 10921 PackageSetting ps = (PackageSetting) p.mExtras; 10922 if (ps != null) { 10923 // System apps are never considered stopped for purposes of 10924 // filtering, because there may be no way for the user to 10925 // actually re-launch them. 10926 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10927 && ps.getStopped(userId); 10928 } 10929 } 10930 return false; 10931 } 10932 10933 @Override 10934 protected boolean isPackageForFilter(String packageName, 10935 PackageParser.ProviderIntentInfo info) { 10936 return packageName.equals(info.provider.owner.packageName); 10937 } 10938 10939 @Override 10940 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10941 int match, int userId) { 10942 if (!sUserManager.exists(userId)) 10943 return null; 10944 final PackageParser.ProviderIntentInfo info = filter; 10945 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10946 return null; 10947 } 10948 final PackageParser.Provider provider = info.provider; 10949 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10950 if (ps == null) { 10951 return null; 10952 } 10953 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10954 ps.readUserState(userId), userId); 10955 if (pi == null) { 10956 return null; 10957 } 10958 final ResolveInfo res = new ResolveInfo(); 10959 res.providerInfo = pi; 10960 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10961 res.filter = filter; 10962 } 10963 res.priority = info.getPriority(); 10964 res.preferredOrder = provider.owner.mPreferredOrder; 10965 res.match = match; 10966 res.isDefault = info.hasDefault; 10967 res.labelRes = info.labelRes; 10968 res.nonLocalizedLabel = info.nonLocalizedLabel; 10969 res.icon = info.icon; 10970 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10971 return res; 10972 } 10973 10974 @Override 10975 protected void sortResults(List<ResolveInfo> results) { 10976 Collections.sort(results, mResolvePrioritySorter); 10977 } 10978 10979 @Override 10980 protected void dumpFilter(PrintWriter out, String prefix, 10981 PackageParser.ProviderIntentInfo filter) { 10982 out.print(prefix); 10983 out.print( 10984 Integer.toHexString(System.identityHashCode(filter.provider))); 10985 out.print(' '); 10986 filter.provider.printComponentShortName(out); 10987 out.print(" filter "); 10988 out.println(Integer.toHexString(System.identityHashCode(filter))); 10989 } 10990 10991 @Override 10992 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10993 return filter.provider; 10994 } 10995 10996 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10997 PackageParser.Provider provider = (PackageParser.Provider)label; 10998 out.print(prefix); out.print( 10999 Integer.toHexString(System.identityHashCode(provider))); 11000 out.print(' '); 11001 provider.printComponentShortName(out); 11002 if (count > 1) { 11003 out.print(" ("); out.print(count); out.print(" filters)"); 11004 } 11005 out.println(); 11006 } 11007 11008 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11009 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11010 private int mFlags; 11011 } 11012 11013 private static final class EphemeralIntentResolver 11014 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11015 @Override 11016 protected EphemeralResolveIntentInfo[] newArray(int size) { 11017 return new EphemeralResolveIntentInfo[size]; 11018 } 11019 11020 @Override 11021 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11022 return true; 11023 } 11024 11025 @Override 11026 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11027 int userId) { 11028 if (!sUserManager.exists(userId)) { 11029 return null; 11030 } 11031 return info.getEphemeralResolveInfo(); 11032 } 11033 } 11034 11035 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11036 new Comparator<ResolveInfo>() { 11037 public int compare(ResolveInfo r1, ResolveInfo r2) { 11038 int v1 = r1.priority; 11039 int v2 = r2.priority; 11040 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11041 if (v1 != v2) { 11042 return (v1 > v2) ? -1 : 1; 11043 } 11044 v1 = r1.preferredOrder; 11045 v2 = r2.preferredOrder; 11046 if (v1 != v2) { 11047 return (v1 > v2) ? -1 : 1; 11048 } 11049 if (r1.isDefault != r2.isDefault) { 11050 return r1.isDefault ? -1 : 1; 11051 } 11052 v1 = r1.match; 11053 v2 = r2.match; 11054 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11055 if (v1 != v2) { 11056 return (v1 > v2) ? -1 : 1; 11057 } 11058 if (r1.system != r2.system) { 11059 return r1.system ? -1 : 1; 11060 } 11061 if (r1.activityInfo != null) { 11062 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11063 } 11064 if (r1.serviceInfo != null) { 11065 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11066 } 11067 if (r1.providerInfo != null) { 11068 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11069 } 11070 return 0; 11071 } 11072 }; 11073 11074 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11075 new Comparator<ProviderInfo>() { 11076 public int compare(ProviderInfo p1, ProviderInfo p2) { 11077 final int v1 = p1.initOrder; 11078 final int v2 = p2.initOrder; 11079 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11080 } 11081 }; 11082 11083 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11084 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11085 final int[] userIds) { 11086 mHandler.post(new Runnable() { 11087 @Override 11088 public void run() { 11089 try { 11090 final IActivityManager am = ActivityManagerNative.getDefault(); 11091 if (am == null) return; 11092 final int[] resolvedUserIds; 11093 if (userIds == null) { 11094 resolvedUserIds = am.getRunningUserIds(); 11095 } else { 11096 resolvedUserIds = userIds; 11097 } 11098 for (int id : resolvedUserIds) { 11099 final Intent intent = new Intent(action, 11100 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11101 if (extras != null) { 11102 intent.putExtras(extras); 11103 } 11104 if (targetPkg != null) { 11105 intent.setPackage(targetPkg); 11106 } 11107 // Modify the UID when posting to other users 11108 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11109 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11110 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11111 intent.putExtra(Intent.EXTRA_UID, uid); 11112 } 11113 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11114 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11115 if (DEBUG_BROADCASTS) { 11116 RuntimeException here = new RuntimeException("here"); 11117 here.fillInStackTrace(); 11118 Slog.d(TAG, "Sending to user " + id + ": " 11119 + intent.toShortString(false, true, false, false) 11120 + " " + intent.getExtras(), here); 11121 } 11122 am.broadcastIntent(null, intent, null, finishedReceiver, 11123 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11124 null, finishedReceiver != null, false, id); 11125 } 11126 } catch (RemoteException ex) { 11127 } 11128 } 11129 }); 11130 } 11131 11132 /** 11133 * Check if the external storage media is available. This is true if there 11134 * is a mounted external storage medium or if the external storage is 11135 * emulated. 11136 */ 11137 private boolean isExternalMediaAvailable() { 11138 return mMediaMounted || Environment.isExternalStorageEmulated(); 11139 } 11140 11141 @Override 11142 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11143 // writer 11144 synchronized (mPackages) { 11145 if (!isExternalMediaAvailable()) { 11146 // If the external storage is no longer mounted at this point, 11147 // the caller may not have been able to delete all of this 11148 // packages files and can not delete any more. Bail. 11149 return null; 11150 } 11151 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11152 if (lastPackage != null) { 11153 pkgs.remove(lastPackage); 11154 } 11155 if (pkgs.size() > 0) { 11156 return pkgs.get(0); 11157 } 11158 } 11159 return null; 11160 } 11161 11162 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11163 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11164 userId, andCode ? 1 : 0, packageName); 11165 if (mSystemReady) { 11166 msg.sendToTarget(); 11167 } else { 11168 if (mPostSystemReadyMessages == null) { 11169 mPostSystemReadyMessages = new ArrayList<>(); 11170 } 11171 mPostSystemReadyMessages.add(msg); 11172 } 11173 } 11174 11175 void startCleaningPackages() { 11176 // reader 11177 if (!isExternalMediaAvailable()) { 11178 return; 11179 } 11180 synchronized (mPackages) { 11181 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11182 return; 11183 } 11184 } 11185 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11186 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11187 IActivityManager am = ActivityManagerNative.getDefault(); 11188 if (am != null) { 11189 try { 11190 am.startService(null, intent, null, mContext.getOpPackageName(), 11191 UserHandle.USER_SYSTEM); 11192 } catch (RemoteException e) { 11193 } 11194 } 11195 } 11196 11197 @Override 11198 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11199 int installFlags, String installerPackageName, int userId) { 11200 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11201 11202 final int callingUid = Binder.getCallingUid(); 11203 enforceCrossUserPermission(callingUid, userId, 11204 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11205 11206 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11207 try { 11208 if (observer != null) { 11209 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11210 } 11211 } catch (RemoteException re) { 11212 } 11213 return; 11214 } 11215 11216 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11217 installFlags |= PackageManager.INSTALL_FROM_ADB; 11218 11219 } else { 11220 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11221 // about installerPackageName. 11222 11223 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11224 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11225 } 11226 11227 UserHandle user; 11228 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11229 user = UserHandle.ALL; 11230 } else { 11231 user = new UserHandle(userId); 11232 } 11233 11234 // Only system components can circumvent runtime permissions when installing. 11235 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11236 && mContext.checkCallingOrSelfPermission(Manifest.permission 11237 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11238 throw new SecurityException("You need the " 11239 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11240 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11241 } 11242 11243 final File originFile = new File(originPath); 11244 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11245 11246 final Message msg = mHandler.obtainMessage(INIT_COPY); 11247 final VerificationInfo verificationInfo = new VerificationInfo( 11248 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11249 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11250 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11251 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11252 null /*certificates*/); 11253 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11254 msg.obj = params; 11255 11256 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11257 System.identityHashCode(msg.obj)); 11258 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11259 System.identityHashCode(msg.obj)); 11260 11261 mHandler.sendMessage(msg); 11262 } 11263 11264 void installStage(String packageName, File stagedDir, String stagedCid, 11265 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11266 String installerPackageName, int installerUid, UserHandle user, 11267 Certificate[][] certificates) { 11268 if (DEBUG_EPHEMERAL) { 11269 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11270 Slog.d(TAG, "Ephemeral install of " + packageName); 11271 } 11272 } 11273 final VerificationInfo verificationInfo = new VerificationInfo( 11274 sessionParams.originatingUri, sessionParams.referrerUri, 11275 sessionParams.originatingUid, installerUid); 11276 11277 final OriginInfo origin; 11278 if (stagedDir != null) { 11279 origin = OriginInfo.fromStagedFile(stagedDir); 11280 } else { 11281 origin = OriginInfo.fromStagedContainer(stagedCid); 11282 } 11283 11284 final Message msg = mHandler.obtainMessage(INIT_COPY); 11285 final InstallParams params = new InstallParams(origin, null, observer, 11286 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11287 verificationInfo, user, sessionParams.abiOverride, 11288 sessionParams.grantedRuntimePermissions, certificates); 11289 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11290 msg.obj = params; 11291 11292 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11293 System.identityHashCode(msg.obj)); 11294 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11295 System.identityHashCode(msg.obj)); 11296 11297 mHandler.sendMessage(msg); 11298 } 11299 11300 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11301 int userId) { 11302 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11303 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11304 } 11305 11306 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11307 int appId, int userId) { 11308 Bundle extras = new Bundle(1); 11309 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11310 11311 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11312 packageName, extras, 0, null, null, new int[] {userId}); 11313 try { 11314 IActivityManager am = ActivityManagerNative.getDefault(); 11315 if (isSystem && am.isUserRunning(userId, 0)) { 11316 // The just-installed/enabled app is bundled on the system, so presumed 11317 // to be able to run automatically without needing an explicit launch. 11318 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11319 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11320 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11321 .setPackage(packageName); 11322 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11323 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11324 } 11325 } catch (RemoteException e) { 11326 // shouldn't happen 11327 Slog.w(TAG, "Unable to bootstrap installed package", e); 11328 } 11329 } 11330 11331 @Override 11332 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11333 int userId) { 11334 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11335 PackageSetting pkgSetting; 11336 final int uid = Binder.getCallingUid(); 11337 enforceCrossUserPermission(uid, userId, 11338 true /* requireFullPermission */, true /* checkShell */, 11339 "setApplicationHiddenSetting for user " + userId); 11340 11341 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11342 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11343 return false; 11344 } 11345 11346 long callingId = Binder.clearCallingIdentity(); 11347 try { 11348 boolean sendAdded = false; 11349 boolean sendRemoved = false; 11350 // writer 11351 synchronized (mPackages) { 11352 pkgSetting = mSettings.mPackages.get(packageName); 11353 if (pkgSetting == null) { 11354 return false; 11355 } 11356 if (pkgSetting.getHidden(userId) != hidden) { 11357 pkgSetting.setHidden(hidden, userId); 11358 mSettings.writePackageRestrictionsLPr(userId); 11359 if (hidden) { 11360 sendRemoved = true; 11361 } else { 11362 sendAdded = true; 11363 } 11364 } 11365 } 11366 if (sendAdded) { 11367 sendPackageAddedForUser(packageName, pkgSetting, userId); 11368 return true; 11369 } 11370 if (sendRemoved) { 11371 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11372 "hiding pkg"); 11373 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11374 return true; 11375 } 11376 } finally { 11377 Binder.restoreCallingIdentity(callingId); 11378 } 11379 return false; 11380 } 11381 11382 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11383 int userId) { 11384 final PackageRemovedInfo info = new PackageRemovedInfo(); 11385 info.removedPackage = packageName; 11386 info.removedUsers = new int[] {userId}; 11387 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11388 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11389 } 11390 11391 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11392 if (pkgList.length > 0) { 11393 Bundle extras = new Bundle(1); 11394 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11395 11396 sendPackageBroadcast( 11397 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11398 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11399 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11400 new int[] {userId}); 11401 } 11402 } 11403 11404 /** 11405 * Returns true if application is not found or there was an error. Otherwise it returns 11406 * the hidden state of the package for the given user. 11407 */ 11408 @Override 11409 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11410 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11411 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11412 true /* requireFullPermission */, false /* checkShell */, 11413 "getApplicationHidden for user " + userId); 11414 PackageSetting pkgSetting; 11415 long callingId = Binder.clearCallingIdentity(); 11416 try { 11417 // writer 11418 synchronized (mPackages) { 11419 pkgSetting = mSettings.mPackages.get(packageName); 11420 if (pkgSetting == null) { 11421 return true; 11422 } 11423 return pkgSetting.getHidden(userId); 11424 } 11425 } finally { 11426 Binder.restoreCallingIdentity(callingId); 11427 } 11428 } 11429 11430 /** 11431 * @hide 11432 */ 11433 @Override 11434 public int installExistingPackageAsUser(String packageName, int userId) { 11435 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11436 null); 11437 PackageSetting pkgSetting; 11438 final int uid = Binder.getCallingUid(); 11439 enforceCrossUserPermission(uid, userId, 11440 true /* requireFullPermission */, true /* checkShell */, 11441 "installExistingPackage for user " + userId); 11442 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11443 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11444 } 11445 11446 long callingId = Binder.clearCallingIdentity(); 11447 try { 11448 boolean installed = false; 11449 11450 // writer 11451 synchronized (mPackages) { 11452 pkgSetting = mSettings.mPackages.get(packageName); 11453 if (pkgSetting == null) { 11454 return PackageManager.INSTALL_FAILED_INVALID_URI; 11455 } 11456 if (!pkgSetting.getInstalled(userId)) { 11457 pkgSetting.setInstalled(true, userId); 11458 pkgSetting.setHidden(false, userId); 11459 mSettings.writePackageRestrictionsLPr(userId); 11460 installed = true; 11461 } 11462 } 11463 11464 if (installed) { 11465 if (pkgSetting.pkg != null) { 11466 synchronized (mInstallLock) { 11467 // We don't need to freeze for a brand new install 11468 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11469 } 11470 } 11471 sendPackageAddedForUser(packageName, pkgSetting, userId); 11472 } 11473 } finally { 11474 Binder.restoreCallingIdentity(callingId); 11475 } 11476 11477 return PackageManager.INSTALL_SUCCEEDED; 11478 } 11479 11480 boolean isUserRestricted(int userId, String restrictionKey) { 11481 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11482 if (restrictions.getBoolean(restrictionKey, false)) { 11483 Log.w(TAG, "User is restricted: " + restrictionKey); 11484 return true; 11485 } 11486 return false; 11487 } 11488 11489 @Override 11490 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11491 int userId) { 11492 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11493 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11494 true /* requireFullPermission */, true /* checkShell */, 11495 "setPackagesSuspended for user " + userId); 11496 11497 if (ArrayUtils.isEmpty(packageNames)) { 11498 return packageNames; 11499 } 11500 11501 // List of package names for whom the suspended state has changed. 11502 List<String> changedPackages = new ArrayList<>(packageNames.length); 11503 // List of package names for whom the suspended state is not set as requested in this 11504 // method. 11505 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11506 long callingId = Binder.clearCallingIdentity(); 11507 try { 11508 for (int i = 0; i < packageNames.length; i++) { 11509 String packageName = packageNames[i]; 11510 boolean changed = false; 11511 final int appId; 11512 synchronized (mPackages) { 11513 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11514 if (pkgSetting == null) { 11515 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11516 + "\". Skipping suspending/un-suspending."); 11517 unactionedPackages.add(packageName); 11518 continue; 11519 } 11520 appId = pkgSetting.appId; 11521 if (pkgSetting.getSuspended(userId) != suspended) { 11522 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11523 unactionedPackages.add(packageName); 11524 continue; 11525 } 11526 pkgSetting.setSuspended(suspended, userId); 11527 mSettings.writePackageRestrictionsLPr(userId); 11528 changed = true; 11529 changedPackages.add(packageName); 11530 } 11531 } 11532 11533 if (changed && suspended) { 11534 killApplication(packageName, UserHandle.getUid(userId, appId), 11535 "suspending package"); 11536 } 11537 } 11538 } finally { 11539 Binder.restoreCallingIdentity(callingId); 11540 } 11541 11542 if (!changedPackages.isEmpty()) { 11543 sendPackagesSuspendedForUser(changedPackages.toArray( 11544 new String[changedPackages.size()]), userId, suspended); 11545 } 11546 11547 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11548 } 11549 11550 @Override 11551 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11552 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11553 true /* requireFullPermission */, false /* checkShell */, 11554 "isPackageSuspendedForUser for user " + userId); 11555 synchronized (mPackages) { 11556 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11557 if (pkgSetting == null) { 11558 throw new IllegalArgumentException("Unknown target package: " + packageName); 11559 } 11560 return pkgSetting.getSuspended(userId); 11561 } 11562 } 11563 11564 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11565 if (isPackageDeviceAdmin(packageName, userId)) { 11566 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11567 + "\": has an active device admin"); 11568 return false; 11569 } 11570 11571 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11572 if (packageName.equals(activeLauncherPackageName)) { 11573 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11574 + "\": contains the active launcher"); 11575 return false; 11576 } 11577 11578 if (packageName.equals(mRequiredInstallerPackage)) { 11579 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11580 + "\": required for package installation"); 11581 return false; 11582 } 11583 11584 if (packageName.equals(mRequiredVerifierPackage)) { 11585 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11586 + "\": required for package verification"); 11587 return false; 11588 } 11589 11590 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11591 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11592 + "\": is the default dialer"); 11593 return false; 11594 } 11595 11596 return true; 11597 } 11598 11599 private String getActiveLauncherPackageName(int userId) { 11600 Intent intent = new Intent(Intent.ACTION_MAIN); 11601 intent.addCategory(Intent.CATEGORY_HOME); 11602 ResolveInfo resolveInfo = resolveIntent( 11603 intent, 11604 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11605 PackageManager.MATCH_DEFAULT_ONLY, 11606 userId); 11607 11608 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11609 } 11610 11611 private String getDefaultDialerPackageName(int userId) { 11612 synchronized (mPackages) { 11613 return mSettings.getDefaultDialerPackageNameLPw(userId); 11614 } 11615 } 11616 11617 @Override 11618 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11619 mContext.enforceCallingOrSelfPermission( 11620 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11621 "Only package verification agents can verify applications"); 11622 11623 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11624 final PackageVerificationResponse response = new PackageVerificationResponse( 11625 verificationCode, Binder.getCallingUid()); 11626 msg.arg1 = id; 11627 msg.obj = response; 11628 mHandler.sendMessage(msg); 11629 } 11630 11631 @Override 11632 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11633 long millisecondsToDelay) { 11634 mContext.enforceCallingOrSelfPermission( 11635 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11636 "Only package verification agents can extend verification timeouts"); 11637 11638 final PackageVerificationState state = mPendingVerification.get(id); 11639 final PackageVerificationResponse response = new PackageVerificationResponse( 11640 verificationCodeAtTimeout, Binder.getCallingUid()); 11641 11642 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11643 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11644 } 11645 if (millisecondsToDelay < 0) { 11646 millisecondsToDelay = 0; 11647 } 11648 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11649 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11650 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11651 } 11652 11653 if ((state != null) && !state.timeoutExtended()) { 11654 state.extendTimeout(); 11655 11656 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11657 msg.arg1 = id; 11658 msg.obj = response; 11659 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11660 } 11661 } 11662 11663 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11664 int verificationCode, UserHandle user) { 11665 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11666 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11667 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11668 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11669 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11670 11671 mContext.sendBroadcastAsUser(intent, user, 11672 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11673 } 11674 11675 private ComponentName matchComponentForVerifier(String packageName, 11676 List<ResolveInfo> receivers) { 11677 ActivityInfo targetReceiver = null; 11678 11679 final int NR = receivers.size(); 11680 for (int i = 0; i < NR; i++) { 11681 final ResolveInfo info = receivers.get(i); 11682 if (info.activityInfo == null) { 11683 continue; 11684 } 11685 11686 if (packageName.equals(info.activityInfo.packageName)) { 11687 targetReceiver = info.activityInfo; 11688 break; 11689 } 11690 } 11691 11692 if (targetReceiver == null) { 11693 return null; 11694 } 11695 11696 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11697 } 11698 11699 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11700 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11701 if (pkgInfo.verifiers.length == 0) { 11702 return null; 11703 } 11704 11705 final int N = pkgInfo.verifiers.length; 11706 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11707 for (int i = 0; i < N; i++) { 11708 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11709 11710 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11711 receivers); 11712 if (comp == null) { 11713 continue; 11714 } 11715 11716 final int verifierUid = getUidForVerifier(verifierInfo); 11717 if (verifierUid == -1) { 11718 continue; 11719 } 11720 11721 if (DEBUG_VERIFY) { 11722 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11723 + " with the correct signature"); 11724 } 11725 sufficientVerifiers.add(comp); 11726 verificationState.addSufficientVerifier(verifierUid); 11727 } 11728 11729 return sufficientVerifiers; 11730 } 11731 11732 private int getUidForVerifier(VerifierInfo verifierInfo) { 11733 synchronized (mPackages) { 11734 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11735 if (pkg == null) { 11736 return -1; 11737 } else if (pkg.mSignatures.length != 1) { 11738 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11739 + " has more than one signature; ignoring"); 11740 return -1; 11741 } 11742 11743 /* 11744 * If the public key of the package's signature does not match 11745 * our expected public key, then this is a different package and 11746 * we should skip. 11747 */ 11748 11749 final byte[] expectedPublicKey; 11750 try { 11751 final Signature verifierSig = pkg.mSignatures[0]; 11752 final PublicKey publicKey = verifierSig.getPublicKey(); 11753 expectedPublicKey = publicKey.getEncoded(); 11754 } catch (CertificateException e) { 11755 return -1; 11756 } 11757 11758 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11759 11760 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11761 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11762 + " does not have the expected public key; ignoring"); 11763 return -1; 11764 } 11765 11766 return pkg.applicationInfo.uid; 11767 } 11768 } 11769 11770 @Override 11771 public void finishPackageInstall(int token, boolean didLaunch) { 11772 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11773 11774 if (DEBUG_INSTALL) { 11775 Slog.v(TAG, "BM finishing package install for " + token); 11776 } 11777 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11778 11779 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11780 mHandler.sendMessage(msg); 11781 } 11782 11783 /** 11784 * Get the verification agent timeout. 11785 * 11786 * @return verification timeout in milliseconds 11787 */ 11788 private long getVerificationTimeout() { 11789 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11790 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11791 DEFAULT_VERIFICATION_TIMEOUT); 11792 } 11793 11794 /** 11795 * Get the default verification agent response code. 11796 * 11797 * @return default verification response code 11798 */ 11799 private int getDefaultVerificationResponse() { 11800 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11801 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11802 DEFAULT_VERIFICATION_RESPONSE); 11803 } 11804 11805 /** 11806 * Check whether or not package verification has been enabled. 11807 * 11808 * @return true if verification should be performed 11809 */ 11810 private boolean isVerificationEnabled(int userId, int installFlags) { 11811 if (!DEFAULT_VERIFY_ENABLE) { 11812 return false; 11813 } 11814 // Ephemeral apps don't get the full verification treatment 11815 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11816 if (DEBUG_EPHEMERAL) { 11817 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11818 } 11819 return false; 11820 } 11821 11822 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11823 11824 // Check if installing from ADB 11825 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11826 // Do not run verification in a test harness environment 11827 if (ActivityManager.isRunningInTestHarness()) { 11828 return false; 11829 } 11830 if (ensureVerifyAppsEnabled) { 11831 return true; 11832 } 11833 // Check if the developer does not want package verification for ADB installs 11834 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11835 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11836 return false; 11837 } 11838 } 11839 11840 if (ensureVerifyAppsEnabled) { 11841 return true; 11842 } 11843 11844 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11845 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11846 } 11847 11848 @Override 11849 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11850 throws RemoteException { 11851 mContext.enforceCallingOrSelfPermission( 11852 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11853 "Only intentfilter verification agents can verify applications"); 11854 11855 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11856 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11857 Binder.getCallingUid(), verificationCode, failedDomains); 11858 msg.arg1 = id; 11859 msg.obj = response; 11860 mHandler.sendMessage(msg); 11861 } 11862 11863 @Override 11864 public int getIntentVerificationStatus(String packageName, int userId) { 11865 synchronized (mPackages) { 11866 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11867 } 11868 } 11869 11870 @Override 11871 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11872 mContext.enforceCallingOrSelfPermission( 11873 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11874 11875 boolean result = false; 11876 synchronized (mPackages) { 11877 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11878 } 11879 if (result) { 11880 scheduleWritePackageRestrictionsLocked(userId); 11881 } 11882 return result; 11883 } 11884 11885 @Override 11886 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11887 String packageName) { 11888 synchronized (mPackages) { 11889 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11890 } 11891 } 11892 11893 @Override 11894 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11895 if (TextUtils.isEmpty(packageName)) { 11896 return ParceledListSlice.emptyList(); 11897 } 11898 synchronized (mPackages) { 11899 PackageParser.Package pkg = mPackages.get(packageName); 11900 if (pkg == null || pkg.activities == null) { 11901 return ParceledListSlice.emptyList(); 11902 } 11903 final int count = pkg.activities.size(); 11904 ArrayList<IntentFilter> result = new ArrayList<>(); 11905 for (int n=0; n<count; n++) { 11906 PackageParser.Activity activity = pkg.activities.get(n); 11907 if (activity.intents != null && activity.intents.size() > 0) { 11908 result.addAll(activity.intents); 11909 } 11910 } 11911 return new ParceledListSlice<>(result); 11912 } 11913 } 11914 11915 @Override 11916 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11917 mContext.enforceCallingOrSelfPermission( 11918 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11919 11920 synchronized (mPackages) { 11921 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11922 if (packageName != null) { 11923 result |= updateIntentVerificationStatus(packageName, 11924 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11925 userId); 11926 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11927 packageName, userId); 11928 } 11929 return result; 11930 } 11931 } 11932 11933 @Override 11934 public String getDefaultBrowserPackageName(int userId) { 11935 synchronized (mPackages) { 11936 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11937 } 11938 } 11939 11940 /** 11941 * Get the "allow unknown sources" setting. 11942 * 11943 * @return the current "allow unknown sources" setting 11944 */ 11945 private int getUnknownSourcesSettings() { 11946 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11947 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11948 -1); 11949 } 11950 11951 @Override 11952 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11953 final int uid = Binder.getCallingUid(); 11954 // writer 11955 synchronized (mPackages) { 11956 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11957 if (targetPackageSetting == null) { 11958 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11959 } 11960 11961 PackageSetting installerPackageSetting; 11962 if (installerPackageName != null) { 11963 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11964 if (installerPackageSetting == null) { 11965 throw new IllegalArgumentException("Unknown installer package: " 11966 + installerPackageName); 11967 } 11968 } else { 11969 installerPackageSetting = null; 11970 } 11971 11972 Signature[] callerSignature; 11973 Object obj = mSettings.getUserIdLPr(uid); 11974 if (obj != null) { 11975 if (obj instanceof SharedUserSetting) { 11976 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11977 } else if (obj instanceof PackageSetting) { 11978 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11979 } else { 11980 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11981 } 11982 } else { 11983 throw new SecurityException("Unknown calling UID: " + uid); 11984 } 11985 11986 // Verify: can't set installerPackageName to a package that is 11987 // not signed with the same cert as the caller. 11988 if (installerPackageSetting != null) { 11989 if (compareSignatures(callerSignature, 11990 installerPackageSetting.signatures.mSignatures) 11991 != PackageManager.SIGNATURE_MATCH) { 11992 throw new SecurityException( 11993 "Caller does not have same cert as new installer package " 11994 + installerPackageName); 11995 } 11996 } 11997 11998 // Verify: if target already has an installer package, it must 11999 // be signed with the same cert as the caller. 12000 if (targetPackageSetting.installerPackageName != null) { 12001 PackageSetting setting = mSettings.mPackages.get( 12002 targetPackageSetting.installerPackageName); 12003 // If the currently set package isn't valid, then it's always 12004 // okay to change it. 12005 if (setting != null) { 12006 if (compareSignatures(callerSignature, 12007 setting.signatures.mSignatures) 12008 != PackageManager.SIGNATURE_MATCH) { 12009 throw new SecurityException( 12010 "Caller does not have same cert as old installer package " 12011 + targetPackageSetting.installerPackageName); 12012 } 12013 } 12014 } 12015 12016 // Okay! 12017 targetPackageSetting.installerPackageName = installerPackageName; 12018 if (installerPackageName != null) { 12019 mSettings.mInstallerPackages.add(installerPackageName); 12020 } 12021 scheduleWriteSettingsLocked(); 12022 } 12023 } 12024 12025 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12026 // Queue up an async operation since the package installation may take a little while. 12027 mHandler.post(new Runnable() { 12028 public void run() { 12029 mHandler.removeCallbacks(this); 12030 // Result object to be returned 12031 PackageInstalledInfo res = new PackageInstalledInfo(); 12032 res.setReturnCode(currentStatus); 12033 res.uid = -1; 12034 res.pkg = null; 12035 res.removedInfo = null; 12036 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12037 args.doPreInstall(res.returnCode); 12038 synchronized (mInstallLock) { 12039 installPackageTracedLI(args, res); 12040 } 12041 args.doPostInstall(res.returnCode, res.uid); 12042 } 12043 12044 // A restore should be performed at this point if (a) the install 12045 // succeeded, (b) the operation is not an update, and (c) the new 12046 // package has not opted out of backup participation. 12047 final boolean update = res.removedInfo != null 12048 && res.removedInfo.removedPackage != null; 12049 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12050 boolean doRestore = !update 12051 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12052 12053 // Set up the post-install work request bookkeeping. This will be used 12054 // and cleaned up by the post-install event handling regardless of whether 12055 // there's a restore pass performed. Token values are >= 1. 12056 int token; 12057 if (mNextInstallToken < 0) mNextInstallToken = 1; 12058 token = mNextInstallToken++; 12059 12060 PostInstallData data = new PostInstallData(args, res); 12061 mRunningInstalls.put(token, data); 12062 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12063 12064 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12065 // Pass responsibility to the Backup Manager. It will perform a 12066 // restore if appropriate, then pass responsibility back to the 12067 // Package Manager to run the post-install observer callbacks 12068 // and broadcasts. 12069 IBackupManager bm = IBackupManager.Stub.asInterface( 12070 ServiceManager.getService(Context.BACKUP_SERVICE)); 12071 if (bm != null) { 12072 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12073 + " to BM for possible restore"); 12074 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12075 try { 12076 // TODO: http://b/22388012 12077 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12078 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12079 } else { 12080 doRestore = false; 12081 } 12082 } catch (RemoteException e) { 12083 // can't happen; the backup manager is local 12084 } catch (Exception e) { 12085 Slog.e(TAG, "Exception trying to enqueue restore", e); 12086 doRestore = false; 12087 } 12088 } else { 12089 Slog.e(TAG, "Backup Manager not found!"); 12090 doRestore = false; 12091 } 12092 } 12093 12094 if (!doRestore) { 12095 // No restore possible, or the Backup Manager was mysteriously not 12096 // available -- just fire the post-install work request directly. 12097 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12098 12099 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12100 12101 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12102 mHandler.sendMessage(msg); 12103 } 12104 } 12105 }); 12106 } 12107 12108 /** 12109 * Callback from PackageSettings whenever an app is first transitioned out of the 12110 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12111 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12112 * here whether the app is the target of an ongoing install, and only send the 12113 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12114 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12115 * handling. 12116 */ 12117 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12118 // Serialize this with the rest of the install-process message chain. In the 12119 // restore-at-install case, this Runnable will necessarily run before the 12120 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12121 // are coherent. In the non-restore case, the app has already completed install 12122 // and been launched through some other means, so it is not in a problematic 12123 // state for observers to see the FIRST_LAUNCH signal. 12124 mHandler.post(new Runnable() { 12125 @Override 12126 public void run() { 12127 for (int i = 0; i < mRunningInstalls.size(); i++) { 12128 final PostInstallData data = mRunningInstalls.valueAt(i); 12129 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12130 // right package; but is it for the right user? 12131 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12132 if (userId == data.res.newUsers[uIndex]) { 12133 if (DEBUG_BACKUP) { 12134 Slog.i(TAG, "Package " + pkgName 12135 + " being restored so deferring FIRST_LAUNCH"); 12136 } 12137 return; 12138 } 12139 } 12140 } 12141 } 12142 // didn't find it, so not being restored 12143 if (DEBUG_BACKUP) { 12144 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12145 } 12146 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12147 } 12148 }); 12149 } 12150 12151 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12152 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12153 installerPkg, null, userIds); 12154 } 12155 12156 private abstract class HandlerParams { 12157 private static final int MAX_RETRIES = 4; 12158 12159 /** 12160 * Number of times startCopy() has been attempted and had a non-fatal 12161 * error. 12162 */ 12163 private int mRetries = 0; 12164 12165 /** User handle for the user requesting the information or installation. */ 12166 private final UserHandle mUser; 12167 String traceMethod; 12168 int traceCookie; 12169 12170 HandlerParams(UserHandle user) { 12171 mUser = user; 12172 } 12173 12174 UserHandle getUser() { 12175 return mUser; 12176 } 12177 12178 HandlerParams setTraceMethod(String traceMethod) { 12179 this.traceMethod = traceMethod; 12180 return this; 12181 } 12182 12183 HandlerParams setTraceCookie(int traceCookie) { 12184 this.traceCookie = traceCookie; 12185 return this; 12186 } 12187 12188 final boolean startCopy() { 12189 boolean res; 12190 try { 12191 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12192 12193 if (++mRetries > MAX_RETRIES) { 12194 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12195 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12196 handleServiceError(); 12197 return false; 12198 } else { 12199 handleStartCopy(); 12200 res = true; 12201 } 12202 } catch (RemoteException e) { 12203 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12204 mHandler.sendEmptyMessage(MCS_RECONNECT); 12205 res = false; 12206 } 12207 handleReturnCode(); 12208 return res; 12209 } 12210 12211 final void serviceError() { 12212 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12213 handleServiceError(); 12214 handleReturnCode(); 12215 } 12216 12217 abstract void handleStartCopy() throws RemoteException; 12218 abstract void handleServiceError(); 12219 abstract void handleReturnCode(); 12220 } 12221 12222 class MeasureParams extends HandlerParams { 12223 private final PackageStats mStats; 12224 private boolean mSuccess; 12225 12226 private final IPackageStatsObserver mObserver; 12227 12228 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12229 super(new UserHandle(stats.userHandle)); 12230 mObserver = observer; 12231 mStats = stats; 12232 } 12233 12234 @Override 12235 public String toString() { 12236 return "MeasureParams{" 12237 + Integer.toHexString(System.identityHashCode(this)) 12238 + " " + mStats.packageName + "}"; 12239 } 12240 12241 @Override 12242 void handleStartCopy() throws RemoteException { 12243 synchronized (mInstallLock) { 12244 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12245 } 12246 12247 if (mSuccess) { 12248 final boolean mounted; 12249 if (Environment.isExternalStorageEmulated()) { 12250 mounted = true; 12251 } else { 12252 final String status = Environment.getExternalStorageState(); 12253 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12254 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12255 } 12256 12257 if (mounted) { 12258 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12259 12260 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12261 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12262 12263 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12264 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12265 12266 // Always subtract cache size, since it's a subdirectory 12267 mStats.externalDataSize -= mStats.externalCacheSize; 12268 12269 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12270 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12271 12272 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12273 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12274 } 12275 } 12276 } 12277 12278 @Override 12279 void handleReturnCode() { 12280 if (mObserver != null) { 12281 try { 12282 mObserver.onGetStatsCompleted(mStats, mSuccess); 12283 } catch (RemoteException e) { 12284 Slog.i(TAG, "Observer no longer exists."); 12285 } 12286 } 12287 } 12288 12289 @Override 12290 void handleServiceError() { 12291 Slog.e(TAG, "Could not measure application " + mStats.packageName 12292 + " external storage"); 12293 } 12294 } 12295 12296 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12297 throws RemoteException { 12298 long result = 0; 12299 for (File path : paths) { 12300 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12301 } 12302 return result; 12303 } 12304 12305 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12306 for (File path : paths) { 12307 try { 12308 mcs.clearDirectory(path.getAbsolutePath()); 12309 } catch (RemoteException e) { 12310 } 12311 } 12312 } 12313 12314 static class OriginInfo { 12315 /** 12316 * Location where install is coming from, before it has been 12317 * copied/renamed into place. This could be a single monolithic APK 12318 * file, or a cluster directory. This location may be untrusted. 12319 */ 12320 final File file; 12321 final String cid; 12322 12323 /** 12324 * Flag indicating that {@link #file} or {@link #cid} has already been 12325 * staged, meaning downstream users don't need to defensively copy the 12326 * contents. 12327 */ 12328 final boolean staged; 12329 12330 /** 12331 * Flag indicating that {@link #file} or {@link #cid} is an already 12332 * installed app that is being moved. 12333 */ 12334 final boolean existing; 12335 12336 final String resolvedPath; 12337 final File resolvedFile; 12338 12339 static OriginInfo fromNothing() { 12340 return new OriginInfo(null, null, false, false); 12341 } 12342 12343 static OriginInfo fromUntrustedFile(File file) { 12344 return new OriginInfo(file, null, false, false); 12345 } 12346 12347 static OriginInfo fromExistingFile(File file) { 12348 return new OriginInfo(file, null, false, true); 12349 } 12350 12351 static OriginInfo fromStagedFile(File file) { 12352 return new OriginInfo(file, null, true, false); 12353 } 12354 12355 static OriginInfo fromStagedContainer(String cid) { 12356 return new OriginInfo(null, cid, true, false); 12357 } 12358 12359 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12360 this.file = file; 12361 this.cid = cid; 12362 this.staged = staged; 12363 this.existing = existing; 12364 12365 if (cid != null) { 12366 resolvedPath = PackageHelper.getSdDir(cid); 12367 resolvedFile = new File(resolvedPath); 12368 } else if (file != null) { 12369 resolvedPath = file.getAbsolutePath(); 12370 resolvedFile = file; 12371 } else { 12372 resolvedPath = null; 12373 resolvedFile = null; 12374 } 12375 } 12376 } 12377 12378 static class MoveInfo { 12379 final int moveId; 12380 final String fromUuid; 12381 final String toUuid; 12382 final String packageName; 12383 final String dataAppName; 12384 final int appId; 12385 final String seinfo; 12386 final int targetSdkVersion; 12387 12388 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12389 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12390 this.moveId = moveId; 12391 this.fromUuid = fromUuid; 12392 this.toUuid = toUuid; 12393 this.packageName = packageName; 12394 this.dataAppName = dataAppName; 12395 this.appId = appId; 12396 this.seinfo = seinfo; 12397 this.targetSdkVersion = targetSdkVersion; 12398 } 12399 } 12400 12401 static class VerificationInfo { 12402 /** A constant used to indicate that a uid value is not present. */ 12403 public static final int NO_UID = -1; 12404 12405 /** URI referencing where the package was downloaded from. */ 12406 final Uri originatingUri; 12407 12408 /** HTTP referrer URI associated with the originatingURI. */ 12409 final Uri referrer; 12410 12411 /** UID of the application that the install request originated from. */ 12412 final int originatingUid; 12413 12414 /** UID of application requesting the install */ 12415 final int installerUid; 12416 12417 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12418 this.originatingUri = originatingUri; 12419 this.referrer = referrer; 12420 this.originatingUid = originatingUid; 12421 this.installerUid = installerUid; 12422 } 12423 } 12424 12425 class InstallParams extends HandlerParams { 12426 final OriginInfo origin; 12427 final MoveInfo move; 12428 final IPackageInstallObserver2 observer; 12429 int installFlags; 12430 final String installerPackageName; 12431 final String volumeUuid; 12432 private InstallArgs mArgs; 12433 private int mRet; 12434 final String packageAbiOverride; 12435 final String[] grantedRuntimePermissions; 12436 final VerificationInfo verificationInfo; 12437 final Certificate[][] certificates; 12438 12439 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12440 int installFlags, String installerPackageName, String volumeUuid, 12441 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12442 String[] grantedPermissions, Certificate[][] certificates) { 12443 super(user); 12444 this.origin = origin; 12445 this.move = move; 12446 this.observer = observer; 12447 this.installFlags = installFlags; 12448 this.installerPackageName = installerPackageName; 12449 this.volumeUuid = volumeUuid; 12450 this.verificationInfo = verificationInfo; 12451 this.packageAbiOverride = packageAbiOverride; 12452 this.grantedRuntimePermissions = grantedPermissions; 12453 this.certificates = certificates; 12454 } 12455 12456 @Override 12457 public String toString() { 12458 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12459 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12460 } 12461 12462 private int installLocationPolicy(PackageInfoLite pkgLite) { 12463 String packageName = pkgLite.packageName; 12464 int installLocation = pkgLite.installLocation; 12465 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12466 // reader 12467 synchronized (mPackages) { 12468 // Currently installed package which the new package is attempting to replace or 12469 // null if no such package is installed. 12470 PackageParser.Package installedPkg = mPackages.get(packageName); 12471 // Package which currently owns the data which the new package will own if installed. 12472 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12473 // will be null whereas dataOwnerPkg will contain information about the package 12474 // which was uninstalled while keeping its data. 12475 PackageParser.Package dataOwnerPkg = installedPkg; 12476 if (dataOwnerPkg == null) { 12477 PackageSetting ps = mSettings.mPackages.get(packageName); 12478 if (ps != null) { 12479 dataOwnerPkg = ps.pkg; 12480 } 12481 } 12482 12483 if (dataOwnerPkg != null) { 12484 // If installed, the package will get access to data left on the device by its 12485 // predecessor. As a security measure, this is permited only if this is not a 12486 // version downgrade or if the predecessor package is marked as debuggable and 12487 // a downgrade is explicitly requested. 12488 // 12489 // On debuggable platform builds, downgrades are permitted even for 12490 // non-debuggable packages to make testing easier. Debuggable platform builds do 12491 // not offer security guarantees and thus it's OK to disable some security 12492 // mechanisms to make debugging/testing easier on those builds. However, even on 12493 // debuggable builds downgrades of packages are permitted only if requested via 12494 // installFlags. This is because we aim to keep the behavior of debuggable 12495 // platform builds as close as possible to the behavior of non-debuggable 12496 // platform builds. 12497 final boolean downgradeRequested = 12498 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12499 final boolean packageDebuggable = 12500 (dataOwnerPkg.applicationInfo.flags 12501 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12502 final boolean downgradePermitted = 12503 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12504 if (!downgradePermitted) { 12505 try { 12506 checkDowngrade(dataOwnerPkg, pkgLite); 12507 } catch (PackageManagerException e) { 12508 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12509 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12510 } 12511 } 12512 } 12513 12514 if (installedPkg != null) { 12515 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12516 // Check for updated system application. 12517 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12518 if (onSd) { 12519 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12520 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12521 } 12522 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12523 } else { 12524 if (onSd) { 12525 // Install flag overrides everything. 12526 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12527 } 12528 // If current upgrade specifies particular preference 12529 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12530 // Application explicitly specified internal. 12531 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12532 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12533 // App explictly prefers external. Let policy decide 12534 } else { 12535 // Prefer previous location 12536 if (isExternal(installedPkg)) { 12537 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12538 } 12539 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12540 } 12541 } 12542 } else { 12543 // Invalid install. Return error code 12544 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12545 } 12546 } 12547 } 12548 // All the special cases have been taken care of. 12549 // Return result based on recommended install location. 12550 if (onSd) { 12551 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12552 } 12553 return pkgLite.recommendedInstallLocation; 12554 } 12555 12556 /* 12557 * Invoke remote method to get package information and install 12558 * location values. Override install location based on default 12559 * policy if needed and then create install arguments based 12560 * on the install location. 12561 */ 12562 public void handleStartCopy() throws RemoteException { 12563 int ret = PackageManager.INSTALL_SUCCEEDED; 12564 12565 // If we're already staged, we've firmly committed to an install location 12566 if (origin.staged) { 12567 if (origin.file != null) { 12568 installFlags |= PackageManager.INSTALL_INTERNAL; 12569 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12570 } else if (origin.cid != null) { 12571 installFlags |= PackageManager.INSTALL_EXTERNAL; 12572 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12573 } else { 12574 throw new IllegalStateException("Invalid stage location"); 12575 } 12576 } 12577 12578 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12579 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12580 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12581 PackageInfoLite pkgLite = null; 12582 12583 if (onInt && onSd) { 12584 // Check if both bits are set. 12585 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12586 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12587 } else if (onSd && ephemeral) { 12588 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12589 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12590 } else { 12591 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12592 packageAbiOverride); 12593 12594 if (DEBUG_EPHEMERAL && ephemeral) { 12595 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12596 } 12597 12598 /* 12599 * If we have too little free space, try to free cache 12600 * before giving up. 12601 */ 12602 if (!origin.staged && pkgLite.recommendedInstallLocation 12603 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12604 // TODO: focus freeing disk space on the target device 12605 final StorageManager storage = StorageManager.from(mContext); 12606 final long lowThreshold = storage.getStorageLowBytes( 12607 Environment.getDataDirectory()); 12608 12609 final long sizeBytes = mContainerService.calculateInstalledSize( 12610 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12611 12612 try { 12613 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12614 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12615 installFlags, packageAbiOverride); 12616 } catch (InstallerException e) { 12617 Slog.w(TAG, "Failed to free cache", e); 12618 } 12619 12620 /* 12621 * The cache free must have deleted the file we 12622 * downloaded to install. 12623 * 12624 * TODO: fix the "freeCache" call to not delete 12625 * the file we care about. 12626 */ 12627 if (pkgLite.recommendedInstallLocation 12628 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12629 pkgLite.recommendedInstallLocation 12630 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12631 } 12632 } 12633 } 12634 12635 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12636 int loc = pkgLite.recommendedInstallLocation; 12637 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12638 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12639 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12640 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12641 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12642 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12643 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12644 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12645 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12646 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12647 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12648 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12649 } else { 12650 // Override with defaults if needed. 12651 loc = installLocationPolicy(pkgLite); 12652 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12653 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12654 } else if (!onSd && !onInt) { 12655 // Override install location with flags 12656 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12657 // Set the flag to install on external media. 12658 installFlags |= PackageManager.INSTALL_EXTERNAL; 12659 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12660 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12661 if (DEBUG_EPHEMERAL) { 12662 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12663 } 12664 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12665 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12666 |PackageManager.INSTALL_INTERNAL); 12667 } else { 12668 // Make sure the flag for installing on external 12669 // media is unset 12670 installFlags |= PackageManager.INSTALL_INTERNAL; 12671 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12672 } 12673 } 12674 } 12675 } 12676 12677 final InstallArgs args = createInstallArgs(this); 12678 mArgs = args; 12679 12680 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12681 // TODO: http://b/22976637 12682 // Apps installed for "all" users use the device owner to verify the app 12683 UserHandle verifierUser = getUser(); 12684 if (verifierUser == UserHandle.ALL) { 12685 verifierUser = UserHandle.SYSTEM; 12686 } 12687 12688 /* 12689 * Determine if we have any installed package verifiers. If we 12690 * do, then we'll defer to them to verify the packages. 12691 */ 12692 final int requiredUid = mRequiredVerifierPackage == null ? -1 12693 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12694 verifierUser.getIdentifier()); 12695 if (!origin.existing && requiredUid != -1 12696 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12697 final Intent verification = new Intent( 12698 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12699 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12700 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12701 PACKAGE_MIME_TYPE); 12702 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12703 12704 // Query all live verifiers based on current user state 12705 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12706 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12707 12708 if (DEBUG_VERIFY) { 12709 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12710 + verification.toString() + " with " + pkgLite.verifiers.length 12711 + " optional verifiers"); 12712 } 12713 12714 final int verificationId = mPendingVerificationToken++; 12715 12716 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12717 12718 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12719 installerPackageName); 12720 12721 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12722 installFlags); 12723 12724 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12725 pkgLite.packageName); 12726 12727 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12728 pkgLite.versionCode); 12729 12730 if (verificationInfo != null) { 12731 if (verificationInfo.originatingUri != null) { 12732 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12733 verificationInfo.originatingUri); 12734 } 12735 if (verificationInfo.referrer != null) { 12736 verification.putExtra(Intent.EXTRA_REFERRER, 12737 verificationInfo.referrer); 12738 } 12739 if (verificationInfo.originatingUid >= 0) { 12740 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12741 verificationInfo.originatingUid); 12742 } 12743 if (verificationInfo.installerUid >= 0) { 12744 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12745 verificationInfo.installerUid); 12746 } 12747 } 12748 12749 final PackageVerificationState verificationState = new PackageVerificationState( 12750 requiredUid, args); 12751 12752 mPendingVerification.append(verificationId, verificationState); 12753 12754 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12755 receivers, verificationState); 12756 12757 /* 12758 * If any sufficient verifiers were listed in the package 12759 * manifest, attempt to ask them. 12760 */ 12761 if (sufficientVerifiers != null) { 12762 final int N = sufficientVerifiers.size(); 12763 if (N == 0) { 12764 Slog.i(TAG, "Additional verifiers required, but none installed."); 12765 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12766 } else { 12767 for (int i = 0; i < N; i++) { 12768 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12769 12770 final Intent sufficientIntent = new Intent(verification); 12771 sufficientIntent.setComponent(verifierComponent); 12772 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12773 } 12774 } 12775 } 12776 12777 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12778 mRequiredVerifierPackage, receivers); 12779 if (ret == PackageManager.INSTALL_SUCCEEDED 12780 && mRequiredVerifierPackage != null) { 12781 Trace.asyncTraceBegin( 12782 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12783 /* 12784 * Send the intent to the required verification agent, 12785 * but only start the verification timeout after the 12786 * target BroadcastReceivers have run. 12787 */ 12788 verification.setComponent(requiredVerifierComponent); 12789 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12790 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12791 new BroadcastReceiver() { 12792 @Override 12793 public void onReceive(Context context, Intent intent) { 12794 final Message msg = mHandler 12795 .obtainMessage(CHECK_PENDING_VERIFICATION); 12796 msg.arg1 = verificationId; 12797 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12798 } 12799 }, null, 0, null, null); 12800 12801 /* 12802 * We don't want the copy to proceed until verification 12803 * succeeds, so null out this field. 12804 */ 12805 mArgs = null; 12806 } 12807 } else { 12808 /* 12809 * No package verification is enabled, so immediately start 12810 * the remote call to initiate copy using temporary file. 12811 */ 12812 ret = args.copyApk(mContainerService, true); 12813 } 12814 } 12815 12816 mRet = ret; 12817 } 12818 12819 @Override 12820 void handleReturnCode() { 12821 // If mArgs is null, then MCS couldn't be reached. When it 12822 // reconnects, it will try again to install. At that point, this 12823 // will succeed. 12824 if (mArgs != null) { 12825 processPendingInstall(mArgs, mRet); 12826 } 12827 } 12828 12829 @Override 12830 void handleServiceError() { 12831 mArgs = createInstallArgs(this); 12832 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12833 } 12834 12835 public boolean isForwardLocked() { 12836 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12837 } 12838 } 12839 12840 /** 12841 * Used during creation of InstallArgs 12842 * 12843 * @param installFlags package installation flags 12844 * @return true if should be installed on external storage 12845 */ 12846 private static boolean installOnExternalAsec(int installFlags) { 12847 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12848 return false; 12849 } 12850 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12851 return true; 12852 } 12853 return false; 12854 } 12855 12856 /** 12857 * Used during creation of InstallArgs 12858 * 12859 * @param installFlags package installation flags 12860 * @return true if should be installed as forward locked 12861 */ 12862 private static boolean installForwardLocked(int installFlags) { 12863 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12864 } 12865 12866 private InstallArgs createInstallArgs(InstallParams params) { 12867 if (params.move != null) { 12868 return new MoveInstallArgs(params); 12869 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12870 return new AsecInstallArgs(params); 12871 } else { 12872 return new FileInstallArgs(params); 12873 } 12874 } 12875 12876 /** 12877 * Create args that describe an existing installed package. Typically used 12878 * when cleaning up old installs, or used as a move source. 12879 */ 12880 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12881 String resourcePath, String[] instructionSets) { 12882 final boolean isInAsec; 12883 if (installOnExternalAsec(installFlags)) { 12884 /* Apps on SD card are always in ASEC containers. */ 12885 isInAsec = true; 12886 } else if (installForwardLocked(installFlags) 12887 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12888 /* 12889 * Forward-locked apps are only in ASEC containers if they're the 12890 * new style 12891 */ 12892 isInAsec = true; 12893 } else { 12894 isInAsec = false; 12895 } 12896 12897 if (isInAsec) { 12898 return new AsecInstallArgs(codePath, instructionSets, 12899 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12900 } else { 12901 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12902 } 12903 } 12904 12905 static abstract class InstallArgs { 12906 /** @see InstallParams#origin */ 12907 final OriginInfo origin; 12908 /** @see InstallParams#move */ 12909 final MoveInfo move; 12910 12911 final IPackageInstallObserver2 observer; 12912 // Always refers to PackageManager flags only 12913 final int installFlags; 12914 final String installerPackageName; 12915 final String volumeUuid; 12916 final UserHandle user; 12917 final String abiOverride; 12918 final String[] installGrantPermissions; 12919 /** If non-null, drop an async trace when the install completes */ 12920 final String traceMethod; 12921 final int traceCookie; 12922 final Certificate[][] certificates; 12923 12924 // The list of instruction sets supported by this app. This is currently 12925 // only used during the rmdex() phase to clean up resources. We can get rid of this 12926 // if we move dex files under the common app path. 12927 /* nullable */ String[] instructionSets; 12928 12929 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12930 int installFlags, String installerPackageName, String volumeUuid, 12931 UserHandle user, String[] instructionSets, 12932 String abiOverride, String[] installGrantPermissions, 12933 String traceMethod, int traceCookie, Certificate[][] certificates) { 12934 this.origin = origin; 12935 this.move = move; 12936 this.installFlags = installFlags; 12937 this.observer = observer; 12938 this.installerPackageName = installerPackageName; 12939 this.volumeUuid = volumeUuid; 12940 this.user = user; 12941 this.instructionSets = instructionSets; 12942 this.abiOverride = abiOverride; 12943 this.installGrantPermissions = installGrantPermissions; 12944 this.traceMethod = traceMethod; 12945 this.traceCookie = traceCookie; 12946 this.certificates = certificates; 12947 } 12948 12949 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12950 abstract int doPreInstall(int status); 12951 12952 /** 12953 * Rename package into final resting place. All paths on the given 12954 * scanned package should be updated to reflect the rename. 12955 */ 12956 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12957 abstract int doPostInstall(int status, int uid); 12958 12959 /** @see PackageSettingBase#codePathString */ 12960 abstract String getCodePath(); 12961 /** @see PackageSettingBase#resourcePathString */ 12962 abstract String getResourcePath(); 12963 12964 // Need installer lock especially for dex file removal. 12965 abstract void cleanUpResourcesLI(); 12966 abstract boolean doPostDeleteLI(boolean delete); 12967 12968 /** 12969 * Called before the source arguments are copied. This is used mostly 12970 * for MoveParams when it needs to read the source file to put it in the 12971 * destination. 12972 */ 12973 int doPreCopy() { 12974 return PackageManager.INSTALL_SUCCEEDED; 12975 } 12976 12977 /** 12978 * Called after the source arguments are copied. This is used mostly for 12979 * MoveParams when it needs to read the source file to put it in the 12980 * destination. 12981 */ 12982 int doPostCopy(int uid) { 12983 return PackageManager.INSTALL_SUCCEEDED; 12984 } 12985 12986 protected boolean isFwdLocked() { 12987 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12988 } 12989 12990 protected boolean isExternalAsec() { 12991 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12992 } 12993 12994 protected boolean isEphemeral() { 12995 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12996 } 12997 12998 UserHandle getUser() { 12999 return user; 13000 } 13001 } 13002 13003 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13004 if (!allCodePaths.isEmpty()) { 13005 if (instructionSets == null) { 13006 throw new IllegalStateException("instructionSet == null"); 13007 } 13008 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13009 for (String codePath : allCodePaths) { 13010 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13011 try { 13012 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13013 } catch (InstallerException ignored) { 13014 } 13015 } 13016 } 13017 } 13018 } 13019 13020 /** 13021 * Logic to handle installation of non-ASEC applications, including copying 13022 * and renaming logic. 13023 */ 13024 class FileInstallArgs extends InstallArgs { 13025 private File codeFile; 13026 private File resourceFile; 13027 13028 // Example topology: 13029 // /data/app/com.example/base.apk 13030 // /data/app/com.example/split_foo.apk 13031 // /data/app/com.example/lib/arm/libfoo.so 13032 // /data/app/com.example/lib/arm64/libfoo.so 13033 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13034 13035 /** New install */ 13036 FileInstallArgs(InstallParams params) { 13037 super(params.origin, params.move, params.observer, params.installFlags, 13038 params.installerPackageName, params.volumeUuid, 13039 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13040 params.grantedRuntimePermissions, 13041 params.traceMethod, params.traceCookie, params.certificates); 13042 if (isFwdLocked()) { 13043 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13044 } 13045 } 13046 13047 /** Existing install */ 13048 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13049 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13050 null, null, null, 0, null /*certificates*/); 13051 this.codeFile = (codePath != null) ? new File(codePath) : null; 13052 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13053 } 13054 13055 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13056 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13057 try { 13058 return doCopyApk(imcs, temp); 13059 } finally { 13060 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13061 } 13062 } 13063 13064 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13065 if (origin.staged) { 13066 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13067 codeFile = origin.file; 13068 resourceFile = origin.file; 13069 return PackageManager.INSTALL_SUCCEEDED; 13070 } 13071 13072 try { 13073 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13074 final File tempDir = 13075 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13076 codeFile = tempDir; 13077 resourceFile = tempDir; 13078 } catch (IOException e) { 13079 Slog.w(TAG, "Failed to create copy file: " + e); 13080 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13081 } 13082 13083 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13084 @Override 13085 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13086 if (!FileUtils.isValidExtFilename(name)) { 13087 throw new IllegalArgumentException("Invalid filename: " + name); 13088 } 13089 try { 13090 final File file = new File(codeFile, name); 13091 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13092 O_RDWR | O_CREAT, 0644); 13093 Os.chmod(file.getAbsolutePath(), 0644); 13094 return new ParcelFileDescriptor(fd); 13095 } catch (ErrnoException e) { 13096 throw new RemoteException("Failed to open: " + e.getMessage()); 13097 } 13098 } 13099 }; 13100 13101 int ret = PackageManager.INSTALL_SUCCEEDED; 13102 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13103 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13104 Slog.e(TAG, "Failed to copy package"); 13105 return ret; 13106 } 13107 13108 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13109 NativeLibraryHelper.Handle handle = null; 13110 try { 13111 handle = NativeLibraryHelper.Handle.create(codeFile); 13112 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13113 abiOverride); 13114 } catch (IOException e) { 13115 Slog.e(TAG, "Copying native libraries failed", e); 13116 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13117 } finally { 13118 IoUtils.closeQuietly(handle); 13119 } 13120 13121 return ret; 13122 } 13123 13124 int doPreInstall(int status) { 13125 if (status != PackageManager.INSTALL_SUCCEEDED) { 13126 cleanUp(); 13127 } 13128 return status; 13129 } 13130 13131 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13132 if (status != PackageManager.INSTALL_SUCCEEDED) { 13133 cleanUp(); 13134 return false; 13135 } 13136 13137 final File targetDir = codeFile.getParentFile(); 13138 final File beforeCodeFile = codeFile; 13139 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13140 13141 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13142 try { 13143 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13144 } catch (ErrnoException e) { 13145 Slog.w(TAG, "Failed to rename", e); 13146 return false; 13147 } 13148 13149 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13150 Slog.w(TAG, "Failed to restorecon"); 13151 return false; 13152 } 13153 13154 // Reflect the rename internally 13155 codeFile = afterCodeFile; 13156 resourceFile = afterCodeFile; 13157 13158 // Reflect the rename in scanned details 13159 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13160 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13161 afterCodeFile, pkg.baseCodePath)); 13162 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13163 afterCodeFile, pkg.splitCodePaths)); 13164 13165 // Reflect the rename in app info 13166 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13167 pkg.setApplicationInfoCodePath(pkg.codePath); 13168 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13169 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13170 pkg.setApplicationInfoResourcePath(pkg.codePath); 13171 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13172 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13173 13174 return true; 13175 } 13176 13177 int doPostInstall(int status, int uid) { 13178 if (status != PackageManager.INSTALL_SUCCEEDED) { 13179 cleanUp(); 13180 } 13181 return status; 13182 } 13183 13184 @Override 13185 String getCodePath() { 13186 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13187 } 13188 13189 @Override 13190 String getResourcePath() { 13191 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13192 } 13193 13194 private boolean cleanUp() { 13195 if (codeFile == null || !codeFile.exists()) { 13196 return false; 13197 } 13198 13199 removeCodePathLI(codeFile); 13200 13201 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13202 resourceFile.delete(); 13203 } 13204 13205 return true; 13206 } 13207 13208 void cleanUpResourcesLI() { 13209 // Try enumerating all code paths before deleting 13210 List<String> allCodePaths = Collections.EMPTY_LIST; 13211 if (codeFile != null && codeFile.exists()) { 13212 try { 13213 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13214 allCodePaths = pkg.getAllCodePaths(); 13215 } catch (PackageParserException e) { 13216 // Ignored; we tried our best 13217 } 13218 } 13219 13220 cleanUp(); 13221 removeDexFiles(allCodePaths, instructionSets); 13222 } 13223 13224 boolean doPostDeleteLI(boolean delete) { 13225 // XXX err, shouldn't we respect the delete flag? 13226 cleanUpResourcesLI(); 13227 return true; 13228 } 13229 } 13230 13231 private boolean isAsecExternal(String cid) { 13232 final String asecPath = PackageHelper.getSdFilesystem(cid); 13233 return !asecPath.startsWith(mAsecInternalPath); 13234 } 13235 13236 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13237 PackageManagerException { 13238 if (copyRet < 0) { 13239 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13240 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13241 throw new PackageManagerException(copyRet, message); 13242 } 13243 } 13244 } 13245 13246 /** 13247 * Extract the MountService "container ID" from the full code path of an 13248 * .apk. 13249 */ 13250 static String cidFromCodePath(String fullCodePath) { 13251 int eidx = fullCodePath.lastIndexOf("/"); 13252 String subStr1 = fullCodePath.substring(0, eidx); 13253 int sidx = subStr1.lastIndexOf("/"); 13254 return subStr1.substring(sidx+1, eidx); 13255 } 13256 13257 /** 13258 * Logic to handle installation of ASEC applications, including copying and 13259 * renaming logic. 13260 */ 13261 class AsecInstallArgs extends InstallArgs { 13262 static final String RES_FILE_NAME = "pkg.apk"; 13263 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13264 13265 String cid; 13266 String packagePath; 13267 String resourcePath; 13268 13269 /** New install */ 13270 AsecInstallArgs(InstallParams params) { 13271 super(params.origin, params.move, params.observer, params.installFlags, 13272 params.installerPackageName, params.volumeUuid, 13273 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13274 params.grantedRuntimePermissions, 13275 params.traceMethod, params.traceCookie, params.certificates); 13276 } 13277 13278 /** Existing install */ 13279 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13280 boolean isExternal, boolean isForwardLocked) { 13281 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13282 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13283 instructionSets, null, null, null, 0, null /*certificates*/); 13284 // Hackily pretend we're still looking at a full code path 13285 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13286 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13287 } 13288 13289 // Extract cid from fullCodePath 13290 int eidx = fullCodePath.lastIndexOf("/"); 13291 String subStr1 = fullCodePath.substring(0, eidx); 13292 int sidx = subStr1.lastIndexOf("/"); 13293 cid = subStr1.substring(sidx+1, eidx); 13294 setMountPath(subStr1); 13295 } 13296 13297 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13298 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13299 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13300 instructionSets, null, null, null, 0, null /*certificates*/); 13301 this.cid = cid; 13302 setMountPath(PackageHelper.getSdDir(cid)); 13303 } 13304 13305 void createCopyFile() { 13306 cid = mInstallerService.allocateExternalStageCidLegacy(); 13307 } 13308 13309 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13310 if (origin.staged && origin.cid != null) { 13311 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13312 cid = origin.cid; 13313 setMountPath(PackageHelper.getSdDir(cid)); 13314 return PackageManager.INSTALL_SUCCEEDED; 13315 } 13316 13317 if (temp) { 13318 createCopyFile(); 13319 } else { 13320 /* 13321 * Pre-emptively destroy the container since it's destroyed if 13322 * copying fails due to it existing anyway. 13323 */ 13324 PackageHelper.destroySdDir(cid); 13325 } 13326 13327 final String newMountPath = imcs.copyPackageToContainer( 13328 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13329 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13330 13331 if (newMountPath != null) { 13332 setMountPath(newMountPath); 13333 return PackageManager.INSTALL_SUCCEEDED; 13334 } else { 13335 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13336 } 13337 } 13338 13339 @Override 13340 String getCodePath() { 13341 return packagePath; 13342 } 13343 13344 @Override 13345 String getResourcePath() { 13346 return resourcePath; 13347 } 13348 13349 int doPreInstall(int status) { 13350 if (status != PackageManager.INSTALL_SUCCEEDED) { 13351 // Destroy container 13352 PackageHelper.destroySdDir(cid); 13353 } else { 13354 boolean mounted = PackageHelper.isContainerMounted(cid); 13355 if (!mounted) { 13356 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13357 Process.SYSTEM_UID); 13358 if (newMountPath != null) { 13359 setMountPath(newMountPath); 13360 } else { 13361 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13362 } 13363 } 13364 } 13365 return status; 13366 } 13367 13368 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13369 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13370 String newMountPath = null; 13371 if (PackageHelper.isContainerMounted(cid)) { 13372 // Unmount the container 13373 if (!PackageHelper.unMountSdDir(cid)) { 13374 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13375 return false; 13376 } 13377 } 13378 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13379 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13380 " which might be stale. Will try to clean up."); 13381 // Clean up the stale container and proceed to recreate. 13382 if (!PackageHelper.destroySdDir(newCacheId)) { 13383 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13384 return false; 13385 } 13386 // Successfully cleaned up stale container. Try to rename again. 13387 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13388 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13389 + " inspite of cleaning it up."); 13390 return false; 13391 } 13392 } 13393 if (!PackageHelper.isContainerMounted(newCacheId)) { 13394 Slog.w(TAG, "Mounting container " + newCacheId); 13395 newMountPath = PackageHelper.mountSdDir(newCacheId, 13396 getEncryptKey(), Process.SYSTEM_UID); 13397 } else { 13398 newMountPath = PackageHelper.getSdDir(newCacheId); 13399 } 13400 if (newMountPath == null) { 13401 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13402 return false; 13403 } 13404 Log.i(TAG, "Succesfully renamed " + cid + 13405 " to " + newCacheId + 13406 " at new path: " + newMountPath); 13407 cid = newCacheId; 13408 13409 final File beforeCodeFile = new File(packagePath); 13410 setMountPath(newMountPath); 13411 final File afterCodeFile = new File(packagePath); 13412 13413 // Reflect the rename in scanned details 13414 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13415 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13416 afterCodeFile, pkg.baseCodePath)); 13417 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13418 afterCodeFile, pkg.splitCodePaths)); 13419 13420 // Reflect the rename in app info 13421 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13422 pkg.setApplicationInfoCodePath(pkg.codePath); 13423 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13424 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13425 pkg.setApplicationInfoResourcePath(pkg.codePath); 13426 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13427 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13428 13429 return true; 13430 } 13431 13432 private void setMountPath(String mountPath) { 13433 final File mountFile = new File(mountPath); 13434 13435 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13436 if (monolithicFile.exists()) { 13437 packagePath = monolithicFile.getAbsolutePath(); 13438 if (isFwdLocked()) { 13439 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13440 } else { 13441 resourcePath = packagePath; 13442 } 13443 } else { 13444 packagePath = mountFile.getAbsolutePath(); 13445 resourcePath = packagePath; 13446 } 13447 } 13448 13449 int doPostInstall(int status, int uid) { 13450 if (status != PackageManager.INSTALL_SUCCEEDED) { 13451 cleanUp(); 13452 } else { 13453 final int groupOwner; 13454 final String protectedFile; 13455 if (isFwdLocked()) { 13456 groupOwner = UserHandle.getSharedAppGid(uid); 13457 protectedFile = RES_FILE_NAME; 13458 } else { 13459 groupOwner = -1; 13460 protectedFile = null; 13461 } 13462 13463 if (uid < Process.FIRST_APPLICATION_UID 13464 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13465 Slog.e(TAG, "Failed to finalize " + cid); 13466 PackageHelper.destroySdDir(cid); 13467 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13468 } 13469 13470 boolean mounted = PackageHelper.isContainerMounted(cid); 13471 if (!mounted) { 13472 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13473 } 13474 } 13475 return status; 13476 } 13477 13478 private void cleanUp() { 13479 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13480 13481 // Destroy secure container 13482 PackageHelper.destroySdDir(cid); 13483 } 13484 13485 private List<String> getAllCodePaths() { 13486 final File codeFile = new File(getCodePath()); 13487 if (codeFile != null && codeFile.exists()) { 13488 try { 13489 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13490 return pkg.getAllCodePaths(); 13491 } catch (PackageParserException e) { 13492 // Ignored; we tried our best 13493 } 13494 } 13495 return Collections.EMPTY_LIST; 13496 } 13497 13498 void cleanUpResourcesLI() { 13499 // Enumerate all code paths before deleting 13500 cleanUpResourcesLI(getAllCodePaths()); 13501 } 13502 13503 private void cleanUpResourcesLI(List<String> allCodePaths) { 13504 cleanUp(); 13505 removeDexFiles(allCodePaths, instructionSets); 13506 } 13507 13508 String getPackageName() { 13509 return getAsecPackageName(cid); 13510 } 13511 13512 boolean doPostDeleteLI(boolean delete) { 13513 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13514 final List<String> allCodePaths = getAllCodePaths(); 13515 boolean mounted = PackageHelper.isContainerMounted(cid); 13516 if (mounted) { 13517 // Unmount first 13518 if (PackageHelper.unMountSdDir(cid)) { 13519 mounted = false; 13520 } 13521 } 13522 if (!mounted && delete) { 13523 cleanUpResourcesLI(allCodePaths); 13524 } 13525 return !mounted; 13526 } 13527 13528 @Override 13529 int doPreCopy() { 13530 if (isFwdLocked()) { 13531 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13532 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13533 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13534 } 13535 } 13536 13537 return PackageManager.INSTALL_SUCCEEDED; 13538 } 13539 13540 @Override 13541 int doPostCopy(int uid) { 13542 if (isFwdLocked()) { 13543 if (uid < Process.FIRST_APPLICATION_UID 13544 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13545 RES_FILE_NAME)) { 13546 Slog.e(TAG, "Failed to finalize " + cid); 13547 PackageHelper.destroySdDir(cid); 13548 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13549 } 13550 } 13551 13552 return PackageManager.INSTALL_SUCCEEDED; 13553 } 13554 } 13555 13556 /** 13557 * Logic to handle movement of existing installed applications. 13558 */ 13559 class MoveInstallArgs extends InstallArgs { 13560 private File codeFile; 13561 private File resourceFile; 13562 13563 /** New install */ 13564 MoveInstallArgs(InstallParams params) { 13565 super(params.origin, params.move, params.observer, params.installFlags, 13566 params.installerPackageName, params.volumeUuid, 13567 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13568 params.grantedRuntimePermissions, 13569 params.traceMethod, params.traceCookie, params.certificates); 13570 } 13571 13572 int copyApk(IMediaContainerService imcs, boolean temp) { 13573 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13574 + move.fromUuid + " to " + move.toUuid); 13575 synchronized (mInstaller) { 13576 try { 13577 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13578 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13579 } catch (InstallerException e) { 13580 Slog.w(TAG, "Failed to move app", e); 13581 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13582 } 13583 } 13584 13585 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13586 resourceFile = codeFile; 13587 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13588 13589 return PackageManager.INSTALL_SUCCEEDED; 13590 } 13591 13592 int doPreInstall(int status) { 13593 if (status != PackageManager.INSTALL_SUCCEEDED) { 13594 cleanUp(move.toUuid); 13595 } 13596 return status; 13597 } 13598 13599 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13600 if (status != PackageManager.INSTALL_SUCCEEDED) { 13601 cleanUp(move.toUuid); 13602 return false; 13603 } 13604 13605 // Reflect the move in app info 13606 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13607 pkg.setApplicationInfoCodePath(pkg.codePath); 13608 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13609 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13610 pkg.setApplicationInfoResourcePath(pkg.codePath); 13611 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13612 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13613 13614 return true; 13615 } 13616 13617 int doPostInstall(int status, int uid) { 13618 if (status == PackageManager.INSTALL_SUCCEEDED) { 13619 cleanUp(move.fromUuid); 13620 } else { 13621 cleanUp(move.toUuid); 13622 } 13623 return status; 13624 } 13625 13626 @Override 13627 String getCodePath() { 13628 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13629 } 13630 13631 @Override 13632 String getResourcePath() { 13633 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13634 } 13635 13636 private boolean cleanUp(String volumeUuid) { 13637 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13638 move.dataAppName); 13639 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13640 final int[] userIds = sUserManager.getUserIds(); 13641 synchronized (mInstallLock) { 13642 // Clean up both app data and code 13643 // All package moves are frozen until finished 13644 for (int userId : userIds) { 13645 try { 13646 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13647 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13648 } catch (InstallerException e) { 13649 Slog.w(TAG, String.valueOf(e)); 13650 } 13651 } 13652 removeCodePathLI(codeFile); 13653 } 13654 return true; 13655 } 13656 13657 void cleanUpResourcesLI() { 13658 throw new UnsupportedOperationException(); 13659 } 13660 13661 boolean doPostDeleteLI(boolean delete) { 13662 throw new UnsupportedOperationException(); 13663 } 13664 } 13665 13666 static String getAsecPackageName(String packageCid) { 13667 int idx = packageCid.lastIndexOf("-"); 13668 if (idx == -1) { 13669 return packageCid; 13670 } 13671 return packageCid.substring(0, idx); 13672 } 13673 13674 // Utility method used to create code paths based on package name and available index. 13675 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13676 String idxStr = ""; 13677 int idx = 1; 13678 // Fall back to default value of idx=1 if prefix is not 13679 // part of oldCodePath 13680 if (oldCodePath != null) { 13681 String subStr = oldCodePath; 13682 // Drop the suffix right away 13683 if (suffix != null && subStr.endsWith(suffix)) { 13684 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13685 } 13686 // If oldCodePath already contains prefix find out the 13687 // ending index to either increment or decrement. 13688 int sidx = subStr.lastIndexOf(prefix); 13689 if (sidx != -1) { 13690 subStr = subStr.substring(sidx + prefix.length()); 13691 if (subStr != null) { 13692 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13693 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13694 } 13695 try { 13696 idx = Integer.parseInt(subStr); 13697 if (idx <= 1) { 13698 idx++; 13699 } else { 13700 idx--; 13701 } 13702 } catch(NumberFormatException e) { 13703 } 13704 } 13705 } 13706 } 13707 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13708 return prefix + idxStr; 13709 } 13710 13711 private File getNextCodePath(File targetDir, String packageName) { 13712 int suffix = 1; 13713 File result; 13714 do { 13715 result = new File(targetDir, packageName + "-" + suffix); 13716 suffix++; 13717 } while (result.exists()); 13718 return result; 13719 } 13720 13721 // Utility method that returns the relative package path with respect 13722 // to the installation directory. Like say for /data/data/com.test-1.apk 13723 // string com.test-1 is returned. 13724 static String deriveCodePathName(String codePath) { 13725 if (codePath == null) { 13726 return null; 13727 } 13728 final File codeFile = new File(codePath); 13729 final String name = codeFile.getName(); 13730 if (codeFile.isDirectory()) { 13731 return name; 13732 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13733 final int lastDot = name.lastIndexOf('.'); 13734 return name.substring(0, lastDot); 13735 } else { 13736 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13737 return null; 13738 } 13739 } 13740 13741 static class PackageInstalledInfo { 13742 String name; 13743 int uid; 13744 // The set of users that originally had this package installed. 13745 int[] origUsers; 13746 // The set of users that now have this package installed. 13747 int[] newUsers; 13748 PackageParser.Package pkg; 13749 int returnCode; 13750 String returnMsg; 13751 PackageRemovedInfo removedInfo; 13752 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13753 13754 public void setError(int code, String msg) { 13755 setReturnCode(code); 13756 setReturnMessage(msg); 13757 Slog.w(TAG, msg); 13758 } 13759 13760 public void setError(String msg, PackageParserException e) { 13761 setReturnCode(e.error); 13762 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13763 Slog.w(TAG, msg, e); 13764 } 13765 13766 public void setError(String msg, PackageManagerException e) { 13767 returnCode = e.error; 13768 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13769 Slog.w(TAG, msg, e); 13770 } 13771 13772 public void setReturnCode(int returnCode) { 13773 this.returnCode = returnCode; 13774 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13775 for (int i = 0; i < childCount; i++) { 13776 addedChildPackages.valueAt(i).returnCode = returnCode; 13777 } 13778 } 13779 13780 private void setReturnMessage(String returnMsg) { 13781 this.returnMsg = returnMsg; 13782 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13783 for (int i = 0; i < childCount; i++) { 13784 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13785 } 13786 } 13787 13788 // In some error cases we want to convey more info back to the observer 13789 String origPackage; 13790 String origPermission; 13791 } 13792 13793 /* 13794 * Install a non-existing package. 13795 */ 13796 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13797 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13798 PackageInstalledInfo res) { 13799 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13800 13801 // Remember this for later, in case we need to rollback this install 13802 String pkgName = pkg.packageName; 13803 13804 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13805 13806 synchronized(mPackages) { 13807 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13808 // A package with the same name is already installed, though 13809 // it has been renamed to an older name. The package we 13810 // are trying to install should be installed as an update to 13811 // the existing one, but that has not been requested, so bail. 13812 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13813 + " without first uninstalling package running as " 13814 + mSettings.mRenamedPackages.get(pkgName)); 13815 return; 13816 } 13817 if (mPackages.containsKey(pkgName)) { 13818 // Don't allow installation over an existing package with the same name. 13819 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13820 + " without first uninstalling."); 13821 return; 13822 } 13823 } 13824 13825 try { 13826 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13827 System.currentTimeMillis(), user); 13828 13829 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13830 13831 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13832 prepareAppDataAfterInstallLIF(newPackage); 13833 13834 } else { 13835 // Remove package from internal structures, but keep around any 13836 // data that might have already existed 13837 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13838 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13839 } 13840 } catch (PackageManagerException e) { 13841 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13842 } 13843 13844 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13845 } 13846 13847 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13848 // Can't rotate keys during boot or if sharedUser. 13849 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13850 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13851 return false; 13852 } 13853 // app is using upgradeKeySets; make sure all are valid 13854 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13855 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13856 for (int i = 0; i < upgradeKeySets.length; i++) { 13857 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13858 Slog.wtf(TAG, "Package " 13859 + (oldPs.name != null ? oldPs.name : "<null>") 13860 + " contains upgrade-key-set reference to unknown key-set: " 13861 + upgradeKeySets[i] 13862 + " reverting to signatures check."); 13863 return false; 13864 } 13865 } 13866 return true; 13867 } 13868 13869 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13870 // Upgrade keysets are being used. Determine if new package has a superset of the 13871 // required keys. 13872 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13873 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13874 for (int i = 0; i < upgradeKeySets.length; i++) { 13875 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13876 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13877 return true; 13878 } 13879 } 13880 return false; 13881 } 13882 13883 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13884 try (DigestInputStream digestStream = 13885 new DigestInputStream(new FileInputStream(file), digest)) { 13886 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13887 } 13888 } 13889 13890 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13891 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13892 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13893 13894 final PackageParser.Package oldPackage; 13895 final String pkgName = pkg.packageName; 13896 final int[] allUsers; 13897 final int[] installedUsers; 13898 13899 synchronized(mPackages) { 13900 oldPackage = mPackages.get(pkgName); 13901 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13902 13903 // don't allow upgrade to target a release SDK from a pre-release SDK 13904 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13905 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13906 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13907 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13908 if (oldTargetsPreRelease 13909 && !newTargetsPreRelease 13910 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13911 Slog.w(TAG, "Can't install package targeting released sdk"); 13912 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13913 return; 13914 } 13915 13916 // don't allow an upgrade from full to ephemeral 13917 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13918 if (isEphemeral && !oldIsEphemeral) { 13919 // can't downgrade from full to ephemeral 13920 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13921 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13922 return; 13923 } 13924 13925 // verify signatures are valid 13926 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13927 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13928 if (!checkUpgradeKeySetLP(ps, pkg)) { 13929 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13930 "New package not signed by keys specified by upgrade-keysets: " 13931 + pkgName); 13932 return; 13933 } 13934 } else { 13935 // default to original signature matching 13936 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13937 != PackageManager.SIGNATURE_MATCH) { 13938 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13939 "New package has a different signature: " + pkgName); 13940 return; 13941 } 13942 } 13943 13944 // don't allow a system upgrade unless the upgrade hash matches 13945 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13946 byte[] digestBytes = null; 13947 try { 13948 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13949 updateDigest(digest, new File(pkg.baseCodePath)); 13950 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13951 for (String path : pkg.splitCodePaths) { 13952 updateDigest(digest, new File(path)); 13953 } 13954 } 13955 digestBytes = digest.digest(); 13956 } catch (NoSuchAlgorithmException | IOException e) { 13957 res.setError(INSTALL_FAILED_INVALID_APK, 13958 "Could not compute hash: " + pkgName); 13959 return; 13960 } 13961 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13962 res.setError(INSTALL_FAILED_INVALID_APK, 13963 "New package fails restrict-update check: " + pkgName); 13964 return; 13965 } 13966 // retain upgrade restriction 13967 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13968 } 13969 13970 // Check for shared user id changes 13971 String invalidPackageName = 13972 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13973 if (invalidPackageName != null) { 13974 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13975 "Package " + invalidPackageName + " tried to change user " 13976 + oldPackage.mSharedUserId); 13977 return; 13978 } 13979 13980 // In case of rollback, remember per-user/profile install state 13981 allUsers = sUserManager.getUserIds(); 13982 installedUsers = ps.queryInstalledUsers(allUsers, true); 13983 } 13984 13985 // Update what is removed 13986 res.removedInfo = new PackageRemovedInfo(); 13987 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13988 res.removedInfo.removedPackage = oldPackage.packageName; 13989 res.removedInfo.isUpdate = true; 13990 res.removedInfo.origUsers = installedUsers; 13991 final int childCount = (oldPackage.childPackages != null) 13992 ? oldPackage.childPackages.size() : 0; 13993 for (int i = 0; i < childCount; i++) { 13994 boolean childPackageUpdated = false; 13995 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13996 if (res.addedChildPackages != null) { 13997 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13998 if (childRes != null) { 13999 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14000 childRes.removedInfo.removedPackage = childPkg.packageName; 14001 childRes.removedInfo.isUpdate = true; 14002 childPackageUpdated = true; 14003 } 14004 } 14005 if (!childPackageUpdated) { 14006 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14007 childRemovedRes.removedPackage = childPkg.packageName; 14008 childRemovedRes.isUpdate = false; 14009 childRemovedRes.dataRemoved = true; 14010 synchronized (mPackages) { 14011 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14012 if (childPs != null) { 14013 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14014 } 14015 } 14016 if (res.removedInfo.removedChildPackages == null) { 14017 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14018 } 14019 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14020 } 14021 } 14022 14023 boolean sysPkg = (isSystemApp(oldPackage)); 14024 if (sysPkg) { 14025 // Set the system/privileged flags as needed 14026 final boolean privileged = 14027 (oldPackage.applicationInfo.privateFlags 14028 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14029 final int systemPolicyFlags = policyFlags 14030 | PackageParser.PARSE_IS_SYSTEM 14031 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14032 14033 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14034 user, allUsers, installerPackageName, res); 14035 } else { 14036 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14037 user, allUsers, installerPackageName, res); 14038 } 14039 } 14040 14041 public List<String> getPreviousCodePaths(String packageName) { 14042 final PackageSetting ps = mSettings.mPackages.get(packageName); 14043 final List<String> result = new ArrayList<String>(); 14044 if (ps != null && ps.oldCodePaths != null) { 14045 result.addAll(ps.oldCodePaths); 14046 } 14047 return result; 14048 } 14049 14050 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14051 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14052 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14053 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14054 + deletedPackage); 14055 14056 String pkgName = deletedPackage.packageName; 14057 boolean deletedPkg = true; 14058 boolean addedPkg = false; 14059 boolean updatedSettings = false; 14060 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14061 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14062 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14063 14064 final long origUpdateTime = (pkg.mExtras != null) 14065 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14066 14067 // First delete the existing package while retaining the data directory 14068 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14069 res.removedInfo, true, pkg)) { 14070 // If the existing package wasn't successfully deleted 14071 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14072 deletedPkg = false; 14073 } else { 14074 // Successfully deleted the old package; proceed with replace. 14075 14076 // If deleted package lived in a container, give users a chance to 14077 // relinquish resources before killing. 14078 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14079 if (DEBUG_INSTALL) { 14080 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14081 } 14082 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14083 final ArrayList<String> pkgList = new ArrayList<String>(1); 14084 pkgList.add(deletedPackage.applicationInfo.packageName); 14085 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14086 } 14087 14088 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14089 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14090 clearAppProfilesLIF(pkg); 14091 14092 try { 14093 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14094 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14095 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14096 14097 // Update the in-memory copy of the previous code paths. 14098 PackageSetting ps = mSettings.mPackages.get(pkgName); 14099 if (!killApp) { 14100 if (ps.oldCodePaths == null) { 14101 ps.oldCodePaths = new ArraySet<>(); 14102 } 14103 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14104 if (deletedPackage.splitCodePaths != null) { 14105 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14106 } 14107 } else { 14108 ps.oldCodePaths = null; 14109 } 14110 if (ps.childPackageNames != null) { 14111 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14112 final String childPkgName = ps.childPackageNames.get(i); 14113 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14114 childPs.oldCodePaths = ps.oldCodePaths; 14115 } 14116 } 14117 prepareAppDataAfterInstallLIF(newPackage); 14118 addedPkg = true; 14119 } catch (PackageManagerException e) { 14120 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14121 } 14122 } 14123 14124 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14125 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14126 14127 // Revert all internal state mutations and added folders for the failed install 14128 if (addedPkg) { 14129 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14130 res.removedInfo, true, null); 14131 } 14132 14133 // Restore the old package 14134 if (deletedPkg) { 14135 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14136 File restoreFile = new File(deletedPackage.codePath); 14137 // Parse old package 14138 boolean oldExternal = isExternal(deletedPackage); 14139 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14140 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14141 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14142 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14143 try { 14144 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14145 null); 14146 } catch (PackageManagerException e) { 14147 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14148 + e.getMessage()); 14149 return; 14150 } 14151 14152 synchronized (mPackages) { 14153 // Ensure the installer package name up to date 14154 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14155 14156 // Update permissions for restored package 14157 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14158 14159 mSettings.writeLPr(); 14160 } 14161 14162 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14163 } 14164 } else { 14165 synchronized (mPackages) { 14166 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14167 if (ps != null) { 14168 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14169 if (res.removedInfo.removedChildPackages != null) { 14170 final int childCount = res.removedInfo.removedChildPackages.size(); 14171 // Iterate in reverse as we may modify the collection 14172 for (int i = childCount - 1; i >= 0; i--) { 14173 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14174 if (res.addedChildPackages.containsKey(childPackageName)) { 14175 res.removedInfo.removedChildPackages.removeAt(i); 14176 } else { 14177 PackageRemovedInfo childInfo = res.removedInfo 14178 .removedChildPackages.valueAt(i); 14179 childInfo.removedForAllUsers = mPackages.get( 14180 childInfo.removedPackage) == null; 14181 } 14182 } 14183 } 14184 } 14185 } 14186 } 14187 } 14188 14189 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14190 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14191 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14192 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14193 + ", old=" + deletedPackage); 14194 14195 final boolean disabledSystem; 14196 14197 // Remove existing system package 14198 removePackageLI(deletedPackage, true); 14199 14200 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14201 if (!disabledSystem) { 14202 // We didn't need to disable the .apk as a current system package, 14203 // which means we are replacing another update that is already 14204 // installed. We need to make sure to delete the older one's .apk. 14205 res.removedInfo.args = createInstallArgsForExisting(0, 14206 deletedPackage.applicationInfo.getCodePath(), 14207 deletedPackage.applicationInfo.getResourcePath(), 14208 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14209 } else { 14210 res.removedInfo.args = null; 14211 } 14212 14213 // Successfully disabled the old package. Now proceed with re-installation 14214 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14215 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14216 clearAppProfilesLIF(pkg); 14217 14218 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14219 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14220 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14221 14222 PackageParser.Package newPackage = null; 14223 try { 14224 // Add the package to the internal data structures 14225 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14226 14227 // Set the update and install times 14228 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14229 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14230 System.currentTimeMillis()); 14231 14232 // Update the package dynamic state if succeeded 14233 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14234 // Now that the install succeeded make sure we remove data 14235 // directories for any child package the update removed. 14236 final int deletedChildCount = (deletedPackage.childPackages != null) 14237 ? deletedPackage.childPackages.size() : 0; 14238 final int newChildCount = (newPackage.childPackages != null) 14239 ? newPackage.childPackages.size() : 0; 14240 for (int i = 0; i < deletedChildCount; i++) { 14241 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14242 boolean childPackageDeleted = true; 14243 for (int j = 0; j < newChildCount; j++) { 14244 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14245 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14246 childPackageDeleted = false; 14247 break; 14248 } 14249 } 14250 if (childPackageDeleted) { 14251 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14252 deletedChildPkg.packageName); 14253 if (ps != null && res.removedInfo.removedChildPackages != null) { 14254 PackageRemovedInfo removedChildRes = res.removedInfo 14255 .removedChildPackages.get(deletedChildPkg.packageName); 14256 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14257 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14258 } 14259 } 14260 } 14261 14262 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14263 prepareAppDataAfterInstallLIF(newPackage); 14264 } 14265 } catch (PackageManagerException e) { 14266 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14267 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14268 } 14269 14270 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14271 // Re installation failed. Restore old information 14272 // Remove new pkg information 14273 if (newPackage != null) { 14274 removeInstalledPackageLI(newPackage, true); 14275 } 14276 // Add back the old system package 14277 try { 14278 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14279 } catch (PackageManagerException e) { 14280 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14281 } 14282 14283 synchronized (mPackages) { 14284 if (disabledSystem) { 14285 enableSystemPackageLPw(deletedPackage); 14286 } 14287 14288 // Ensure the installer package name up to date 14289 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14290 14291 // Update permissions for restored package 14292 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14293 14294 mSettings.writeLPr(); 14295 } 14296 14297 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14298 + " after failed upgrade"); 14299 } 14300 } 14301 14302 /** 14303 * Checks whether the parent or any of the child packages have a change shared 14304 * user. For a package to be a valid update the shred users of the parent and 14305 * the children should match. We may later support changing child shared users. 14306 * @param oldPkg The updated package. 14307 * @param newPkg The update package. 14308 * @return The shared user that change between the versions. 14309 */ 14310 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14311 PackageParser.Package newPkg) { 14312 // Check parent shared user 14313 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14314 return newPkg.packageName; 14315 } 14316 // Check child shared users 14317 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14318 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14319 for (int i = 0; i < newChildCount; i++) { 14320 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14321 // If this child was present, did it have the same shared user? 14322 for (int j = 0; j < oldChildCount; j++) { 14323 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14324 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14325 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14326 return newChildPkg.packageName; 14327 } 14328 } 14329 } 14330 return null; 14331 } 14332 14333 private void removeNativeBinariesLI(PackageSetting ps) { 14334 // Remove the lib path for the parent package 14335 if (ps != null) { 14336 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14337 // Remove the lib path for the child packages 14338 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14339 for (int i = 0; i < childCount; i++) { 14340 PackageSetting childPs = null; 14341 synchronized (mPackages) { 14342 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14343 } 14344 if (childPs != null) { 14345 NativeLibraryHelper.removeNativeBinariesLI(childPs 14346 .legacyNativeLibraryPathString); 14347 } 14348 } 14349 } 14350 } 14351 14352 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14353 // Enable the parent package 14354 mSettings.enableSystemPackageLPw(pkg.packageName); 14355 // Enable the child packages 14356 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14357 for (int i = 0; i < childCount; i++) { 14358 PackageParser.Package childPkg = pkg.childPackages.get(i); 14359 mSettings.enableSystemPackageLPw(childPkg.packageName); 14360 } 14361 } 14362 14363 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14364 PackageParser.Package newPkg) { 14365 // Disable the parent package (parent always replaced) 14366 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14367 // Disable the child packages 14368 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14369 for (int i = 0; i < childCount; i++) { 14370 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14371 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14372 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14373 } 14374 return disabled; 14375 } 14376 14377 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14378 String installerPackageName) { 14379 // Enable the parent package 14380 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14381 // Enable the child packages 14382 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14383 for (int i = 0; i < childCount; i++) { 14384 PackageParser.Package childPkg = pkg.childPackages.get(i); 14385 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14386 } 14387 } 14388 14389 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14390 // Collect all used permissions in the UID 14391 ArraySet<String> usedPermissions = new ArraySet<>(); 14392 final int packageCount = su.packages.size(); 14393 for (int i = 0; i < packageCount; i++) { 14394 PackageSetting ps = su.packages.valueAt(i); 14395 if (ps.pkg == null) { 14396 continue; 14397 } 14398 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14399 for (int j = 0; j < requestedPermCount; j++) { 14400 String permission = ps.pkg.requestedPermissions.get(j); 14401 BasePermission bp = mSettings.mPermissions.get(permission); 14402 if (bp != null) { 14403 usedPermissions.add(permission); 14404 } 14405 } 14406 } 14407 14408 PermissionsState permissionsState = su.getPermissionsState(); 14409 // Prune install permissions 14410 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14411 final int installPermCount = installPermStates.size(); 14412 for (int i = installPermCount - 1; i >= 0; i--) { 14413 PermissionState permissionState = installPermStates.get(i); 14414 if (!usedPermissions.contains(permissionState.getName())) { 14415 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14416 if (bp != null) { 14417 permissionsState.revokeInstallPermission(bp); 14418 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14419 PackageManager.MASK_PERMISSION_FLAGS, 0); 14420 } 14421 } 14422 } 14423 14424 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14425 14426 // Prune runtime permissions 14427 for (int userId : allUserIds) { 14428 List<PermissionState> runtimePermStates = permissionsState 14429 .getRuntimePermissionStates(userId); 14430 final int runtimePermCount = runtimePermStates.size(); 14431 for (int i = runtimePermCount - 1; i >= 0; i--) { 14432 PermissionState permissionState = runtimePermStates.get(i); 14433 if (!usedPermissions.contains(permissionState.getName())) { 14434 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14435 if (bp != null) { 14436 permissionsState.revokeRuntimePermission(bp, userId); 14437 permissionsState.updatePermissionFlags(bp, userId, 14438 PackageManager.MASK_PERMISSION_FLAGS, 0); 14439 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14440 runtimePermissionChangedUserIds, userId); 14441 } 14442 } 14443 } 14444 } 14445 14446 return runtimePermissionChangedUserIds; 14447 } 14448 14449 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14450 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14451 // Update the parent package setting 14452 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14453 res, user); 14454 // Update the child packages setting 14455 final int childCount = (newPackage.childPackages != null) 14456 ? newPackage.childPackages.size() : 0; 14457 for (int i = 0; i < childCount; i++) { 14458 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14459 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14460 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14461 childRes.origUsers, childRes, user); 14462 } 14463 } 14464 14465 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14466 String installerPackageName, int[] allUsers, int[] installedForUsers, 14467 PackageInstalledInfo res, UserHandle user) { 14468 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14469 14470 String pkgName = newPackage.packageName; 14471 synchronized (mPackages) { 14472 //write settings. the installStatus will be incomplete at this stage. 14473 //note that the new package setting would have already been 14474 //added to mPackages. It hasn't been persisted yet. 14475 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14476 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14477 mSettings.writeLPr(); 14478 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14479 } 14480 14481 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14482 synchronized (mPackages) { 14483 updatePermissionsLPw(newPackage.packageName, newPackage, 14484 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14485 ? UPDATE_PERMISSIONS_ALL : 0)); 14486 // For system-bundled packages, we assume that installing an upgraded version 14487 // of the package implies that the user actually wants to run that new code, 14488 // so we enable the package. 14489 PackageSetting ps = mSettings.mPackages.get(pkgName); 14490 final int userId = user.getIdentifier(); 14491 if (ps != null) { 14492 if (isSystemApp(newPackage)) { 14493 if (DEBUG_INSTALL) { 14494 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14495 } 14496 // Enable system package for requested users 14497 if (res.origUsers != null) { 14498 for (int origUserId : res.origUsers) { 14499 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14500 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14501 origUserId, installerPackageName); 14502 } 14503 } 14504 } 14505 // Also convey the prior install/uninstall state 14506 if (allUsers != null && installedForUsers != null) { 14507 for (int currentUserId : allUsers) { 14508 final boolean installed = ArrayUtils.contains( 14509 installedForUsers, currentUserId); 14510 if (DEBUG_INSTALL) { 14511 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14512 } 14513 ps.setInstalled(installed, currentUserId); 14514 } 14515 // these install state changes will be persisted in the 14516 // upcoming call to mSettings.writeLPr(). 14517 } 14518 } 14519 // It's implied that when a user requests installation, they want the app to be 14520 // installed and enabled. 14521 if (userId != UserHandle.USER_ALL) { 14522 ps.setInstalled(true, userId); 14523 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14524 } 14525 } 14526 res.name = pkgName; 14527 res.uid = newPackage.applicationInfo.uid; 14528 res.pkg = newPackage; 14529 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14530 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14531 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14532 //to update install status 14533 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14534 mSettings.writeLPr(); 14535 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14536 } 14537 14538 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14539 } 14540 14541 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14542 try { 14543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14544 installPackageLI(args, res); 14545 } finally { 14546 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14547 } 14548 } 14549 14550 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14551 final int installFlags = args.installFlags; 14552 final String installerPackageName = args.installerPackageName; 14553 final String volumeUuid = args.volumeUuid; 14554 final File tmpPackageFile = new File(args.getCodePath()); 14555 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14556 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14557 || (args.volumeUuid != null)); 14558 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14559 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14560 boolean replace = false; 14561 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14562 if (args.move != null) { 14563 // moving a complete application; perform an initial scan on the new install location 14564 scanFlags |= SCAN_INITIAL; 14565 } 14566 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14567 scanFlags |= SCAN_DONT_KILL_APP; 14568 } 14569 14570 // Result object to be returned 14571 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14572 14573 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14574 14575 // Sanity check 14576 if (ephemeral && (forwardLocked || onExternal)) { 14577 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14578 + " external=" + onExternal); 14579 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14580 return; 14581 } 14582 14583 // Retrieve PackageSettings and parse package 14584 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14585 | PackageParser.PARSE_ENFORCE_CODE 14586 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14587 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14588 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14589 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14590 PackageParser pp = new PackageParser(); 14591 pp.setSeparateProcesses(mSeparateProcesses); 14592 pp.setDisplayMetrics(mMetrics); 14593 14594 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14595 final PackageParser.Package pkg; 14596 try { 14597 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14598 } catch (PackageParserException e) { 14599 res.setError("Failed parse during installPackageLI", e); 14600 return; 14601 } finally { 14602 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14603 } 14604 14605 // If we are installing a clustered package add results for the children 14606 if (pkg.childPackages != null) { 14607 synchronized (mPackages) { 14608 final int childCount = pkg.childPackages.size(); 14609 for (int i = 0; i < childCount; i++) { 14610 PackageParser.Package childPkg = pkg.childPackages.get(i); 14611 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14612 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14613 childRes.pkg = childPkg; 14614 childRes.name = childPkg.packageName; 14615 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14616 if (childPs != null) { 14617 childRes.origUsers = childPs.queryInstalledUsers( 14618 sUserManager.getUserIds(), true); 14619 } 14620 if ((mPackages.containsKey(childPkg.packageName))) { 14621 childRes.removedInfo = new PackageRemovedInfo(); 14622 childRes.removedInfo.removedPackage = childPkg.packageName; 14623 } 14624 if (res.addedChildPackages == null) { 14625 res.addedChildPackages = new ArrayMap<>(); 14626 } 14627 res.addedChildPackages.put(childPkg.packageName, childRes); 14628 } 14629 } 14630 } 14631 14632 // If package doesn't declare API override, mark that we have an install 14633 // time CPU ABI override. 14634 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14635 pkg.cpuAbiOverride = args.abiOverride; 14636 } 14637 14638 String pkgName = res.name = pkg.packageName; 14639 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14640 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14641 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14642 return; 14643 } 14644 } 14645 14646 try { 14647 // either use what we've been given or parse directly from the APK 14648 if (args.certificates != null) { 14649 try { 14650 PackageParser.populateCertificates(pkg, args.certificates); 14651 } catch (PackageParserException e) { 14652 // there was something wrong with the certificates we were given; 14653 // try to pull them from the APK 14654 PackageParser.collectCertificates(pkg, parseFlags); 14655 } 14656 } else { 14657 PackageParser.collectCertificates(pkg, parseFlags); 14658 } 14659 } catch (PackageParserException e) { 14660 res.setError("Failed collect during installPackageLI", e); 14661 return; 14662 } 14663 14664 // Get rid of all references to package scan path via parser. 14665 pp = null; 14666 String oldCodePath = null; 14667 boolean systemApp = false; 14668 synchronized (mPackages) { 14669 // Check if installing already existing package 14670 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14671 String oldName = mSettings.mRenamedPackages.get(pkgName); 14672 if (pkg.mOriginalPackages != null 14673 && pkg.mOriginalPackages.contains(oldName) 14674 && mPackages.containsKey(oldName)) { 14675 // This package is derived from an original package, 14676 // and this device has been updating from that original 14677 // name. We must continue using the original name, so 14678 // rename the new package here. 14679 pkg.setPackageName(oldName); 14680 pkgName = pkg.packageName; 14681 replace = true; 14682 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14683 + oldName + " pkgName=" + pkgName); 14684 } else if (mPackages.containsKey(pkgName)) { 14685 // This package, under its official name, already exists 14686 // on the device; we should replace it. 14687 replace = true; 14688 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14689 } 14690 14691 // Child packages are installed through the parent package 14692 if (pkg.parentPackage != null) { 14693 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14694 "Package " + pkg.packageName + " is child of package " 14695 + pkg.parentPackage.parentPackage + ". Child packages " 14696 + "can be updated only through the parent package."); 14697 return; 14698 } 14699 14700 if (replace) { 14701 // Prevent apps opting out from runtime permissions 14702 PackageParser.Package oldPackage = mPackages.get(pkgName); 14703 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14704 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14705 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14706 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14707 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14708 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14709 + " doesn't support runtime permissions but the old" 14710 + " target SDK " + oldTargetSdk + " does."); 14711 return; 14712 } 14713 14714 // Prevent installing of child packages 14715 if (oldPackage.parentPackage != null) { 14716 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14717 "Package " + pkg.packageName + " is child of package " 14718 + oldPackage.parentPackage + ". Child packages " 14719 + "can be updated only through the parent package."); 14720 return; 14721 } 14722 } 14723 } 14724 14725 PackageSetting ps = mSettings.mPackages.get(pkgName); 14726 if (ps != null) { 14727 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14728 14729 // Quick sanity check that we're signed correctly if updating; 14730 // we'll check this again later when scanning, but we want to 14731 // bail early here before tripping over redefined permissions. 14732 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14733 if (!checkUpgradeKeySetLP(ps, pkg)) { 14734 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14735 + pkg.packageName + " upgrade keys do not match the " 14736 + "previously installed version"); 14737 return; 14738 } 14739 } else { 14740 try { 14741 verifySignaturesLP(ps, pkg); 14742 } catch (PackageManagerException e) { 14743 res.setError(e.error, e.getMessage()); 14744 return; 14745 } 14746 } 14747 14748 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14749 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14750 systemApp = (ps.pkg.applicationInfo.flags & 14751 ApplicationInfo.FLAG_SYSTEM) != 0; 14752 } 14753 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14754 } 14755 14756 // Check whether the newly-scanned package wants to define an already-defined perm 14757 int N = pkg.permissions.size(); 14758 for (int i = N-1; i >= 0; i--) { 14759 PackageParser.Permission perm = pkg.permissions.get(i); 14760 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14761 if (bp != null) { 14762 // If the defining package is signed with our cert, it's okay. This 14763 // also includes the "updating the same package" case, of course. 14764 // "updating same package" could also involve key-rotation. 14765 final boolean sigsOk; 14766 if (bp.sourcePackage.equals(pkg.packageName) 14767 && (bp.packageSetting instanceof PackageSetting) 14768 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14769 scanFlags))) { 14770 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14771 } else { 14772 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14773 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14774 } 14775 if (!sigsOk) { 14776 // If the owning package is the system itself, we log but allow 14777 // install to proceed; we fail the install on all other permission 14778 // redefinitions. 14779 if (!bp.sourcePackage.equals("android")) { 14780 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14781 + pkg.packageName + " attempting to redeclare permission " 14782 + perm.info.name + " already owned by " + bp.sourcePackage); 14783 res.origPermission = perm.info.name; 14784 res.origPackage = bp.sourcePackage; 14785 return; 14786 } else { 14787 Slog.w(TAG, "Package " + pkg.packageName 14788 + " attempting to redeclare system permission " 14789 + perm.info.name + "; ignoring new declaration"); 14790 pkg.permissions.remove(i); 14791 } 14792 } 14793 } 14794 } 14795 } 14796 14797 if (systemApp) { 14798 if (onExternal) { 14799 // Abort update; system app can't be replaced with app on sdcard 14800 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14801 "Cannot install updates to system apps on sdcard"); 14802 return; 14803 } else if (ephemeral) { 14804 // Abort update; system app can't be replaced with an ephemeral app 14805 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14806 "Cannot update a system app with an ephemeral app"); 14807 return; 14808 } 14809 } 14810 14811 if (args.move != null) { 14812 // We did an in-place move, so dex is ready to roll 14813 scanFlags |= SCAN_NO_DEX; 14814 scanFlags |= SCAN_MOVE; 14815 14816 synchronized (mPackages) { 14817 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14818 if (ps == null) { 14819 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14820 "Missing settings for moved package " + pkgName); 14821 } 14822 14823 // We moved the entire application as-is, so bring over the 14824 // previously derived ABI information. 14825 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14826 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14827 } 14828 14829 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14830 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14831 scanFlags |= SCAN_NO_DEX; 14832 14833 try { 14834 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14835 args.abiOverride : pkg.cpuAbiOverride); 14836 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14837 true /* extract libs */); 14838 } catch (PackageManagerException pme) { 14839 Slog.e(TAG, "Error deriving application ABI", pme); 14840 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14841 return; 14842 } 14843 14844 // Shared libraries for the package need to be updated. 14845 synchronized (mPackages) { 14846 try { 14847 updateSharedLibrariesLPw(pkg, null); 14848 } catch (PackageManagerException e) { 14849 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14850 } 14851 } 14852 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14853 // Do not run PackageDexOptimizer through the local performDexOpt 14854 // method because `pkg` is not in `mPackages` yet. 14855 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14856 null /* instructionSets */, false /* checkProfiles */, 14857 getCompilerFilterForReason(REASON_INSTALL)); 14858 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14859 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14860 String msg = "Extracting package failed for " + pkgName; 14861 res.setError(INSTALL_FAILED_DEXOPT, msg); 14862 return; 14863 } 14864 14865 // Notify BackgroundDexOptService that the package has been changed. 14866 // If this is an update of a package which used to fail to compile, 14867 // BDOS will remove it from its blacklist. 14868 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14869 } 14870 14871 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14872 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14873 return; 14874 } 14875 14876 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14877 14878 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14879 "installPackageLI")) { 14880 if (replace) { 14881 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14882 installerPackageName, res); 14883 } else { 14884 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14885 args.user, installerPackageName, volumeUuid, res); 14886 } 14887 } 14888 synchronized (mPackages) { 14889 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14890 if (ps != null) { 14891 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14892 } 14893 14894 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14895 for (int i = 0; i < childCount; i++) { 14896 PackageParser.Package childPkg = pkg.childPackages.get(i); 14897 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14898 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14899 if (childPs != null) { 14900 childRes.newUsers = childPs.queryInstalledUsers( 14901 sUserManager.getUserIds(), true); 14902 } 14903 } 14904 } 14905 } 14906 14907 private void startIntentFilterVerifications(int userId, boolean replacing, 14908 PackageParser.Package pkg) { 14909 if (mIntentFilterVerifierComponent == null) { 14910 Slog.w(TAG, "No IntentFilter verification will not be done as " 14911 + "there is no IntentFilterVerifier available!"); 14912 return; 14913 } 14914 14915 final int verifierUid = getPackageUid( 14916 mIntentFilterVerifierComponent.getPackageName(), 14917 MATCH_DEBUG_TRIAGED_MISSING, 14918 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14919 14920 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14921 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14922 mHandler.sendMessage(msg); 14923 14924 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14925 for (int i = 0; i < childCount; i++) { 14926 PackageParser.Package childPkg = pkg.childPackages.get(i); 14927 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14928 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14929 mHandler.sendMessage(msg); 14930 } 14931 } 14932 14933 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14934 PackageParser.Package pkg) { 14935 int size = pkg.activities.size(); 14936 if (size == 0) { 14937 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14938 "No activity, so no need to verify any IntentFilter!"); 14939 return; 14940 } 14941 14942 final boolean hasDomainURLs = hasDomainURLs(pkg); 14943 if (!hasDomainURLs) { 14944 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14945 "No domain URLs, so no need to verify any IntentFilter!"); 14946 return; 14947 } 14948 14949 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14950 + " if any IntentFilter from the " + size 14951 + " Activities needs verification ..."); 14952 14953 int count = 0; 14954 final String packageName = pkg.packageName; 14955 14956 synchronized (mPackages) { 14957 // If this is a new install and we see that we've already run verification for this 14958 // package, we have nothing to do: it means the state was restored from backup. 14959 if (!replacing) { 14960 IntentFilterVerificationInfo ivi = 14961 mSettings.getIntentFilterVerificationLPr(packageName); 14962 if (ivi != null) { 14963 if (DEBUG_DOMAIN_VERIFICATION) { 14964 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14965 + ivi.getStatusString()); 14966 } 14967 return; 14968 } 14969 } 14970 14971 // If any filters need to be verified, then all need to be. 14972 boolean needToVerify = false; 14973 for (PackageParser.Activity a : pkg.activities) { 14974 for (ActivityIntentInfo filter : a.intents) { 14975 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14976 if (DEBUG_DOMAIN_VERIFICATION) { 14977 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14978 } 14979 needToVerify = true; 14980 break; 14981 } 14982 } 14983 } 14984 14985 if (needToVerify) { 14986 final int verificationId = mIntentFilterVerificationToken++; 14987 for (PackageParser.Activity a : pkg.activities) { 14988 for (ActivityIntentInfo filter : a.intents) { 14989 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14990 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14991 "Verification needed for IntentFilter:" + filter.toString()); 14992 mIntentFilterVerifier.addOneIntentFilterVerification( 14993 verifierUid, userId, verificationId, filter, packageName); 14994 count++; 14995 } 14996 } 14997 } 14998 } 14999 } 15000 15001 if (count > 0) { 15002 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15003 + " IntentFilter verification" + (count > 1 ? "s" : "") 15004 + " for userId:" + userId); 15005 mIntentFilterVerifier.startVerifications(userId); 15006 } else { 15007 if (DEBUG_DOMAIN_VERIFICATION) { 15008 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15009 } 15010 } 15011 } 15012 15013 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15014 final ComponentName cn = filter.activity.getComponentName(); 15015 final String packageName = cn.getPackageName(); 15016 15017 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15018 packageName); 15019 if (ivi == null) { 15020 return true; 15021 } 15022 int status = ivi.getStatus(); 15023 switch (status) { 15024 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15025 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15026 return true; 15027 15028 default: 15029 // Nothing to do 15030 return false; 15031 } 15032 } 15033 15034 private static boolean isMultiArch(ApplicationInfo info) { 15035 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15036 } 15037 15038 private static boolean isExternal(PackageParser.Package pkg) { 15039 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15040 } 15041 15042 private static boolean isExternal(PackageSetting ps) { 15043 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15044 } 15045 15046 private static boolean isEphemeral(PackageParser.Package pkg) { 15047 return pkg.applicationInfo.isEphemeralApp(); 15048 } 15049 15050 private static boolean isEphemeral(PackageSetting ps) { 15051 return ps.pkg != null && isEphemeral(ps.pkg); 15052 } 15053 15054 private static boolean isSystemApp(PackageParser.Package pkg) { 15055 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15056 } 15057 15058 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15059 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15060 } 15061 15062 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15063 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15064 } 15065 15066 private static boolean isSystemApp(PackageSetting ps) { 15067 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15068 } 15069 15070 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15071 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15072 } 15073 15074 private int packageFlagsToInstallFlags(PackageSetting ps) { 15075 int installFlags = 0; 15076 if (isEphemeral(ps)) { 15077 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15078 } 15079 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15080 // This existing package was an external ASEC install when we have 15081 // the external flag without a UUID 15082 installFlags |= PackageManager.INSTALL_EXTERNAL; 15083 } 15084 if (ps.isForwardLocked()) { 15085 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15086 } 15087 return installFlags; 15088 } 15089 15090 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15091 if (isExternal(pkg)) { 15092 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15093 return StorageManager.UUID_PRIMARY_PHYSICAL; 15094 } else { 15095 return pkg.volumeUuid; 15096 } 15097 } else { 15098 return StorageManager.UUID_PRIVATE_INTERNAL; 15099 } 15100 } 15101 15102 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15103 if (isExternal(pkg)) { 15104 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15105 return mSettings.getExternalVersion(); 15106 } else { 15107 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15108 } 15109 } else { 15110 return mSettings.getInternalVersion(); 15111 } 15112 } 15113 15114 private void deleteTempPackageFiles() { 15115 final FilenameFilter filter = new FilenameFilter() { 15116 public boolean accept(File dir, String name) { 15117 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15118 } 15119 }; 15120 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15121 file.delete(); 15122 } 15123 } 15124 15125 @Override 15126 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15127 int flags) { 15128 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15129 flags); 15130 } 15131 15132 @Override 15133 public void deletePackage(final String packageName, 15134 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15135 mContext.enforceCallingOrSelfPermission( 15136 android.Manifest.permission.DELETE_PACKAGES, null); 15137 Preconditions.checkNotNull(packageName); 15138 Preconditions.checkNotNull(observer); 15139 final int uid = Binder.getCallingUid(); 15140 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15141 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15142 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15143 mContext.enforceCallingOrSelfPermission( 15144 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15145 "deletePackage for user " + userId); 15146 } 15147 15148 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15149 try { 15150 observer.onPackageDeleted(packageName, 15151 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15152 } catch (RemoteException re) { 15153 } 15154 return; 15155 } 15156 15157 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15158 try { 15159 observer.onPackageDeleted(packageName, 15160 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15161 } catch (RemoteException re) { 15162 } 15163 return; 15164 } 15165 15166 if (DEBUG_REMOVE) { 15167 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15168 + " deleteAllUsers: " + deleteAllUsers ); 15169 } 15170 // Queue up an async operation since the package deletion may take a little while. 15171 mHandler.post(new Runnable() { 15172 public void run() { 15173 mHandler.removeCallbacks(this); 15174 int returnCode; 15175 if (!deleteAllUsers) { 15176 returnCode = deletePackageX(packageName, userId, deleteFlags); 15177 } else { 15178 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15179 // If nobody is blocking uninstall, proceed with delete for all users 15180 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15181 returnCode = deletePackageX(packageName, userId, deleteFlags); 15182 } else { 15183 // Otherwise uninstall individually for users with blockUninstalls=false 15184 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15185 for (int userId : users) { 15186 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15187 returnCode = deletePackageX(packageName, userId, userFlags); 15188 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15189 Slog.w(TAG, "Package delete failed for user " + userId 15190 + ", returnCode " + returnCode); 15191 } 15192 } 15193 } 15194 // The app has only been marked uninstalled for certain users. 15195 // We still need to report that delete was blocked 15196 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15197 } 15198 } 15199 try { 15200 observer.onPackageDeleted(packageName, returnCode, null); 15201 } catch (RemoteException e) { 15202 Log.i(TAG, "Observer no longer exists."); 15203 } //end catch 15204 } //end run 15205 }); 15206 } 15207 15208 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15209 int[] result = EMPTY_INT_ARRAY; 15210 for (int userId : userIds) { 15211 if (getBlockUninstallForUser(packageName, userId)) { 15212 result = ArrayUtils.appendInt(result, userId); 15213 } 15214 } 15215 return result; 15216 } 15217 15218 @Override 15219 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15220 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15221 } 15222 15223 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15224 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15225 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15226 try { 15227 if (dpm != null) { 15228 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15229 /* callingUserOnly =*/ false); 15230 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15231 : deviceOwnerComponentName.getPackageName(); 15232 // Does the package contains the device owner? 15233 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15234 // this check is probably not needed, since DO should be registered as a device 15235 // admin on some user too. (Original bug for this: b/17657954) 15236 if (packageName.equals(deviceOwnerPackageName)) { 15237 return true; 15238 } 15239 // Does it contain a device admin for any user? 15240 int[] users; 15241 if (userId == UserHandle.USER_ALL) { 15242 users = sUserManager.getUserIds(); 15243 } else { 15244 users = new int[]{userId}; 15245 } 15246 for (int i = 0; i < users.length; ++i) { 15247 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15248 return true; 15249 } 15250 } 15251 } 15252 } catch (RemoteException e) { 15253 } 15254 return false; 15255 } 15256 15257 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15258 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15259 } 15260 15261 /** 15262 * This method is an internal method that could be get invoked either 15263 * to delete an installed package or to clean up a failed installation. 15264 * After deleting an installed package, a broadcast is sent to notify any 15265 * listeners that the package has been removed. For cleaning up a failed 15266 * installation, the broadcast is not necessary since the package's 15267 * installation wouldn't have sent the initial broadcast either 15268 * The key steps in deleting a package are 15269 * deleting the package information in internal structures like mPackages, 15270 * deleting the packages base directories through installd 15271 * updating mSettings to reflect current status 15272 * persisting settings for later use 15273 * sending a broadcast if necessary 15274 */ 15275 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15276 final PackageRemovedInfo info = new PackageRemovedInfo(); 15277 final boolean res; 15278 15279 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15280 ? UserHandle.ALL : new UserHandle(userId); 15281 15282 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15283 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15284 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15285 } 15286 15287 PackageSetting uninstalledPs = null; 15288 15289 // for the uninstall-updates case and restricted profiles, remember the per- 15290 // user handle installed state 15291 int[] allUsers; 15292 synchronized (mPackages) { 15293 uninstalledPs = mSettings.mPackages.get(packageName); 15294 if (uninstalledPs == null) { 15295 Slog.w(TAG, "Not removing non-existent package " + packageName); 15296 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15297 } 15298 allUsers = sUserManager.getUserIds(); 15299 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15300 } 15301 15302 synchronized (mInstallLock) { 15303 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15304 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15305 "deletePackageX")) { 15306 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15307 deleteFlags | REMOVE_CHATTY, info, true, null); 15308 } 15309 synchronized (mPackages) { 15310 if (res) { 15311 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15312 } 15313 } 15314 } 15315 15316 if (res) { 15317 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15318 info.sendPackageRemovedBroadcasts(killApp); 15319 info.sendSystemPackageUpdatedBroadcasts(); 15320 info.sendSystemPackageAppearedBroadcasts(); 15321 } 15322 // Force a gc here. 15323 Runtime.getRuntime().gc(); 15324 // Delete the resources here after sending the broadcast to let 15325 // other processes clean up before deleting resources. 15326 if (info.args != null) { 15327 synchronized (mInstallLock) { 15328 info.args.doPostDeleteLI(true); 15329 } 15330 } 15331 15332 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15333 } 15334 15335 class PackageRemovedInfo { 15336 String removedPackage; 15337 int uid = -1; 15338 int removedAppId = -1; 15339 int[] origUsers; 15340 int[] removedUsers = null; 15341 boolean isRemovedPackageSystemUpdate = false; 15342 boolean isUpdate; 15343 boolean dataRemoved; 15344 boolean removedForAllUsers; 15345 // Clean up resources deleted packages. 15346 InstallArgs args = null; 15347 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15348 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15349 15350 void sendPackageRemovedBroadcasts(boolean killApp) { 15351 sendPackageRemovedBroadcastInternal(killApp); 15352 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15353 for (int i = 0; i < childCount; i++) { 15354 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15355 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15356 } 15357 } 15358 15359 void sendSystemPackageUpdatedBroadcasts() { 15360 if (isRemovedPackageSystemUpdate) { 15361 sendSystemPackageUpdatedBroadcastsInternal(); 15362 final int childCount = (removedChildPackages != null) 15363 ? removedChildPackages.size() : 0; 15364 for (int i = 0; i < childCount; i++) { 15365 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15366 if (childInfo.isRemovedPackageSystemUpdate) { 15367 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15368 } 15369 } 15370 } 15371 } 15372 15373 void sendSystemPackageAppearedBroadcasts() { 15374 final int packageCount = (appearedChildPackages != null) 15375 ? appearedChildPackages.size() : 0; 15376 for (int i = 0; i < packageCount; i++) { 15377 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15378 for (int userId : installedInfo.newUsers) { 15379 sendPackageAddedForUser(installedInfo.name, true, 15380 UserHandle.getAppId(installedInfo.uid), userId); 15381 } 15382 } 15383 } 15384 15385 private void sendSystemPackageUpdatedBroadcastsInternal() { 15386 Bundle extras = new Bundle(2); 15387 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15388 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15389 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15390 extras, 0, null, null, null); 15391 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15392 extras, 0, null, null, null); 15393 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15394 null, 0, removedPackage, null, null); 15395 } 15396 15397 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15398 Bundle extras = new Bundle(2); 15399 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15400 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15401 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15402 if (isUpdate || isRemovedPackageSystemUpdate) { 15403 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15404 } 15405 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15406 if (removedPackage != null) { 15407 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15408 extras, 0, null, null, removedUsers); 15409 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15410 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15411 removedPackage, extras, 0, null, null, removedUsers); 15412 } 15413 } 15414 if (removedAppId >= 0) { 15415 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15416 removedUsers); 15417 } 15418 } 15419 } 15420 15421 /* 15422 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15423 * flag is not set, the data directory is removed as well. 15424 * make sure this flag is set for partially installed apps. If not its meaningless to 15425 * delete a partially installed application. 15426 */ 15427 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15428 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15429 String packageName = ps.name; 15430 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15431 // Retrieve object to delete permissions for shared user later on 15432 final PackageParser.Package deletedPkg; 15433 final PackageSetting deletedPs; 15434 // reader 15435 synchronized (mPackages) { 15436 deletedPkg = mPackages.get(packageName); 15437 deletedPs = mSettings.mPackages.get(packageName); 15438 if (outInfo != null) { 15439 outInfo.removedPackage = packageName; 15440 outInfo.removedUsers = deletedPs != null 15441 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15442 : null; 15443 } 15444 } 15445 15446 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15447 15448 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15449 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15450 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15451 destroyAppProfilesLIF(deletedPkg); 15452 if (outInfo != null) { 15453 outInfo.dataRemoved = true; 15454 } 15455 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15456 } 15457 15458 // writer 15459 synchronized (mPackages) { 15460 if (deletedPs != null) { 15461 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15462 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15463 clearDefaultBrowserIfNeeded(packageName); 15464 if (outInfo != null) { 15465 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15466 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15467 } 15468 updatePermissionsLPw(deletedPs.name, null, 0); 15469 if (deletedPs.sharedUser != null) { 15470 // Remove permissions associated with package. Since runtime 15471 // permissions are per user we have to kill the removed package 15472 // or packages running under the shared user of the removed 15473 // package if revoking the permissions requested only by the removed 15474 // package is successful and this causes a change in gids. 15475 for (int userId : UserManagerService.getInstance().getUserIds()) { 15476 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15477 userId); 15478 if (userIdToKill == UserHandle.USER_ALL 15479 || userIdToKill >= UserHandle.USER_SYSTEM) { 15480 // If gids changed for this user, kill all affected packages. 15481 mHandler.post(new Runnable() { 15482 @Override 15483 public void run() { 15484 // This has to happen with no lock held. 15485 killApplication(deletedPs.name, deletedPs.appId, 15486 KILL_APP_REASON_GIDS_CHANGED); 15487 } 15488 }); 15489 break; 15490 } 15491 } 15492 } 15493 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15494 } 15495 // make sure to preserve per-user disabled state if this removal was just 15496 // a downgrade of a system app to the factory package 15497 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15498 if (DEBUG_REMOVE) { 15499 Slog.d(TAG, "Propagating install state across downgrade"); 15500 } 15501 for (int userId : allUserHandles) { 15502 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15503 if (DEBUG_REMOVE) { 15504 Slog.d(TAG, " user " + userId + " => " + installed); 15505 } 15506 ps.setInstalled(installed, userId); 15507 } 15508 } 15509 } 15510 // can downgrade to reader 15511 if (writeSettings) { 15512 // Save settings now 15513 mSettings.writeLPr(); 15514 } 15515 } 15516 if (outInfo != null) { 15517 // A user ID was deleted here. Go through all users and remove it 15518 // from KeyStore. 15519 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15520 } 15521 } 15522 15523 static boolean locationIsPrivileged(File path) { 15524 try { 15525 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15526 .getCanonicalPath(); 15527 return path.getCanonicalPath().startsWith(privilegedAppDir); 15528 } catch (IOException e) { 15529 Slog.e(TAG, "Unable to access code path " + path); 15530 } 15531 return false; 15532 } 15533 15534 /* 15535 * Tries to delete system package. 15536 */ 15537 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15538 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15539 boolean writeSettings) { 15540 if (deletedPs.parentPackageName != null) { 15541 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15542 return false; 15543 } 15544 15545 final boolean applyUserRestrictions 15546 = (allUserHandles != null) && (outInfo.origUsers != null); 15547 final PackageSetting disabledPs; 15548 // Confirm if the system package has been updated 15549 // An updated system app can be deleted. This will also have to restore 15550 // the system pkg from system partition 15551 // reader 15552 synchronized (mPackages) { 15553 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15554 } 15555 15556 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15557 + " disabledPs=" + disabledPs); 15558 15559 if (disabledPs == null) { 15560 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15561 return false; 15562 } else if (DEBUG_REMOVE) { 15563 Slog.d(TAG, "Deleting system pkg from data partition"); 15564 } 15565 15566 if (DEBUG_REMOVE) { 15567 if (applyUserRestrictions) { 15568 Slog.d(TAG, "Remembering install states:"); 15569 for (int userId : allUserHandles) { 15570 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15571 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15572 } 15573 } 15574 } 15575 15576 // Delete the updated package 15577 outInfo.isRemovedPackageSystemUpdate = true; 15578 if (outInfo.removedChildPackages != null) { 15579 final int childCount = (deletedPs.childPackageNames != null) 15580 ? deletedPs.childPackageNames.size() : 0; 15581 for (int i = 0; i < childCount; i++) { 15582 String childPackageName = deletedPs.childPackageNames.get(i); 15583 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15584 .contains(childPackageName)) { 15585 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15586 childPackageName); 15587 if (childInfo != null) { 15588 childInfo.isRemovedPackageSystemUpdate = true; 15589 } 15590 } 15591 } 15592 } 15593 15594 if (disabledPs.versionCode < deletedPs.versionCode) { 15595 // Delete data for downgrades 15596 flags &= ~PackageManager.DELETE_KEEP_DATA; 15597 } else { 15598 // Preserve data by setting flag 15599 flags |= PackageManager.DELETE_KEEP_DATA; 15600 } 15601 15602 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15603 outInfo, writeSettings, disabledPs.pkg); 15604 if (!ret) { 15605 return false; 15606 } 15607 15608 // writer 15609 synchronized (mPackages) { 15610 // Reinstate the old system package 15611 enableSystemPackageLPw(disabledPs.pkg); 15612 // Remove any native libraries from the upgraded package. 15613 removeNativeBinariesLI(deletedPs); 15614 } 15615 15616 // Install the system package 15617 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15618 int parseFlags = mDefParseFlags 15619 | PackageParser.PARSE_MUST_BE_APK 15620 | PackageParser.PARSE_IS_SYSTEM 15621 | PackageParser.PARSE_IS_SYSTEM_DIR; 15622 if (locationIsPrivileged(disabledPs.codePath)) { 15623 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15624 } 15625 15626 final PackageParser.Package newPkg; 15627 try { 15628 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15629 } catch (PackageManagerException e) { 15630 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15631 + e.getMessage()); 15632 return false; 15633 } 15634 15635 prepareAppDataAfterInstallLIF(newPkg); 15636 15637 // writer 15638 synchronized (mPackages) { 15639 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15640 15641 // Propagate the permissions state as we do not want to drop on the floor 15642 // runtime permissions. The update permissions method below will take 15643 // care of removing obsolete permissions and grant install permissions. 15644 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15645 updatePermissionsLPw(newPkg.packageName, newPkg, 15646 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15647 15648 if (applyUserRestrictions) { 15649 if (DEBUG_REMOVE) { 15650 Slog.d(TAG, "Propagating install state across reinstall"); 15651 } 15652 for (int userId : allUserHandles) { 15653 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15654 if (DEBUG_REMOVE) { 15655 Slog.d(TAG, " user " + userId + " => " + installed); 15656 } 15657 ps.setInstalled(installed, userId); 15658 15659 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15660 } 15661 // Regardless of writeSettings we need to ensure that this restriction 15662 // state propagation is persisted 15663 mSettings.writeAllUsersPackageRestrictionsLPr(); 15664 } 15665 // can downgrade to reader here 15666 if (writeSettings) { 15667 mSettings.writeLPr(); 15668 } 15669 } 15670 return true; 15671 } 15672 15673 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15674 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15675 PackageRemovedInfo outInfo, boolean writeSettings, 15676 PackageParser.Package replacingPackage) { 15677 synchronized (mPackages) { 15678 if (outInfo != null) { 15679 outInfo.uid = ps.appId; 15680 } 15681 15682 if (outInfo != null && outInfo.removedChildPackages != null) { 15683 final int childCount = (ps.childPackageNames != null) 15684 ? ps.childPackageNames.size() : 0; 15685 for (int i = 0; i < childCount; i++) { 15686 String childPackageName = ps.childPackageNames.get(i); 15687 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15688 if (childPs == null) { 15689 return false; 15690 } 15691 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15692 childPackageName); 15693 if (childInfo != null) { 15694 childInfo.uid = childPs.appId; 15695 } 15696 } 15697 } 15698 } 15699 15700 // Delete package data from internal structures and also remove data if flag is set 15701 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15702 15703 // Delete the child packages data 15704 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15705 for (int i = 0; i < childCount; i++) { 15706 PackageSetting childPs; 15707 synchronized (mPackages) { 15708 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15709 } 15710 if (childPs != null) { 15711 PackageRemovedInfo childOutInfo = (outInfo != null 15712 && outInfo.removedChildPackages != null) 15713 ? outInfo.removedChildPackages.get(childPs.name) : null; 15714 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15715 && (replacingPackage != null 15716 && !replacingPackage.hasChildPackage(childPs.name)) 15717 ? flags & ~DELETE_KEEP_DATA : flags; 15718 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15719 deleteFlags, writeSettings); 15720 } 15721 } 15722 15723 // Delete application code and resources only for parent packages 15724 if (ps.parentPackageName == null) { 15725 if (deleteCodeAndResources && (outInfo != null)) { 15726 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15727 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15728 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15729 } 15730 } 15731 15732 return true; 15733 } 15734 15735 @Override 15736 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15737 int userId) { 15738 mContext.enforceCallingOrSelfPermission( 15739 android.Manifest.permission.DELETE_PACKAGES, null); 15740 synchronized (mPackages) { 15741 PackageSetting ps = mSettings.mPackages.get(packageName); 15742 if (ps == null) { 15743 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15744 return false; 15745 } 15746 if (!ps.getInstalled(userId)) { 15747 // Can't block uninstall for an app that is not installed or enabled. 15748 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15749 return false; 15750 } 15751 ps.setBlockUninstall(blockUninstall, userId); 15752 mSettings.writePackageRestrictionsLPr(userId); 15753 } 15754 return true; 15755 } 15756 15757 @Override 15758 public boolean getBlockUninstallForUser(String packageName, int userId) { 15759 synchronized (mPackages) { 15760 PackageSetting ps = mSettings.mPackages.get(packageName); 15761 if (ps == null) { 15762 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15763 return false; 15764 } 15765 return ps.getBlockUninstall(userId); 15766 } 15767 } 15768 15769 @Override 15770 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15771 int callingUid = Binder.getCallingUid(); 15772 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15773 throw new SecurityException( 15774 "setRequiredForSystemUser can only be run by the system or root"); 15775 } 15776 synchronized (mPackages) { 15777 PackageSetting ps = mSettings.mPackages.get(packageName); 15778 if (ps == null) { 15779 Log.w(TAG, "Package doesn't exist: " + packageName); 15780 return false; 15781 } 15782 if (systemUserApp) { 15783 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15784 } else { 15785 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15786 } 15787 mSettings.writeLPr(); 15788 } 15789 return true; 15790 } 15791 15792 /* 15793 * This method handles package deletion in general 15794 */ 15795 private boolean deletePackageLIF(String packageName, UserHandle user, 15796 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15797 PackageRemovedInfo outInfo, boolean writeSettings, 15798 PackageParser.Package replacingPackage) { 15799 if (packageName == null) { 15800 Slog.w(TAG, "Attempt to delete null packageName."); 15801 return false; 15802 } 15803 15804 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15805 15806 PackageSetting ps; 15807 15808 synchronized (mPackages) { 15809 ps = mSettings.mPackages.get(packageName); 15810 if (ps == null) { 15811 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15812 return false; 15813 } 15814 15815 if (ps.parentPackageName != null && (!isSystemApp(ps) 15816 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15817 if (DEBUG_REMOVE) { 15818 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15819 + ((user == null) ? UserHandle.USER_ALL : user)); 15820 } 15821 final int removedUserId = (user != null) ? user.getIdentifier() 15822 : UserHandle.USER_ALL; 15823 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15824 return false; 15825 } 15826 markPackageUninstalledForUserLPw(ps, user); 15827 scheduleWritePackageRestrictionsLocked(user); 15828 return true; 15829 } 15830 } 15831 15832 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15833 && user.getIdentifier() != UserHandle.USER_ALL)) { 15834 // The caller is asking that the package only be deleted for a single 15835 // user. To do this, we just mark its uninstalled state and delete 15836 // its data. If this is a system app, we only allow this to happen if 15837 // they have set the special DELETE_SYSTEM_APP which requests different 15838 // semantics than normal for uninstalling system apps. 15839 markPackageUninstalledForUserLPw(ps, user); 15840 15841 if (!isSystemApp(ps)) { 15842 // Do not uninstall the APK if an app should be cached 15843 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15844 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15845 // Other user still have this package installed, so all 15846 // we need to do is clear this user's data and save that 15847 // it is uninstalled. 15848 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15849 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15850 return false; 15851 } 15852 scheduleWritePackageRestrictionsLocked(user); 15853 return true; 15854 } else { 15855 // We need to set it back to 'installed' so the uninstall 15856 // broadcasts will be sent correctly. 15857 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15858 ps.setInstalled(true, user.getIdentifier()); 15859 } 15860 } else { 15861 // This is a system app, so we assume that the 15862 // other users still have this package installed, so all 15863 // we need to do is clear this user's data and save that 15864 // it is uninstalled. 15865 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15866 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15867 return false; 15868 } 15869 scheduleWritePackageRestrictionsLocked(user); 15870 return true; 15871 } 15872 } 15873 15874 // If we are deleting a composite package for all users, keep track 15875 // of result for each child. 15876 if (ps.childPackageNames != null && outInfo != null) { 15877 synchronized (mPackages) { 15878 final int childCount = ps.childPackageNames.size(); 15879 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15880 for (int i = 0; i < childCount; i++) { 15881 String childPackageName = ps.childPackageNames.get(i); 15882 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15883 childInfo.removedPackage = childPackageName; 15884 outInfo.removedChildPackages.put(childPackageName, childInfo); 15885 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15886 if (childPs != null) { 15887 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15888 } 15889 } 15890 } 15891 } 15892 15893 boolean ret = false; 15894 if (isSystemApp(ps)) { 15895 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15896 // When an updated system application is deleted we delete the existing resources 15897 // as well and fall back to existing code in system partition 15898 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15899 } else { 15900 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15901 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15902 outInfo, writeSettings, replacingPackage); 15903 } 15904 15905 // Take a note whether we deleted the package for all users 15906 if (outInfo != null) { 15907 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15908 if (outInfo.removedChildPackages != null) { 15909 synchronized (mPackages) { 15910 final int childCount = outInfo.removedChildPackages.size(); 15911 for (int i = 0; i < childCount; i++) { 15912 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15913 if (childInfo != null) { 15914 childInfo.removedForAllUsers = mPackages.get( 15915 childInfo.removedPackage) == null; 15916 } 15917 } 15918 } 15919 } 15920 // If we uninstalled an update to a system app there may be some 15921 // child packages that appeared as they are declared in the system 15922 // app but were not declared in the update. 15923 if (isSystemApp(ps)) { 15924 synchronized (mPackages) { 15925 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15926 final int childCount = (updatedPs.childPackageNames != null) 15927 ? updatedPs.childPackageNames.size() : 0; 15928 for (int i = 0; i < childCount; i++) { 15929 String childPackageName = updatedPs.childPackageNames.get(i); 15930 if (outInfo.removedChildPackages == null 15931 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15932 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15933 if (childPs == null) { 15934 continue; 15935 } 15936 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15937 installRes.name = childPackageName; 15938 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15939 installRes.pkg = mPackages.get(childPackageName); 15940 installRes.uid = childPs.pkg.applicationInfo.uid; 15941 if (outInfo.appearedChildPackages == null) { 15942 outInfo.appearedChildPackages = new ArrayMap<>(); 15943 } 15944 outInfo.appearedChildPackages.put(childPackageName, installRes); 15945 } 15946 } 15947 } 15948 } 15949 } 15950 15951 return ret; 15952 } 15953 15954 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15955 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15956 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15957 for (int nextUserId : userIds) { 15958 if (DEBUG_REMOVE) { 15959 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15960 } 15961 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15962 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15963 false /*hidden*/, false /*suspended*/, null, null, null, 15964 false /*blockUninstall*/, 15965 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15966 } 15967 } 15968 15969 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15970 PackageRemovedInfo outInfo) { 15971 final PackageParser.Package pkg; 15972 synchronized (mPackages) { 15973 pkg = mPackages.get(ps.name); 15974 } 15975 15976 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15977 : new int[] {userId}; 15978 for (int nextUserId : userIds) { 15979 if (DEBUG_REMOVE) { 15980 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15981 + nextUserId); 15982 } 15983 15984 destroyAppDataLIF(pkg, userId, 15985 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15986 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15987 schedulePackageCleaning(ps.name, nextUserId, false); 15988 synchronized (mPackages) { 15989 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15990 scheduleWritePackageRestrictionsLocked(nextUserId); 15991 } 15992 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15993 } 15994 } 15995 15996 if (outInfo != null) { 15997 outInfo.removedPackage = ps.name; 15998 outInfo.removedAppId = ps.appId; 15999 outInfo.removedUsers = userIds; 16000 } 16001 16002 return true; 16003 } 16004 16005 private final class ClearStorageConnection implements ServiceConnection { 16006 IMediaContainerService mContainerService; 16007 16008 @Override 16009 public void onServiceConnected(ComponentName name, IBinder service) { 16010 synchronized (this) { 16011 mContainerService = IMediaContainerService.Stub.asInterface(service); 16012 notifyAll(); 16013 } 16014 } 16015 16016 @Override 16017 public void onServiceDisconnected(ComponentName name) { 16018 } 16019 } 16020 16021 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16022 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16023 16024 final boolean mounted; 16025 if (Environment.isExternalStorageEmulated()) { 16026 mounted = true; 16027 } else { 16028 final String status = Environment.getExternalStorageState(); 16029 16030 mounted = status.equals(Environment.MEDIA_MOUNTED) 16031 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16032 } 16033 16034 if (!mounted) { 16035 return; 16036 } 16037 16038 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16039 int[] users; 16040 if (userId == UserHandle.USER_ALL) { 16041 users = sUserManager.getUserIds(); 16042 } else { 16043 users = new int[] { userId }; 16044 } 16045 final ClearStorageConnection conn = new ClearStorageConnection(); 16046 if (mContext.bindServiceAsUser( 16047 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16048 try { 16049 for (int curUser : users) { 16050 long timeout = SystemClock.uptimeMillis() + 5000; 16051 synchronized (conn) { 16052 long now = SystemClock.uptimeMillis(); 16053 while (conn.mContainerService == null && now < timeout) { 16054 try { 16055 conn.wait(timeout - now); 16056 } catch (InterruptedException e) { 16057 } 16058 } 16059 } 16060 if (conn.mContainerService == null) { 16061 return; 16062 } 16063 16064 final UserEnvironment userEnv = new UserEnvironment(curUser); 16065 clearDirectory(conn.mContainerService, 16066 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16067 if (allData) { 16068 clearDirectory(conn.mContainerService, 16069 userEnv.buildExternalStorageAppDataDirs(packageName)); 16070 clearDirectory(conn.mContainerService, 16071 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16072 } 16073 } 16074 } finally { 16075 mContext.unbindService(conn); 16076 } 16077 } 16078 } 16079 16080 @Override 16081 public void clearApplicationProfileData(String packageName) { 16082 enforceSystemOrRoot("Only the system can clear all profile data"); 16083 16084 final PackageParser.Package pkg; 16085 synchronized (mPackages) { 16086 pkg = mPackages.get(packageName); 16087 } 16088 16089 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16090 synchronized (mInstallLock) { 16091 clearAppProfilesLIF(pkg); 16092 } 16093 } 16094 } 16095 16096 @Override 16097 public void clearApplicationUserData(final String packageName, 16098 final IPackageDataObserver observer, final int userId) { 16099 mContext.enforceCallingOrSelfPermission( 16100 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16101 16102 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16103 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16104 16105 final DevicePolicyManagerInternal dpmi = LocalServices 16106 .getService(DevicePolicyManagerInternal.class); 16107 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16108 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16109 } 16110 // Queue up an async operation since the package deletion may take a little while. 16111 mHandler.post(new Runnable() { 16112 public void run() { 16113 mHandler.removeCallbacks(this); 16114 final boolean succeeded; 16115 try (PackageFreezer freezer = freezePackage(packageName, 16116 "clearApplicationUserData")) { 16117 synchronized (mInstallLock) { 16118 succeeded = clearApplicationUserDataLIF(packageName, userId); 16119 } 16120 clearExternalStorageDataSync(packageName, userId, true); 16121 } 16122 if (succeeded) { 16123 // invoke DeviceStorageMonitor's update method to clear any notifications 16124 DeviceStorageMonitorInternal dsm = LocalServices 16125 .getService(DeviceStorageMonitorInternal.class); 16126 if (dsm != null) { 16127 dsm.checkMemory(); 16128 } 16129 } 16130 if(observer != null) { 16131 try { 16132 observer.onRemoveCompleted(packageName, succeeded); 16133 } catch (RemoteException e) { 16134 Log.i(TAG, "Observer no longer exists."); 16135 } 16136 } //end if observer 16137 } //end run 16138 }); 16139 } 16140 16141 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16142 if (packageName == null) { 16143 Slog.w(TAG, "Attempt to delete null packageName."); 16144 return false; 16145 } 16146 16147 // Try finding details about the requested package 16148 PackageParser.Package pkg; 16149 synchronized (mPackages) { 16150 pkg = mPackages.get(packageName); 16151 if (pkg == null) { 16152 final PackageSetting ps = mSettings.mPackages.get(packageName); 16153 if (ps != null) { 16154 pkg = ps.pkg; 16155 } 16156 } 16157 16158 if (pkg == null) { 16159 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16160 return false; 16161 } 16162 16163 PackageSetting ps = (PackageSetting) pkg.mExtras; 16164 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16165 } 16166 16167 clearAppDataLIF(pkg, userId, 16168 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16169 16170 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16171 removeKeystoreDataIfNeeded(userId, appId); 16172 16173 final UserManager um = mContext.getSystemService(UserManager.class); 16174 final int flags; 16175 if (um.isUserUnlockingOrUnlocked(userId)) { 16176 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16177 } else if (um.isUserRunning(userId)) { 16178 flags = StorageManager.FLAG_STORAGE_DE; 16179 } else { 16180 flags = 0; 16181 } 16182 prepareAppDataContentsLIF(pkg, userId, flags); 16183 16184 return true; 16185 } 16186 16187 /** 16188 * Reverts user permission state changes (permissions and flags) in 16189 * all packages for a given user. 16190 * 16191 * @param userId The device user for which to do a reset. 16192 */ 16193 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16194 final int packageCount = mPackages.size(); 16195 for (int i = 0; i < packageCount; i++) { 16196 PackageParser.Package pkg = mPackages.valueAt(i); 16197 PackageSetting ps = (PackageSetting) pkg.mExtras; 16198 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16199 } 16200 } 16201 16202 private void resetNetworkPolicies(int userId) { 16203 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16204 } 16205 16206 /** 16207 * Reverts user permission state changes (permissions and flags). 16208 * 16209 * @param ps The package for which to reset. 16210 * @param userId The device user for which to do a reset. 16211 */ 16212 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16213 final PackageSetting ps, final int userId) { 16214 if (ps.pkg == null) { 16215 return; 16216 } 16217 16218 // These are flags that can change base on user actions. 16219 final int userSettableMask = FLAG_PERMISSION_USER_SET 16220 | FLAG_PERMISSION_USER_FIXED 16221 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16222 | FLAG_PERMISSION_REVIEW_REQUIRED; 16223 16224 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16225 | FLAG_PERMISSION_POLICY_FIXED; 16226 16227 boolean writeInstallPermissions = false; 16228 boolean writeRuntimePermissions = false; 16229 16230 final int permissionCount = ps.pkg.requestedPermissions.size(); 16231 for (int i = 0; i < permissionCount; i++) { 16232 String permission = ps.pkg.requestedPermissions.get(i); 16233 16234 BasePermission bp = mSettings.mPermissions.get(permission); 16235 if (bp == null) { 16236 continue; 16237 } 16238 16239 // If shared user we just reset the state to which only this app contributed. 16240 if (ps.sharedUser != null) { 16241 boolean used = false; 16242 final int packageCount = ps.sharedUser.packages.size(); 16243 for (int j = 0; j < packageCount; j++) { 16244 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16245 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16246 && pkg.pkg.requestedPermissions.contains(permission)) { 16247 used = true; 16248 break; 16249 } 16250 } 16251 if (used) { 16252 continue; 16253 } 16254 } 16255 16256 PermissionsState permissionsState = ps.getPermissionsState(); 16257 16258 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16259 16260 // Always clear the user settable flags. 16261 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16262 bp.name) != null; 16263 // If permission review is enabled and this is a legacy app, mark the 16264 // permission as requiring a review as this is the initial state. 16265 int flags = 0; 16266 if (Build.PERMISSIONS_REVIEW_REQUIRED 16267 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16268 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16269 } 16270 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16271 if (hasInstallState) { 16272 writeInstallPermissions = true; 16273 } else { 16274 writeRuntimePermissions = true; 16275 } 16276 } 16277 16278 // Below is only runtime permission handling. 16279 if (!bp.isRuntime()) { 16280 continue; 16281 } 16282 16283 // Never clobber system or policy. 16284 if ((oldFlags & policyOrSystemFlags) != 0) { 16285 continue; 16286 } 16287 16288 // If this permission was granted by default, make sure it is. 16289 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16290 if (permissionsState.grantRuntimePermission(bp, userId) 16291 != PERMISSION_OPERATION_FAILURE) { 16292 writeRuntimePermissions = true; 16293 } 16294 // If permission review is enabled the permissions for a legacy apps 16295 // are represented as constantly granted runtime ones, so don't revoke. 16296 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16297 // Otherwise, reset the permission. 16298 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16299 switch (revokeResult) { 16300 case PERMISSION_OPERATION_SUCCESS: 16301 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16302 writeRuntimePermissions = true; 16303 final int appId = ps.appId; 16304 mHandler.post(new Runnable() { 16305 @Override 16306 public void run() { 16307 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16308 } 16309 }); 16310 } break; 16311 } 16312 } 16313 } 16314 16315 // Synchronously write as we are taking permissions away. 16316 if (writeRuntimePermissions) { 16317 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16318 } 16319 16320 // Synchronously write as we are taking permissions away. 16321 if (writeInstallPermissions) { 16322 mSettings.writeLPr(); 16323 } 16324 } 16325 16326 /** 16327 * Remove entries from the keystore daemon. Will only remove it if the 16328 * {@code appId} is valid. 16329 */ 16330 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16331 if (appId < 0) { 16332 return; 16333 } 16334 16335 final KeyStore keyStore = KeyStore.getInstance(); 16336 if (keyStore != null) { 16337 if (userId == UserHandle.USER_ALL) { 16338 for (final int individual : sUserManager.getUserIds()) { 16339 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16340 } 16341 } else { 16342 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16343 } 16344 } else { 16345 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16346 } 16347 } 16348 16349 @Override 16350 public void deleteApplicationCacheFiles(final String packageName, 16351 final IPackageDataObserver observer) { 16352 final int userId = UserHandle.getCallingUserId(); 16353 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16354 } 16355 16356 @Override 16357 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16358 final IPackageDataObserver observer) { 16359 mContext.enforceCallingOrSelfPermission( 16360 android.Manifest.permission.DELETE_CACHE_FILES, null); 16361 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16362 /* requireFullPermission= */ true, /* checkShell= */ false, 16363 "delete application cache files"); 16364 16365 final PackageParser.Package pkg; 16366 synchronized (mPackages) { 16367 pkg = mPackages.get(packageName); 16368 } 16369 16370 // Queue up an async operation since the package deletion may take a little while. 16371 mHandler.post(new Runnable() { 16372 public void run() { 16373 synchronized (mInstallLock) { 16374 final int flags = StorageManager.FLAG_STORAGE_DE 16375 | StorageManager.FLAG_STORAGE_CE; 16376 // We're only clearing cache files, so we don't care if the 16377 // app is unfrozen and still able to run 16378 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16379 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16380 } 16381 clearExternalStorageDataSync(packageName, userId, false); 16382 if (observer != null) { 16383 try { 16384 observer.onRemoveCompleted(packageName, true); 16385 } catch (RemoteException e) { 16386 Log.i(TAG, "Observer no longer exists."); 16387 } 16388 } 16389 } 16390 }); 16391 } 16392 16393 @Override 16394 public void getPackageSizeInfo(final String packageName, int userHandle, 16395 final IPackageStatsObserver observer) { 16396 mContext.enforceCallingOrSelfPermission( 16397 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16398 if (packageName == null) { 16399 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16400 } 16401 16402 PackageStats stats = new PackageStats(packageName, userHandle); 16403 16404 /* 16405 * Queue up an async operation since the package measurement may take a 16406 * little while. 16407 */ 16408 Message msg = mHandler.obtainMessage(INIT_COPY); 16409 msg.obj = new MeasureParams(stats, observer); 16410 mHandler.sendMessage(msg); 16411 } 16412 16413 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16414 final PackageSetting ps; 16415 synchronized (mPackages) { 16416 ps = mSettings.mPackages.get(packageName); 16417 if (ps == null) { 16418 Slog.w(TAG, "Failed to find settings for " + packageName); 16419 return false; 16420 } 16421 } 16422 try { 16423 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16424 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16425 ps.getCeDataInode(userId), ps.codePathString, stats); 16426 } catch (InstallerException e) { 16427 Slog.w(TAG, String.valueOf(e)); 16428 return false; 16429 } 16430 16431 // For now, ignore code size of packages on system partition 16432 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16433 stats.codeSize = 0; 16434 } 16435 16436 return true; 16437 } 16438 16439 private int getUidTargetSdkVersionLockedLPr(int uid) { 16440 Object obj = mSettings.getUserIdLPr(uid); 16441 if (obj instanceof SharedUserSetting) { 16442 final SharedUserSetting sus = (SharedUserSetting) obj; 16443 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16444 final Iterator<PackageSetting> it = sus.packages.iterator(); 16445 while (it.hasNext()) { 16446 final PackageSetting ps = it.next(); 16447 if (ps.pkg != null) { 16448 int v = ps.pkg.applicationInfo.targetSdkVersion; 16449 if (v < vers) vers = v; 16450 } 16451 } 16452 return vers; 16453 } else if (obj instanceof PackageSetting) { 16454 final PackageSetting ps = (PackageSetting) obj; 16455 if (ps.pkg != null) { 16456 return ps.pkg.applicationInfo.targetSdkVersion; 16457 } 16458 } 16459 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16460 } 16461 16462 @Override 16463 public void addPreferredActivity(IntentFilter filter, int match, 16464 ComponentName[] set, ComponentName activity, int userId) { 16465 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16466 "Adding preferred"); 16467 } 16468 16469 private void addPreferredActivityInternal(IntentFilter filter, int match, 16470 ComponentName[] set, ComponentName activity, boolean always, int userId, 16471 String opname) { 16472 // writer 16473 int callingUid = Binder.getCallingUid(); 16474 enforceCrossUserPermission(callingUid, userId, 16475 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16476 if (filter.countActions() == 0) { 16477 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16478 return; 16479 } 16480 synchronized (mPackages) { 16481 if (mContext.checkCallingOrSelfPermission( 16482 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16483 != PackageManager.PERMISSION_GRANTED) { 16484 if (getUidTargetSdkVersionLockedLPr(callingUid) 16485 < Build.VERSION_CODES.FROYO) { 16486 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16487 + callingUid); 16488 return; 16489 } 16490 mContext.enforceCallingOrSelfPermission( 16491 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16492 } 16493 16494 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16495 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16496 + userId + ":"); 16497 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16498 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16499 scheduleWritePackageRestrictionsLocked(userId); 16500 } 16501 } 16502 16503 @Override 16504 public void replacePreferredActivity(IntentFilter filter, int match, 16505 ComponentName[] set, ComponentName activity, int userId) { 16506 if (filter.countActions() != 1) { 16507 throw new IllegalArgumentException( 16508 "replacePreferredActivity expects filter to have only 1 action."); 16509 } 16510 if (filter.countDataAuthorities() != 0 16511 || filter.countDataPaths() != 0 16512 || filter.countDataSchemes() > 1 16513 || filter.countDataTypes() != 0) { 16514 throw new IllegalArgumentException( 16515 "replacePreferredActivity expects filter to have no data authorities, " + 16516 "paths, or types; and at most one scheme."); 16517 } 16518 16519 final int callingUid = Binder.getCallingUid(); 16520 enforceCrossUserPermission(callingUid, userId, 16521 true /* requireFullPermission */, false /* checkShell */, 16522 "replace preferred activity"); 16523 synchronized (mPackages) { 16524 if (mContext.checkCallingOrSelfPermission( 16525 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16526 != PackageManager.PERMISSION_GRANTED) { 16527 if (getUidTargetSdkVersionLockedLPr(callingUid) 16528 < Build.VERSION_CODES.FROYO) { 16529 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16530 + Binder.getCallingUid()); 16531 return; 16532 } 16533 mContext.enforceCallingOrSelfPermission( 16534 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16535 } 16536 16537 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16538 if (pir != null) { 16539 // Get all of the existing entries that exactly match this filter. 16540 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16541 if (existing != null && existing.size() == 1) { 16542 PreferredActivity cur = existing.get(0); 16543 if (DEBUG_PREFERRED) { 16544 Slog.i(TAG, "Checking replace of preferred:"); 16545 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16546 if (!cur.mPref.mAlways) { 16547 Slog.i(TAG, " -- CUR; not mAlways!"); 16548 } else { 16549 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16550 Slog.i(TAG, " -- CUR: mSet=" 16551 + Arrays.toString(cur.mPref.mSetComponents)); 16552 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16553 Slog.i(TAG, " -- NEW: mMatch=" 16554 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16555 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16556 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16557 } 16558 } 16559 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16560 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16561 && cur.mPref.sameSet(set)) { 16562 // Setting the preferred activity to what it happens to be already 16563 if (DEBUG_PREFERRED) { 16564 Slog.i(TAG, "Replacing with same preferred activity " 16565 + cur.mPref.mShortComponent + " for user " 16566 + userId + ":"); 16567 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16568 } 16569 return; 16570 } 16571 } 16572 16573 if (existing != null) { 16574 if (DEBUG_PREFERRED) { 16575 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16576 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16577 } 16578 for (int i = 0; i < existing.size(); i++) { 16579 PreferredActivity pa = existing.get(i); 16580 if (DEBUG_PREFERRED) { 16581 Slog.i(TAG, "Removing existing preferred activity " 16582 + pa.mPref.mComponent + ":"); 16583 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16584 } 16585 pir.removeFilter(pa); 16586 } 16587 } 16588 } 16589 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16590 "Replacing preferred"); 16591 } 16592 } 16593 16594 @Override 16595 public void clearPackagePreferredActivities(String packageName) { 16596 final int uid = Binder.getCallingUid(); 16597 // writer 16598 synchronized (mPackages) { 16599 PackageParser.Package pkg = mPackages.get(packageName); 16600 if (pkg == null || pkg.applicationInfo.uid != uid) { 16601 if (mContext.checkCallingOrSelfPermission( 16602 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16603 != PackageManager.PERMISSION_GRANTED) { 16604 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16605 < Build.VERSION_CODES.FROYO) { 16606 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16607 + Binder.getCallingUid()); 16608 return; 16609 } 16610 mContext.enforceCallingOrSelfPermission( 16611 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16612 } 16613 } 16614 16615 int user = UserHandle.getCallingUserId(); 16616 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16617 scheduleWritePackageRestrictionsLocked(user); 16618 } 16619 } 16620 } 16621 16622 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16623 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16624 ArrayList<PreferredActivity> removed = null; 16625 boolean changed = false; 16626 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16627 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16628 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16629 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16630 continue; 16631 } 16632 Iterator<PreferredActivity> it = pir.filterIterator(); 16633 while (it.hasNext()) { 16634 PreferredActivity pa = it.next(); 16635 // Mark entry for removal only if it matches the package name 16636 // and the entry is of type "always". 16637 if (packageName == null || 16638 (pa.mPref.mComponent.getPackageName().equals(packageName) 16639 && pa.mPref.mAlways)) { 16640 if (removed == null) { 16641 removed = new ArrayList<PreferredActivity>(); 16642 } 16643 removed.add(pa); 16644 } 16645 } 16646 if (removed != null) { 16647 for (int j=0; j<removed.size(); j++) { 16648 PreferredActivity pa = removed.get(j); 16649 pir.removeFilter(pa); 16650 } 16651 changed = true; 16652 } 16653 } 16654 return changed; 16655 } 16656 16657 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16658 private void clearIntentFilterVerificationsLPw(int userId) { 16659 final int packageCount = mPackages.size(); 16660 for (int i = 0; i < packageCount; i++) { 16661 PackageParser.Package pkg = mPackages.valueAt(i); 16662 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16663 } 16664 } 16665 16666 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16667 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16668 if (userId == UserHandle.USER_ALL) { 16669 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16670 sUserManager.getUserIds())) { 16671 for (int oneUserId : sUserManager.getUserIds()) { 16672 scheduleWritePackageRestrictionsLocked(oneUserId); 16673 } 16674 } 16675 } else { 16676 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16677 scheduleWritePackageRestrictionsLocked(userId); 16678 } 16679 } 16680 } 16681 16682 void clearDefaultBrowserIfNeeded(String packageName) { 16683 for (int oneUserId : sUserManager.getUserIds()) { 16684 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16685 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16686 if (packageName.equals(defaultBrowserPackageName)) { 16687 setDefaultBrowserPackageName(null, oneUserId); 16688 } 16689 } 16690 } 16691 16692 @Override 16693 public void resetApplicationPreferences(int userId) { 16694 mContext.enforceCallingOrSelfPermission( 16695 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16696 final long identity = Binder.clearCallingIdentity(); 16697 // writer 16698 try { 16699 synchronized (mPackages) { 16700 clearPackagePreferredActivitiesLPw(null, userId); 16701 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16702 // TODO: We have to reset the default SMS and Phone. This requires 16703 // significant refactoring to keep all default apps in the package 16704 // manager (cleaner but more work) or have the services provide 16705 // callbacks to the package manager to request a default app reset. 16706 applyFactoryDefaultBrowserLPw(userId); 16707 clearIntentFilterVerificationsLPw(userId); 16708 primeDomainVerificationsLPw(userId); 16709 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16710 scheduleWritePackageRestrictionsLocked(userId); 16711 } 16712 resetNetworkPolicies(userId); 16713 } finally { 16714 Binder.restoreCallingIdentity(identity); 16715 } 16716 } 16717 16718 @Override 16719 public int getPreferredActivities(List<IntentFilter> outFilters, 16720 List<ComponentName> outActivities, String packageName) { 16721 16722 int num = 0; 16723 final int userId = UserHandle.getCallingUserId(); 16724 // reader 16725 synchronized (mPackages) { 16726 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16727 if (pir != null) { 16728 final Iterator<PreferredActivity> it = pir.filterIterator(); 16729 while (it.hasNext()) { 16730 final PreferredActivity pa = it.next(); 16731 if (packageName == null 16732 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16733 && pa.mPref.mAlways)) { 16734 if (outFilters != null) { 16735 outFilters.add(new IntentFilter(pa)); 16736 } 16737 if (outActivities != null) { 16738 outActivities.add(pa.mPref.mComponent); 16739 } 16740 } 16741 } 16742 } 16743 } 16744 16745 return num; 16746 } 16747 16748 @Override 16749 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16750 int userId) { 16751 int callingUid = Binder.getCallingUid(); 16752 if (callingUid != Process.SYSTEM_UID) { 16753 throw new SecurityException( 16754 "addPersistentPreferredActivity can only be run by the system"); 16755 } 16756 if (filter.countActions() == 0) { 16757 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16758 return; 16759 } 16760 synchronized (mPackages) { 16761 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16762 ":"); 16763 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16764 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16765 new PersistentPreferredActivity(filter, activity)); 16766 scheduleWritePackageRestrictionsLocked(userId); 16767 } 16768 } 16769 16770 @Override 16771 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16772 int callingUid = Binder.getCallingUid(); 16773 if (callingUid != Process.SYSTEM_UID) { 16774 throw new SecurityException( 16775 "clearPackagePersistentPreferredActivities can only be run by the system"); 16776 } 16777 ArrayList<PersistentPreferredActivity> removed = null; 16778 boolean changed = false; 16779 synchronized (mPackages) { 16780 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16781 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16782 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16783 .valueAt(i); 16784 if (userId != thisUserId) { 16785 continue; 16786 } 16787 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16788 while (it.hasNext()) { 16789 PersistentPreferredActivity ppa = it.next(); 16790 // Mark entry for removal only if it matches the package name. 16791 if (ppa.mComponent.getPackageName().equals(packageName)) { 16792 if (removed == null) { 16793 removed = new ArrayList<PersistentPreferredActivity>(); 16794 } 16795 removed.add(ppa); 16796 } 16797 } 16798 if (removed != null) { 16799 for (int j=0; j<removed.size(); j++) { 16800 PersistentPreferredActivity ppa = removed.get(j); 16801 ppir.removeFilter(ppa); 16802 } 16803 changed = true; 16804 } 16805 } 16806 16807 if (changed) { 16808 scheduleWritePackageRestrictionsLocked(userId); 16809 } 16810 } 16811 } 16812 16813 /** 16814 * Common machinery for picking apart a restored XML blob and passing 16815 * it to a caller-supplied functor to be applied to the running system. 16816 */ 16817 private void restoreFromXml(XmlPullParser parser, int userId, 16818 String expectedStartTag, BlobXmlRestorer functor) 16819 throws IOException, XmlPullParserException { 16820 int type; 16821 while ((type = parser.next()) != XmlPullParser.START_TAG 16822 && type != XmlPullParser.END_DOCUMENT) { 16823 } 16824 if (type != XmlPullParser.START_TAG) { 16825 // oops didn't find a start tag?! 16826 if (DEBUG_BACKUP) { 16827 Slog.e(TAG, "Didn't find start tag during restore"); 16828 } 16829 return; 16830 } 16831Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16832 // this is supposed to be TAG_PREFERRED_BACKUP 16833 if (!expectedStartTag.equals(parser.getName())) { 16834 if (DEBUG_BACKUP) { 16835 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16836 } 16837 return; 16838 } 16839 16840 // skip interfering stuff, then we're aligned with the backing implementation 16841 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16842Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16843 functor.apply(parser, userId); 16844 } 16845 16846 private interface BlobXmlRestorer { 16847 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16848 } 16849 16850 /** 16851 * Non-Binder method, support for the backup/restore mechanism: write the 16852 * full set of preferred activities in its canonical XML format. Returns the 16853 * XML output as a byte array, or null if there is none. 16854 */ 16855 @Override 16856 public byte[] getPreferredActivityBackup(int userId) { 16857 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16858 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16859 } 16860 16861 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16862 try { 16863 final XmlSerializer serializer = new FastXmlSerializer(); 16864 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16865 serializer.startDocument(null, true); 16866 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16867 16868 synchronized (mPackages) { 16869 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16870 } 16871 16872 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16873 serializer.endDocument(); 16874 serializer.flush(); 16875 } catch (Exception e) { 16876 if (DEBUG_BACKUP) { 16877 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16878 } 16879 return null; 16880 } 16881 16882 return dataStream.toByteArray(); 16883 } 16884 16885 @Override 16886 public void restorePreferredActivities(byte[] backup, int userId) { 16887 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16888 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16889 } 16890 16891 try { 16892 final XmlPullParser parser = Xml.newPullParser(); 16893 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16894 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16895 new BlobXmlRestorer() { 16896 @Override 16897 public void apply(XmlPullParser parser, int userId) 16898 throws XmlPullParserException, IOException { 16899 synchronized (mPackages) { 16900 mSettings.readPreferredActivitiesLPw(parser, userId); 16901 } 16902 } 16903 } ); 16904 } catch (Exception e) { 16905 if (DEBUG_BACKUP) { 16906 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16907 } 16908 } 16909 } 16910 16911 /** 16912 * Non-Binder method, support for the backup/restore mechanism: write the 16913 * default browser (etc) settings in its canonical XML format. Returns the default 16914 * browser XML representation as a byte array, or null if there is none. 16915 */ 16916 @Override 16917 public byte[] getDefaultAppsBackup(int userId) { 16918 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16919 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16920 } 16921 16922 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16923 try { 16924 final XmlSerializer serializer = new FastXmlSerializer(); 16925 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16926 serializer.startDocument(null, true); 16927 serializer.startTag(null, TAG_DEFAULT_APPS); 16928 16929 synchronized (mPackages) { 16930 mSettings.writeDefaultAppsLPr(serializer, userId); 16931 } 16932 16933 serializer.endTag(null, TAG_DEFAULT_APPS); 16934 serializer.endDocument(); 16935 serializer.flush(); 16936 } catch (Exception e) { 16937 if (DEBUG_BACKUP) { 16938 Slog.e(TAG, "Unable to write default apps for backup", e); 16939 } 16940 return null; 16941 } 16942 16943 return dataStream.toByteArray(); 16944 } 16945 16946 @Override 16947 public void restoreDefaultApps(byte[] backup, int userId) { 16948 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16949 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16950 } 16951 16952 try { 16953 final XmlPullParser parser = Xml.newPullParser(); 16954 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16955 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16956 new BlobXmlRestorer() { 16957 @Override 16958 public void apply(XmlPullParser parser, int userId) 16959 throws XmlPullParserException, IOException { 16960 synchronized (mPackages) { 16961 mSettings.readDefaultAppsLPw(parser, userId); 16962 } 16963 } 16964 } ); 16965 } catch (Exception e) { 16966 if (DEBUG_BACKUP) { 16967 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16968 } 16969 } 16970 } 16971 16972 @Override 16973 public byte[] getIntentFilterVerificationBackup(int userId) { 16974 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16975 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16976 } 16977 16978 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16979 try { 16980 final XmlSerializer serializer = new FastXmlSerializer(); 16981 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16982 serializer.startDocument(null, true); 16983 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16984 16985 synchronized (mPackages) { 16986 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16987 } 16988 16989 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16990 serializer.endDocument(); 16991 serializer.flush(); 16992 } catch (Exception e) { 16993 if (DEBUG_BACKUP) { 16994 Slog.e(TAG, "Unable to write default apps for backup", e); 16995 } 16996 return null; 16997 } 16998 16999 return dataStream.toByteArray(); 17000 } 17001 17002 @Override 17003 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17004 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17005 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17006 } 17007 17008 try { 17009 final XmlPullParser parser = Xml.newPullParser(); 17010 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17011 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17012 new BlobXmlRestorer() { 17013 @Override 17014 public void apply(XmlPullParser parser, int userId) 17015 throws XmlPullParserException, IOException { 17016 synchronized (mPackages) { 17017 mSettings.readAllDomainVerificationsLPr(parser, userId); 17018 mSettings.writeLPr(); 17019 } 17020 } 17021 } ); 17022 } catch (Exception e) { 17023 if (DEBUG_BACKUP) { 17024 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17025 } 17026 } 17027 } 17028 17029 @Override 17030 public byte[] getPermissionGrantBackup(int userId) { 17031 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17032 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17033 } 17034 17035 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17036 try { 17037 final XmlSerializer serializer = new FastXmlSerializer(); 17038 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17039 serializer.startDocument(null, true); 17040 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17041 17042 synchronized (mPackages) { 17043 serializeRuntimePermissionGrantsLPr(serializer, userId); 17044 } 17045 17046 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17047 serializer.endDocument(); 17048 serializer.flush(); 17049 } catch (Exception e) { 17050 if (DEBUG_BACKUP) { 17051 Slog.e(TAG, "Unable to write default apps for backup", e); 17052 } 17053 return null; 17054 } 17055 17056 return dataStream.toByteArray(); 17057 } 17058 17059 @Override 17060 public void restorePermissionGrants(byte[] backup, int userId) { 17061 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17062 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17063 } 17064 17065 try { 17066 final XmlPullParser parser = Xml.newPullParser(); 17067 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17068 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17069 new BlobXmlRestorer() { 17070 @Override 17071 public void apply(XmlPullParser parser, int userId) 17072 throws XmlPullParserException, IOException { 17073 synchronized (mPackages) { 17074 processRestoredPermissionGrantsLPr(parser, userId); 17075 } 17076 } 17077 } ); 17078 } catch (Exception e) { 17079 if (DEBUG_BACKUP) { 17080 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17081 } 17082 } 17083 } 17084 17085 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17086 throws IOException { 17087 serializer.startTag(null, TAG_ALL_GRANTS); 17088 17089 final int N = mSettings.mPackages.size(); 17090 for (int i = 0; i < N; i++) { 17091 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17092 boolean pkgGrantsKnown = false; 17093 17094 PermissionsState packagePerms = ps.getPermissionsState(); 17095 17096 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17097 final int grantFlags = state.getFlags(); 17098 // only look at grants that are not system/policy fixed 17099 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17100 final boolean isGranted = state.isGranted(); 17101 // And only back up the user-twiddled state bits 17102 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17103 final String packageName = mSettings.mPackages.keyAt(i); 17104 if (!pkgGrantsKnown) { 17105 serializer.startTag(null, TAG_GRANT); 17106 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17107 pkgGrantsKnown = true; 17108 } 17109 17110 final boolean userSet = 17111 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17112 final boolean userFixed = 17113 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17114 final boolean revoke = 17115 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17116 17117 serializer.startTag(null, TAG_PERMISSION); 17118 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17119 if (isGranted) { 17120 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17121 } 17122 if (userSet) { 17123 serializer.attribute(null, ATTR_USER_SET, "true"); 17124 } 17125 if (userFixed) { 17126 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17127 } 17128 if (revoke) { 17129 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17130 } 17131 serializer.endTag(null, TAG_PERMISSION); 17132 } 17133 } 17134 } 17135 17136 if (pkgGrantsKnown) { 17137 serializer.endTag(null, TAG_GRANT); 17138 } 17139 } 17140 17141 serializer.endTag(null, TAG_ALL_GRANTS); 17142 } 17143 17144 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17145 throws XmlPullParserException, IOException { 17146 String pkgName = null; 17147 int outerDepth = parser.getDepth(); 17148 int type; 17149 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17150 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17151 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17152 continue; 17153 } 17154 17155 final String tagName = parser.getName(); 17156 if (tagName.equals(TAG_GRANT)) { 17157 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17158 if (DEBUG_BACKUP) { 17159 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17160 } 17161 } else if (tagName.equals(TAG_PERMISSION)) { 17162 17163 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17164 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17165 17166 int newFlagSet = 0; 17167 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17168 newFlagSet |= FLAG_PERMISSION_USER_SET; 17169 } 17170 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17171 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17172 } 17173 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17174 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17175 } 17176 if (DEBUG_BACKUP) { 17177 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17178 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17179 } 17180 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17181 if (ps != null) { 17182 // Already installed so we apply the grant immediately 17183 if (DEBUG_BACKUP) { 17184 Slog.v(TAG, " + already installed; applying"); 17185 } 17186 PermissionsState perms = ps.getPermissionsState(); 17187 BasePermission bp = mSettings.mPermissions.get(permName); 17188 if (bp != null) { 17189 if (isGranted) { 17190 perms.grantRuntimePermission(bp, userId); 17191 } 17192 if (newFlagSet != 0) { 17193 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17194 } 17195 } 17196 } else { 17197 // Need to wait for post-restore install to apply the grant 17198 if (DEBUG_BACKUP) { 17199 Slog.v(TAG, " - not yet installed; saving for later"); 17200 } 17201 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17202 isGranted, newFlagSet, userId); 17203 } 17204 } else { 17205 PackageManagerService.reportSettingsProblem(Log.WARN, 17206 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17207 XmlUtils.skipCurrentTag(parser); 17208 } 17209 } 17210 17211 scheduleWriteSettingsLocked(); 17212 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17213 } 17214 17215 @Override 17216 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17217 int sourceUserId, int targetUserId, int flags) { 17218 mContext.enforceCallingOrSelfPermission( 17219 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17220 int callingUid = Binder.getCallingUid(); 17221 enforceOwnerRights(ownerPackage, callingUid); 17222 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17223 if (intentFilter.countActions() == 0) { 17224 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17225 return; 17226 } 17227 synchronized (mPackages) { 17228 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17229 ownerPackage, targetUserId, flags); 17230 CrossProfileIntentResolver resolver = 17231 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17232 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17233 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17234 if (existing != null) { 17235 int size = existing.size(); 17236 for (int i = 0; i < size; i++) { 17237 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17238 return; 17239 } 17240 } 17241 } 17242 resolver.addFilter(newFilter); 17243 scheduleWritePackageRestrictionsLocked(sourceUserId); 17244 } 17245 } 17246 17247 @Override 17248 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17249 mContext.enforceCallingOrSelfPermission( 17250 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17251 int callingUid = Binder.getCallingUid(); 17252 enforceOwnerRights(ownerPackage, callingUid); 17253 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17254 synchronized (mPackages) { 17255 CrossProfileIntentResolver resolver = 17256 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17257 ArraySet<CrossProfileIntentFilter> set = 17258 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17259 for (CrossProfileIntentFilter filter : set) { 17260 if (filter.getOwnerPackage().equals(ownerPackage)) { 17261 resolver.removeFilter(filter); 17262 } 17263 } 17264 scheduleWritePackageRestrictionsLocked(sourceUserId); 17265 } 17266 } 17267 17268 // Enforcing that callingUid is owning pkg on userId 17269 private void enforceOwnerRights(String pkg, int callingUid) { 17270 // The system owns everything. 17271 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17272 return; 17273 } 17274 int callingUserId = UserHandle.getUserId(callingUid); 17275 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17276 if (pi == null) { 17277 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17278 + callingUserId); 17279 } 17280 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17281 throw new SecurityException("Calling uid " + callingUid 17282 + " does not own package " + pkg); 17283 } 17284 } 17285 17286 @Override 17287 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17288 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17289 } 17290 17291 private Intent getHomeIntent() { 17292 Intent intent = new Intent(Intent.ACTION_MAIN); 17293 intent.addCategory(Intent.CATEGORY_HOME); 17294 return intent; 17295 } 17296 17297 private IntentFilter getHomeFilter() { 17298 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17299 filter.addCategory(Intent.CATEGORY_HOME); 17300 filter.addCategory(Intent.CATEGORY_DEFAULT); 17301 return filter; 17302 } 17303 17304 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17305 int userId) { 17306 Intent intent = getHomeIntent(); 17307 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17308 PackageManager.GET_META_DATA, userId); 17309 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17310 true, false, false, userId); 17311 17312 allHomeCandidates.clear(); 17313 if (list != null) { 17314 for (ResolveInfo ri : list) { 17315 allHomeCandidates.add(ri); 17316 } 17317 } 17318 return (preferred == null || preferred.activityInfo == null) 17319 ? null 17320 : new ComponentName(preferred.activityInfo.packageName, 17321 preferred.activityInfo.name); 17322 } 17323 17324 @Override 17325 public void setHomeActivity(ComponentName comp, int userId) { 17326 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17327 getHomeActivitiesAsUser(homeActivities, userId); 17328 17329 boolean found = false; 17330 17331 final int size = homeActivities.size(); 17332 final ComponentName[] set = new ComponentName[size]; 17333 for (int i = 0; i < size; i++) { 17334 final ResolveInfo candidate = homeActivities.get(i); 17335 final ActivityInfo info = candidate.activityInfo; 17336 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17337 set[i] = activityName; 17338 if (!found && activityName.equals(comp)) { 17339 found = true; 17340 } 17341 } 17342 if (!found) { 17343 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17344 + userId); 17345 } 17346 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17347 set, comp, userId); 17348 } 17349 17350 private @Nullable String getSetupWizardPackageName() { 17351 final Intent intent = new Intent(Intent.ACTION_MAIN); 17352 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17353 17354 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17355 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17356 | MATCH_DISABLED_COMPONENTS, 17357 UserHandle.myUserId()); 17358 if (matches.size() == 1) { 17359 return matches.get(0).getComponentInfo().packageName; 17360 } else { 17361 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17362 + ": matches=" + matches); 17363 return null; 17364 } 17365 } 17366 17367 @Override 17368 public void setApplicationEnabledSetting(String appPackageName, 17369 int newState, int flags, int userId, String callingPackage) { 17370 if (!sUserManager.exists(userId)) return; 17371 if (callingPackage == null) { 17372 callingPackage = Integer.toString(Binder.getCallingUid()); 17373 } 17374 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17375 } 17376 17377 @Override 17378 public void setComponentEnabledSetting(ComponentName componentName, 17379 int newState, int flags, int userId) { 17380 if (!sUserManager.exists(userId)) return; 17381 setEnabledSetting(componentName.getPackageName(), 17382 componentName.getClassName(), newState, flags, userId, null); 17383 } 17384 17385 private void setEnabledSetting(final String packageName, String className, int newState, 17386 final int flags, int userId, String callingPackage) { 17387 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17388 || newState == COMPONENT_ENABLED_STATE_ENABLED 17389 || newState == COMPONENT_ENABLED_STATE_DISABLED 17390 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17391 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17392 throw new IllegalArgumentException("Invalid new component state: " 17393 + newState); 17394 } 17395 PackageSetting pkgSetting; 17396 final int uid = Binder.getCallingUid(); 17397 final int permission; 17398 if (uid == Process.SYSTEM_UID) { 17399 permission = PackageManager.PERMISSION_GRANTED; 17400 } else { 17401 permission = mContext.checkCallingOrSelfPermission( 17402 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17403 } 17404 enforceCrossUserPermission(uid, userId, 17405 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17406 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17407 boolean sendNow = false; 17408 boolean isApp = (className == null); 17409 String componentName = isApp ? packageName : className; 17410 int packageUid = -1; 17411 ArrayList<String> components; 17412 17413 // writer 17414 synchronized (mPackages) { 17415 pkgSetting = mSettings.mPackages.get(packageName); 17416 if (pkgSetting == null) { 17417 if (className == null) { 17418 throw new IllegalArgumentException("Unknown package: " + packageName); 17419 } 17420 throw new IllegalArgumentException( 17421 "Unknown component: " + packageName + "/" + className); 17422 } 17423 // Allow root and verify that userId is not being specified by a different user 17424 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17425 throw new SecurityException( 17426 "Permission Denial: attempt to change component state from pid=" 17427 + Binder.getCallingPid() 17428 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17429 } 17430 if (className == null) { 17431 // We're dealing with an application/package level state change 17432 if (pkgSetting.getEnabled(userId) == newState) { 17433 // Nothing to do 17434 return; 17435 } 17436 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17437 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17438 // Don't care about who enables an app. 17439 callingPackage = null; 17440 } 17441 pkgSetting.setEnabled(newState, userId, callingPackage); 17442 // pkgSetting.pkg.mSetEnabled = newState; 17443 } else { 17444 // We're dealing with a component level state change 17445 // First, verify that this is a valid class name. 17446 PackageParser.Package pkg = pkgSetting.pkg; 17447 if (pkg == null || !pkg.hasComponentClassName(className)) { 17448 if (pkg != null && 17449 pkg.applicationInfo.targetSdkVersion >= 17450 Build.VERSION_CODES.JELLY_BEAN) { 17451 throw new IllegalArgumentException("Component class " + className 17452 + " does not exist in " + packageName); 17453 } else { 17454 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17455 + className + " does not exist in " + packageName); 17456 } 17457 } 17458 switch (newState) { 17459 case COMPONENT_ENABLED_STATE_ENABLED: 17460 if (!pkgSetting.enableComponentLPw(className, userId)) { 17461 return; 17462 } 17463 break; 17464 case COMPONENT_ENABLED_STATE_DISABLED: 17465 if (!pkgSetting.disableComponentLPw(className, userId)) { 17466 return; 17467 } 17468 break; 17469 case COMPONENT_ENABLED_STATE_DEFAULT: 17470 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17471 return; 17472 } 17473 break; 17474 default: 17475 Slog.e(TAG, "Invalid new component state: " + newState); 17476 return; 17477 } 17478 } 17479 scheduleWritePackageRestrictionsLocked(userId); 17480 components = mPendingBroadcasts.get(userId, packageName); 17481 final boolean newPackage = components == null; 17482 if (newPackage) { 17483 components = new ArrayList<String>(); 17484 } 17485 if (!components.contains(componentName)) { 17486 components.add(componentName); 17487 } 17488 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17489 sendNow = true; 17490 // Purge entry from pending broadcast list if another one exists already 17491 // since we are sending one right away. 17492 mPendingBroadcasts.remove(userId, packageName); 17493 } else { 17494 if (newPackage) { 17495 mPendingBroadcasts.put(userId, packageName, components); 17496 } 17497 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17498 // Schedule a message 17499 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17500 } 17501 } 17502 } 17503 17504 long callingId = Binder.clearCallingIdentity(); 17505 try { 17506 if (sendNow) { 17507 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17508 sendPackageChangedBroadcast(packageName, 17509 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17510 } 17511 } finally { 17512 Binder.restoreCallingIdentity(callingId); 17513 } 17514 } 17515 17516 @Override 17517 public void flushPackageRestrictionsAsUser(int userId) { 17518 if (!sUserManager.exists(userId)) { 17519 return; 17520 } 17521 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17522 false /* checkShell */, "flushPackageRestrictions"); 17523 synchronized (mPackages) { 17524 mSettings.writePackageRestrictionsLPr(userId); 17525 mDirtyUsers.remove(userId); 17526 if (mDirtyUsers.isEmpty()) { 17527 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17528 } 17529 } 17530 } 17531 17532 private void sendPackageChangedBroadcast(String packageName, 17533 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17534 if (DEBUG_INSTALL) 17535 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17536 + componentNames); 17537 Bundle extras = new Bundle(4); 17538 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17539 String nameList[] = new String[componentNames.size()]; 17540 componentNames.toArray(nameList); 17541 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17542 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17543 extras.putInt(Intent.EXTRA_UID, packageUid); 17544 // If this is not reporting a change of the overall package, then only send it 17545 // to registered receivers. We don't want to launch a swath of apps for every 17546 // little component state change. 17547 final int flags = !componentNames.contains(packageName) 17548 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17549 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17550 new int[] {UserHandle.getUserId(packageUid)}); 17551 } 17552 17553 @Override 17554 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17555 if (!sUserManager.exists(userId)) return; 17556 final int uid = Binder.getCallingUid(); 17557 final int permission = mContext.checkCallingOrSelfPermission( 17558 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17559 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17560 enforceCrossUserPermission(uid, userId, 17561 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17562 // writer 17563 synchronized (mPackages) { 17564 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17565 allowedByPermission, uid, userId)) { 17566 scheduleWritePackageRestrictionsLocked(userId); 17567 } 17568 } 17569 } 17570 17571 @Override 17572 public String getInstallerPackageName(String packageName) { 17573 // reader 17574 synchronized (mPackages) { 17575 return mSettings.getInstallerPackageNameLPr(packageName); 17576 } 17577 } 17578 17579 public boolean isOrphaned(String packageName) { 17580 // reader 17581 synchronized (mPackages) { 17582 return mSettings.isOrphaned(packageName); 17583 } 17584 } 17585 17586 @Override 17587 public int getApplicationEnabledSetting(String packageName, int userId) { 17588 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17589 int uid = Binder.getCallingUid(); 17590 enforceCrossUserPermission(uid, userId, 17591 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17592 // reader 17593 synchronized (mPackages) { 17594 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17595 } 17596 } 17597 17598 @Override 17599 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17600 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17601 int uid = Binder.getCallingUid(); 17602 enforceCrossUserPermission(uid, userId, 17603 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17604 // reader 17605 synchronized (mPackages) { 17606 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17607 } 17608 } 17609 17610 @Override 17611 public void enterSafeMode() { 17612 enforceSystemOrRoot("Only the system can request entering safe mode"); 17613 17614 if (!mSystemReady) { 17615 mSafeMode = true; 17616 } 17617 } 17618 17619 @Override 17620 public void systemReady() { 17621 mSystemReady = true; 17622 17623 // Read the compatibilty setting when the system is ready. 17624 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17625 mContext.getContentResolver(), 17626 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17627 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17628 if (DEBUG_SETTINGS) { 17629 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17630 } 17631 17632 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17633 17634 synchronized (mPackages) { 17635 // Verify that all of the preferred activity components actually 17636 // exist. It is possible for applications to be updated and at 17637 // that point remove a previously declared activity component that 17638 // had been set as a preferred activity. We try to clean this up 17639 // the next time we encounter that preferred activity, but it is 17640 // possible for the user flow to never be able to return to that 17641 // situation so here we do a sanity check to make sure we haven't 17642 // left any junk around. 17643 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17644 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17645 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17646 removed.clear(); 17647 for (PreferredActivity pa : pir.filterSet()) { 17648 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17649 removed.add(pa); 17650 } 17651 } 17652 if (removed.size() > 0) { 17653 for (int r=0; r<removed.size(); r++) { 17654 PreferredActivity pa = removed.get(r); 17655 Slog.w(TAG, "Removing dangling preferred activity: " 17656 + pa.mPref.mComponent); 17657 pir.removeFilter(pa); 17658 } 17659 mSettings.writePackageRestrictionsLPr( 17660 mSettings.mPreferredActivities.keyAt(i)); 17661 } 17662 } 17663 17664 for (int userId : UserManagerService.getInstance().getUserIds()) { 17665 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17666 grantPermissionsUserIds = ArrayUtils.appendInt( 17667 grantPermissionsUserIds, userId); 17668 } 17669 } 17670 } 17671 sUserManager.systemReady(); 17672 17673 // If we upgraded grant all default permissions before kicking off. 17674 for (int userId : grantPermissionsUserIds) { 17675 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17676 } 17677 17678 // Kick off any messages waiting for system ready 17679 if (mPostSystemReadyMessages != null) { 17680 for (Message msg : mPostSystemReadyMessages) { 17681 msg.sendToTarget(); 17682 } 17683 mPostSystemReadyMessages = null; 17684 } 17685 17686 // Watch for external volumes that come and go over time 17687 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17688 storage.registerListener(mStorageListener); 17689 17690 mInstallerService.systemReady(); 17691 mPackageDexOptimizer.systemReady(); 17692 17693 MountServiceInternal mountServiceInternal = LocalServices.getService( 17694 MountServiceInternal.class); 17695 mountServiceInternal.addExternalStoragePolicy( 17696 new MountServiceInternal.ExternalStorageMountPolicy() { 17697 @Override 17698 public int getMountMode(int uid, String packageName) { 17699 if (Process.isIsolated(uid)) { 17700 return Zygote.MOUNT_EXTERNAL_NONE; 17701 } 17702 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17703 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17704 } 17705 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17706 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17707 } 17708 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17709 return Zygote.MOUNT_EXTERNAL_READ; 17710 } 17711 return Zygote.MOUNT_EXTERNAL_WRITE; 17712 } 17713 17714 @Override 17715 public boolean hasExternalStorage(int uid, String packageName) { 17716 return true; 17717 } 17718 }); 17719 17720 // Now that we're mostly running, clean up stale users and apps 17721 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17722 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17723 } 17724 17725 @Override 17726 public boolean isSafeMode() { 17727 return mSafeMode; 17728 } 17729 17730 @Override 17731 public boolean hasSystemUidErrors() { 17732 return mHasSystemUidErrors; 17733 } 17734 17735 static String arrayToString(int[] array) { 17736 StringBuffer buf = new StringBuffer(128); 17737 buf.append('['); 17738 if (array != null) { 17739 for (int i=0; i<array.length; i++) { 17740 if (i > 0) buf.append(", "); 17741 buf.append(array[i]); 17742 } 17743 } 17744 buf.append(']'); 17745 return buf.toString(); 17746 } 17747 17748 static class DumpState { 17749 public static final int DUMP_LIBS = 1 << 0; 17750 public static final int DUMP_FEATURES = 1 << 1; 17751 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17752 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17753 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17754 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17755 public static final int DUMP_PERMISSIONS = 1 << 6; 17756 public static final int DUMP_PACKAGES = 1 << 7; 17757 public static final int DUMP_SHARED_USERS = 1 << 8; 17758 public static final int DUMP_MESSAGES = 1 << 9; 17759 public static final int DUMP_PROVIDERS = 1 << 10; 17760 public static final int DUMP_VERIFIERS = 1 << 11; 17761 public static final int DUMP_PREFERRED = 1 << 12; 17762 public static final int DUMP_PREFERRED_XML = 1 << 13; 17763 public static final int DUMP_KEYSETS = 1 << 14; 17764 public static final int DUMP_VERSION = 1 << 15; 17765 public static final int DUMP_INSTALLS = 1 << 16; 17766 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17767 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17768 public static final int DUMP_FROZEN = 1 << 19; 17769 17770 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17771 17772 private int mTypes; 17773 17774 private int mOptions; 17775 17776 private boolean mTitlePrinted; 17777 17778 private SharedUserSetting mSharedUser; 17779 17780 public boolean isDumping(int type) { 17781 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17782 return true; 17783 } 17784 17785 return (mTypes & type) != 0; 17786 } 17787 17788 public void setDump(int type) { 17789 mTypes |= type; 17790 } 17791 17792 public boolean isOptionEnabled(int option) { 17793 return (mOptions & option) != 0; 17794 } 17795 17796 public void setOptionEnabled(int option) { 17797 mOptions |= option; 17798 } 17799 17800 public boolean onTitlePrinted() { 17801 final boolean printed = mTitlePrinted; 17802 mTitlePrinted = true; 17803 return printed; 17804 } 17805 17806 public boolean getTitlePrinted() { 17807 return mTitlePrinted; 17808 } 17809 17810 public void setTitlePrinted(boolean enabled) { 17811 mTitlePrinted = enabled; 17812 } 17813 17814 public SharedUserSetting getSharedUser() { 17815 return mSharedUser; 17816 } 17817 17818 public void setSharedUser(SharedUserSetting user) { 17819 mSharedUser = user; 17820 } 17821 } 17822 17823 @Override 17824 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17825 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17826 (new PackageManagerShellCommand(this)).exec( 17827 this, in, out, err, args, resultReceiver); 17828 } 17829 17830 @Override 17831 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17832 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17833 != PackageManager.PERMISSION_GRANTED) { 17834 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17835 + Binder.getCallingPid() 17836 + ", uid=" + Binder.getCallingUid() 17837 + " without permission " 17838 + android.Manifest.permission.DUMP); 17839 return; 17840 } 17841 17842 DumpState dumpState = new DumpState(); 17843 boolean fullPreferred = false; 17844 boolean checkin = false; 17845 17846 String packageName = null; 17847 ArraySet<String> permissionNames = null; 17848 17849 int opti = 0; 17850 while (opti < args.length) { 17851 String opt = args[opti]; 17852 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17853 break; 17854 } 17855 opti++; 17856 17857 if ("-a".equals(opt)) { 17858 // Right now we only know how to print all. 17859 } else if ("-h".equals(opt)) { 17860 pw.println("Package manager dump options:"); 17861 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17862 pw.println(" --checkin: dump for a checkin"); 17863 pw.println(" -f: print details of intent filters"); 17864 pw.println(" -h: print this help"); 17865 pw.println(" cmd may be one of:"); 17866 pw.println(" l[ibraries]: list known shared libraries"); 17867 pw.println(" f[eatures]: list device features"); 17868 pw.println(" k[eysets]: print known keysets"); 17869 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17870 pw.println(" perm[issions]: dump permissions"); 17871 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17872 pw.println(" pref[erred]: print preferred package settings"); 17873 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17874 pw.println(" prov[iders]: dump content providers"); 17875 pw.println(" p[ackages]: dump installed packages"); 17876 pw.println(" s[hared-users]: dump shared user IDs"); 17877 pw.println(" m[essages]: print collected runtime messages"); 17878 pw.println(" v[erifiers]: print package verifier info"); 17879 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17880 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17881 pw.println(" version: print database version info"); 17882 pw.println(" write: write current settings now"); 17883 pw.println(" installs: details about install sessions"); 17884 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17885 pw.println(" <package.name>: info about given package"); 17886 return; 17887 } else if ("--checkin".equals(opt)) { 17888 checkin = true; 17889 } else if ("-f".equals(opt)) { 17890 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17891 } else { 17892 pw.println("Unknown argument: " + opt + "; use -h for help"); 17893 } 17894 } 17895 17896 // Is the caller requesting to dump a particular piece of data? 17897 if (opti < args.length) { 17898 String cmd = args[opti]; 17899 opti++; 17900 // Is this a package name? 17901 if ("android".equals(cmd) || cmd.contains(".")) { 17902 packageName = cmd; 17903 // When dumping a single package, we always dump all of its 17904 // filter information since the amount of data will be reasonable. 17905 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17906 } else if ("check-permission".equals(cmd)) { 17907 if (opti >= args.length) { 17908 pw.println("Error: check-permission missing permission argument"); 17909 return; 17910 } 17911 String perm = args[opti]; 17912 opti++; 17913 if (opti >= args.length) { 17914 pw.println("Error: check-permission missing package argument"); 17915 return; 17916 } 17917 String pkg = args[opti]; 17918 opti++; 17919 int user = UserHandle.getUserId(Binder.getCallingUid()); 17920 if (opti < args.length) { 17921 try { 17922 user = Integer.parseInt(args[opti]); 17923 } catch (NumberFormatException e) { 17924 pw.println("Error: check-permission user argument is not a number: " 17925 + args[opti]); 17926 return; 17927 } 17928 } 17929 pw.println(checkPermission(perm, pkg, user)); 17930 return; 17931 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17932 dumpState.setDump(DumpState.DUMP_LIBS); 17933 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17934 dumpState.setDump(DumpState.DUMP_FEATURES); 17935 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17936 if (opti >= args.length) { 17937 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17938 | DumpState.DUMP_SERVICE_RESOLVERS 17939 | DumpState.DUMP_RECEIVER_RESOLVERS 17940 | DumpState.DUMP_CONTENT_RESOLVERS); 17941 } else { 17942 while (opti < args.length) { 17943 String name = args[opti]; 17944 if ("a".equals(name) || "activity".equals(name)) { 17945 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17946 } else if ("s".equals(name) || "service".equals(name)) { 17947 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17948 } else if ("r".equals(name) || "receiver".equals(name)) { 17949 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17950 } else if ("c".equals(name) || "content".equals(name)) { 17951 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17952 } else { 17953 pw.println("Error: unknown resolver table type: " + name); 17954 return; 17955 } 17956 opti++; 17957 } 17958 } 17959 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17960 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17961 } else if ("permission".equals(cmd)) { 17962 if (opti >= args.length) { 17963 pw.println("Error: permission requires permission name"); 17964 return; 17965 } 17966 permissionNames = new ArraySet<>(); 17967 while (opti < args.length) { 17968 permissionNames.add(args[opti]); 17969 opti++; 17970 } 17971 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17972 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17973 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17974 dumpState.setDump(DumpState.DUMP_PREFERRED); 17975 } else if ("preferred-xml".equals(cmd)) { 17976 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17977 if (opti < args.length && "--full".equals(args[opti])) { 17978 fullPreferred = true; 17979 opti++; 17980 } 17981 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17982 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17983 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17984 dumpState.setDump(DumpState.DUMP_PACKAGES); 17985 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17986 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17987 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17988 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17989 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17990 dumpState.setDump(DumpState.DUMP_MESSAGES); 17991 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17992 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17993 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17994 || "intent-filter-verifiers".equals(cmd)) { 17995 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17996 } else if ("version".equals(cmd)) { 17997 dumpState.setDump(DumpState.DUMP_VERSION); 17998 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17999 dumpState.setDump(DumpState.DUMP_KEYSETS); 18000 } else if ("installs".equals(cmd)) { 18001 dumpState.setDump(DumpState.DUMP_INSTALLS); 18002 } else if ("frozen".equals(cmd)) { 18003 dumpState.setDump(DumpState.DUMP_FROZEN); 18004 } else if ("write".equals(cmd)) { 18005 synchronized (mPackages) { 18006 mSettings.writeLPr(); 18007 pw.println("Settings written."); 18008 return; 18009 } 18010 } 18011 } 18012 18013 if (checkin) { 18014 pw.println("vers,1"); 18015 } 18016 18017 // reader 18018 synchronized (mPackages) { 18019 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18020 if (!checkin) { 18021 if (dumpState.onTitlePrinted()) 18022 pw.println(); 18023 pw.println("Database versions:"); 18024 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18025 } 18026 } 18027 18028 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18029 if (!checkin) { 18030 if (dumpState.onTitlePrinted()) 18031 pw.println(); 18032 pw.println("Verifiers:"); 18033 pw.print(" Required: "); 18034 pw.print(mRequiredVerifierPackage); 18035 pw.print(" (uid="); 18036 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18037 UserHandle.USER_SYSTEM)); 18038 pw.println(")"); 18039 } else if (mRequiredVerifierPackage != null) { 18040 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18041 pw.print(","); 18042 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18043 UserHandle.USER_SYSTEM)); 18044 } 18045 } 18046 18047 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18048 packageName == null) { 18049 if (mIntentFilterVerifierComponent != null) { 18050 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18051 if (!checkin) { 18052 if (dumpState.onTitlePrinted()) 18053 pw.println(); 18054 pw.println("Intent Filter Verifier:"); 18055 pw.print(" Using: "); 18056 pw.print(verifierPackageName); 18057 pw.print(" (uid="); 18058 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18059 UserHandle.USER_SYSTEM)); 18060 pw.println(")"); 18061 } else if (verifierPackageName != null) { 18062 pw.print("ifv,"); pw.print(verifierPackageName); 18063 pw.print(","); 18064 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18065 UserHandle.USER_SYSTEM)); 18066 } 18067 } else { 18068 pw.println(); 18069 pw.println("No Intent Filter Verifier available!"); 18070 } 18071 } 18072 18073 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18074 boolean printedHeader = false; 18075 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18076 while (it.hasNext()) { 18077 String name = it.next(); 18078 SharedLibraryEntry ent = mSharedLibraries.get(name); 18079 if (!checkin) { 18080 if (!printedHeader) { 18081 if (dumpState.onTitlePrinted()) 18082 pw.println(); 18083 pw.println("Libraries:"); 18084 printedHeader = true; 18085 } 18086 pw.print(" "); 18087 } else { 18088 pw.print("lib,"); 18089 } 18090 pw.print(name); 18091 if (!checkin) { 18092 pw.print(" -> "); 18093 } 18094 if (ent.path != null) { 18095 if (!checkin) { 18096 pw.print("(jar) "); 18097 pw.print(ent.path); 18098 } else { 18099 pw.print(",jar,"); 18100 pw.print(ent.path); 18101 } 18102 } else { 18103 if (!checkin) { 18104 pw.print("(apk) "); 18105 pw.print(ent.apk); 18106 } else { 18107 pw.print(",apk,"); 18108 pw.print(ent.apk); 18109 } 18110 } 18111 pw.println(); 18112 } 18113 } 18114 18115 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18116 if (dumpState.onTitlePrinted()) 18117 pw.println(); 18118 if (!checkin) { 18119 pw.println("Features:"); 18120 } 18121 18122 for (FeatureInfo feat : mAvailableFeatures.values()) { 18123 if (checkin) { 18124 pw.print("feat,"); 18125 pw.print(feat.name); 18126 pw.print(","); 18127 pw.println(feat.version); 18128 } else { 18129 pw.print(" "); 18130 pw.print(feat.name); 18131 if (feat.version > 0) { 18132 pw.print(" version="); 18133 pw.print(feat.version); 18134 } 18135 pw.println(); 18136 } 18137 } 18138 } 18139 18140 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18141 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18142 : "Activity Resolver Table:", " ", packageName, 18143 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18144 dumpState.setTitlePrinted(true); 18145 } 18146 } 18147 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18148 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18149 : "Receiver Resolver Table:", " ", packageName, 18150 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18151 dumpState.setTitlePrinted(true); 18152 } 18153 } 18154 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18155 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18156 : "Service Resolver Table:", " ", packageName, 18157 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18158 dumpState.setTitlePrinted(true); 18159 } 18160 } 18161 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18162 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18163 : "Provider Resolver Table:", " ", packageName, 18164 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18165 dumpState.setTitlePrinted(true); 18166 } 18167 } 18168 18169 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18170 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18171 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18172 int user = mSettings.mPreferredActivities.keyAt(i); 18173 if (pir.dump(pw, 18174 dumpState.getTitlePrinted() 18175 ? "\nPreferred Activities User " + user + ":" 18176 : "Preferred Activities User " + user + ":", " ", 18177 packageName, true, false)) { 18178 dumpState.setTitlePrinted(true); 18179 } 18180 } 18181 } 18182 18183 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18184 pw.flush(); 18185 FileOutputStream fout = new FileOutputStream(fd); 18186 BufferedOutputStream str = new BufferedOutputStream(fout); 18187 XmlSerializer serializer = new FastXmlSerializer(); 18188 try { 18189 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18190 serializer.startDocument(null, true); 18191 serializer.setFeature( 18192 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18193 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18194 serializer.endDocument(); 18195 serializer.flush(); 18196 } catch (IllegalArgumentException e) { 18197 pw.println("Failed writing: " + e); 18198 } catch (IllegalStateException e) { 18199 pw.println("Failed writing: " + e); 18200 } catch (IOException e) { 18201 pw.println("Failed writing: " + e); 18202 } 18203 } 18204 18205 if (!checkin 18206 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18207 && packageName == null) { 18208 pw.println(); 18209 int count = mSettings.mPackages.size(); 18210 if (count == 0) { 18211 pw.println("No applications!"); 18212 pw.println(); 18213 } else { 18214 final String prefix = " "; 18215 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18216 if (allPackageSettings.size() == 0) { 18217 pw.println("No domain preferred apps!"); 18218 pw.println(); 18219 } else { 18220 pw.println("App verification status:"); 18221 pw.println(); 18222 count = 0; 18223 for (PackageSetting ps : allPackageSettings) { 18224 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18225 if (ivi == null || ivi.getPackageName() == null) continue; 18226 pw.println(prefix + "Package: " + ivi.getPackageName()); 18227 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18228 pw.println(prefix + "Status: " + ivi.getStatusString()); 18229 pw.println(); 18230 count++; 18231 } 18232 if (count == 0) { 18233 pw.println(prefix + "No app verification established."); 18234 pw.println(); 18235 } 18236 for (int userId : sUserManager.getUserIds()) { 18237 pw.println("App linkages for user " + userId + ":"); 18238 pw.println(); 18239 count = 0; 18240 for (PackageSetting ps : allPackageSettings) { 18241 final long status = ps.getDomainVerificationStatusForUser(userId); 18242 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18243 continue; 18244 } 18245 pw.println(prefix + "Package: " + ps.name); 18246 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18247 String statusStr = IntentFilterVerificationInfo. 18248 getStatusStringFromValue(status); 18249 pw.println(prefix + "Status: " + statusStr); 18250 pw.println(); 18251 count++; 18252 } 18253 if (count == 0) { 18254 pw.println(prefix + "No configured app linkages."); 18255 pw.println(); 18256 } 18257 } 18258 } 18259 } 18260 } 18261 18262 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18263 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18264 if (packageName == null && permissionNames == null) { 18265 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18266 if (iperm == 0) { 18267 if (dumpState.onTitlePrinted()) 18268 pw.println(); 18269 pw.println("AppOp Permissions:"); 18270 } 18271 pw.print(" AppOp Permission "); 18272 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18273 pw.println(":"); 18274 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18275 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18276 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18277 } 18278 } 18279 } 18280 } 18281 18282 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18283 boolean printedSomething = false; 18284 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18285 if (packageName != null && !packageName.equals(p.info.packageName)) { 18286 continue; 18287 } 18288 if (!printedSomething) { 18289 if (dumpState.onTitlePrinted()) 18290 pw.println(); 18291 pw.println("Registered ContentProviders:"); 18292 printedSomething = true; 18293 } 18294 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18295 pw.print(" "); pw.println(p.toString()); 18296 } 18297 printedSomething = false; 18298 for (Map.Entry<String, PackageParser.Provider> entry : 18299 mProvidersByAuthority.entrySet()) { 18300 PackageParser.Provider p = entry.getValue(); 18301 if (packageName != null && !packageName.equals(p.info.packageName)) { 18302 continue; 18303 } 18304 if (!printedSomething) { 18305 if (dumpState.onTitlePrinted()) 18306 pw.println(); 18307 pw.println("ContentProvider Authorities:"); 18308 printedSomething = true; 18309 } 18310 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18311 pw.print(" "); pw.println(p.toString()); 18312 if (p.info != null && p.info.applicationInfo != null) { 18313 final String appInfo = p.info.applicationInfo.toString(); 18314 pw.print(" applicationInfo="); pw.println(appInfo); 18315 } 18316 } 18317 } 18318 18319 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18320 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18321 } 18322 18323 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18324 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18325 } 18326 18327 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18328 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18329 } 18330 18331 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18332 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18333 } 18334 18335 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18336 // XXX should handle packageName != null by dumping only install data that 18337 // the given package is involved with. 18338 if (dumpState.onTitlePrinted()) pw.println(); 18339 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18340 } 18341 18342 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18343 // XXX should handle packageName != null by dumping only install data that 18344 // the given package is involved with. 18345 if (dumpState.onTitlePrinted()) pw.println(); 18346 18347 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18348 ipw.println(); 18349 ipw.println("Frozen packages:"); 18350 ipw.increaseIndent(); 18351 if (mFrozenPackages.size() == 0) { 18352 ipw.println("(none)"); 18353 } else { 18354 for (int i = 0; i < mFrozenPackages.size(); i++) { 18355 ipw.println(mFrozenPackages.valueAt(i)); 18356 } 18357 } 18358 ipw.decreaseIndent(); 18359 } 18360 18361 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18362 if (dumpState.onTitlePrinted()) pw.println(); 18363 mSettings.dumpReadMessagesLPr(pw, dumpState); 18364 18365 pw.println(); 18366 pw.println("Package warning messages:"); 18367 BufferedReader in = null; 18368 String line = null; 18369 try { 18370 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18371 while ((line = in.readLine()) != null) { 18372 if (line.contains("ignored: updated version")) continue; 18373 pw.println(line); 18374 } 18375 } catch (IOException ignored) { 18376 } finally { 18377 IoUtils.closeQuietly(in); 18378 } 18379 } 18380 18381 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18382 BufferedReader in = null; 18383 String line = null; 18384 try { 18385 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18386 while ((line = in.readLine()) != null) { 18387 if (line.contains("ignored: updated version")) continue; 18388 pw.print("msg,"); 18389 pw.println(line); 18390 } 18391 } catch (IOException ignored) { 18392 } finally { 18393 IoUtils.closeQuietly(in); 18394 } 18395 } 18396 } 18397 } 18398 18399 private String dumpDomainString(String packageName) { 18400 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18401 .getList(); 18402 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18403 18404 ArraySet<String> result = new ArraySet<>(); 18405 if (iviList.size() > 0) { 18406 for (IntentFilterVerificationInfo ivi : iviList) { 18407 for (String host : ivi.getDomains()) { 18408 result.add(host); 18409 } 18410 } 18411 } 18412 if (filters != null && filters.size() > 0) { 18413 for (IntentFilter filter : filters) { 18414 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18415 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18416 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18417 result.addAll(filter.getHostsList()); 18418 } 18419 } 18420 } 18421 18422 StringBuilder sb = new StringBuilder(result.size() * 16); 18423 for (String domain : result) { 18424 if (sb.length() > 0) sb.append(" "); 18425 sb.append(domain); 18426 } 18427 return sb.toString(); 18428 } 18429 18430 // ------- apps on sdcard specific code ------- 18431 static final boolean DEBUG_SD_INSTALL = false; 18432 18433 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18434 18435 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18436 18437 private boolean mMediaMounted = false; 18438 18439 static String getEncryptKey() { 18440 try { 18441 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18442 SD_ENCRYPTION_KEYSTORE_NAME); 18443 if (sdEncKey == null) { 18444 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18445 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18446 if (sdEncKey == null) { 18447 Slog.e(TAG, "Failed to create encryption keys"); 18448 return null; 18449 } 18450 } 18451 return sdEncKey; 18452 } catch (NoSuchAlgorithmException nsae) { 18453 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18454 return null; 18455 } catch (IOException ioe) { 18456 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18457 return null; 18458 } 18459 } 18460 18461 /* 18462 * Update media status on PackageManager. 18463 */ 18464 @Override 18465 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18466 int callingUid = Binder.getCallingUid(); 18467 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18468 throw new SecurityException("Media status can only be updated by the system"); 18469 } 18470 // reader; this apparently protects mMediaMounted, but should probably 18471 // be a different lock in that case. 18472 synchronized (mPackages) { 18473 Log.i(TAG, "Updating external media status from " 18474 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18475 + (mediaStatus ? "mounted" : "unmounted")); 18476 if (DEBUG_SD_INSTALL) 18477 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18478 + ", mMediaMounted=" + mMediaMounted); 18479 if (mediaStatus == mMediaMounted) { 18480 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18481 : 0, -1); 18482 mHandler.sendMessage(msg); 18483 return; 18484 } 18485 mMediaMounted = mediaStatus; 18486 } 18487 // Queue up an async operation since the package installation may take a 18488 // little while. 18489 mHandler.post(new Runnable() { 18490 public void run() { 18491 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18492 } 18493 }); 18494 } 18495 18496 /** 18497 * Called by MountService when the initial ASECs to scan are available. 18498 * Should block until all the ASEC containers are finished being scanned. 18499 */ 18500 public void scanAvailableAsecs() { 18501 updateExternalMediaStatusInner(true, false, false); 18502 } 18503 18504 /* 18505 * Collect information of applications on external media, map them against 18506 * existing containers and update information based on current mount status. 18507 * Please note that we always have to report status if reportStatus has been 18508 * set to true especially when unloading packages. 18509 */ 18510 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18511 boolean externalStorage) { 18512 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18513 int[] uidArr = EmptyArray.INT; 18514 18515 final String[] list = PackageHelper.getSecureContainerList(); 18516 if (ArrayUtils.isEmpty(list)) { 18517 Log.i(TAG, "No secure containers found"); 18518 } else { 18519 // Process list of secure containers and categorize them 18520 // as active or stale based on their package internal state. 18521 18522 // reader 18523 synchronized (mPackages) { 18524 for (String cid : list) { 18525 // Leave stages untouched for now; installer service owns them 18526 if (PackageInstallerService.isStageName(cid)) continue; 18527 18528 if (DEBUG_SD_INSTALL) 18529 Log.i(TAG, "Processing container " + cid); 18530 String pkgName = getAsecPackageName(cid); 18531 if (pkgName == null) { 18532 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18533 continue; 18534 } 18535 if (DEBUG_SD_INSTALL) 18536 Log.i(TAG, "Looking for pkg : " + pkgName); 18537 18538 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18539 if (ps == null) { 18540 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18541 continue; 18542 } 18543 18544 /* 18545 * Skip packages that are not external if we're unmounting 18546 * external storage. 18547 */ 18548 if (externalStorage && !isMounted && !isExternal(ps)) { 18549 continue; 18550 } 18551 18552 final AsecInstallArgs args = new AsecInstallArgs(cid, 18553 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18554 // The package status is changed only if the code path 18555 // matches between settings and the container id. 18556 if (ps.codePathString != null 18557 && ps.codePathString.startsWith(args.getCodePath())) { 18558 if (DEBUG_SD_INSTALL) { 18559 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18560 + " at code path: " + ps.codePathString); 18561 } 18562 18563 // We do have a valid package installed on sdcard 18564 processCids.put(args, ps.codePathString); 18565 final int uid = ps.appId; 18566 if (uid != -1) { 18567 uidArr = ArrayUtils.appendInt(uidArr, uid); 18568 } 18569 } else { 18570 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18571 + ps.codePathString); 18572 } 18573 } 18574 } 18575 18576 Arrays.sort(uidArr); 18577 } 18578 18579 // Process packages with valid entries. 18580 if (isMounted) { 18581 if (DEBUG_SD_INSTALL) 18582 Log.i(TAG, "Loading packages"); 18583 loadMediaPackages(processCids, uidArr, externalStorage); 18584 startCleaningPackages(); 18585 mInstallerService.onSecureContainersAvailable(); 18586 } else { 18587 if (DEBUG_SD_INSTALL) 18588 Log.i(TAG, "Unloading packages"); 18589 unloadMediaPackages(processCids, uidArr, reportStatus); 18590 } 18591 } 18592 18593 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18594 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18595 final int size = infos.size(); 18596 final String[] packageNames = new String[size]; 18597 final int[] packageUids = new int[size]; 18598 for (int i = 0; i < size; i++) { 18599 final ApplicationInfo info = infos.get(i); 18600 packageNames[i] = info.packageName; 18601 packageUids[i] = info.uid; 18602 } 18603 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18604 finishedReceiver); 18605 } 18606 18607 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18608 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18609 sendResourcesChangedBroadcast(mediaStatus, replacing, 18610 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18611 } 18612 18613 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18614 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18615 int size = pkgList.length; 18616 if (size > 0) { 18617 // Send broadcasts here 18618 Bundle extras = new Bundle(); 18619 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18620 if (uidArr != null) { 18621 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18622 } 18623 if (replacing) { 18624 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18625 } 18626 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18627 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18628 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18629 } 18630 } 18631 18632 /* 18633 * Look at potentially valid container ids from processCids If package 18634 * information doesn't match the one on record or package scanning fails, 18635 * the cid is added to list of removeCids. We currently don't delete stale 18636 * containers. 18637 */ 18638 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18639 boolean externalStorage) { 18640 ArrayList<String> pkgList = new ArrayList<String>(); 18641 Set<AsecInstallArgs> keys = processCids.keySet(); 18642 18643 for (AsecInstallArgs args : keys) { 18644 String codePath = processCids.get(args); 18645 if (DEBUG_SD_INSTALL) 18646 Log.i(TAG, "Loading container : " + args.cid); 18647 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18648 try { 18649 // Make sure there are no container errors first. 18650 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18651 Slog.e(TAG, "Failed to mount cid : " + args.cid 18652 + " when installing from sdcard"); 18653 continue; 18654 } 18655 // Check code path here. 18656 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18657 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18658 + " does not match one in settings " + codePath); 18659 continue; 18660 } 18661 // Parse package 18662 int parseFlags = mDefParseFlags; 18663 if (args.isExternalAsec()) { 18664 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18665 } 18666 if (args.isFwdLocked()) { 18667 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18668 } 18669 18670 synchronized (mInstallLock) { 18671 PackageParser.Package pkg = null; 18672 try { 18673 // Sadly we don't know the package name yet to freeze it 18674 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18675 SCAN_IGNORE_FROZEN, 0, null); 18676 } catch (PackageManagerException e) { 18677 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18678 } 18679 // Scan the package 18680 if (pkg != null) { 18681 /* 18682 * TODO why is the lock being held? doPostInstall is 18683 * called in other places without the lock. This needs 18684 * to be straightened out. 18685 */ 18686 // writer 18687 synchronized (mPackages) { 18688 retCode = PackageManager.INSTALL_SUCCEEDED; 18689 pkgList.add(pkg.packageName); 18690 // Post process args 18691 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18692 pkg.applicationInfo.uid); 18693 } 18694 } else { 18695 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18696 } 18697 } 18698 18699 } finally { 18700 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18701 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18702 } 18703 } 18704 } 18705 // writer 18706 synchronized (mPackages) { 18707 // If the platform SDK has changed since the last time we booted, 18708 // we need to re-grant app permission to catch any new ones that 18709 // appear. This is really a hack, and means that apps can in some 18710 // cases get permissions that the user didn't initially explicitly 18711 // allow... it would be nice to have some better way to handle 18712 // this situation. 18713 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18714 : mSettings.getInternalVersion(); 18715 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18716 : StorageManager.UUID_PRIVATE_INTERNAL; 18717 18718 int updateFlags = UPDATE_PERMISSIONS_ALL; 18719 if (ver.sdkVersion != mSdkVersion) { 18720 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18721 + mSdkVersion + "; regranting permissions for external"); 18722 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18723 } 18724 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18725 18726 // Yay, everything is now upgraded 18727 ver.forceCurrent(); 18728 18729 // can downgrade to reader 18730 // Persist settings 18731 mSettings.writeLPr(); 18732 } 18733 // Send a broadcast to let everyone know we are done processing 18734 if (pkgList.size() > 0) { 18735 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18736 } 18737 } 18738 18739 /* 18740 * Utility method to unload a list of specified containers 18741 */ 18742 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18743 // Just unmount all valid containers. 18744 for (AsecInstallArgs arg : cidArgs) { 18745 synchronized (mInstallLock) { 18746 arg.doPostDeleteLI(false); 18747 } 18748 } 18749 } 18750 18751 /* 18752 * Unload packages mounted on external media. This involves deleting package 18753 * data from internal structures, sending broadcasts about disabled packages, 18754 * gc'ing to free up references, unmounting all secure containers 18755 * corresponding to packages on external media, and posting a 18756 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18757 * that we always have to post this message if status has been requested no 18758 * matter what. 18759 */ 18760 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18761 final boolean reportStatus) { 18762 if (DEBUG_SD_INSTALL) 18763 Log.i(TAG, "unloading media packages"); 18764 ArrayList<String> pkgList = new ArrayList<String>(); 18765 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18766 final Set<AsecInstallArgs> keys = processCids.keySet(); 18767 for (AsecInstallArgs args : keys) { 18768 String pkgName = args.getPackageName(); 18769 if (DEBUG_SD_INSTALL) 18770 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18771 // Delete package internally 18772 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18773 synchronized (mInstallLock) { 18774 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18775 final boolean res; 18776 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18777 "unloadMediaPackages")) { 18778 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18779 null); 18780 } 18781 if (res) { 18782 pkgList.add(pkgName); 18783 } else { 18784 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18785 failedList.add(args); 18786 } 18787 } 18788 } 18789 18790 // reader 18791 synchronized (mPackages) { 18792 // We didn't update the settings after removing each package; 18793 // write them now for all packages. 18794 mSettings.writeLPr(); 18795 } 18796 18797 // We have to absolutely send UPDATED_MEDIA_STATUS only 18798 // after confirming that all the receivers processed the ordered 18799 // broadcast when packages get disabled, force a gc to clean things up. 18800 // and unload all the containers. 18801 if (pkgList.size() > 0) { 18802 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18803 new IIntentReceiver.Stub() { 18804 public void performReceive(Intent intent, int resultCode, String data, 18805 Bundle extras, boolean ordered, boolean sticky, 18806 int sendingUser) throws RemoteException { 18807 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18808 reportStatus ? 1 : 0, 1, keys); 18809 mHandler.sendMessage(msg); 18810 } 18811 }); 18812 } else { 18813 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18814 keys); 18815 mHandler.sendMessage(msg); 18816 } 18817 } 18818 18819 private void loadPrivatePackages(final VolumeInfo vol) { 18820 mHandler.post(new Runnable() { 18821 @Override 18822 public void run() { 18823 loadPrivatePackagesInner(vol); 18824 } 18825 }); 18826 } 18827 18828 private void loadPrivatePackagesInner(VolumeInfo vol) { 18829 final String volumeUuid = vol.fsUuid; 18830 if (TextUtils.isEmpty(volumeUuid)) { 18831 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18832 return; 18833 } 18834 18835 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18836 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18837 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18838 18839 final VersionInfo ver; 18840 final List<PackageSetting> packages; 18841 synchronized (mPackages) { 18842 ver = mSettings.findOrCreateVersion(volumeUuid); 18843 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18844 } 18845 18846 for (PackageSetting ps : packages) { 18847 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18848 synchronized (mInstallLock) { 18849 final PackageParser.Package pkg; 18850 try { 18851 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18852 loaded.add(pkg.applicationInfo); 18853 18854 } catch (PackageManagerException e) { 18855 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18856 } 18857 18858 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18859 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18860 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18861 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18862 } 18863 } 18864 } 18865 18866 // Reconcile app data for all started/unlocked users 18867 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18868 final UserManager um = mContext.getSystemService(UserManager.class); 18869 for (UserInfo user : um.getUsers()) { 18870 final int flags; 18871 if (um.isUserUnlockingOrUnlocked(user.id)) { 18872 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18873 } else if (um.isUserRunning(user.id)) { 18874 flags = StorageManager.FLAG_STORAGE_DE; 18875 } else { 18876 continue; 18877 } 18878 18879 try { 18880 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18881 synchronized (mInstallLock) { 18882 reconcileAppsDataLI(volumeUuid, user.id, flags); 18883 } 18884 } catch (IllegalStateException e) { 18885 // Device was probably ejected, and we'll process that event momentarily 18886 Slog.w(TAG, "Failed to prepare storage: " + e); 18887 } 18888 } 18889 18890 synchronized (mPackages) { 18891 int updateFlags = UPDATE_PERMISSIONS_ALL; 18892 if (ver.sdkVersion != mSdkVersion) { 18893 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18894 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18895 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18896 } 18897 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18898 18899 // Yay, everything is now upgraded 18900 ver.forceCurrent(); 18901 18902 mSettings.writeLPr(); 18903 } 18904 18905 for (PackageFreezer freezer : freezers) { 18906 freezer.close(); 18907 } 18908 18909 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18910 sendResourcesChangedBroadcast(true, false, loaded, null); 18911 } 18912 18913 private void unloadPrivatePackages(final VolumeInfo vol) { 18914 mHandler.post(new Runnable() { 18915 @Override 18916 public void run() { 18917 unloadPrivatePackagesInner(vol); 18918 } 18919 }); 18920 } 18921 18922 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18923 final String volumeUuid = vol.fsUuid; 18924 if (TextUtils.isEmpty(volumeUuid)) { 18925 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18926 return; 18927 } 18928 18929 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18930 synchronized (mInstallLock) { 18931 synchronized (mPackages) { 18932 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18933 for (PackageSetting ps : packages) { 18934 if (ps.pkg == null) continue; 18935 18936 final ApplicationInfo info = ps.pkg.applicationInfo; 18937 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18938 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18939 18940 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18941 "unloadPrivatePackagesInner")) { 18942 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18943 false, null)) { 18944 unloaded.add(info); 18945 } else { 18946 Slog.w(TAG, "Failed to unload " + ps.codePath); 18947 } 18948 } 18949 } 18950 18951 mSettings.writeLPr(); 18952 } 18953 } 18954 18955 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18956 sendResourcesChangedBroadcast(false, false, unloaded, null); 18957 } 18958 18959 /** 18960 * Prepare storage areas for given user on all mounted devices. 18961 */ 18962 void prepareUserData(int userId, int userSerial, int flags) { 18963 synchronized (mInstallLock) { 18964 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18965 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18966 final String volumeUuid = vol.getFsUuid(); 18967 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18968 } 18969 } 18970 } 18971 18972 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18973 boolean allowRecover) { 18974 // Prepare storage and verify that serial numbers are consistent; if 18975 // there's a mismatch we need to destroy to avoid leaking data 18976 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18977 try { 18978 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18979 18980 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18981 UserManagerService.enforceSerialNumber( 18982 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18983 } 18984 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18985 UserManagerService.enforceSerialNumber( 18986 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18987 } 18988 18989 synchronized (mInstallLock) { 18990 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18991 } 18992 } catch (Exception e) { 18993 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18994 + " because we failed to prepare: " + e); 18995 destroyUserDataLI(volumeUuid, userId, 18996 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18997 18998 if (allowRecover) { 18999 // Try one last time; if we fail again we're really in trouble 19000 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19001 } 19002 } 19003 } 19004 19005 /** 19006 * Destroy storage areas for given user on all mounted devices. 19007 */ 19008 void destroyUserData(int userId, int flags) { 19009 synchronized (mInstallLock) { 19010 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19011 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19012 final String volumeUuid = vol.getFsUuid(); 19013 destroyUserDataLI(volumeUuid, userId, flags); 19014 } 19015 } 19016 } 19017 19018 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19019 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19020 try { 19021 // Clean up app data, profile data, and media data 19022 mInstaller.destroyUserData(volumeUuid, userId, flags); 19023 19024 // Clean up system data 19025 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19026 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19027 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19028 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19029 } 19030 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19031 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19032 } 19033 } 19034 19035 // Data with special labels is now gone, so finish the job 19036 storage.destroyUserStorage(volumeUuid, userId, flags); 19037 19038 } catch (Exception e) { 19039 logCriticalInfo(Log.WARN, 19040 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19041 } 19042 } 19043 19044 /** 19045 * Examine all users present on given mounted volume, and destroy data 19046 * belonging to users that are no longer valid, or whose user ID has been 19047 * recycled. 19048 */ 19049 private void reconcileUsers(String volumeUuid) { 19050 final List<File> files = new ArrayList<>(); 19051 Collections.addAll(files, FileUtils 19052 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19053 Collections.addAll(files, FileUtils 19054 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19055 for (File file : files) { 19056 if (!file.isDirectory()) continue; 19057 19058 final int userId; 19059 final UserInfo info; 19060 try { 19061 userId = Integer.parseInt(file.getName()); 19062 info = sUserManager.getUserInfo(userId); 19063 } catch (NumberFormatException e) { 19064 Slog.w(TAG, "Invalid user directory " + file); 19065 continue; 19066 } 19067 19068 boolean destroyUser = false; 19069 if (info == null) { 19070 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19071 + " because no matching user was found"); 19072 destroyUser = true; 19073 } else if (!mOnlyCore) { 19074 try { 19075 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19076 } catch (IOException e) { 19077 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19078 + " because we failed to enforce serial number: " + e); 19079 destroyUser = true; 19080 } 19081 } 19082 19083 if (destroyUser) { 19084 synchronized (mInstallLock) { 19085 destroyUserDataLI(volumeUuid, userId, 19086 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19087 } 19088 } 19089 } 19090 } 19091 19092 private void assertPackageKnown(String volumeUuid, String packageName) 19093 throws PackageManagerException { 19094 synchronized (mPackages) { 19095 final PackageSetting ps = mSettings.mPackages.get(packageName); 19096 if (ps == null) { 19097 throw new PackageManagerException("Package " + packageName + " is unknown"); 19098 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19099 throw new PackageManagerException( 19100 "Package " + packageName + " found on unknown volume " + volumeUuid 19101 + "; expected volume " + ps.volumeUuid); 19102 } 19103 } 19104 } 19105 19106 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19107 throws PackageManagerException { 19108 synchronized (mPackages) { 19109 final PackageSetting ps = mSettings.mPackages.get(packageName); 19110 if (ps == null) { 19111 throw new PackageManagerException("Package " + packageName + " is unknown"); 19112 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19113 throw new PackageManagerException( 19114 "Package " + packageName + " found on unknown volume " + volumeUuid 19115 + "; expected volume " + ps.volumeUuid); 19116 } else if (!ps.getInstalled(userId)) { 19117 throw new PackageManagerException( 19118 "Package " + packageName + " not installed for user " + userId); 19119 } 19120 } 19121 } 19122 19123 /** 19124 * Examine all apps present on given mounted volume, and destroy apps that 19125 * aren't expected, either due to uninstallation or reinstallation on 19126 * another volume. 19127 */ 19128 private void reconcileApps(String volumeUuid) { 19129 final File[] files = FileUtils 19130 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19131 for (File file : files) { 19132 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19133 && !PackageInstallerService.isStageName(file.getName()); 19134 if (!isPackage) { 19135 // Ignore entries which are not packages 19136 continue; 19137 } 19138 19139 try { 19140 final PackageLite pkg = PackageParser.parsePackageLite(file, 19141 PackageParser.PARSE_MUST_BE_APK); 19142 assertPackageKnown(volumeUuid, pkg.packageName); 19143 19144 } catch (PackageParserException | PackageManagerException e) { 19145 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19146 synchronized (mInstallLock) { 19147 removeCodePathLI(file); 19148 } 19149 } 19150 } 19151 } 19152 19153 /** 19154 * Reconcile all app data for the given user. 19155 * <p> 19156 * Verifies that directories exist and that ownership and labeling is 19157 * correct for all installed apps on all mounted volumes. 19158 */ 19159 void reconcileAppsData(int userId, int flags) { 19160 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19161 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19162 final String volumeUuid = vol.getFsUuid(); 19163 synchronized (mInstallLock) { 19164 reconcileAppsDataLI(volumeUuid, userId, flags); 19165 } 19166 } 19167 } 19168 19169 /** 19170 * Reconcile all app data on given mounted volume. 19171 * <p> 19172 * Destroys app data that isn't expected, either due to uninstallation or 19173 * reinstallation on another volume. 19174 * <p> 19175 * Verifies that directories exist and that ownership and labeling is 19176 * correct for all installed apps. 19177 */ 19178 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19179 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19180 + Integer.toHexString(flags)); 19181 19182 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19183 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19184 19185 boolean restoreconNeeded = false; 19186 19187 // First look for stale data that doesn't belong, and check if things 19188 // have changed since we did our last restorecon 19189 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19190 if (StorageManager.isFileEncryptedNativeOrEmulated() 19191 && !StorageManager.isUserKeyUnlocked(userId)) { 19192 throw new RuntimeException( 19193 "Yikes, someone asked us to reconcile CE storage while " + userId 19194 + " was still locked; this would have caused massive data loss!"); 19195 } 19196 19197 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19198 19199 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19200 for (File file : files) { 19201 final String packageName = file.getName(); 19202 try { 19203 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19204 } catch (PackageManagerException e) { 19205 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19206 try { 19207 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19208 StorageManager.FLAG_STORAGE_CE, 0); 19209 } catch (InstallerException e2) { 19210 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19211 } 19212 } 19213 } 19214 } 19215 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19216 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19217 19218 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19219 for (File file : files) { 19220 final String packageName = file.getName(); 19221 try { 19222 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19223 } catch (PackageManagerException e) { 19224 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19225 try { 19226 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19227 StorageManager.FLAG_STORAGE_DE, 0); 19228 } catch (InstallerException e2) { 19229 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19230 } 19231 } 19232 } 19233 } 19234 19235 // Ensure that data directories are ready to roll for all packages 19236 // installed for this volume and user 19237 final List<PackageSetting> packages; 19238 synchronized (mPackages) { 19239 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19240 } 19241 int preparedCount = 0; 19242 for (PackageSetting ps : packages) { 19243 final String packageName = ps.name; 19244 if (ps.pkg == null) { 19245 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19246 // TODO: might be due to legacy ASEC apps; we should circle back 19247 // and reconcile again once they're scanned 19248 continue; 19249 } 19250 19251 if (ps.getInstalled(userId)) { 19252 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19253 19254 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19255 // We may have just shuffled around app data directories, so 19256 // prepare them one more time 19257 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19258 } 19259 19260 preparedCount++; 19261 } 19262 } 19263 19264 if (restoreconNeeded) { 19265 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19266 SELinuxMMAC.setRestoreconDone(ceDir); 19267 } 19268 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19269 SELinuxMMAC.setRestoreconDone(deDir); 19270 } 19271 } 19272 19273 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19274 + " packages; restoreconNeeded was " + restoreconNeeded); 19275 } 19276 19277 /** 19278 * Prepare app data for the given app just after it was installed or 19279 * upgraded. This method carefully only touches users that it's installed 19280 * for, and it forces a restorecon to handle any seinfo changes. 19281 * <p> 19282 * Verifies that directories exist and that ownership and labeling is 19283 * correct for all installed apps. If there is an ownership mismatch, it 19284 * will try recovering system apps by wiping data; third-party app data is 19285 * left intact. 19286 * <p> 19287 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19288 */ 19289 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19290 final PackageSetting ps; 19291 synchronized (mPackages) { 19292 ps = mSettings.mPackages.get(pkg.packageName); 19293 mSettings.writeKernelMappingLPr(ps); 19294 } 19295 19296 final UserManager um = mContext.getSystemService(UserManager.class); 19297 for (UserInfo user : um.getUsers()) { 19298 final int flags; 19299 if (um.isUserUnlockingOrUnlocked(user.id)) { 19300 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19301 } else if (um.isUserRunning(user.id)) { 19302 flags = StorageManager.FLAG_STORAGE_DE; 19303 } else { 19304 continue; 19305 } 19306 19307 if (ps.getInstalled(user.id)) { 19308 // Whenever an app changes, force a restorecon of its data 19309 // TODO: when user data is locked, mark that we're still dirty 19310 prepareAppDataLIF(pkg, user.id, flags, true); 19311 } 19312 } 19313 } 19314 19315 /** 19316 * Prepare app data for the given app. 19317 * <p> 19318 * Verifies that directories exist and that ownership and labeling is 19319 * correct for all installed apps. If there is an ownership mismatch, this 19320 * will try recovering system apps by wiping data; third-party app data is 19321 * left intact. 19322 */ 19323 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19324 boolean restoreconNeeded) { 19325 if (pkg == null) { 19326 Slog.wtf(TAG, "Package was null!", new Throwable()); 19327 return; 19328 } 19329 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19330 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19331 for (int i = 0; i < childCount; i++) { 19332 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19333 } 19334 } 19335 19336 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19337 boolean restoreconNeeded) { 19338 if (DEBUG_APP_DATA) { 19339 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19340 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19341 } 19342 19343 final String volumeUuid = pkg.volumeUuid; 19344 final String packageName = pkg.packageName; 19345 final ApplicationInfo app = pkg.applicationInfo; 19346 final int appId = UserHandle.getAppId(app.uid); 19347 19348 Preconditions.checkNotNull(app.seinfo); 19349 19350 try { 19351 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19352 appId, app.seinfo, app.targetSdkVersion); 19353 } catch (InstallerException e) { 19354 if (app.isSystemApp()) { 19355 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19356 + ", but trying to recover: " + e); 19357 destroyAppDataLeafLIF(pkg, userId, flags); 19358 try { 19359 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19360 appId, app.seinfo, app.targetSdkVersion); 19361 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19362 } catch (InstallerException e2) { 19363 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19364 } 19365 } else { 19366 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19367 } 19368 } 19369 19370 if (restoreconNeeded) { 19371 try { 19372 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19373 app.seinfo); 19374 } catch (InstallerException e) { 19375 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19376 } 19377 } 19378 19379 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19380 try { 19381 // CE storage is unlocked right now, so read out the inode and 19382 // remember for use later when it's locked 19383 // TODO: mark this structure as dirty so we persist it! 19384 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19385 StorageManager.FLAG_STORAGE_CE); 19386 synchronized (mPackages) { 19387 final PackageSetting ps = mSettings.mPackages.get(packageName); 19388 if (ps != null) { 19389 ps.setCeDataInode(ceDataInode, userId); 19390 } 19391 } 19392 } catch (InstallerException e) { 19393 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19394 } 19395 } 19396 19397 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19398 } 19399 19400 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19401 if (pkg == null) { 19402 Slog.wtf(TAG, "Package was null!", new Throwable()); 19403 return; 19404 } 19405 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19406 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19407 for (int i = 0; i < childCount; i++) { 19408 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19409 } 19410 } 19411 19412 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19413 final String volumeUuid = pkg.volumeUuid; 19414 final String packageName = pkg.packageName; 19415 final ApplicationInfo app = pkg.applicationInfo; 19416 19417 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19418 // Create a native library symlink only if we have native libraries 19419 // and if the native libraries are 32 bit libraries. We do not provide 19420 // this symlink for 64 bit libraries. 19421 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19422 final String nativeLibPath = app.nativeLibraryDir; 19423 try { 19424 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19425 nativeLibPath, userId); 19426 } catch (InstallerException e) { 19427 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19428 } 19429 } 19430 } 19431 } 19432 19433 /** 19434 * For system apps on non-FBE devices, this method migrates any existing 19435 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19436 * requested by the app. 19437 */ 19438 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19439 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19440 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19441 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19442 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19443 try { 19444 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19445 storageTarget); 19446 } catch (InstallerException e) { 19447 logCriticalInfo(Log.WARN, 19448 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19449 } 19450 return true; 19451 } else { 19452 return false; 19453 } 19454 } 19455 19456 public PackageFreezer freezePackage(String packageName, String killReason) { 19457 return new PackageFreezer(packageName, killReason); 19458 } 19459 19460 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19461 String killReason) { 19462 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19463 return new PackageFreezer(); 19464 } else { 19465 return freezePackage(packageName, killReason); 19466 } 19467 } 19468 19469 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19470 String killReason) { 19471 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19472 return new PackageFreezer(); 19473 } else { 19474 return freezePackage(packageName, killReason); 19475 } 19476 } 19477 19478 /** 19479 * Class that freezes and kills the given package upon creation, and 19480 * unfreezes it upon closing. This is typically used when doing surgery on 19481 * app code/data to prevent the app from running while you're working. 19482 */ 19483 private class PackageFreezer implements AutoCloseable { 19484 private final String mPackageName; 19485 private final PackageFreezer[] mChildren; 19486 19487 private final boolean mWeFroze; 19488 19489 private final AtomicBoolean mClosed = new AtomicBoolean(); 19490 private final CloseGuard mCloseGuard = CloseGuard.get(); 19491 19492 /** 19493 * Create and return a stub freezer that doesn't actually do anything, 19494 * typically used when someone requested 19495 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19496 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19497 */ 19498 public PackageFreezer() { 19499 mPackageName = null; 19500 mChildren = null; 19501 mWeFroze = false; 19502 mCloseGuard.open("close"); 19503 } 19504 19505 public PackageFreezer(String packageName, String killReason) { 19506 synchronized (mPackages) { 19507 mPackageName = packageName; 19508 mWeFroze = mFrozenPackages.add(mPackageName); 19509 19510 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19511 if (ps != null) { 19512 killApplication(ps.name, ps.appId, killReason); 19513 } 19514 19515 final PackageParser.Package p = mPackages.get(packageName); 19516 if (p != null && p.childPackages != null) { 19517 final int N = p.childPackages.size(); 19518 mChildren = new PackageFreezer[N]; 19519 for (int i = 0; i < N; i++) { 19520 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19521 killReason); 19522 } 19523 } else { 19524 mChildren = null; 19525 } 19526 } 19527 mCloseGuard.open("close"); 19528 } 19529 19530 @Override 19531 protected void finalize() throws Throwable { 19532 try { 19533 mCloseGuard.warnIfOpen(); 19534 close(); 19535 } finally { 19536 super.finalize(); 19537 } 19538 } 19539 19540 @Override 19541 public void close() { 19542 mCloseGuard.close(); 19543 if (mClosed.compareAndSet(false, true)) { 19544 synchronized (mPackages) { 19545 if (mWeFroze) { 19546 mFrozenPackages.remove(mPackageName); 19547 } 19548 19549 if (mChildren != null) { 19550 for (PackageFreezer freezer : mChildren) { 19551 freezer.close(); 19552 } 19553 } 19554 } 19555 } 19556 } 19557 } 19558 19559 /** 19560 * Verify that given package is currently frozen. 19561 */ 19562 private void checkPackageFrozen(String packageName) { 19563 synchronized (mPackages) { 19564 if (!mFrozenPackages.contains(packageName)) { 19565 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19566 } 19567 } 19568 } 19569 19570 @Override 19571 public int movePackage(final String packageName, final String volumeUuid) { 19572 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19573 19574 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19575 final int moveId = mNextMoveId.getAndIncrement(); 19576 mHandler.post(new Runnable() { 19577 @Override 19578 public void run() { 19579 try { 19580 movePackageInternal(packageName, volumeUuid, moveId, user); 19581 } catch (PackageManagerException e) { 19582 Slog.w(TAG, "Failed to move " + packageName, e); 19583 mMoveCallbacks.notifyStatusChanged(moveId, 19584 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19585 } 19586 } 19587 }); 19588 return moveId; 19589 } 19590 19591 private void movePackageInternal(final String packageName, final String volumeUuid, 19592 final int moveId, UserHandle user) throws PackageManagerException { 19593 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19594 final PackageManager pm = mContext.getPackageManager(); 19595 19596 final boolean currentAsec; 19597 final String currentVolumeUuid; 19598 final File codeFile; 19599 final String installerPackageName; 19600 final String packageAbiOverride; 19601 final int appId; 19602 final String seinfo; 19603 final String label; 19604 final int targetSdkVersion; 19605 final PackageFreezer freezer; 19606 19607 // reader 19608 synchronized (mPackages) { 19609 final PackageParser.Package pkg = mPackages.get(packageName); 19610 final PackageSetting ps = mSettings.mPackages.get(packageName); 19611 if (pkg == null || ps == null) { 19612 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19613 } 19614 19615 if (pkg.applicationInfo.isSystemApp()) { 19616 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19617 "Cannot move system application"); 19618 } 19619 19620 if (pkg.applicationInfo.isExternalAsec()) { 19621 currentAsec = true; 19622 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19623 } else if (pkg.applicationInfo.isForwardLocked()) { 19624 currentAsec = true; 19625 currentVolumeUuid = "forward_locked"; 19626 } else { 19627 currentAsec = false; 19628 currentVolumeUuid = ps.volumeUuid; 19629 19630 final File probe = new File(pkg.codePath); 19631 final File probeOat = new File(probe, "oat"); 19632 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19633 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19634 "Move only supported for modern cluster style installs"); 19635 } 19636 } 19637 19638 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19639 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19640 "Package already moved to " + volumeUuid); 19641 } 19642 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19643 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19644 "Device admin cannot be moved"); 19645 } 19646 19647 if (mFrozenPackages.contains(packageName)) { 19648 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19649 "Failed to move already frozen package"); 19650 } 19651 19652 codeFile = new File(pkg.codePath); 19653 installerPackageName = ps.installerPackageName; 19654 packageAbiOverride = ps.cpuAbiOverrideString; 19655 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19656 seinfo = pkg.applicationInfo.seinfo; 19657 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19658 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19659 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19660 } 19661 19662 final Bundle extras = new Bundle(); 19663 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19664 extras.putString(Intent.EXTRA_TITLE, label); 19665 mMoveCallbacks.notifyCreated(moveId, extras); 19666 19667 int installFlags; 19668 final boolean moveCompleteApp; 19669 final File measurePath; 19670 19671 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19672 installFlags = INSTALL_INTERNAL; 19673 moveCompleteApp = !currentAsec; 19674 measurePath = Environment.getDataAppDirectory(volumeUuid); 19675 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19676 installFlags = INSTALL_EXTERNAL; 19677 moveCompleteApp = false; 19678 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19679 } else { 19680 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19681 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19682 || !volume.isMountedWritable()) { 19683 freezer.close(); 19684 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19685 "Move location not mounted private volume"); 19686 } 19687 19688 Preconditions.checkState(!currentAsec); 19689 19690 installFlags = INSTALL_INTERNAL; 19691 moveCompleteApp = true; 19692 measurePath = Environment.getDataAppDirectory(volumeUuid); 19693 } 19694 19695 final PackageStats stats = new PackageStats(null, -1); 19696 synchronized (mInstaller) { 19697 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19698 freezer.close(); 19699 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19700 "Failed to measure package size"); 19701 } 19702 } 19703 19704 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19705 + stats.dataSize); 19706 19707 final long startFreeBytes = measurePath.getFreeSpace(); 19708 final long sizeBytes; 19709 if (moveCompleteApp) { 19710 sizeBytes = stats.codeSize + stats.dataSize; 19711 } else { 19712 sizeBytes = stats.codeSize; 19713 } 19714 19715 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19716 freezer.close(); 19717 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19718 "Not enough free space to move"); 19719 } 19720 19721 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19722 19723 final CountDownLatch installedLatch = new CountDownLatch(1); 19724 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19725 @Override 19726 public void onUserActionRequired(Intent intent) throws RemoteException { 19727 throw new IllegalStateException(); 19728 } 19729 19730 @Override 19731 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19732 Bundle extras) throws RemoteException { 19733 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19734 + PackageManager.installStatusToString(returnCode, msg)); 19735 19736 installedLatch.countDown(); 19737 freezer.close(); 19738 19739 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19740 switch (status) { 19741 case PackageInstaller.STATUS_SUCCESS: 19742 mMoveCallbacks.notifyStatusChanged(moveId, 19743 PackageManager.MOVE_SUCCEEDED); 19744 break; 19745 case PackageInstaller.STATUS_FAILURE_STORAGE: 19746 mMoveCallbacks.notifyStatusChanged(moveId, 19747 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19748 break; 19749 default: 19750 mMoveCallbacks.notifyStatusChanged(moveId, 19751 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19752 break; 19753 } 19754 } 19755 }; 19756 19757 final MoveInfo move; 19758 if (moveCompleteApp) { 19759 // Kick off a thread to report progress estimates 19760 new Thread() { 19761 @Override 19762 public void run() { 19763 while (true) { 19764 try { 19765 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19766 break; 19767 } 19768 } catch (InterruptedException ignored) { 19769 } 19770 19771 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19772 final int progress = 10 + (int) MathUtils.constrain( 19773 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19774 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19775 } 19776 } 19777 }.start(); 19778 19779 final String dataAppName = codeFile.getName(); 19780 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19781 dataAppName, appId, seinfo, targetSdkVersion); 19782 } else { 19783 move = null; 19784 } 19785 19786 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19787 19788 final Message msg = mHandler.obtainMessage(INIT_COPY); 19789 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19790 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19791 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19792 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19793 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19794 msg.obj = params; 19795 19796 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19797 System.identityHashCode(msg.obj)); 19798 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19799 System.identityHashCode(msg.obj)); 19800 19801 mHandler.sendMessage(msg); 19802 } 19803 19804 @Override 19805 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19806 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19807 19808 final int realMoveId = mNextMoveId.getAndIncrement(); 19809 final Bundle extras = new Bundle(); 19810 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19811 mMoveCallbacks.notifyCreated(realMoveId, extras); 19812 19813 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19814 @Override 19815 public void onCreated(int moveId, Bundle extras) { 19816 // Ignored 19817 } 19818 19819 @Override 19820 public void onStatusChanged(int moveId, int status, long estMillis) { 19821 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19822 } 19823 }; 19824 19825 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19826 storage.setPrimaryStorageUuid(volumeUuid, callback); 19827 return realMoveId; 19828 } 19829 19830 @Override 19831 public int getMoveStatus(int moveId) { 19832 mContext.enforceCallingOrSelfPermission( 19833 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19834 return mMoveCallbacks.mLastStatus.get(moveId); 19835 } 19836 19837 @Override 19838 public void registerMoveCallback(IPackageMoveObserver callback) { 19839 mContext.enforceCallingOrSelfPermission( 19840 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19841 mMoveCallbacks.register(callback); 19842 } 19843 19844 @Override 19845 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19846 mContext.enforceCallingOrSelfPermission( 19847 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19848 mMoveCallbacks.unregister(callback); 19849 } 19850 19851 @Override 19852 public boolean setInstallLocation(int loc) { 19853 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19854 null); 19855 if (getInstallLocation() == loc) { 19856 return true; 19857 } 19858 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19859 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19860 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19861 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19862 return true; 19863 } 19864 return false; 19865 } 19866 19867 @Override 19868 public int getInstallLocation() { 19869 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19870 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19871 PackageHelper.APP_INSTALL_AUTO); 19872 } 19873 19874 /** Called by UserManagerService */ 19875 void cleanUpUser(UserManagerService userManager, int userHandle) { 19876 synchronized (mPackages) { 19877 mDirtyUsers.remove(userHandle); 19878 mUserNeedsBadging.delete(userHandle); 19879 mSettings.removeUserLPw(userHandle); 19880 mPendingBroadcasts.remove(userHandle); 19881 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19882 removeUnusedPackagesLPw(userManager, userHandle); 19883 } 19884 } 19885 19886 /** 19887 * We're removing userHandle and would like to remove any downloaded packages 19888 * that are no longer in use by any other user. 19889 * @param userHandle the user being removed 19890 */ 19891 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19892 final boolean DEBUG_CLEAN_APKS = false; 19893 int [] users = userManager.getUserIds(); 19894 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19895 while (psit.hasNext()) { 19896 PackageSetting ps = psit.next(); 19897 if (ps.pkg == null) { 19898 continue; 19899 } 19900 final String packageName = ps.pkg.packageName; 19901 // Skip over if system app 19902 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19903 continue; 19904 } 19905 if (DEBUG_CLEAN_APKS) { 19906 Slog.i(TAG, "Checking package " + packageName); 19907 } 19908 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19909 if (keep) { 19910 if (DEBUG_CLEAN_APKS) { 19911 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19912 } 19913 } else { 19914 for (int i = 0; i < users.length; i++) { 19915 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19916 keep = true; 19917 if (DEBUG_CLEAN_APKS) { 19918 Slog.i(TAG, " Keeping package " + packageName + " for user " 19919 + users[i]); 19920 } 19921 break; 19922 } 19923 } 19924 } 19925 if (!keep) { 19926 if (DEBUG_CLEAN_APKS) { 19927 Slog.i(TAG, " Removing package " + packageName); 19928 } 19929 mHandler.post(new Runnable() { 19930 public void run() { 19931 deletePackageX(packageName, userHandle, 0); 19932 } //end run 19933 }); 19934 } 19935 } 19936 } 19937 19938 /** Called by UserManagerService */ 19939 void createNewUser(int userHandle) { 19940 synchronized (mInstallLock) { 19941 mSettings.createNewUserLI(this, mInstaller, userHandle); 19942 } 19943 synchronized (mPackages) { 19944 applyFactoryDefaultBrowserLPw(userHandle); 19945 primeDomainVerificationsLPw(userHandle); 19946 } 19947 } 19948 19949 void newUserCreated(final int userHandle) { 19950 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19951 // If permission review for legacy apps is required, we represent 19952 // dagerous permissions for such apps as always granted runtime 19953 // permissions to keep per user flag state whether review is needed. 19954 // Hence, if a new user is added we have to propagate dangerous 19955 // permission grants for these legacy apps. 19956 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19957 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19958 | UPDATE_PERMISSIONS_REPLACE_ALL); 19959 } 19960 } 19961 19962 @Override 19963 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19964 mContext.enforceCallingOrSelfPermission( 19965 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19966 "Only package verification agents can read the verifier device identity"); 19967 19968 synchronized (mPackages) { 19969 return mSettings.getVerifierDeviceIdentityLPw(); 19970 } 19971 } 19972 19973 @Override 19974 public void setPermissionEnforced(String permission, boolean enforced) { 19975 // TODO: Now that we no longer change GID for storage, this should to away. 19976 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19977 "setPermissionEnforced"); 19978 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19979 synchronized (mPackages) { 19980 if (mSettings.mReadExternalStorageEnforced == null 19981 || mSettings.mReadExternalStorageEnforced != enforced) { 19982 mSettings.mReadExternalStorageEnforced = enforced; 19983 mSettings.writeLPr(); 19984 } 19985 } 19986 // kill any non-foreground processes so we restart them and 19987 // grant/revoke the GID. 19988 final IActivityManager am = ActivityManagerNative.getDefault(); 19989 if (am != null) { 19990 final long token = Binder.clearCallingIdentity(); 19991 try { 19992 am.killProcessesBelowForeground("setPermissionEnforcement"); 19993 } catch (RemoteException e) { 19994 } finally { 19995 Binder.restoreCallingIdentity(token); 19996 } 19997 } 19998 } else { 19999 throw new IllegalArgumentException("No selective enforcement for " + permission); 20000 } 20001 } 20002 20003 @Override 20004 @Deprecated 20005 public boolean isPermissionEnforced(String permission) { 20006 return true; 20007 } 20008 20009 @Override 20010 public boolean isStorageLow() { 20011 final long token = Binder.clearCallingIdentity(); 20012 try { 20013 final DeviceStorageMonitorInternal 20014 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20015 if (dsm != null) { 20016 return dsm.isMemoryLow(); 20017 } else { 20018 return false; 20019 } 20020 } finally { 20021 Binder.restoreCallingIdentity(token); 20022 } 20023 } 20024 20025 @Override 20026 public IPackageInstaller getPackageInstaller() { 20027 return mInstallerService; 20028 } 20029 20030 private boolean userNeedsBadging(int userId) { 20031 int index = mUserNeedsBadging.indexOfKey(userId); 20032 if (index < 0) { 20033 final UserInfo userInfo; 20034 final long token = Binder.clearCallingIdentity(); 20035 try { 20036 userInfo = sUserManager.getUserInfo(userId); 20037 } finally { 20038 Binder.restoreCallingIdentity(token); 20039 } 20040 final boolean b; 20041 if (userInfo != null && userInfo.isManagedProfile()) { 20042 b = true; 20043 } else { 20044 b = false; 20045 } 20046 mUserNeedsBadging.put(userId, b); 20047 return b; 20048 } 20049 return mUserNeedsBadging.valueAt(index); 20050 } 20051 20052 @Override 20053 public KeySet getKeySetByAlias(String packageName, String alias) { 20054 if (packageName == null || alias == null) { 20055 return null; 20056 } 20057 synchronized(mPackages) { 20058 final PackageParser.Package pkg = mPackages.get(packageName); 20059 if (pkg == null) { 20060 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20061 throw new IllegalArgumentException("Unknown package: " + packageName); 20062 } 20063 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20064 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20065 } 20066 } 20067 20068 @Override 20069 public KeySet getSigningKeySet(String packageName) { 20070 if (packageName == null) { 20071 return null; 20072 } 20073 synchronized(mPackages) { 20074 final PackageParser.Package pkg = mPackages.get(packageName); 20075 if (pkg == null) { 20076 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20077 throw new IllegalArgumentException("Unknown package: " + packageName); 20078 } 20079 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20080 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20081 throw new SecurityException("May not access signing KeySet of other apps."); 20082 } 20083 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20084 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20085 } 20086 } 20087 20088 @Override 20089 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20090 if (packageName == null || ks == null) { 20091 return false; 20092 } 20093 synchronized(mPackages) { 20094 final PackageParser.Package pkg = mPackages.get(packageName); 20095 if (pkg == null) { 20096 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20097 throw new IllegalArgumentException("Unknown package: " + packageName); 20098 } 20099 IBinder ksh = ks.getToken(); 20100 if (ksh instanceof KeySetHandle) { 20101 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20102 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20103 } 20104 return false; 20105 } 20106 } 20107 20108 @Override 20109 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20110 if (packageName == null || ks == null) { 20111 return false; 20112 } 20113 synchronized(mPackages) { 20114 final PackageParser.Package pkg = mPackages.get(packageName); 20115 if (pkg == null) { 20116 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20117 throw new IllegalArgumentException("Unknown package: " + packageName); 20118 } 20119 IBinder ksh = ks.getToken(); 20120 if (ksh instanceof KeySetHandle) { 20121 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20122 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20123 } 20124 return false; 20125 } 20126 } 20127 20128 private void deletePackageIfUnusedLPr(final String packageName) { 20129 PackageSetting ps = mSettings.mPackages.get(packageName); 20130 if (ps == null) { 20131 return; 20132 } 20133 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20134 // TODO Implement atomic delete if package is unused 20135 // It is currently possible that the package will be deleted even if it is installed 20136 // after this method returns. 20137 mHandler.post(new Runnable() { 20138 public void run() { 20139 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20140 } 20141 }); 20142 } 20143 } 20144 20145 /** 20146 * Check and throw if the given before/after packages would be considered a 20147 * downgrade. 20148 */ 20149 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20150 throws PackageManagerException { 20151 if (after.versionCode < before.mVersionCode) { 20152 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20153 "Update version code " + after.versionCode + " is older than current " 20154 + before.mVersionCode); 20155 } else if (after.versionCode == before.mVersionCode) { 20156 if (after.baseRevisionCode < before.baseRevisionCode) { 20157 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20158 "Update base revision code " + after.baseRevisionCode 20159 + " is older than current " + before.baseRevisionCode); 20160 } 20161 20162 if (!ArrayUtils.isEmpty(after.splitNames)) { 20163 for (int i = 0; i < after.splitNames.length; i++) { 20164 final String splitName = after.splitNames[i]; 20165 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20166 if (j != -1) { 20167 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20168 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20169 "Update split " + splitName + " revision code " 20170 + after.splitRevisionCodes[i] + " is older than current " 20171 + before.splitRevisionCodes[j]); 20172 } 20173 } 20174 } 20175 } 20176 } 20177 } 20178 20179 private static class MoveCallbacks extends Handler { 20180 private static final int MSG_CREATED = 1; 20181 private static final int MSG_STATUS_CHANGED = 2; 20182 20183 private final RemoteCallbackList<IPackageMoveObserver> 20184 mCallbacks = new RemoteCallbackList<>(); 20185 20186 private final SparseIntArray mLastStatus = new SparseIntArray(); 20187 20188 public MoveCallbacks(Looper looper) { 20189 super(looper); 20190 } 20191 20192 public void register(IPackageMoveObserver callback) { 20193 mCallbacks.register(callback); 20194 } 20195 20196 public void unregister(IPackageMoveObserver callback) { 20197 mCallbacks.unregister(callback); 20198 } 20199 20200 @Override 20201 public void handleMessage(Message msg) { 20202 final SomeArgs args = (SomeArgs) msg.obj; 20203 final int n = mCallbacks.beginBroadcast(); 20204 for (int i = 0; i < n; i++) { 20205 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20206 try { 20207 invokeCallback(callback, msg.what, args); 20208 } catch (RemoteException ignored) { 20209 } 20210 } 20211 mCallbacks.finishBroadcast(); 20212 args.recycle(); 20213 } 20214 20215 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20216 throws RemoteException { 20217 switch (what) { 20218 case MSG_CREATED: { 20219 callback.onCreated(args.argi1, (Bundle) args.arg2); 20220 break; 20221 } 20222 case MSG_STATUS_CHANGED: { 20223 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20224 break; 20225 } 20226 } 20227 } 20228 20229 private void notifyCreated(int moveId, Bundle extras) { 20230 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20231 20232 final SomeArgs args = SomeArgs.obtain(); 20233 args.argi1 = moveId; 20234 args.arg2 = extras; 20235 obtainMessage(MSG_CREATED, args).sendToTarget(); 20236 } 20237 20238 private void notifyStatusChanged(int moveId, int status) { 20239 notifyStatusChanged(moveId, status, -1); 20240 } 20241 20242 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20243 Slog.v(TAG, "Move " + moveId + " status " + status); 20244 20245 final SomeArgs args = SomeArgs.obtain(); 20246 args.argi1 = moveId; 20247 args.argi2 = status; 20248 args.arg3 = estMillis; 20249 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20250 20251 synchronized (mLastStatus) { 20252 mLastStatus.put(moveId, status); 20253 } 20254 } 20255 } 20256 20257 private final static class OnPermissionChangeListeners extends Handler { 20258 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20259 20260 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20261 new RemoteCallbackList<>(); 20262 20263 public OnPermissionChangeListeners(Looper looper) { 20264 super(looper); 20265 } 20266 20267 @Override 20268 public void handleMessage(Message msg) { 20269 switch (msg.what) { 20270 case MSG_ON_PERMISSIONS_CHANGED: { 20271 final int uid = msg.arg1; 20272 handleOnPermissionsChanged(uid); 20273 } break; 20274 } 20275 } 20276 20277 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20278 mPermissionListeners.register(listener); 20279 20280 } 20281 20282 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20283 mPermissionListeners.unregister(listener); 20284 } 20285 20286 public void onPermissionsChanged(int uid) { 20287 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20288 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20289 } 20290 } 20291 20292 private void handleOnPermissionsChanged(int uid) { 20293 final int count = mPermissionListeners.beginBroadcast(); 20294 try { 20295 for (int i = 0; i < count; i++) { 20296 IOnPermissionsChangeListener callback = mPermissionListeners 20297 .getBroadcastItem(i); 20298 try { 20299 callback.onPermissionsChanged(uid); 20300 } catch (RemoteException e) { 20301 Log.e(TAG, "Permission listener is dead", e); 20302 } 20303 } 20304 } finally { 20305 mPermissionListeners.finishBroadcast(); 20306 } 20307 } 20308 } 20309 20310 private class PackageManagerInternalImpl extends PackageManagerInternal { 20311 @Override 20312 public void setLocationPackagesProvider(PackagesProvider provider) { 20313 synchronized (mPackages) { 20314 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20315 } 20316 } 20317 20318 @Override 20319 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20320 synchronized (mPackages) { 20321 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20322 } 20323 } 20324 20325 @Override 20326 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20327 synchronized (mPackages) { 20328 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20329 } 20330 } 20331 20332 @Override 20333 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20334 synchronized (mPackages) { 20335 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20336 } 20337 } 20338 20339 @Override 20340 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20341 synchronized (mPackages) { 20342 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20343 } 20344 } 20345 20346 @Override 20347 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20348 synchronized (mPackages) { 20349 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20350 } 20351 } 20352 20353 @Override 20354 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20355 synchronized (mPackages) { 20356 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20357 packageName, userId); 20358 } 20359 } 20360 20361 @Override 20362 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20363 synchronized (mPackages) { 20364 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20365 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20366 packageName, userId); 20367 } 20368 } 20369 20370 @Override 20371 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20372 synchronized (mPackages) { 20373 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20374 packageName, userId); 20375 } 20376 } 20377 20378 @Override 20379 public void setKeepUninstalledPackages(final List<String> packageList) { 20380 Preconditions.checkNotNull(packageList); 20381 List<String> removedFromList = null; 20382 synchronized (mPackages) { 20383 if (mKeepUninstalledPackages != null) { 20384 final int packagesCount = mKeepUninstalledPackages.size(); 20385 for (int i = 0; i < packagesCount; i++) { 20386 String oldPackage = mKeepUninstalledPackages.get(i); 20387 if (packageList != null && packageList.contains(oldPackage)) { 20388 continue; 20389 } 20390 if (removedFromList == null) { 20391 removedFromList = new ArrayList<>(); 20392 } 20393 removedFromList.add(oldPackage); 20394 } 20395 } 20396 mKeepUninstalledPackages = new ArrayList<>(packageList); 20397 if (removedFromList != null) { 20398 final int removedCount = removedFromList.size(); 20399 for (int i = 0; i < removedCount; i++) { 20400 deletePackageIfUnusedLPr(removedFromList.get(i)); 20401 } 20402 } 20403 } 20404 } 20405 20406 @Override 20407 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20408 synchronized (mPackages) { 20409 // If we do not support permission review, done. 20410 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20411 return false; 20412 } 20413 20414 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20415 if (packageSetting == null) { 20416 return false; 20417 } 20418 20419 // Permission review applies only to apps not supporting the new permission model. 20420 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20421 return false; 20422 } 20423 20424 // Legacy apps have the permission and get user consent on launch. 20425 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20426 return permissionsState.isPermissionReviewRequired(userId); 20427 } 20428 } 20429 20430 @Override 20431 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20432 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20433 } 20434 20435 @Override 20436 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20437 int userId) { 20438 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20439 } 20440 } 20441 20442 @Override 20443 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20444 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20445 synchronized (mPackages) { 20446 final long identity = Binder.clearCallingIdentity(); 20447 try { 20448 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20449 packageNames, userId); 20450 } finally { 20451 Binder.restoreCallingIdentity(identity); 20452 } 20453 } 20454 } 20455 20456 private static void enforceSystemOrPhoneCaller(String tag) { 20457 int callingUid = Binder.getCallingUid(); 20458 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20459 throw new SecurityException( 20460 "Cannot call " + tag + " from UID " + callingUid); 20461 } 20462 } 20463 20464 boolean isHistoricalPackageUsageAvailable() { 20465 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20466 } 20467 20468 /** 20469 * Return a <b>copy</b> of the collection of packages known to the package manager. 20470 * @return A copy of the values of mPackages. 20471 */ 20472 Collection<PackageParser.Package> getPackages() { 20473 synchronized (mPackages) { 20474 return new ArrayList<>(mPackages.values()); 20475 } 20476 } 20477 20478 /** 20479 * Logs process start information (including base APK hash) to the security log. 20480 * @hide 20481 */ 20482 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20483 String apkFile, int pid) { 20484 if (!SecurityLog.isLoggingEnabled()) { 20485 return; 20486 } 20487 Bundle data = new Bundle(); 20488 data.putLong("startTimestamp", System.currentTimeMillis()); 20489 data.putString("processName", processName); 20490 data.putInt("uid", uid); 20491 data.putString("seinfo", seinfo); 20492 data.putString("apkFile", apkFile); 20493 data.putInt("pid", pid); 20494 Message msg = mProcessLoggingHandler.obtainMessage( 20495 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20496 msg.setData(data); 20497 mProcessLoggingHandler.sendMessage(msg); 20498 } 20499} 20500