PackageManagerService.java revision 1475701100d07af2fad563891082d7712e385950
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.INetworkPolicyManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.security.KeyStore; 201import android.security.SystemKeyStore; 202import android.system.ErrnoException; 203import android.system.Os; 204import android.text.TextUtils; 205import android.text.format.DateUtils; 206import android.util.ArrayMap; 207import android.util.ArraySet; 208import android.util.AtomicFile; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.EventLogTags; 243import com.android.server.FgThread; 244import com.android.server.IntentResolver; 245import com.android.server.LocalServices; 246import com.android.server.ServiceThread; 247import com.android.server.SystemConfig; 248import com.android.server.Watchdog; 249import com.android.server.net.NetworkPolicyManagerInternal; 250import com.android.server.pm.PermissionsState.PermissionState; 251import com.android.server.pm.Settings.DatabaseVersion; 252import com.android.server.pm.Settings.VersionInfo; 253import com.android.server.storage.DeviceStorageMonitorInternal; 254 255import dalvik.system.CloseGuard; 256import dalvik.system.DexFile; 257import dalvik.system.VMRuntime; 258 259import libcore.io.IoUtils; 260import libcore.util.EmptyArray; 261 262import org.xmlpull.v1.XmlPullParser; 263import org.xmlpull.v1.XmlPullParserException; 264import org.xmlpull.v1.XmlSerializer; 265 266import java.io.BufferedInputStream; 267import java.io.BufferedOutputStream; 268import java.io.BufferedReader; 269import java.io.ByteArrayInputStream; 270import java.io.ByteArrayOutputStream; 271import java.io.File; 272import java.io.FileDescriptor; 273import java.io.FileInputStream; 274import java.io.FileNotFoundException; 275import java.io.FileOutputStream; 276import java.io.FileReader; 277import java.io.FilenameFilter; 278import java.io.IOException; 279import java.io.InputStream; 280import java.io.PrintWriter; 281import java.nio.charset.StandardCharsets; 282import java.security.DigestInputStream; 283import java.security.MessageDigest; 284import java.security.NoSuchAlgorithmException; 285import java.security.PublicKey; 286import java.security.cert.Certificate; 287import java.security.cert.CertificateEncodingException; 288import java.security.cert.CertificateException; 289import java.text.SimpleDateFormat; 290import java.util.ArrayList; 291import java.util.Arrays; 292import java.util.Collection; 293import java.util.Collections; 294import java.util.Comparator; 295import java.util.Date; 296import java.util.HashSet; 297import java.util.Iterator; 298import java.util.List; 299import java.util.Map; 300import java.util.Objects; 301import java.util.Set; 302import java.util.concurrent.CountDownLatch; 303import java.util.concurrent.TimeUnit; 304import java.util.concurrent.atomic.AtomicBoolean; 305import java.util.concurrent.atomic.AtomicInteger; 306import java.util.concurrent.atomic.AtomicLong; 307 308/** 309 * Keep track of all those APKs everywhere. 310 * <p> 311 * Internally there are two important locks: 312 * <ul> 313 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 314 * and other related state. It is a fine-grained lock that should only be held 315 * momentarily, as it's one of the most contended locks in the system. 316 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 317 * operations typically involve heavy lifting of application data on disk. Since 318 * {@code installd} is single-threaded, and it's operations can often be slow, 319 * this lock should never be acquired while already holding {@link #mPackages}. 320 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 321 * holding {@link #mInstallLock}. 322 * </ul> 323 * Many internal methods rely on the caller to hold the appropriate locks, and 324 * this contract is expressed through method name suffixes: 325 * <ul> 326 * <li>fooLI(): the caller must hold {@link #mInstallLock} 327 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 328 * being modified must be frozen 329 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 330 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 331 * </ul> 332 * <p> 333 * Because this class is very central to the platform's security; please run all 334 * CTS and unit tests whenever making modifications: 335 * 336 * <pre> 337 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 338 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 339 * </pre> 340 */ 341public class PackageManagerService extends IPackageManager.Stub { 342 static final String TAG = "PackageManager"; 343 static final boolean DEBUG_SETTINGS = false; 344 static final boolean DEBUG_PREFERRED = false; 345 static final boolean DEBUG_UPGRADE = false; 346 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 347 private static final boolean DEBUG_BACKUP = false; 348 private static final boolean DEBUG_INSTALL = false; 349 private static final boolean DEBUG_REMOVE = false; 350 private static final boolean DEBUG_BROADCASTS = false; 351 private static final boolean DEBUG_SHOW_INFO = false; 352 private static final boolean DEBUG_PACKAGE_INFO = false; 353 private static final boolean DEBUG_INTENT_MATCHING = false; 354 private static final boolean DEBUG_PACKAGE_SCANNING = false; 355 private static final boolean DEBUG_VERIFY = false; 356 private static final boolean DEBUG_FILTERS = false; 357 358 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 359 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 360 // user, but by default initialize to this. 361 static final boolean DEBUG_DEXOPT = false; 362 363 private static final boolean DEBUG_ABI_SELECTION = false; 364 private static final boolean DEBUG_EPHEMERAL = false; 365 private static final boolean DEBUG_TRIAGED_MISSING = false; 366 private static final boolean DEBUG_APP_DATA = false; 367 368 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 369 370 private static final boolean DISABLE_EPHEMERAL_APPS = true; 371 372 private static final int RADIO_UID = Process.PHONE_UID; 373 private static final int LOG_UID = Process.LOG_UID; 374 private static final int NFC_UID = Process.NFC_UID; 375 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 376 private static final int SHELL_UID = Process.SHELL_UID; 377 378 // Cap the size of permission trees that 3rd party apps can define 379 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 380 381 // Suffix used during package installation when copying/moving 382 // package apks to install directory. 383 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 384 385 static final int SCAN_NO_DEX = 1<<1; 386 static final int SCAN_FORCE_DEX = 1<<2; 387 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 388 static final int SCAN_NEW_INSTALL = 1<<4; 389 static final int SCAN_NO_PATHS = 1<<5; 390 static final int SCAN_UPDATE_TIME = 1<<6; 391 static final int SCAN_DEFER_DEX = 1<<7; 392 static final int SCAN_BOOTING = 1<<8; 393 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 394 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 395 static final int SCAN_REPLACING = 1<<11; 396 static final int SCAN_REQUIRE_KNOWN = 1<<12; 397 static final int SCAN_MOVE = 1<<13; 398 static final int SCAN_INITIAL = 1<<14; 399 static final int SCAN_CHECK_ONLY = 1<<15; 400 static final int SCAN_DONT_KILL_APP = 1<<17; 401 static final int SCAN_IGNORE_FROZEN = 1<<18; 402 403 static final int REMOVE_CHATTY = 1<<16; 404 405 private static final int[] EMPTY_INT_ARRAY = new int[0]; 406 407 /** 408 * Timeout (in milliseconds) after which the watchdog should declare that 409 * our handler thread is wedged. The usual default for such things is one 410 * minute but we sometimes do very lengthy I/O operations on this thread, 411 * such as installing multi-gigabyte applications, so ours needs to be longer. 412 */ 413 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 414 415 /** 416 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 417 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 418 * settings entry if available, otherwise we use the hardcoded default. If it's been 419 * more than this long since the last fstrim, we force one during the boot sequence. 420 * 421 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 422 * one gets run at the next available charging+idle time. This final mandatory 423 * no-fstrim check kicks in only of the other scheduling criteria is never met. 424 */ 425 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 426 427 /** 428 * Whether verification is enabled by default. 429 */ 430 private static final boolean DEFAULT_VERIFY_ENABLE = true; 431 432 /** 433 * The default maximum time to wait for the verification agent to return in 434 * milliseconds. 435 */ 436 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 437 438 /** 439 * The default response for package verification timeout. 440 * 441 * This can be either PackageManager.VERIFICATION_ALLOW or 442 * PackageManager.VERIFICATION_REJECT. 443 */ 444 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 445 446 static final String PLATFORM_PACKAGE_NAME = "android"; 447 448 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 449 450 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 451 DEFAULT_CONTAINER_PACKAGE, 452 "com.android.defcontainer.DefaultContainerService"); 453 454 private static final String KILL_APP_REASON_GIDS_CHANGED = 455 "permission grant or revoke changed gids"; 456 457 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 458 "permissions revoked"; 459 460 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 461 462 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 463 464 /** Permission grant: not grant the permission. */ 465 private static final int GRANT_DENIED = 1; 466 467 /** Permission grant: grant the permission as an install permission. */ 468 private static final int GRANT_INSTALL = 2; 469 470 /** Permission grant: grant the permission as a runtime one. */ 471 private static final int GRANT_RUNTIME = 3; 472 473 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 474 private static final int GRANT_UPGRADE = 4; 475 476 /** Canonical intent used to identify what counts as a "web browser" app */ 477 private static final Intent sBrowserIntent; 478 static { 479 sBrowserIntent = new Intent(); 480 sBrowserIntent.setAction(Intent.ACTION_VIEW); 481 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 482 sBrowserIntent.setData(Uri.parse("http:")); 483 } 484 485 /** 486 * The set of all protected actions [i.e. those actions for which a high priority 487 * intent filter is disallowed]. 488 */ 489 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 490 static { 491 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 492 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 494 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 495 } 496 497 // Compilation reasons. 498 public static final int REASON_FIRST_BOOT = 0; 499 public static final int REASON_BOOT = 1; 500 public static final int REASON_INSTALL = 2; 501 public static final int REASON_BACKGROUND_DEXOPT = 3; 502 public static final int REASON_AB_OTA = 4; 503 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 504 public static final int REASON_SHARED_APK = 6; 505 public static final int REASON_FORCED_DEXOPT = 7; 506 507 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 508 509 /** Special library name that skips shared libraries check during compilation. */ 510 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 511 512 final ServiceThread mHandlerThread; 513 514 final PackageHandler mHandler; 515 516 private final ProcessLoggingHandler mProcessLoggingHandler; 517 518 /** 519 * Messages for {@link #mHandler} that need to wait for system ready before 520 * being dispatched. 521 */ 522 private ArrayList<Message> mPostSystemReadyMessages; 523 524 final int mSdkVersion = Build.VERSION.SDK_INT; 525 526 final Context mContext; 527 final boolean mFactoryTest; 528 final boolean mOnlyCore; 529 final DisplayMetrics mMetrics; 530 final int mDefParseFlags; 531 final String[] mSeparateProcesses; 532 final boolean mIsUpgrade; 533 final boolean mIsPreNUpgrade; 534 535 /** The location for ASEC container files on internal storage. */ 536 final String mAsecInternalPath; 537 538 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 539 // LOCK HELD. Can be called with mInstallLock held. 540 @GuardedBy("mInstallLock") 541 final Installer mInstaller; 542 543 /** Directory where installed third-party apps stored */ 544 final File mAppInstallDir; 545 final File mEphemeralInstallDir; 546 547 /** 548 * Directory to which applications installed internally have their 549 * 32 bit native libraries copied. 550 */ 551 private File mAppLib32InstallDir; 552 553 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 554 // apps. 555 final File mDrmAppPrivateInstallDir; 556 557 // ---------------------------------------------------------------- 558 559 // Lock for state used when installing and doing other long running 560 // operations. Methods that must be called with this lock held have 561 // the suffix "LI". 562 final Object mInstallLock = new Object(); 563 564 // ---------------------------------------------------------------- 565 566 // Keys are String (package name), values are Package. This also serves 567 // as the lock for the global state. Methods that must be called with 568 // this lock held have the prefix "LP". 569 @GuardedBy("mPackages") 570 final ArrayMap<String, PackageParser.Package> mPackages = 571 new ArrayMap<String, PackageParser.Package>(); 572 573 final ArrayMap<String, Set<String>> mKnownCodebase = 574 new ArrayMap<String, Set<String>>(); 575 576 // Tracks available target package names -> overlay package paths. 577 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 578 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 579 580 /** 581 * Tracks new system packages [received in an OTA] that we expect to 582 * find updated user-installed versions. Keys are package name, values 583 * are package location. 584 */ 585 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 586 /** 587 * Tracks high priority intent filters for protected actions. During boot, certain 588 * filter actions are protected and should never be allowed to have a high priority 589 * intent filter for them. However, there is one, and only one exception -- the 590 * setup wizard. It must be able to define a high priority intent filter for these 591 * actions to ensure there are no escapes from the wizard. We need to delay processing 592 * of these during boot as we need to look at all of the system packages in order 593 * to know which component is the setup wizard. 594 */ 595 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 596 /** 597 * Whether or not processing protected filters should be deferred. 598 */ 599 private boolean mDeferProtectedFilters = true; 600 601 /** 602 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 603 */ 604 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 605 /** 606 * Whether or not system app permissions should be promoted from install to runtime. 607 */ 608 boolean mPromoteSystemApps; 609 610 @GuardedBy("mPackages") 611 final Settings mSettings; 612 613 /** 614 * Set of package names that are currently "frozen", which means active 615 * surgery is being done on the code/data for that package. The platform 616 * will refuse to launch frozen packages to avoid race conditions. 617 * 618 * @see PackageFreezer 619 */ 620 @GuardedBy("mPackages") 621 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 622 623 boolean mRestoredSettings; 624 625 // System configuration read by SystemConfig. 626 final int[] mGlobalGids; 627 final SparseArray<ArraySet<String>> mSystemPermissions; 628 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 629 630 // If mac_permissions.xml was found for seinfo labeling. 631 boolean mFoundPolicyFile; 632 633 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 634 635 public static final class SharedLibraryEntry { 636 public final String path; 637 public final String apk; 638 639 SharedLibraryEntry(String _path, String _apk) { 640 path = _path; 641 apk = _apk; 642 } 643 } 644 645 // Currently known shared libraries. 646 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 647 new ArrayMap<String, SharedLibraryEntry>(); 648 649 // All available activities, for your resolving pleasure. 650 final ActivityIntentResolver mActivities = 651 new ActivityIntentResolver(); 652 653 // All available receivers, for your resolving pleasure. 654 final ActivityIntentResolver mReceivers = 655 new ActivityIntentResolver(); 656 657 // All available services, for your resolving pleasure. 658 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 659 660 // All available providers, for your resolving pleasure. 661 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 662 663 // Mapping from provider base names (first directory in content URI codePath) 664 // to the provider information. 665 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 666 new ArrayMap<String, PackageParser.Provider>(); 667 668 // Mapping from instrumentation class names to info about them. 669 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 670 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 671 672 // Mapping from permission names to info about them. 673 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 674 new ArrayMap<String, PackageParser.PermissionGroup>(); 675 676 // Packages whose data we have transfered into another package, thus 677 // should no longer exist. 678 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 679 680 // Broadcast actions that are only available to the system. 681 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 682 683 /** List of packages waiting for verification. */ 684 final SparseArray<PackageVerificationState> mPendingVerification 685 = new SparseArray<PackageVerificationState>(); 686 687 /** Set of packages associated with each app op permission. */ 688 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 689 690 final PackageInstallerService mInstallerService; 691 692 private final PackageDexOptimizer mPackageDexOptimizer; 693 694 private AtomicInteger mNextMoveId = new AtomicInteger(); 695 private final MoveCallbacks mMoveCallbacks; 696 697 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 698 699 // Cache of users who need badging. 700 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 701 702 /** Token for keys in mPendingVerification. */ 703 private int mPendingVerificationToken = 0; 704 705 volatile boolean mSystemReady; 706 volatile boolean mSafeMode; 707 volatile boolean mHasSystemUidErrors; 708 709 ApplicationInfo mAndroidApplication; 710 final ActivityInfo mResolveActivity = new ActivityInfo(); 711 final ResolveInfo mResolveInfo = new ResolveInfo(); 712 ComponentName mResolveComponentName; 713 PackageParser.Package mPlatformPackage; 714 ComponentName mCustomResolverComponentName; 715 716 boolean mResolverReplaced = false; 717 718 private final @Nullable ComponentName mIntentFilterVerifierComponent; 719 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 720 721 private int mIntentFilterVerificationToken = 0; 722 723 /** Component that knows whether or not an ephemeral application exists */ 724 final ComponentName mEphemeralResolverComponent; 725 /** The service connection to the ephemeral resolver */ 726 final EphemeralResolverConnection mEphemeralResolverConnection; 727 728 /** Component used to install ephemeral applications */ 729 final ComponentName mEphemeralInstallerComponent; 730 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 731 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 732 733 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 734 = new SparseArray<IntentFilterVerificationState>(); 735 736 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 737 new DefaultPermissionGrantPolicy(this); 738 739 // List of packages names to keep cached, even if they are uninstalled for all users 740 private List<String> mKeepUninstalledPackages; 741 742 private UserManagerInternal mUserManagerInternal; 743 744 private static class IFVerificationParams { 745 PackageParser.Package pkg; 746 boolean replacing; 747 int userId; 748 int verifierUid; 749 750 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 751 int _userId, int _verifierUid) { 752 pkg = _pkg; 753 replacing = _replacing; 754 userId = _userId; 755 replacing = _replacing; 756 verifierUid = _verifierUid; 757 } 758 } 759 760 private interface IntentFilterVerifier<T extends IntentFilter> { 761 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 762 T filter, String packageName); 763 void startVerifications(int userId); 764 void receiveVerificationResponse(int verificationId); 765 } 766 767 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 768 private Context mContext; 769 private ComponentName mIntentFilterVerifierComponent; 770 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 771 772 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 773 mContext = context; 774 mIntentFilterVerifierComponent = verifierComponent; 775 } 776 777 private String getDefaultScheme() { 778 return IntentFilter.SCHEME_HTTPS; 779 } 780 781 @Override 782 public void startVerifications(int userId) { 783 // Launch verifications requests 784 int count = mCurrentIntentFilterVerifications.size(); 785 for (int n=0; n<count; n++) { 786 int verificationId = mCurrentIntentFilterVerifications.get(n); 787 final IntentFilterVerificationState ivs = 788 mIntentFilterVerificationStates.get(verificationId); 789 790 String packageName = ivs.getPackageName(); 791 792 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 793 final int filterCount = filters.size(); 794 ArraySet<String> domainsSet = new ArraySet<>(); 795 for (int m=0; m<filterCount; m++) { 796 PackageParser.ActivityIntentInfo filter = filters.get(m); 797 domainsSet.addAll(filter.getHostsList()); 798 } 799 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 800 synchronized (mPackages) { 801 if (mSettings.createIntentFilterVerificationIfNeededLPw( 802 packageName, domainsList) != null) { 803 scheduleWriteSettingsLocked(); 804 } 805 } 806 sendVerificationRequest(userId, verificationId, ivs); 807 } 808 mCurrentIntentFilterVerifications.clear(); 809 } 810 811 private void sendVerificationRequest(int userId, int verificationId, 812 IntentFilterVerificationState ivs) { 813 814 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 815 verificationIntent.putExtra( 816 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 817 verificationId); 818 verificationIntent.putExtra( 819 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 820 getDefaultScheme()); 821 verificationIntent.putExtra( 822 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 823 ivs.getHostsString()); 824 verificationIntent.putExtra( 825 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 826 ivs.getPackageName()); 827 verificationIntent.setComponent(mIntentFilterVerifierComponent); 828 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 829 830 UserHandle user = new UserHandle(userId); 831 mContext.sendBroadcastAsUser(verificationIntent, user); 832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 833 "Sending IntentFilter verification broadcast"); 834 } 835 836 public void receiveVerificationResponse(int verificationId) { 837 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 838 839 final boolean verified = ivs.isVerified(); 840 841 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 842 final int count = filters.size(); 843 if (DEBUG_DOMAIN_VERIFICATION) { 844 Slog.i(TAG, "Received verification response " + verificationId 845 + " for " + count + " filters, verified=" + verified); 846 } 847 for (int n=0; n<count; n++) { 848 PackageParser.ActivityIntentInfo filter = filters.get(n); 849 filter.setVerified(verified); 850 851 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 852 + " verified with result:" + verified + " and hosts:" 853 + ivs.getHostsString()); 854 } 855 856 mIntentFilterVerificationStates.remove(verificationId); 857 858 final String packageName = ivs.getPackageName(); 859 IntentFilterVerificationInfo ivi = null; 860 861 synchronized (mPackages) { 862 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 863 } 864 if (ivi == null) { 865 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 866 + verificationId + " packageName:" + packageName); 867 return; 868 } 869 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 870 "Updating IntentFilterVerificationInfo for package " + packageName 871 +" verificationId:" + verificationId); 872 873 synchronized (mPackages) { 874 if (verified) { 875 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 876 } else { 877 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 878 } 879 scheduleWriteSettingsLocked(); 880 881 final int userId = ivs.getUserId(); 882 if (userId != UserHandle.USER_ALL) { 883 final int userStatus = 884 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 885 886 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 887 boolean needUpdate = false; 888 889 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 890 // already been set by the User thru the Disambiguation dialog 891 switch (userStatus) { 892 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 893 if (verified) { 894 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 895 } else { 896 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 897 } 898 needUpdate = true; 899 break; 900 901 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 902 if (verified) { 903 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 904 needUpdate = true; 905 } 906 break; 907 908 default: 909 // Nothing to do 910 } 911 912 if (needUpdate) { 913 mSettings.updateIntentFilterVerificationStatusLPw( 914 packageName, updatedStatus, userId); 915 scheduleWritePackageRestrictionsLocked(userId); 916 } 917 } 918 } 919 } 920 921 @Override 922 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 923 ActivityIntentInfo filter, String packageName) { 924 if (!hasValidDomains(filter)) { 925 return false; 926 } 927 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 928 if (ivs == null) { 929 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 930 packageName); 931 } 932 if (DEBUG_DOMAIN_VERIFICATION) { 933 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 934 } 935 ivs.addFilter(filter); 936 return true; 937 } 938 939 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 940 int userId, int verificationId, String packageName) { 941 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 942 verifierUid, userId, packageName); 943 ivs.setPendingState(); 944 synchronized (mPackages) { 945 mIntentFilterVerificationStates.append(verificationId, ivs); 946 mCurrentIntentFilterVerifications.add(verificationId); 947 } 948 return ivs; 949 } 950 } 951 952 private static boolean hasValidDomains(ActivityIntentInfo filter) { 953 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 954 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 955 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 956 } 957 958 // Set of pending broadcasts for aggregating enable/disable of components. 959 static class PendingPackageBroadcasts { 960 // for each user id, a map of <package name -> components within that package> 961 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 962 963 public PendingPackageBroadcasts() { 964 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 965 } 966 967 public ArrayList<String> get(int userId, String packageName) { 968 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 969 return packages.get(packageName); 970 } 971 972 public void put(int userId, String packageName, ArrayList<String> components) { 973 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 974 packages.put(packageName, components); 975 } 976 977 public void remove(int userId, String packageName) { 978 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 979 if (packages != null) { 980 packages.remove(packageName); 981 } 982 } 983 984 public void remove(int userId) { 985 mUidMap.remove(userId); 986 } 987 988 public int userIdCount() { 989 return mUidMap.size(); 990 } 991 992 public int userIdAt(int n) { 993 return mUidMap.keyAt(n); 994 } 995 996 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 997 return mUidMap.get(userId); 998 } 999 1000 public int size() { 1001 // total number of pending broadcast entries across all userIds 1002 int num = 0; 1003 for (int i = 0; i< mUidMap.size(); i++) { 1004 num += mUidMap.valueAt(i).size(); 1005 } 1006 return num; 1007 } 1008 1009 public void clear() { 1010 mUidMap.clear(); 1011 } 1012 1013 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1014 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1015 if (map == null) { 1016 map = new ArrayMap<String, ArrayList<String>>(); 1017 mUidMap.put(userId, map); 1018 } 1019 return map; 1020 } 1021 } 1022 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1023 1024 // Service Connection to remote media container service to copy 1025 // package uri's from external media onto secure containers 1026 // or internal storage. 1027 private IMediaContainerService mContainerService = null; 1028 1029 static final int SEND_PENDING_BROADCAST = 1; 1030 static final int MCS_BOUND = 3; 1031 static final int END_COPY = 4; 1032 static final int INIT_COPY = 5; 1033 static final int MCS_UNBIND = 6; 1034 static final int START_CLEANING_PACKAGE = 7; 1035 static final int FIND_INSTALL_LOC = 8; 1036 static final int POST_INSTALL = 9; 1037 static final int MCS_RECONNECT = 10; 1038 static final int MCS_GIVE_UP = 11; 1039 static final int UPDATED_MEDIA_STATUS = 12; 1040 static final int WRITE_SETTINGS = 13; 1041 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1042 static final int PACKAGE_VERIFIED = 15; 1043 static final int CHECK_PENDING_VERIFICATION = 16; 1044 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1045 static final int INTENT_FILTER_VERIFIED = 18; 1046 1047 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1048 1049 // Delay time in millisecs 1050 static final int BROADCAST_DELAY = 10 * 1000; 1051 1052 static UserManagerService sUserManager; 1053 1054 // Stores a list of users whose package restrictions file needs to be updated 1055 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1056 1057 final private DefaultContainerConnection mDefContainerConn = 1058 new DefaultContainerConnection(); 1059 class DefaultContainerConnection implements ServiceConnection { 1060 public void onServiceConnected(ComponentName name, IBinder service) { 1061 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1062 IMediaContainerService imcs = 1063 IMediaContainerService.Stub.asInterface(service); 1064 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1065 } 1066 1067 public void onServiceDisconnected(ComponentName name) { 1068 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1069 } 1070 } 1071 1072 // Recordkeeping of restore-after-install operations that are currently in flight 1073 // between the Package Manager and the Backup Manager 1074 static class PostInstallData { 1075 public InstallArgs args; 1076 public PackageInstalledInfo res; 1077 1078 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1079 args = _a; 1080 res = _r; 1081 } 1082 } 1083 1084 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1085 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1086 1087 // XML tags for backup/restore of various bits of state 1088 private static final String TAG_PREFERRED_BACKUP = "pa"; 1089 private static final String TAG_DEFAULT_APPS = "da"; 1090 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1091 1092 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1093 private static final String TAG_ALL_GRANTS = "rt-grants"; 1094 private static final String TAG_GRANT = "grant"; 1095 private static final String ATTR_PACKAGE_NAME = "pkg"; 1096 1097 private static final String TAG_PERMISSION = "perm"; 1098 private static final String ATTR_PERMISSION_NAME = "name"; 1099 private static final String ATTR_IS_GRANTED = "g"; 1100 private static final String ATTR_USER_SET = "set"; 1101 private static final String ATTR_USER_FIXED = "fixed"; 1102 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1103 1104 // System/policy permission grants are not backed up 1105 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1106 FLAG_PERMISSION_POLICY_FIXED 1107 | FLAG_PERMISSION_SYSTEM_FIXED 1108 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1109 1110 // And we back up these user-adjusted states 1111 private static final int USER_RUNTIME_GRANT_MASK = 1112 FLAG_PERMISSION_USER_SET 1113 | FLAG_PERMISSION_USER_FIXED 1114 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1115 1116 final @Nullable String mRequiredVerifierPackage; 1117 final @NonNull String mRequiredInstallerPackage; 1118 final @Nullable String mSetupWizardPackage; 1119 final @NonNull String mServicesSystemSharedLibraryPackageName; 1120 final @NonNull String mSharedSystemSharedLibraryPackageName; 1121 1122 private final PackageUsage mPackageUsage = new PackageUsage(); 1123 1124 private class PackageUsage { 1125 private static final int WRITE_INTERVAL 1126 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1127 1128 private final Object mFileLock = new Object(); 1129 private final AtomicLong mLastWritten = new AtomicLong(0); 1130 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1131 1132 private boolean mIsHistoricalPackageUsageAvailable = true; 1133 1134 boolean isHistoricalPackageUsageAvailable() { 1135 return mIsHistoricalPackageUsageAvailable; 1136 } 1137 1138 void write(boolean force) { 1139 if (force) { 1140 writeInternal(); 1141 return; 1142 } 1143 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1144 && !DEBUG_DEXOPT) { 1145 return; 1146 } 1147 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1148 new Thread("PackageUsage_DiskWriter") { 1149 @Override 1150 public void run() { 1151 try { 1152 writeInternal(); 1153 } finally { 1154 mBackgroundWriteRunning.set(false); 1155 } 1156 } 1157 }.start(); 1158 } 1159 } 1160 1161 private void writeInternal() { 1162 synchronized (mPackages) { 1163 synchronized (mFileLock) { 1164 AtomicFile file = getFile(); 1165 FileOutputStream f = null; 1166 try { 1167 f = file.startWrite(); 1168 BufferedOutputStream out = new BufferedOutputStream(f); 1169 FileUtils.setPermissions(file.getBaseFile().getPath(), 1170 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1171 StringBuilder sb = new StringBuilder(); 1172 1173 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1174 sb.append('\n'); 1175 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1176 1177 for (PackageParser.Package pkg : mPackages.values()) { 1178 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1179 continue; 1180 } 1181 sb.setLength(0); 1182 sb.append(pkg.packageName); 1183 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1184 sb.append(' '); 1185 sb.append(usageTimeInMillis); 1186 } 1187 sb.append('\n'); 1188 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1189 } 1190 out.flush(); 1191 file.finishWrite(f); 1192 } catch (IOException e) { 1193 if (f != null) { 1194 file.failWrite(f); 1195 } 1196 Log.e(TAG, "Failed to write package usage times", e); 1197 } 1198 } 1199 } 1200 mLastWritten.set(SystemClock.elapsedRealtime()); 1201 } 1202 1203 void readLP() { 1204 synchronized (mFileLock) { 1205 AtomicFile file = getFile(); 1206 BufferedInputStream in = null; 1207 try { 1208 in = new BufferedInputStream(file.openRead()); 1209 StringBuffer sb = new StringBuffer(); 1210 1211 String firstLine = readLine(in, sb); 1212 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1213 readVersion1LP(in, sb); 1214 } else { 1215 readVersion0LP(in, sb, firstLine); 1216 } 1217 } catch (FileNotFoundException expected) { 1218 mIsHistoricalPackageUsageAvailable = false; 1219 } catch (IOException e) { 1220 Log.w(TAG, "Failed to read package usage times", e); 1221 } finally { 1222 IoUtils.closeQuietly(in); 1223 } 1224 } 1225 mLastWritten.set(SystemClock.elapsedRealtime()); 1226 } 1227 1228 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1229 throws IOException { 1230 // Initial version of the file had no version number and stored one 1231 // package-timestamp pair per line. 1232 // Note that the first line has already been read from the InputStream. 1233 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1234 String[] tokens = line.split(" "); 1235 if (tokens.length != 2) { 1236 throw new IOException("Failed to parse " + line + 1237 " as package-timestamp pair."); 1238 } 1239 1240 String packageName = tokens[0]; 1241 PackageParser.Package pkg = mPackages.get(packageName); 1242 if (pkg == null) { 1243 continue; 1244 } 1245 1246 long timestamp = parseAsLong(tokens[1]); 1247 for (int reason = 0; 1248 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1249 reason++) { 1250 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1251 } 1252 } 1253 } 1254 1255 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1256 // Version 1 of the file started with the corresponding version 1257 // number and then stored a package name and eight timestamps per line. 1258 String line; 1259 while ((line = readLine(in, sb)) != null) { 1260 String[] tokens = line.split(" "); 1261 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1262 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1263 } 1264 1265 String packageName = tokens[0]; 1266 PackageParser.Package pkg = mPackages.get(packageName); 1267 if (pkg == null) { 1268 continue; 1269 } 1270 1271 for (int reason = 0; 1272 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1273 reason++) { 1274 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1275 } 1276 } 1277 } 1278 1279 private long parseAsLong(String token) throws IOException { 1280 try { 1281 return Long.parseLong(token); 1282 } catch (NumberFormatException e) { 1283 throw new IOException("Failed to parse " + token + " as a long.", e); 1284 } 1285 } 1286 1287 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1288 return readToken(in, sb, '\n'); 1289 } 1290 1291 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1292 throws IOException { 1293 sb.setLength(0); 1294 while (true) { 1295 int ch = in.read(); 1296 if (ch == -1) { 1297 if (sb.length() == 0) { 1298 return null; 1299 } 1300 throw new IOException("Unexpected EOF"); 1301 } 1302 if (ch == endOfToken) { 1303 return sb.toString(); 1304 } 1305 sb.append((char)ch); 1306 } 1307 } 1308 1309 private AtomicFile getFile() { 1310 File dataDir = Environment.getDataDirectory(); 1311 File systemDir = new File(dataDir, "system"); 1312 File fname = new File(systemDir, "package-usage.list"); 1313 return new AtomicFile(fname); 1314 } 1315 1316 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1317 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1318 } 1319 1320 class PackageHandler extends Handler { 1321 private boolean mBound = false; 1322 final ArrayList<HandlerParams> mPendingInstalls = 1323 new ArrayList<HandlerParams>(); 1324 1325 private boolean connectToService() { 1326 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1327 " DefaultContainerService"); 1328 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1330 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1331 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1333 mBound = true; 1334 return true; 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 return false; 1338 } 1339 1340 private void disconnectService() { 1341 mContainerService = null; 1342 mBound = false; 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1344 mContext.unbindService(mDefContainerConn); 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 } 1347 1348 PackageHandler(Looper looper) { 1349 super(looper); 1350 } 1351 1352 public void handleMessage(Message msg) { 1353 try { 1354 doHandleMessage(msg); 1355 } finally { 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 } 1358 } 1359 1360 void doHandleMessage(Message msg) { 1361 switch (msg.what) { 1362 case INIT_COPY: { 1363 HandlerParams params = (HandlerParams) msg.obj; 1364 int idx = mPendingInstalls.size(); 1365 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1366 // If a bind was already initiated we dont really 1367 // need to do anything. The pending install 1368 // will be processed later on. 1369 if (!mBound) { 1370 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1371 System.identityHashCode(mHandler)); 1372 // If this is the only one pending we might 1373 // have to bind to the service again. 1374 if (!connectToService()) { 1375 Slog.e(TAG, "Failed to bind to media container service"); 1376 params.serviceError(); 1377 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1378 System.identityHashCode(mHandler)); 1379 if (params.traceMethod != null) { 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1381 params.traceCookie); 1382 } 1383 return; 1384 } else { 1385 // Once we bind to the service, the first 1386 // pending request will be processed. 1387 mPendingInstalls.add(idx, params); 1388 } 1389 } else { 1390 mPendingInstalls.add(idx, params); 1391 // Already bound to the service. Just make 1392 // sure we trigger off processing the first request. 1393 if (idx == 0) { 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 } 1397 break; 1398 } 1399 case MCS_BOUND: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1401 if (msg.obj != null) { 1402 mContainerService = (IMediaContainerService) msg.obj; 1403 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1404 System.identityHashCode(mHandler)); 1405 } 1406 if (mContainerService == null) { 1407 if (!mBound) { 1408 // Something seriously wrong since we are not bound and we are not 1409 // waiting for connection. Bail out. 1410 Slog.e(TAG, "Cannot bind to media container service"); 1411 for (HandlerParams params : mPendingInstalls) { 1412 // Indicate service bind error 1413 params.serviceError(); 1414 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1415 System.identityHashCode(params)); 1416 if (params.traceMethod != null) { 1417 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1418 params.traceMethod, params.traceCookie); 1419 } 1420 return; 1421 } 1422 mPendingInstalls.clear(); 1423 } else { 1424 Slog.w(TAG, "Waiting to connect to media container service"); 1425 } 1426 } else if (mPendingInstalls.size() > 0) { 1427 HandlerParams params = mPendingInstalls.get(0); 1428 if (params != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1430 System.identityHashCode(params)); 1431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1432 if (params.startCopy()) { 1433 // We are done... look for more work or to 1434 // go idle. 1435 if (DEBUG_SD_INSTALL) Log.i(TAG, 1436 "Checking for more work or unbind..."); 1437 // Delete pending install 1438 if (mPendingInstalls.size() > 0) { 1439 mPendingInstalls.remove(0); 1440 } 1441 if (mPendingInstalls.size() == 0) { 1442 if (mBound) { 1443 if (DEBUG_SD_INSTALL) Log.i(TAG, 1444 "Posting delayed MCS_UNBIND"); 1445 removeMessages(MCS_UNBIND); 1446 Message ubmsg = obtainMessage(MCS_UNBIND); 1447 // Unbind after a little delay, to avoid 1448 // continual thrashing. 1449 sendMessageDelayed(ubmsg, 10000); 1450 } 1451 } else { 1452 // There are more pending requests in queue. 1453 // Just post MCS_BOUND message to trigger processing 1454 // of next pending install. 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting MCS_BOUND for next work"); 1457 mHandler.sendEmptyMessage(MCS_BOUND); 1458 } 1459 } 1460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1461 } 1462 } else { 1463 // Should never happen ideally. 1464 Slog.w(TAG, "Empty queue"); 1465 } 1466 break; 1467 } 1468 case MCS_RECONNECT: { 1469 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1470 if (mPendingInstalls.size() > 0) { 1471 if (mBound) { 1472 disconnectService(); 1473 } 1474 if (!connectToService()) { 1475 Slog.e(TAG, "Failed to bind to media container service"); 1476 for (HandlerParams params : mPendingInstalls) { 1477 // Indicate service bind error 1478 params.serviceError(); 1479 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1480 System.identityHashCode(params)); 1481 } 1482 mPendingInstalls.clear(); 1483 } 1484 } 1485 break; 1486 } 1487 case MCS_UNBIND: { 1488 // If there is no actual work left, then time to unbind. 1489 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1490 1491 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1492 if (mBound) { 1493 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1494 1495 disconnectService(); 1496 } 1497 } else if (mPendingInstalls.size() > 0) { 1498 // There are more pending requests in queue. 1499 // Just post MCS_BOUND message to trigger processing 1500 // of next pending install. 1501 mHandler.sendEmptyMessage(MCS_BOUND); 1502 } 1503 1504 break; 1505 } 1506 case MCS_GIVE_UP: { 1507 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1508 HandlerParams params = mPendingInstalls.remove(0); 1509 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1510 System.identityHashCode(params)); 1511 break; 1512 } 1513 case SEND_PENDING_BROADCAST: { 1514 String packages[]; 1515 ArrayList<String> components[]; 1516 int size = 0; 1517 int uids[]; 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 if (mPendingBroadcasts == null) { 1521 return; 1522 } 1523 size = mPendingBroadcasts.size(); 1524 if (size <= 0) { 1525 // Nothing to be done. Just return 1526 return; 1527 } 1528 packages = new String[size]; 1529 components = new ArrayList[size]; 1530 uids = new int[size]; 1531 int i = 0; // filling out the above arrays 1532 1533 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1534 int packageUserId = mPendingBroadcasts.userIdAt(n); 1535 Iterator<Map.Entry<String, ArrayList<String>>> it 1536 = mPendingBroadcasts.packagesForUserId(packageUserId) 1537 .entrySet().iterator(); 1538 while (it.hasNext() && i < size) { 1539 Map.Entry<String, ArrayList<String>> ent = it.next(); 1540 packages[i] = ent.getKey(); 1541 components[i] = ent.getValue(); 1542 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1543 uids[i] = (ps != null) 1544 ? UserHandle.getUid(packageUserId, ps.appId) 1545 : -1; 1546 i++; 1547 } 1548 } 1549 size = i; 1550 mPendingBroadcasts.clear(); 1551 } 1552 // Send broadcasts 1553 for (int i = 0; i < size; i++) { 1554 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1555 } 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1557 break; 1558 } 1559 case START_CLEANING_PACKAGE: { 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1561 final String packageName = (String)msg.obj; 1562 final int userId = msg.arg1; 1563 final boolean andCode = msg.arg2 != 0; 1564 synchronized (mPackages) { 1565 if (userId == UserHandle.USER_ALL) { 1566 int[] users = sUserManager.getUserIds(); 1567 for (int user : users) { 1568 mSettings.addPackageToCleanLPw( 1569 new PackageCleanItem(user, packageName, andCode)); 1570 } 1571 } else { 1572 mSettings.addPackageToCleanLPw( 1573 new PackageCleanItem(userId, packageName, andCode)); 1574 } 1575 } 1576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1577 startCleaningPackages(); 1578 } break; 1579 case POST_INSTALL: { 1580 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1581 1582 PostInstallData data = mRunningInstalls.get(msg.arg1); 1583 final boolean didRestore = (msg.arg2 != 0); 1584 mRunningInstalls.delete(msg.arg1); 1585 1586 if (data != null) { 1587 InstallArgs args = data.args; 1588 PackageInstalledInfo parentRes = data.res; 1589 1590 final boolean grantPermissions = (args.installFlags 1591 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1592 final boolean killApp = (args.installFlags 1593 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1594 final String[] grantedPermissions = args.installGrantPermissions; 1595 1596 // Handle the parent package 1597 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1598 grantedPermissions, didRestore, args.installerPackageName, 1599 args.observer); 1600 1601 // Handle the child packages 1602 final int childCount = (parentRes.addedChildPackages != null) 1603 ? parentRes.addedChildPackages.size() : 0; 1604 for (int i = 0; i < childCount; i++) { 1605 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1606 handlePackagePostInstall(childRes, grantPermissions, killApp, 1607 grantedPermissions, false, args.installerPackageName, 1608 args.observer); 1609 } 1610 1611 // Log tracing if needed 1612 if (args.traceMethod != null) { 1613 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1614 args.traceCookie); 1615 } 1616 } else { 1617 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1618 } 1619 1620 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1621 } break; 1622 case UPDATED_MEDIA_STATUS: { 1623 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1624 boolean reportStatus = msg.arg1 == 1; 1625 boolean doGc = msg.arg2 == 1; 1626 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1627 if (doGc) { 1628 // Force a gc to clear up stale containers. 1629 Runtime.getRuntime().gc(); 1630 } 1631 if (msg.obj != null) { 1632 @SuppressWarnings("unchecked") 1633 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1635 // Unload containers 1636 unloadAllContainers(args); 1637 } 1638 if (reportStatus) { 1639 try { 1640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1641 PackageHelper.getMountService().finishMediaUpdate(); 1642 } catch (RemoteException e) { 1643 Log.e(TAG, "MountService not running?"); 1644 } 1645 } 1646 } break; 1647 case WRITE_SETTINGS: { 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1649 synchronized (mPackages) { 1650 removeMessages(WRITE_SETTINGS); 1651 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1652 mSettings.writeLPr(); 1653 mDirtyUsers.clear(); 1654 } 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1656 } break; 1657 case WRITE_PACKAGE_RESTRICTIONS: { 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1659 synchronized (mPackages) { 1660 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1661 for (int userId : mDirtyUsers) { 1662 mSettings.writePackageRestrictionsLPr(userId); 1663 } 1664 mDirtyUsers.clear(); 1665 } 1666 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1667 } break; 1668 case CHECK_PENDING_VERIFICATION: { 1669 final int verificationId = msg.arg1; 1670 final PackageVerificationState state = mPendingVerification.get(verificationId); 1671 1672 if ((state != null) && !state.timeoutExtended()) { 1673 final InstallArgs args = state.getInstallArgs(); 1674 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1675 1676 Slog.i(TAG, "Verification timed out for " + originUri); 1677 mPendingVerification.remove(verificationId); 1678 1679 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1680 1681 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1682 Slog.i(TAG, "Continuing with installation of " + originUri); 1683 state.setVerifierResponse(Binder.getCallingUid(), 1684 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1685 broadcastPackageVerified(verificationId, originUri, 1686 PackageManager.VERIFICATION_ALLOW, 1687 state.getInstallArgs().getUser()); 1688 try { 1689 ret = args.copyApk(mContainerService, true); 1690 } catch (RemoteException e) { 1691 Slog.e(TAG, "Could not contact the ContainerService"); 1692 } 1693 } else { 1694 broadcastPackageVerified(verificationId, originUri, 1695 PackageManager.VERIFICATION_REJECT, 1696 state.getInstallArgs().getUser()); 1697 } 1698 1699 Trace.asyncTraceEnd( 1700 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1701 1702 processPendingInstall(args, ret); 1703 mHandler.sendEmptyMessage(MCS_UNBIND); 1704 } 1705 break; 1706 } 1707 case PACKAGE_VERIFIED: { 1708 final int verificationId = msg.arg1; 1709 1710 final PackageVerificationState state = mPendingVerification.get(verificationId); 1711 if (state == null) { 1712 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1713 break; 1714 } 1715 1716 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1717 1718 state.setVerifierResponse(response.callerUid, response.code); 1719 1720 if (state.isVerificationComplete()) { 1721 mPendingVerification.remove(verificationId); 1722 1723 final InstallArgs args = state.getInstallArgs(); 1724 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1725 1726 int ret; 1727 if (state.isInstallAllowed()) { 1728 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1729 broadcastPackageVerified(verificationId, originUri, 1730 response.code, state.getInstallArgs().getUser()); 1731 try { 1732 ret = args.copyApk(mContainerService, true); 1733 } catch (RemoteException e) { 1734 Slog.e(TAG, "Could not contact the ContainerService"); 1735 } 1736 } else { 1737 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1738 } 1739 1740 Trace.asyncTraceEnd( 1741 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1742 1743 processPendingInstall(args, ret); 1744 mHandler.sendEmptyMessage(MCS_UNBIND); 1745 } 1746 1747 break; 1748 } 1749 case START_INTENT_FILTER_VERIFICATIONS: { 1750 IFVerificationParams params = (IFVerificationParams) msg.obj; 1751 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1752 params.replacing, params.pkg); 1753 break; 1754 } 1755 case INTENT_FILTER_VERIFIED: { 1756 final int verificationId = msg.arg1; 1757 1758 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1759 verificationId); 1760 if (state == null) { 1761 Slog.w(TAG, "Invalid IntentFilter verification token " 1762 + verificationId + " received"); 1763 break; 1764 } 1765 1766 final int userId = state.getUserId(); 1767 1768 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1769 "Processing IntentFilter verification with token:" 1770 + verificationId + " and userId:" + userId); 1771 1772 final IntentFilterVerificationResponse response = 1773 (IntentFilterVerificationResponse) msg.obj; 1774 1775 state.setVerifierResponse(response.callerUid, response.code); 1776 1777 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1778 "IntentFilter verification with token:" + verificationId 1779 + " and userId:" + userId 1780 + " is settings verifier response with response code:" 1781 + response.code); 1782 1783 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1784 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1785 + response.getFailedDomainsString()); 1786 } 1787 1788 if (state.isVerificationComplete()) { 1789 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1790 } else { 1791 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1792 "IntentFilter verification with token:" + verificationId 1793 + " was not said to be complete"); 1794 } 1795 1796 break; 1797 } 1798 } 1799 } 1800 } 1801 1802 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1803 boolean killApp, String[] grantedPermissions, 1804 boolean launchedForRestore, String installerPackage, 1805 IPackageInstallObserver2 installObserver) { 1806 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1807 // Send the removed broadcasts 1808 if (res.removedInfo != null) { 1809 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1810 } 1811 1812 // Now that we successfully installed the package, grant runtime 1813 // permissions if requested before broadcasting the install. 1814 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1815 >= Build.VERSION_CODES.M) { 1816 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1817 } 1818 1819 final boolean update = res.removedInfo != null 1820 && res.removedInfo.removedPackage != null; 1821 1822 // If this is the first time we have child packages for a disabled privileged 1823 // app that had no children, we grant requested runtime permissions to the new 1824 // children if the parent on the system image had them already granted. 1825 if (res.pkg.parentPackage != null) { 1826 synchronized (mPackages) { 1827 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1828 } 1829 } 1830 1831 synchronized (mPackages) { 1832 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1833 } 1834 1835 final String packageName = res.pkg.applicationInfo.packageName; 1836 Bundle extras = new Bundle(1); 1837 extras.putInt(Intent.EXTRA_UID, res.uid); 1838 1839 // Determine the set of users who are adding this package for 1840 // the first time vs. those who are seeing an update. 1841 int[] firstUsers = EMPTY_INT_ARRAY; 1842 int[] updateUsers = EMPTY_INT_ARRAY; 1843 if (res.origUsers == null || res.origUsers.length == 0) { 1844 firstUsers = res.newUsers; 1845 } else { 1846 for (int newUser : res.newUsers) { 1847 boolean isNew = true; 1848 for (int origUser : res.origUsers) { 1849 if (origUser == newUser) { 1850 isNew = false; 1851 break; 1852 } 1853 } 1854 if (isNew) { 1855 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1856 } else { 1857 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1858 } 1859 } 1860 } 1861 1862 // Send installed broadcasts if the install/update is not ephemeral 1863 if (!isEphemeral(res.pkg)) { 1864 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1865 1866 // Send added for users that see the package for the first time 1867 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1868 extras, 0 /*flags*/, null /*targetPackage*/, 1869 null /*finishedReceiver*/, firstUsers); 1870 1871 // Send added for users that don't see the package for the first time 1872 if (update) { 1873 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1874 } 1875 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1876 extras, 0 /*flags*/, null /*targetPackage*/, 1877 null /*finishedReceiver*/, updateUsers); 1878 1879 // Send replaced for users that don't see the package for the first time 1880 if (update) { 1881 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1882 packageName, extras, 0 /*flags*/, 1883 null /*targetPackage*/, null /*finishedReceiver*/, 1884 updateUsers); 1885 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1886 null /*package*/, null /*extras*/, 0 /*flags*/, 1887 packageName /*targetPackage*/, 1888 null /*finishedReceiver*/, updateUsers); 1889 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1890 // First-install and we did a restore, so we're responsible for the 1891 // first-launch broadcast. 1892 if (DEBUG_BACKUP) { 1893 Slog.i(TAG, "Post-restore of " + packageName 1894 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1895 } 1896 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1897 } 1898 1899 // Send broadcast package appeared if forward locked/external for all users 1900 // treat asec-hosted packages like removable media on upgrade 1901 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1902 if (DEBUG_INSTALL) { 1903 Slog.i(TAG, "upgrading pkg " + res.pkg 1904 + " is ASEC-hosted -> AVAILABLE"); 1905 } 1906 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1907 ArrayList<String> pkgList = new ArrayList<>(1); 1908 pkgList.add(packageName); 1909 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1910 } 1911 } 1912 1913 // Work that needs to happen on first install within each user 1914 if (firstUsers != null && firstUsers.length > 0) { 1915 synchronized (mPackages) { 1916 for (int userId : firstUsers) { 1917 // If this app is a browser and it's newly-installed for some 1918 // users, clear any default-browser state in those users. The 1919 // app's nature doesn't depend on the user, so we can just check 1920 // its browser nature in any user and generalize. 1921 if (packageIsBrowser(packageName, userId)) { 1922 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1923 } 1924 1925 // We may also need to apply pending (restored) runtime 1926 // permission grants within these users. 1927 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1928 } 1929 } 1930 } 1931 1932 // Log current value of "unknown sources" setting 1933 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1934 getUnknownSourcesSettings()); 1935 1936 // Force a gc to clear up things 1937 Runtime.getRuntime().gc(); 1938 1939 // Remove the replaced package's older resources safely now 1940 // We delete after a gc for applications on sdcard. 1941 if (res.removedInfo != null && res.removedInfo.args != null) { 1942 synchronized (mInstallLock) { 1943 res.removedInfo.args.doPostDeleteLI(true); 1944 } 1945 } 1946 } 1947 1948 // If someone is watching installs - notify them 1949 if (installObserver != null) { 1950 try { 1951 Bundle extras = extrasForInstallResult(res); 1952 installObserver.onPackageInstalled(res.name, res.returnCode, 1953 res.returnMsg, extras); 1954 } catch (RemoteException e) { 1955 Slog.i(TAG, "Observer no longer exists."); 1956 } 1957 } 1958 } 1959 1960 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1961 PackageParser.Package pkg) { 1962 if (pkg.parentPackage == null) { 1963 return; 1964 } 1965 if (pkg.requestedPermissions == null) { 1966 return; 1967 } 1968 final PackageSetting disabledSysParentPs = mSettings 1969 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1970 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1971 || !disabledSysParentPs.isPrivileged() 1972 || (disabledSysParentPs.childPackageNames != null 1973 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1974 return; 1975 } 1976 final int[] allUserIds = sUserManager.getUserIds(); 1977 final int permCount = pkg.requestedPermissions.size(); 1978 for (int i = 0; i < permCount; i++) { 1979 String permission = pkg.requestedPermissions.get(i); 1980 BasePermission bp = mSettings.mPermissions.get(permission); 1981 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1982 continue; 1983 } 1984 for (int userId : allUserIds) { 1985 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1986 permission, userId)) { 1987 grantRuntimePermission(pkg.packageName, permission, userId); 1988 } 1989 } 1990 } 1991 } 1992 1993 private StorageEventListener mStorageListener = new StorageEventListener() { 1994 @Override 1995 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1996 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1997 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1998 final String volumeUuid = vol.getFsUuid(); 1999 2000 // Clean up any users or apps that were removed or recreated 2001 // while this volume was missing 2002 reconcileUsers(volumeUuid); 2003 reconcileApps(volumeUuid); 2004 2005 // Clean up any install sessions that expired or were 2006 // cancelled while this volume was missing 2007 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2008 2009 loadPrivatePackages(vol); 2010 2011 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2012 unloadPrivatePackages(vol); 2013 } 2014 } 2015 2016 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2017 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2018 updateExternalMediaStatus(true, false); 2019 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2020 updateExternalMediaStatus(false, false); 2021 } 2022 } 2023 } 2024 2025 @Override 2026 public void onVolumeForgotten(String fsUuid) { 2027 if (TextUtils.isEmpty(fsUuid)) { 2028 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2029 return; 2030 } 2031 2032 // Remove any apps installed on the forgotten volume 2033 synchronized (mPackages) { 2034 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2035 for (PackageSetting ps : packages) { 2036 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2037 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2038 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2039 } 2040 2041 mSettings.onVolumeForgotten(fsUuid); 2042 mSettings.writeLPr(); 2043 } 2044 } 2045 }; 2046 2047 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2048 String[] grantedPermissions) { 2049 for (int userId : userIds) { 2050 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2051 } 2052 2053 // We could have touched GID membership, so flush out packages.list 2054 synchronized (mPackages) { 2055 mSettings.writePackageListLPr(); 2056 } 2057 } 2058 2059 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2060 String[] grantedPermissions) { 2061 SettingBase sb = (SettingBase) pkg.mExtras; 2062 if (sb == null) { 2063 return; 2064 } 2065 2066 PermissionsState permissionsState = sb.getPermissionsState(); 2067 2068 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2069 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2070 2071 for (String permission : pkg.requestedPermissions) { 2072 final BasePermission bp; 2073 synchronized (mPackages) { 2074 bp = mSettings.mPermissions.get(permission); 2075 } 2076 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2077 && (grantedPermissions == null 2078 || ArrayUtils.contains(grantedPermissions, permission))) { 2079 final int flags = permissionsState.getPermissionFlags(permission, userId); 2080 // Installer cannot change immutable permissions. 2081 if ((flags & immutableFlags) == 0) { 2082 grantRuntimePermission(pkg.packageName, permission, userId); 2083 } 2084 } 2085 } 2086 } 2087 2088 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2089 Bundle extras = null; 2090 switch (res.returnCode) { 2091 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2092 extras = new Bundle(); 2093 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2094 res.origPermission); 2095 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2096 res.origPackage); 2097 break; 2098 } 2099 case PackageManager.INSTALL_SUCCEEDED: { 2100 extras = new Bundle(); 2101 extras.putBoolean(Intent.EXTRA_REPLACING, 2102 res.removedInfo != null && res.removedInfo.removedPackage != null); 2103 break; 2104 } 2105 } 2106 return extras; 2107 } 2108 2109 void scheduleWriteSettingsLocked() { 2110 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2111 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2112 } 2113 } 2114 2115 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2116 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2117 scheduleWritePackageRestrictionsLocked(userId); 2118 } 2119 2120 void scheduleWritePackageRestrictionsLocked(int userId) { 2121 final int[] userIds = (userId == UserHandle.USER_ALL) 2122 ? sUserManager.getUserIds() : new int[]{userId}; 2123 for (int nextUserId : userIds) { 2124 if (!sUserManager.exists(nextUserId)) return; 2125 mDirtyUsers.add(nextUserId); 2126 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2127 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2128 } 2129 } 2130 } 2131 2132 public static PackageManagerService main(Context context, Installer installer, 2133 boolean factoryTest, boolean onlyCore) { 2134 // Self-check for initial settings. 2135 PackageManagerServiceCompilerMapping.checkProperties(); 2136 2137 PackageManagerService m = new PackageManagerService(context, installer, 2138 factoryTest, onlyCore); 2139 m.enableSystemUserPackages(); 2140 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2141 // disabled after already being started. 2142 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2143 UserHandle.USER_SYSTEM); 2144 ServiceManager.addService("package", m); 2145 return m; 2146 } 2147 2148 private void enableSystemUserPackages() { 2149 if (!UserManager.isSplitSystemUser()) { 2150 return; 2151 } 2152 // For system user, enable apps based on the following conditions: 2153 // - app is whitelisted or belong to one of these groups: 2154 // -- system app which has no launcher icons 2155 // -- system app which has INTERACT_ACROSS_USERS permission 2156 // -- system IME app 2157 // - app is not in the blacklist 2158 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2159 Set<String> enableApps = new ArraySet<>(); 2160 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2161 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2162 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2163 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2164 enableApps.addAll(wlApps); 2165 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2166 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2167 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2168 enableApps.removeAll(blApps); 2169 Log.i(TAG, "Applications installed for system user: " + enableApps); 2170 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2171 UserHandle.SYSTEM); 2172 final int allAppsSize = allAps.size(); 2173 synchronized (mPackages) { 2174 for (int i = 0; i < allAppsSize; i++) { 2175 String pName = allAps.get(i); 2176 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2177 // Should not happen, but we shouldn't be failing if it does 2178 if (pkgSetting == null) { 2179 continue; 2180 } 2181 boolean install = enableApps.contains(pName); 2182 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2183 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2184 + " for system user"); 2185 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2186 } 2187 } 2188 } 2189 } 2190 2191 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2192 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2193 Context.DISPLAY_SERVICE); 2194 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2195 } 2196 2197 public PackageManagerService(Context context, Installer installer, 2198 boolean factoryTest, boolean onlyCore) { 2199 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2200 SystemClock.uptimeMillis()); 2201 2202 if (mSdkVersion <= 0) { 2203 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2204 } 2205 2206 mContext = context; 2207 mFactoryTest = factoryTest; 2208 mOnlyCore = onlyCore; 2209 mMetrics = new DisplayMetrics(); 2210 mSettings = new Settings(mPackages); 2211 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2214 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2215 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2216 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2217 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2218 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2219 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2220 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2221 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2222 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2223 2224 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2225 if (separateProcesses != null && separateProcesses.length() > 0) { 2226 if ("*".equals(separateProcesses)) { 2227 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2228 mSeparateProcesses = null; 2229 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2230 } else { 2231 mDefParseFlags = 0; 2232 mSeparateProcesses = separateProcesses.split(","); 2233 Slog.w(TAG, "Running with debug.separate_processes: " 2234 + separateProcesses); 2235 } 2236 } else { 2237 mDefParseFlags = 0; 2238 mSeparateProcesses = null; 2239 } 2240 2241 mInstaller = installer; 2242 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2243 "*dexopt*"); 2244 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2245 2246 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2247 FgThread.get().getLooper()); 2248 2249 getDefaultDisplayMetrics(context, mMetrics); 2250 2251 SystemConfig systemConfig = SystemConfig.getInstance(); 2252 mGlobalGids = systemConfig.getGlobalGids(); 2253 mSystemPermissions = systemConfig.getSystemPermissions(); 2254 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2255 2256 synchronized (mInstallLock) { 2257 // writer 2258 synchronized (mPackages) { 2259 mHandlerThread = new ServiceThread(TAG, 2260 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2261 mHandlerThread.start(); 2262 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2263 mProcessLoggingHandler = new ProcessLoggingHandler(); 2264 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2265 2266 File dataDir = Environment.getDataDirectory(); 2267 mAppInstallDir = new File(dataDir, "app"); 2268 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2269 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2270 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2271 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2272 2273 sUserManager = new UserManagerService(context, this, mPackages); 2274 2275 // Propagate permission configuration in to package manager. 2276 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2277 = systemConfig.getPermissions(); 2278 for (int i=0; i<permConfig.size(); i++) { 2279 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2280 BasePermission bp = mSettings.mPermissions.get(perm.name); 2281 if (bp == null) { 2282 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2283 mSettings.mPermissions.put(perm.name, bp); 2284 } 2285 if (perm.gids != null) { 2286 bp.setGids(perm.gids, perm.perUser); 2287 } 2288 } 2289 2290 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2291 for (int i=0; i<libConfig.size(); i++) { 2292 mSharedLibraries.put(libConfig.keyAt(i), 2293 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2294 } 2295 2296 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2297 2298 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2299 2300 String customResolverActivity = Resources.getSystem().getString( 2301 R.string.config_customResolverActivity); 2302 if (TextUtils.isEmpty(customResolverActivity)) { 2303 customResolverActivity = null; 2304 } else { 2305 mCustomResolverComponentName = ComponentName.unflattenFromString( 2306 customResolverActivity); 2307 } 2308 2309 long startTime = SystemClock.uptimeMillis(); 2310 2311 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2312 startTime); 2313 2314 // Set flag to monitor and not change apk file paths when 2315 // scanning install directories. 2316 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2317 2318 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2319 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2320 2321 if (bootClassPath == null) { 2322 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2323 } 2324 2325 if (systemServerClassPath == null) { 2326 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2327 } 2328 2329 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2330 final String[] dexCodeInstructionSets = 2331 getDexCodeInstructionSets( 2332 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2333 2334 /** 2335 * Ensure all external libraries have had dexopt run on them. 2336 */ 2337 if (mSharedLibraries.size() > 0) { 2338 // NOTE: For now, we're compiling these system "shared libraries" 2339 // (and framework jars) into all available architectures. It's possible 2340 // to compile them only when we come across an app that uses them (there's 2341 // already logic for that in scanPackageLI) but that adds some complexity. 2342 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2343 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2344 final String lib = libEntry.path; 2345 if (lib == null) { 2346 continue; 2347 } 2348 2349 try { 2350 // Shared libraries do not have profiles so we perform a full 2351 // AOT compilation (if needed). 2352 int dexoptNeeded = DexFile.getDexOptNeeded( 2353 lib, dexCodeInstructionSet, 2354 getCompilerFilterForReason(REASON_SHARED_APK), 2355 false /* newProfile */); 2356 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2357 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2358 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2359 getCompilerFilterForReason(REASON_SHARED_APK), 2360 StorageManager.UUID_PRIVATE_INTERNAL, 2361 SKIP_SHARED_LIBRARY_CHECK); 2362 } 2363 } catch (FileNotFoundException e) { 2364 Slog.w(TAG, "Library not found: " + lib); 2365 } catch (IOException | InstallerException e) { 2366 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2367 + e.getMessage()); 2368 } 2369 } 2370 } 2371 } 2372 2373 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2374 2375 final VersionInfo ver = mSettings.getInternalVersion(); 2376 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2377 2378 // when upgrading from pre-M, promote system app permissions from install to runtime 2379 mPromoteSystemApps = 2380 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2381 2382 // save off the names of pre-existing system packages prior to scanning; we don't 2383 // want to automatically grant runtime permissions for new system apps 2384 if (mPromoteSystemApps) { 2385 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2386 while (pkgSettingIter.hasNext()) { 2387 PackageSetting ps = pkgSettingIter.next(); 2388 if (isSystemApp(ps)) { 2389 mExistingSystemPackages.add(ps.name); 2390 } 2391 } 2392 } 2393 2394 // When upgrading from pre-N, we need to handle package extraction like first boot, 2395 // as there is no profiling data available. 2396 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2397 mSettings.setNWorkDone(); 2398 2399 // Collect vendor overlay packages. 2400 // (Do this before scanning any apps.) 2401 // For security and version matching reason, only consider 2402 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2403 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2404 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2405 | PackageParser.PARSE_IS_SYSTEM 2406 | PackageParser.PARSE_IS_SYSTEM_DIR 2407 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2408 2409 // Find base frameworks (resource packages without code). 2410 scanDirTracedLI(frameworkDir, mDefParseFlags 2411 | PackageParser.PARSE_IS_SYSTEM 2412 | PackageParser.PARSE_IS_SYSTEM_DIR 2413 | PackageParser.PARSE_IS_PRIVILEGED, 2414 scanFlags | SCAN_NO_DEX, 0); 2415 2416 // Collected privileged system packages. 2417 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2418 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2419 | PackageParser.PARSE_IS_SYSTEM 2420 | PackageParser.PARSE_IS_SYSTEM_DIR 2421 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2422 2423 // Collect ordinary system packages. 2424 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2425 scanDirTracedLI(systemAppDir, mDefParseFlags 2426 | PackageParser.PARSE_IS_SYSTEM 2427 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2428 2429 // Collect all vendor packages. 2430 File vendorAppDir = new File("/vendor/app"); 2431 try { 2432 vendorAppDir = vendorAppDir.getCanonicalFile(); 2433 } catch (IOException e) { 2434 // failed to look up canonical path, continue with original one 2435 } 2436 scanDirTracedLI(vendorAppDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2439 2440 // Collect all OEM packages. 2441 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2442 scanDirTracedLI(oemAppDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2445 2446 // Prune any system packages that no longer exist. 2447 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2448 if (!mOnlyCore) { 2449 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2450 while (psit.hasNext()) { 2451 PackageSetting ps = psit.next(); 2452 2453 /* 2454 * If this is not a system app, it can't be a 2455 * disable system app. 2456 */ 2457 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2458 continue; 2459 } 2460 2461 /* 2462 * If the package is scanned, it's not erased. 2463 */ 2464 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2465 if (scannedPkg != null) { 2466 /* 2467 * If the system app is both scanned and in the 2468 * disabled packages list, then it must have been 2469 * added via OTA. Remove it from the currently 2470 * scanned package so the previously user-installed 2471 * application can be scanned. 2472 */ 2473 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2474 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2475 + ps.name + "; removing system app. Last known codePath=" 2476 + ps.codePathString + ", installStatus=" + ps.installStatus 2477 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2478 + scannedPkg.mVersionCode); 2479 removePackageLI(scannedPkg, true); 2480 mExpectingBetter.put(ps.name, ps.codePath); 2481 } 2482 2483 continue; 2484 } 2485 2486 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2487 psit.remove(); 2488 logCriticalInfo(Log.WARN, "System package " + ps.name 2489 + " no longer exists; it's data will be wiped"); 2490 // Actual deletion of code and data will be handled by later 2491 // reconciliation step 2492 } else { 2493 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2494 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2495 possiblyDeletedUpdatedSystemApps.add(ps.name); 2496 } 2497 } 2498 } 2499 } 2500 2501 //look for any incomplete package installations 2502 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2503 for (int i = 0; i < deletePkgsList.size(); i++) { 2504 // Actual deletion of code and data will be handled by later 2505 // reconciliation step 2506 final String packageName = deletePkgsList.get(i).name; 2507 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2508 synchronized (mPackages) { 2509 mSettings.removePackageLPw(packageName); 2510 } 2511 } 2512 2513 //delete tmp files 2514 deleteTempPackageFiles(); 2515 2516 // Remove any shared userIDs that have no associated packages 2517 mSettings.pruneSharedUsersLPw(); 2518 2519 if (!mOnlyCore) { 2520 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2521 SystemClock.uptimeMillis()); 2522 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2523 2524 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2525 | PackageParser.PARSE_FORWARD_LOCK, 2526 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2527 2528 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2529 | PackageParser.PARSE_IS_EPHEMERAL, 2530 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2531 2532 /** 2533 * Remove disable package settings for any updated system 2534 * apps that were removed via an OTA. If they're not a 2535 * previously-updated app, remove them completely. 2536 * Otherwise, just revoke their system-level permissions. 2537 */ 2538 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2539 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2540 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2541 2542 String msg; 2543 if (deletedPkg == null) { 2544 msg = "Updated system package " + deletedAppName 2545 + " no longer exists; it's data will be wiped"; 2546 // Actual deletion of code and data will be handled by later 2547 // reconciliation step 2548 } else { 2549 msg = "Updated system app + " + deletedAppName 2550 + " no longer present; removing system privileges for " 2551 + deletedAppName; 2552 2553 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2554 2555 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2556 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2557 } 2558 logCriticalInfo(Log.WARN, msg); 2559 } 2560 2561 /** 2562 * Make sure all system apps that we expected to appear on 2563 * the userdata partition actually showed up. If they never 2564 * appeared, crawl back and revive the system version. 2565 */ 2566 for (int i = 0; i < mExpectingBetter.size(); i++) { 2567 final String packageName = mExpectingBetter.keyAt(i); 2568 if (!mPackages.containsKey(packageName)) { 2569 final File scanFile = mExpectingBetter.valueAt(i); 2570 2571 logCriticalInfo(Log.WARN, "Expected better " + packageName 2572 + " but never showed up; reverting to system"); 2573 2574 int reparseFlags = mDefParseFlags; 2575 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2576 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2577 | PackageParser.PARSE_IS_SYSTEM_DIR 2578 | PackageParser.PARSE_IS_PRIVILEGED; 2579 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2580 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2581 | PackageParser.PARSE_IS_SYSTEM_DIR; 2582 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2583 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2584 | PackageParser.PARSE_IS_SYSTEM_DIR; 2585 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2586 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2587 | PackageParser.PARSE_IS_SYSTEM_DIR; 2588 } else { 2589 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2590 continue; 2591 } 2592 2593 mSettings.enableSystemPackageLPw(packageName); 2594 2595 try { 2596 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2597 } catch (PackageManagerException e) { 2598 Slog.e(TAG, "Failed to parse original system package: " 2599 + e.getMessage()); 2600 } 2601 } 2602 } 2603 } 2604 mExpectingBetter.clear(); 2605 2606 // Resolve protected action filters. Only the setup wizard is allowed to 2607 // have a high priority filter for these actions. 2608 mSetupWizardPackage = getSetupWizardPackageName(); 2609 if (mProtectedFilters.size() > 0) { 2610 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2611 Slog.i(TAG, "No setup wizard;" 2612 + " All protected intents capped to priority 0"); 2613 } 2614 for (ActivityIntentInfo filter : mProtectedFilters) { 2615 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2616 if (DEBUG_FILTERS) { 2617 Slog.i(TAG, "Found setup wizard;" 2618 + " allow priority " + filter.getPriority() + ";" 2619 + " package: " + filter.activity.info.packageName 2620 + " activity: " + filter.activity.className 2621 + " priority: " + filter.getPriority()); 2622 } 2623 // skip setup wizard; allow it to keep the high priority filter 2624 continue; 2625 } 2626 Slog.w(TAG, "Protected action; cap priority to 0;" 2627 + " package: " + filter.activity.info.packageName 2628 + " activity: " + filter.activity.className 2629 + " origPrio: " + filter.getPriority()); 2630 filter.setPriority(0); 2631 } 2632 } 2633 mDeferProtectedFilters = false; 2634 mProtectedFilters.clear(); 2635 2636 // Now that we know all of the shared libraries, update all clients to have 2637 // the correct library paths. 2638 updateAllSharedLibrariesLPw(); 2639 2640 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2641 // NOTE: We ignore potential failures here during a system scan (like 2642 // the rest of the commands above) because there's precious little we 2643 // can do about it. A settings error is reported, though. 2644 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2645 false /* boot complete */); 2646 } 2647 2648 // Now that we know all the packages we are keeping, 2649 // read and update their last usage times. 2650 mPackageUsage.readLP(); 2651 2652 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2653 SystemClock.uptimeMillis()); 2654 Slog.i(TAG, "Time to scan packages: " 2655 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2656 + " seconds"); 2657 2658 // If the platform SDK has changed since the last time we booted, 2659 // we need to re-grant app permission to catch any new ones that 2660 // appear. This is really a hack, and means that apps can in some 2661 // cases get permissions that the user didn't initially explicitly 2662 // allow... it would be nice to have some better way to handle 2663 // this situation. 2664 int updateFlags = UPDATE_PERMISSIONS_ALL; 2665 if (ver.sdkVersion != mSdkVersion) { 2666 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2667 + mSdkVersion + "; regranting permissions for internal storage"); 2668 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2669 } 2670 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2671 ver.sdkVersion = mSdkVersion; 2672 2673 // If this is the first boot or an update from pre-M, and it is a normal 2674 // boot, then we need to initialize the default preferred apps across 2675 // all defined users. 2676 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2677 for (UserInfo user : sUserManager.getUsers(true)) { 2678 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2679 applyFactoryDefaultBrowserLPw(user.id); 2680 primeDomainVerificationsLPw(user.id); 2681 } 2682 } 2683 2684 // Prepare storage for system user really early during boot, 2685 // since core system apps like SettingsProvider and SystemUI 2686 // can't wait for user to start 2687 final int storageFlags; 2688 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2689 storageFlags = StorageManager.FLAG_STORAGE_DE; 2690 } else { 2691 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2692 } 2693 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2694 storageFlags); 2695 2696 // If this is first boot after an OTA, and a normal boot, then 2697 // we need to clear code cache directories. 2698 // Note that we do *not* clear the application profiles. These remain valid 2699 // across OTAs and are used to drive profile verification (post OTA) and 2700 // profile compilation (without waiting to collect a fresh set of profiles). 2701 if (mIsUpgrade && !onlyCore) { 2702 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2703 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2704 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2705 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2706 // No apps are running this early, so no need to freeze 2707 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2708 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2709 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2710 } 2711 clearAppProfilesLIF(ps.pkg, UserHandle.USER_ALL); 2712 } 2713 ver.fingerprint = Build.FINGERPRINT; 2714 } 2715 2716 checkDefaultBrowser(); 2717 2718 // clear only after permissions and other defaults have been updated 2719 mExistingSystemPackages.clear(); 2720 mPromoteSystemApps = false; 2721 2722 // All the changes are done during package scanning. 2723 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2724 2725 // can downgrade to reader 2726 mSettings.writeLPr(); 2727 2728 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2729 SystemClock.uptimeMillis()); 2730 2731 if (!mOnlyCore) { 2732 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2733 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2734 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2735 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2736 mIntentFilterVerifierComponent); 2737 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2738 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2739 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2740 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2741 } else { 2742 mRequiredVerifierPackage = null; 2743 mRequiredInstallerPackage = null; 2744 mIntentFilterVerifierComponent = null; 2745 mIntentFilterVerifier = null; 2746 mServicesSystemSharedLibraryPackageName = null; 2747 mSharedSystemSharedLibraryPackageName = null; 2748 } 2749 2750 mInstallerService = new PackageInstallerService(context, this); 2751 2752 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2753 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2754 // both the installer and resolver must be present to enable ephemeral 2755 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2756 if (DEBUG_EPHEMERAL) { 2757 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2758 + " installer:" + ephemeralInstallerComponent); 2759 } 2760 mEphemeralResolverComponent = ephemeralResolverComponent; 2761 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2762 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2763 mEphemeralResolverConnection = 2764 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2765 } else { 2766 if (DEBUG_EPHEMERAL) { 2767 final String missingComponent = 2768 (ephemeralResolverComponent == null) 2769 ? (ephemeralInstallerComponent == null) 2770 ? "resolver and installer" 2771 : "resolver" 2772 : "installer"; 2773 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2774 } 2775 mEphemeralResolverComponent = null; 2776 mEphemeralInstallerComponent = null; 2777 mEphemeralResolverConnection = null; 2778 } 2779 2780 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2781 } // synchronized (mPackages) 2782 } // synchronized (mInstallLock) 2783 2784 // Now after opening every single application zip, make sure they 2785 // are all flushed. Not really needed, but keeps things nice and 2786 // tidy. 2787 Runtime.getRuntime().gc(); 2788 2789 // The initial scanning above does many calls into installd while 2790 // holding the mPackages lock, but we're mostly interested in yelling 2791 // once we have a booted system. 2792 mInstaller.setWarnIfHeld(mPackages); 2793 2794 // Expose private service for system components to use. 2795 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2796 } 2797 2798 @Override 2799 public boolean isFirstBoot() { 2800 return !mRestoredSettings; 2801 } 2802 2803 @Override 2804 public boolean isOnlyCoreApps() { 2805 return mOnlyCore; 2806 } 2807 2808 @Override 2809 public boolean isUpgrade() { 2810 return mIsUpgrade; 2811 } 2812 2813 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2814 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2815 2816 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2817 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2818 UserHandle.USER_SYSTEM); 2819 if (matches.size() == 1) { 2820 return matches.get(0).getComponentInfo().packageName; 2821 } else { 2822 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2823 return null; 2824 } 2825 } 2826 2827 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2828 synchronized (mPackages) { 2829 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2830 if (libraryEntry == null) { 2831 throw new IllegalStateException("Missing required shared library:" + libraryName); 2832 } 2833 return libraryEntry.apk; 2834 } 2835 } 2836 2837 private @NonNull String getRequiredInstallerLPr() { 2838 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2839 intent.addCategory(Intent.CATEGORY_DEFAULT); 2840 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2841 2842 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2843 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2844 UserHandle.USER_SYSTEM); 2845 if (matches.size() == 1) { 2846 ResolveInfo resolveInfo = matches.get(0); 2847 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2848 throw new RuntimeException("The installer must be a privileged app"); 2849 } 2850 return matches.get(0).getComponentInfo().packageName; 2851 } else { 2852 throw new RuntimeException("There must be exactly one installer; found " + matches); 2853 } 2854 } 2855 2856 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2857 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2858 2859 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2860 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2861 UserHandle.USER_SYSTEM); 2862 ResolveInfo best = null; 2863 final int N = matches.size(); 2864 for (int i = 0; i < N; i++) { 2865 final ResolveInfo cur = matches.get(i); 2866 final String packageName = cur.getComponentInfo().packageName; 2867 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2868 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2869 continue; 2870 } 2871 2872 if (best == null || cur.priority > best.priority) { 2873 best = cur; 2874 } 2875 } 2876 2877 if (best != null) { 2878 return best.getComponentInfo().getComponentName(); 2879 } else { 2880 throw new RuntimeException("There must be at least one intent filter verifier"); 2881 } 2882 } 2883 2884 private @Nullable ComponentName getEphemeralResolverLPr() { 2885 final String[] packageArray = 2886 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2887 if (packageArray.length == 0) { 2888 if (DEBUG_EPHEMERAL) { 2889 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2890 } 2891 return null; 2892 } 2893 2894 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2895 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2896 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2897 UserHandle.USER_SYSTEM); 2898 2899 final int N = resolvers.size(); 2900 if (N == 0) { 2901 if (DEBUG_EPHEMERAL) { 2902 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2903 } 2904 return null; 2905 } 2906 2907 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2908 for (int i = 0; i < N; i++) { 2909 final ResolveInfo info = resolvers.get(i); 2910 2911 if (info.serviceInfo == null) { 2912 continue; 2913 } 2914 2915 final String packageName = info.serviceInfo.packageName; 2916 if (!possiblePackages.contains(packageName)) { 2917 if (DEBUG_EPHEMERAL) { 2918 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2919 + " pkg: " + packageName + ", info:" + info); 2920 } 2921 continue; 2922 } 2923 2924 if (DEBUG_EPHEMERAL) { 2925 Slog.v(TAG, "Ephemeral resolver found;" 2926 + " pkg: " + packageName + ", info:" + info); 2927 } 2928 return new ComponentName(packageName, info.serviceInfo.name); 2929 } 2930 if (DEBUG_EPHEMERAL) { 2931 Slog.v(TAG, "Ephemeral resolver NOT found"); 2932 } 2933 return null; 2934 } 2935 2936 private @Nullable ComponentName getEphemeralInstallerLPr() { 2937 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2938 intent.addCategory(Intent.CATEGORY_DEFAULT); 2939 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2940 2941 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2942 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2943 UserHandle.USER_SYSTEM); 2944 if (matches.size() == 0) { 2945 return null; 2946 } else if (matches.size() == 1) { 2947 return matches.get(0).getComponentInfo().getComponentName(); 2948 } else { 2949 throw new RuntimeException( 2950 "There must be at most one ephemeral installer; found " + matches); 2951 } 2952 } 2953 2954 private void primeDomainVerificationsLPw(int userId) { 2955 if (DEBUG_DOMAIN_VERIFICATION) { 2956 Slog.d(TAG, "Priming domain verifications in user " + userId); 2957 } 2958 2959 SystemConfig systemConfig = SystemConfig.getInstance(); 2960 ArraySet<String> packages = systemConfig.getLinkedApps(); 2961 ArraySet<String> domains = new ArraySet<String>(); 2962 2963 for (String packageName : packages) { 2964 PackageParser.Package pkg = mPackages.get(packageName); 2965 if (pkg != null) { 2966 if (!pkg.isSystemApp()) { 2967 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2968 continue; 2969 } 2970 2971 domains.clear(); 2972 for (PackageParser.Activity a : pkg.activities) { 2973 for (ActivityIntentInfo filter : a.intents) { 2974 if (hasValidDomains(filter)) { 2975 domains.addAll(filter.getHostsList()); 2976 } 2977 } 2978 } 2979 2980 if (domains.size() > 0) { 2981 if (DEBUG_DOMAIN_VERIFICATION) { 2982 Slog.v(TAG, " + " + packageName); 2983 } 2984 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2985 // state w.r.t. the formal app-linkage "no verification attempted" state; 2986 // and then 'always' in the per-user state actually used for intent resolution. 2987 final IntentFilterVerificationInfo ivi; 2988 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2989 new ArrayList<String>(domains)); 2990 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2991 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2992 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2993 } else { 2994 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2995 + "' does not handle web links"); 2996 } 2997 } else { 2998 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2999 } 3000 } 3001 3002 scheduleWritePackageRestrictionsLocked(userId); 3003 scheduleWriteSettingsLocked(); 3004 } 3005 3006 private void applyFactoryDefaultBrowserLPw(int userId) { 3007 // The default browser app's package name is stored in a string resource, 3008 // with a product-specific overlay used for vendor customization. 3009 String browserPkg = mContext.getResources().getString( 3010 com.android.internal.R.string.default_browser); 3011 if (!TextUtils.isEmpty(browserPkg)) { 3012 // non-empty string => required to be a known package 3013 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3014 if (ps == null) { 3015 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3016 browserPkg = null; 3017 } else { 3018 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3019 } 3020 } 3021 3022 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3023 // default. If there's more than one, just leave everything alone. 3024 if (browserPkg == null) { 3025 calculateDefaultBrowserLPw(userId); 3026 } 3027 } 3028 3029 private void calculateDefaultBrowserLPw(int userId) { 3030 List<String> allBrowsers = resolveAllBrowserApps(userId); 3031 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3032 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3033 } 3034 3035 private List<String> resolveAllBrowserApps(int userId) { 3036 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3037 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3038 PackageManager.MATCH_ALL, userId); 3039 3040 final int count = list.size(); 3041 List<String> result = new ArrayList<String>(count); 3042 for (int i=0; i<count; i++) { 3043 ResolveInfo info = list.get(i); 3044 if (info.activityInfo == null 3045 || !info.handleAllWebDataURI 3046 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3047 || result.contains(info.activityInfo.packageName)) { 3048 continue; 3049 } 3050 result.add(info.activityInfo.packageName); 3051 } 3052 3053 return result; 3054 } 3055 3056 private boolean packageIsBrowser(String packageName, int userId) { 3057 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3058 PackageManager.MATCH_ALL, userId); 3059 final int N = list.size(); 3060 for (int i = 0; i < N; i++) { 3061 ResolveInfo info = list.get(i); 3062 if (packageName.equals(info.activityInfo.packageName)) { 3063 return true; 3064 } 3065 } 3066 return false; 3067 } 3068 3069 private void checkDefaultBrowser() { 3070 final int myUserId = UserHandle.myUserId(); 3071 final String packageName = getDefaultBrowserPackageName(myUserId); 3072 if (packageName != null) { 3073 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3074 if (info == null) { 3075 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3076 synchronized (mPackages) { 3077 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3078 } 3079 } 3080 } 3081 } 3082 3083 @Override 3084 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3085 throws RemoteException { 3086 try { 3087 return super.onTransact(code, data, reply, flags); 3088 } catch (RuntimeException e) { 3089 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3090 Slog.wtf(TAG, "Package Manager Crash", e); 3091 } 3092 throw e; 3093 } 3094 } 3095 3096 static int[] appendInts(int[] cur, int[] add) { 3097 if (add == null) return cur; 3098 if (cur == null) return add; 3099 final int N = add.length; 3100 for (int i=0; i<N; i++) { 3101 cur = appendInt(cur, add[i]); 3102 } 3103 return cur; 3104 } 3105 3106 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3107 if (!sUserManager.exists(userId)) return null; 3108 if (ps == null) { 3109 return null; 3110 } 3111 final PackageParser.Package p = ps.pkg; 3112 if (p == null) { 3113 return null; 3114 } 3115 3116 final PermissionsState permissionsState = ps.getPermissionsState(); 3117 3118 final int[] gids = permissionsState.computeGids(userId); 3119 final Set<String> permissions = permissionsState.getPermissions(userId); 3120 final PackageUserState state = ps.readUserState(userId); 3121 3122 return PackageParser.generatePackageInfo(p, gids, flags, 3123 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3124 } 3125 3126 @Override 3127 public void checkPackageStartable(String packageName, int userId) { 3128 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3129 3130 synchronized (mPackages) { 3131 final PackageSetting ps = mSettings.mPackages.get(packageName); 3132 if (ps == null) { 3133 throw new SecurityException("Package " + packageName + " was not found!"); 3134 } 3135 3136 if (!ps.getInstalled(userId)) { 3137 throw new SecurityException( 3138 "Package " + packageName + " was not installed for user " + userId + "!"); 3139 } 3140 3141 if (mSafeMode && !ps.isSystem()) { 3142 throw new SecurityException("Package " + packageName + " not a system app!"); 3143 } 3144 3145 if (mFrozenPackages.contains(packageName)) { 3146 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3147 } 3148 3149 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3150 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3151 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3152 } 3153 } 3154 } 3155 3156 @Override 3157 public boolean isPackageAvailable(String packageName, int userId) { 3158 if (!sUserManager.exists(userId)) return false; 3159 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3160 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3161 synchronized (mPackages) { 3162 PackageParser.Package p = mPackages.get(packageName); 3163 if (p != null) { 3164 final PackageSetting ps = (PackageSetting) p.mExtras; 3165 if (ps != null) { 3166 final PackageUserState state = ps.readUserState(userId); 3167 if (state != null) { 3168 return PackageParser.isAvailable(state); 3169 } 3170 } 3171 } 3172 } 3173 return false; 3174 } 3175 3176 @Override 3177 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3178 if (!sUserManager.exists(userId)) return null; 3179 flags = updateFlagsForPackage(flags, userId, packageName); 3180 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3181 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3182 // reader 3183 synchronized (mPackages) { 3184 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3185 PackageParser.Package p = null; 3186 if (matchFactoryOnly) { 3187 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3188 if (ps != null) { 3189 return generatePackageInfo(ps, flags, userId); 3190 } 3191 } 3192 if (p == null) { 3193 p = mPackages.get(packageName); 3194 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3195 return null; 3196 } 3197 } 3198 if (DEBUG_PACKAGE_INFO) 3199 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3200 if (p != null) { 3201 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3202 } 3203 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3204 final PackageSetting ps = mSettings.mPackages.get(packageName); 3205 return generatePackageInfo(ps, flags, userId); 3206 } 3207 } 3208 return null; 3209 } 3210 3211 @Override 3212 public String[] currentToCanonicalPackageNames(String[] names) { 3213 String[] out = new String[names.length]; 3214 // reader 3215 synchronized (mPackages) { 3216 for (int i=names.length-1; i>=0; i--) { 3217 PackageSetting ps = mSettings.mPackages.get(names[i]); 3218 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3219 } 3220 } 3221 return out; 3222 } 3223 3224 @Override 3225 public String[] canonicalToCurrentPackageNames(String[] names) { 3226 String[] out = new String[names.length]; 3227 // reader 3228 synchronized (mPackages) { 3229 for (int i=names.length-1; i>=0; i--) { 3230 String cur = mSettings.mRenamedPackages.get(names[i]); 3231 out[i] = cur != null ? cur : names[i]; 3232 } 3233 } 3234 return out; 3235 } 3236 3237 @Override 3238 public int getPackageUid(String packageName, int flags, int userId) { 3239 if (!sUserManager.exists(userId)) return -1; 3240 flags = updateFlagsForPackage(flags, userId, packageName); 3241 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3242 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3243 3244 // reader 3245 synchronized (mPackages) { 3246 final PackageParser.Package p = mPackages.get(packageName); 3247 if (p != null && p.isMatch(flags)) { 3248 return UserHandle.getUid(userId, p.applicationInfo.uid); 3249 } 3250 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3251 final PackageSetting ps = mSettings.mPackages.get(packageName); 3252 if (ps != null && ps.isMatch(flags)) { 3253 return UserHandle.getUid(userId, ps.appId); 3254 } 3255 } 3256 } 3257 3258 return -1; 3259 } 3260 3261 @Override 3262 public int[] getPackageGids(String packageName, int flags, int userId) { 3263 if (!sUserManager.exists(userId)) return null; 3264 flags = updateFlagsForPackage(flags, userId, packageName); 3265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3266 false /* requireFullPermission */, false /* checkShell */, 3267 "getPackageGids"); 3268 3269 // reader 3270 synchronized (mPackages) { 3271 final PackageParser.Package p = mPackages.get(packageName); 3272 if (p != null && p.isMatch(flags)) { 3273 PackageSetting ps = (PackageSetting) p.mExtras; 3274 return ps.getPermissionsState().computeGids(userId); 3275 } 3276 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3277 final PackageSetting ps = mSettings.mPackages.get(packageName); 3278 if (ps != null && ps.isMatch(flags)) { 3279 return ps.getPermissionsState().computeGids(userId); 3280 } 3281 } 3282 } 3283 3284 return null; 3285 } 3286 3287 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3288 if (bp.perm != null) { 3289 return PackageParser.generatePermissionInfo(bp.perm, flags); 3290 } 3291 PermissionInfo pi = new PermissionInfo(); 3292 pi.name = bp.name; 3293 pi.packageName = bp.sourcePackage; 3294 pi.nonLocalizedLabel = bp.name; 3295 pi.protectionLevel = bp.protectionLevel; 3296 return pi; 3297 } 3298 3299 @Override 3300 public PermissionInfo getPermissionInfo(String name, int flags) { 3301 // reader 3302 synchronized (mPackages) { 3303 final BasePermission p = mSettings.mPermissions.get(name); 3304 if (p != null) { 3305 return generatePermissionInfo(p, flags); 3306 } 3307 return null; 3308 } 3309 } 3310 3311 @Override 3312 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3313 int flags) { 3314 // reader 3315 synchronized (mPackages) { 3316 if (group != null && !mPermissionGroups.containsKey(group)) { 3317 // This is thrown as NameNotFoundException 3318 return null; 3319 } 3320 3321 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3322 for (BasePermission p : mSettings.mPermissions.values()) { 3323 if (group == null) { 3324 if (p.perm == null || p.perm.info.group == null) { 3325 out.add(generatePermissionInfo(p, flags)); 3326 } 3327 } else { 3328 if (p.perm != null && group.equals(p.perm.info.group)) { 3329 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3330 } 3331 } 3332 } 3333 return new ParceledListSlice<>(out); 3334 } 3335 } 3336 3337 @Override 3338 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3339 // reader 3340 synchronized (mPackages) { 3341 return PackageParser.generatePermissionGroupInfo( 3342 mPermissionGroups.get(name), flags); 3343 } 3344 } 3345 3346 @Override 3347 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3348 // reader 3349 synchronized (mPackages) { 3350 final int N = mPermissionGroups.size(); 3351 ArrayList<PermissionGroupInfo> out 3352 = new ArrayList<PermissionGroupInfo>(N); 3353 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3354 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3355 } 3356 return new ParceledListSlice<>(out); 3357 } 3358 } 3359 3360 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3361 int userId) { 3362 if (!sUserManager.exists(userId)) return null; 3363 PackageSetting ps = mSettings.mPackages.get(packageName); 3364 if (ps != null) { 3365 if (ps.pkg == null) { 3366 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3367 if (pInfo != null) { 3368 return pInfo.applicationInfo; 3369 } 3370 return null; 3371 } 3372 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3373 ps.readUserState(userId), userId); 3374 } 3375 return null; 3376 } 3377 3378 @Override 3379 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3380 if (!sUserManager.exists(userId)) return null; 3381 flags = updateFlagsForApplication(flags, userId, packageName); 3382 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3383 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3384 // writer 3385 synchronized (mPackages) { 3386 PackageParser.Package p = mPackages.get(packageName); 3387 if (DEBUG_PACKAGE_INFO) Log.v( 3388 TAG, "getApplicationInfo " + packageName 3389 + ": " + p); 3390 if (p != null) { 3391 PackageSetting ps = mSettings.mPackages.get(packageName); 3392 if (ps == null) return null; 3393 // Note: isEnabledLP() does not apply here - always return info 3394 return PackageParser.generateApplicationInfo( 3395 p, flags, ps.readUserState(userId), userId); 3396 } 3397 if ("android".equals(packageName)||"system".equals(packageName)) { 3398 return mAndroidApplication; 3399 } 3400 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3401 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3402 } 3403 } 3404 return null; 3405 } 3406 3407 @Override 3408 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3409 final IPackageDataObserver observer) { 3410 mContext.enforceCallingOrSelfPermission( 3411 android.Manifest.permission.CLEAR_APP_CACHE, null); 3412 // Queue up an async operation since clearing cache may take a little while. 3413 mHandler.post(new Runnable() { 3414 public void run() { 3415 mHandler.removeCallbacks(this); 3416 boolean success = true; 3417 synchronized (mInstallLock) { 3418 try { 3419 mInstaller.freeCache(volumeUuid, freeStorageSize); 3420 } catch (InstallerException e) { 3421 Slog.w(TAG, "Couldn't clear application caches: " + e); 3422 success = false; 3423 } 3424 } 3425 if (observer != null) { 3426 try { 3427 observer.onRemoveCompleted(null, success); 3428 } catch (RemoteException e) { 3429 Slog.w(TAG, "RemoveException when invoking call back"); 3430 } 3431 } 3432 } 3433 }); 3434 } 3435 3436 @Override 3437 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3438 final IntentSender pi) { 3439 mContext.enforceCallingOrSelfPermission( 3440 android.Manifest.permission.CLEAR_APP_CACHE, null); 3441 // Queue up an async operation since clearing cache may take a little while. 3442 mHandler.post(new Runnable() { 3443 public void run() { 3444 mHandler.removeCallbacks(this); 3445 boolean success = true; 3446 synchronized (mInstallLock) { 3447 try { 3448 mInstaller.freeCache(volumeUuid, freeStorageSize); 3449 } catch (InstallerException e) { 3450 Slog.w(TAG, "Couldn't clear application caches: " + e); 3451 success = false; 3452 } 3453 } 3454 if(pi != null) { 3455 try { 3456 // Callback via pending intent 3457 int code = success ? 1 : 0; 3458 pi.sendIntent(null, code, null, 3459 null, null); 3460 } catch (SendIntentException e1) { 3461 Slog.i(TAG, "Failed to send pending intent"); 3462 } 3463 } 3464 } 3465 }); 3466 } 3467 3468 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3469 synchronized (mInstallLock) { 3470 try { 3471 mInstaller.freeCache(volumeUuid, freeStorageSize); 3472 } catch (InstallerException e) { 3473 throw new IOException("Failed to free enough space", e); 3474 } 3475 } 3476 } 3477 3478 /** 3479 * Update given flags based on encryption status of current user. 3480 */ 3481 private int updateFlags(int flags, int userId) { 3482 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3483 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3484 // Caller expressed an explicit opinion about what encryption 3485 // aware/unaware components they want to see, so fall through and 3486 // give them what they want 3487 } else { 3488 // Caller expressed no opinion, so match based on user state 3489 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3490 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3491 } else { 3492 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3493 } 3494 } 3495 return flags; 3496 } 3497 3498 private UserManagerInternal getUserManagerInternal() { 3499 if (mUserManagerInternal == null) { 3500 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3501 } 3502 return mUserManagerInternal; 3503 } 3504 3505 /** 3506 * Update given flags when being used to request {@link PackageInfo}. 3507 */ 3508 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3509 boolean triaged = true; 3510 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3511 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3512 // Caller is asking for component details, so they'd better be 3513 // asking for specific encryption matching behavior, or be triaged 3514 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3515 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3516 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3517 triaged = false; 3518 } 3519 } 3520 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3521 | PackageManager.MATCH_SYSTEM_ONLY 3522 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3523 triaged = false; 3524 } 3525 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3526 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3527 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3528 } 3529 return updateFlags(flags, userId); 3530 } 3531 3532 /** 3533 * Update given flags when being used to request {@link ApplicationInfo}. 3534 */ 3535 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3536 return updateFlagsForPackage(flags, userId, cookie); 3537 } 3538 3539 /** 3540 * Update given flags when being used to request {@link ComponentInfo}. 3541 */ 3542 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3543 if (cookie instanceof Intent) { 3544 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3545 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3546 } 3547 } 3548 3549 boolean triaged = true; 3550 // Caller is asking for component details, so they'd better be 3551 // asking for specific encryption matching behavior, or be triaged 3552 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3553 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3554 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3555 triaged = false; 3556 } 3557 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3558 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3559 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3560 } 3561 3562 return updateFlags(flags, userId); 3563 } 3564 3565 /** 3566 * Update given flags when being used to request {@link ResolveInfo}. 3567 */ 3568 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3569 // Safe mode means we shouldn't match any third-party components 3570 if (mSafeMode) { 3571 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3572 } 3573 3574 return updateFlagsForComponent(flags, userId, cookie); 3575 } 3576 3577 @Override 3578 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3579 if (!sUserManager.exists(userId)) return null; 3580 flags = updateFlagsForComponent(flags, userId, component); 3581 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3582 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3583 synchronized (mPackages) { 3584 PackageParser.Activity a = mActivities.mActivities.get(component); 3585 3586 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3587 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3588 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3589 if (ps == null) return null; 3590 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3591 userId); 3592 } 3593 if (mResolveComponentName.equals(component)) { 3594 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3595 new PackageUserState(), userId); 3596 } 3597 } 3598 return null; 3599 } 3600 3601 @Override 3602 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3603 String resolvedType) { 3604 synchronized (mPackages) { 3605 if (component.equals(mResolveComponentName)) { 3606 // The resolver supports EVERYTHING! 3607 return true; 3608 } 3609 PackageParser.Activity a = mActivities.mActivities.get(component); 3610 if (a == null) { 3611 return false; 3612 } 3613 for (int i=0; i<a.intents.size(); i++) { 3614 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3615 intent.getData(), intent.getCategories(), TAG) >= 0) { 3616 return true; 3617 } 3618 } 3619 return false; 3620 } 3621 } 3622 3623 @Override 3624 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3625 if (!sUserManager.exists(userId)) return null; 3626 flags = updateFlagsForComponent(flags, userId, component); 3627 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3628 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3629 synchronized (mPackages) { 3630 PackageParser.Activity a = mReceivers.mActivities.get(component); 3631 if (DEBUG_PACKAGE_INFO) Log.v( 3632 TAG, "getReceiverInfo " + component + ": " + a); 3633 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3634 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3635 if (ps == null) return null; 3636 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3637 userId); 3638 } 3639 } 3640 return null; 3641 } 3642 3643 @Override 3644 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3645 if (!sUserManager.exists(userId)) return null; 3646 flags = updateFlagsForComponent(flags, userId, component); 3647 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3648 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3649 synchronized (mPackages) { 3650 PackageParser.Service s = mServices.mServices.get(component); 3651 if (DEBUG_PACKAGE_INFO) Log.v( 3652 TAG, "getServiceInfo " + component + ": " + s); 3653 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3654 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3655 if (ps == null) return null; 3656 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3657 userId); 3658 } 3659 } 3660 return null; 3661 } 3662 3663 @Override 3664 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3665 if (!sUserManager.exists(userId)) return null; 3666 flags = updateFlagsForComponent(flags, userId, component); 3667 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3668 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3669 synchronized (mPackages) { 3670 PackageParser.Provider p = mProviders.mProviders.get(component); 3671 if (DEBUG_PACKAGE_INFO) Log.v( 3672 TAG, "getProviderInfo " + component + ": " + p); 3673 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3674 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3675 if (ps == null) return null; 3676 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3677 userId); 3678 } 3679 } 3680 return null; 3681 } 3682 3683 @Override 3684 public String[] getSystemSharedLibraryNames() { 3685 Set<String> libSet; 3686 synchronized (mPackages) { 3687 libSet = mSharedLibraries.keySet(); 3688 int size = libSet.size(); 3689 if (size > 0) { 3690 String[] libs = new String[size]; 3691 libSet.toArray(libs); 3692 return libs; 3693 } 3694 } 3695 return null; 3696 } 3697 3698 @Override 3699 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3700 synchronized (mPackages) { 3701 return mServicesSystemSharedLibraryPackageName; 3702 } 3703 } 3704 3705 @Override 3706 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3707 synchronized (mPackages) { 3708 return mSharedSystemSharedLibraryPackageName; 3709 } 3710 } 3711 3712 @Override 3713 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3714 synchronized (mPackages) { 3715 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3716 3717 final FeatureInfo fi = new FeatureInfo(); 3718 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3719 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3720 res.add(fi); 3721 3722 return new ParceledListSlice<>(res); 3723 } 3724 } 3725 3726 @Override 3727 public boolean hasSystemFeature(String name, int version) { 3728 synchronized (mPackages) { 3729 final FeatureInfo feat = mAvailableFeatures.get(name); 3730 if (feat == null) { 3731 return false; 3732 } else { 3733 return feat.version >= version; 3734 } 3735 } 3736 } 3737 3738 @Override 3739 public int checkPermission(String permName, String pkgName, int userId) { 3740 if (!sUserManager.exists(userId)) { 3741 return PackageManager.PERMISSION_DENIED; 3742 } 3743 3744 synchronized (mPackages) { 3745 final PackageParser.Package p = mPackages.get(pkgName); 3746 if (p != null && p.mExtras != null) { 3747 final PackageSetting ps = (PackageSetting) p.mExtras; 3748 final PermissionsState permissionsState = ps.getPermissionsState(); 3749 if (permissionsState.hasPermission(permName, userId)) { 3750 return PackageManager.PERMISSION_GRANTED; 3751 } 3752 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3753 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3754 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3755 return PackageManager.PERMISSION_GRANTED; 3756 } 3757 } 3758 } 3759 3760 return PackageManager.PERMISSION_DENIED; 3761 } 3762 3763 @Override 3764 public int checkUidPermission(String permName, int uid) { 3765 final int userId = UserHandle.getUserId(uid); 3766 3767 if (!sUserManager.exists(userId)) { 3768 return PackageManager.PERMISSION_DENIED; 3769 } 3770 3771 synchronized (mPackages) { 3772 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3773 if (obj != null) { 3774 final SettingBase ps = (SettingBase) obj; 3775 final PermissionsState permissionsState = ps.getPermissionsState(); 3776 if (permissionsState.hasPermission(permName, userId)) { 3777 return PackageManager.PERMISSION_GRANTED; 3778 } 3779 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3780 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3781 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3782 return PackageManager.PERMISSION_GRANTED; 3783 } 3784 } else { 3785 ArraySet<String> perms = mSystemPermissions.get(uid); 3786 if (perms != null) { 3787 if (perms.contains(permName)) { 3788 return PackageManager.PERMISSION_GRANTED; 3789 } 3790 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3791 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3792 return PackageManager.PERMISSION_GRANTED; 3793 } 3794 } 3795 } 3796 } 3797 3798 return PackageManager.PERMISSION_DENIED; 3799 } 3800 3801 @Override 3802 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3803 if (UserHandle.getCallingUserId() != userId) { 3804 mContext.enforceCallingPermission( 3805 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3806 "isPermissionRevokedByPolicy for user " + userId); 3807 } 3808 3809 if (checkPermission(permission, packageName, userId) 3810 == PackageManager.PERMISSION_GRANTED) { 3811 return false; 3812 } 3813 3814 final long identity = Binder.clearCallingIdentity(); 3815 try { 3816 final int flags = getPermissionFlags(permission, packageName, userId); 3817 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3818 } finally { 3819 Binder.restoreCallingIdentity(identity); 3820 } 3821 } 3822 3823 @Override 3824 public String getPermissionControllerPackageName() { 3825 synchronized (mPackages) { 3826 return mRequiredInstallerPackage; 3827 } 3828 } 3829 3830 /** 3831 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3832 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3833 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3834 * @param message the message to log on security exception 3835 */ 3836 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3837 boolean checkShell, String message) { 3838 if (userId < 0) { 3839 throw new IllegalArgumentException("Invalid userId " + userId); 3840 } 3841 if (checkShell) { 3842 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3843 } 3844 if (userId == UserHandle.getUserId(callingUid)) return; 3845 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3846 if (requireFullPermission) { 3847 mContext.enforceCallingOrSelfPermission( 3848 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3849 } else { 3850 try { 3851 mContext.enforceCallingOrSelfPermission( 3852 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3853 } catch (SecurityException se) { 3854 mContext.enforceCallingOrSelfPermission( 3855 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3856 } 3857 } 3858 } 3859 } 3860 3861 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3862 if (callingUid == Process.SHELL_UID) { 3863 if (userHandle >= 0 3864 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3865 throw new SecurityException("Shell does not have permission to access user " 3866 + userHandle); 3867 } else if (userHandle < 0) { 3868 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3869 + Debug.getCallers(3)); 3870 } 3871 } 3872 } 3873 3874 private BasePermission findPermissionTreeLP(String permName) { 3875 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3876 if (permName.startsWith(bp.name) && 3877 permName.length() > bp.name.length() && 3878 permName.charAt(bp.name.length()) == '.') { 3879 return bp; 3880 } 3881 } 3882 return null; 3883 } 3884 3885 private BasePermission checkPermissionTreeLP(String permName) { 3886 if (permName != null) { 3887 BasePermission bp = findPermissionTreeLP(permName); 3888 if (bp != null) { 3889 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3890 return bp; 3891 } 3892 throw new SecurityException("Calling uid " 3893 + Binder.getCallingUid() 3894 + " is not allowed to add to permission tree " 3895 + bp.name + " owned by uid " + bp.uid); 3896 } 3897 } 3898 throw new SecurityException("No permission tree found for " + permName); 3899 } 3900 3901 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3902 if (s1 == null) { 3903 return s2 == null; 3904 } 3905 if (s2 == null) { 3906 return false; 3907 } 3908 if (s1.getClass() != s2.getClass()) { 3909 return false; 3910 } 3911 return s1.equals(s2); 3912 } 3913 3914 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3915 if (pi1.icon != pi2.icon) return false; 3916 if (pi1.logo != pi2.logo) return false; 3917 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3918 if (!compareStrings(pi1.name, pi2.name)) return false; 3919 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3920 // We'll take care of setting this one. 3921 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3922 // These are not currently stored in settings. 3923 //if (!compareStrings(pi1.group, pi2.group)) return false; 3924 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3925 //if (pi1.labelRes != pi2.labelRes) return false; 3926 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3927 return true; 3928 } 3929 3930 int permissionInfoFootprint(PermissionInfo info) { 3931 int size = info.name.length(); 3932 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3933 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3934 return size; 3935 } 3936 3937 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3938 int size = 0; 3939 for (BasePermission perm : mSettings.mPermissions.values()) { 3940 if (perm.uid == tree.uid) { 3941 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3942 } 3943 } 3944 return size; 3945 } 3946 3947 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3948 // We calculate the max size of permissions defined by this uid and throw 3949 // if that plus the size of 'info' would exceed our stated maximum. 3950 if (tree.uid != Process.SYSTEM_UID) { 3951 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3952 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3953 throw new SecurityException("Permission tree size cap exceeded"); 3954 } 3955 } 3956 } 3957 3958 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3959 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3960 throw new SecurityException("Label must be specified in permission"); 3961 } 3962 BasePermission tree = checkPermissionTreeLP(info.name); 3963 BasePermission bp = mSettings.mPermissions.get(info.name); 3964 boolean added = bp == null; 3965 boolean changed = true; 3966 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3967 if (added) { 3968 enforcePermissionCapLocked(info, tree); 3969 bp = new BasePermission(info.name, tree.sourcePackage, 3970 BasePermission.TYPE_DYNAMIC); 3971 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3972 throw new SecurityException( 3973 "Not allowed to modify non-dynamic permission " 3974 + info.name); 3975 } else { 3976 if (bp.protectionLevel == fixedLevel 3977 && bp.perm.owner.equals(tree.perm.owner) 3978 && bp.uid == tree.uid 3979 && comparePermissionInfos(bp.perm.info, info)) { 3980 changed = false; 3981 } 3982 } 3983 bp.protectionLevel = fixedLevel; 3984 info = new PermissionInfo(info); 3985 info.protectionLevel = fixedLevel; 3986 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3987 bp.perm.info.packageName = tree.perm.info.packageName; 3988 bp.uid = tree.uid; 3989 if (added) { 3990 mSettings.mPermissions.put(info.name, bp); 3991 } 3992 if (changed) { 3993 if (!async) { 3994 mSettings.writeLPr(); 3995 } else { 3996 scheduleWriteSettingsLocked(); 3997 } 3998 } 3999 return added; 4000 } 4001 4002 @Override 4003 public boolean addPermission(PermissionInfo info) { 4004 synchronized (mPackages) { 4005 return addPermissionLocked(info, false); 4006 } 4007 } 4008 4009 @Override 4010 public boolean addPermissionAsync(PermissionInfo info) { 4011 synchronized (mPackages) { 4012 return addPermissionLocked(info, true); 4013 } 4014 } 4015 4016 @Override 4017 public void removePermission(String name) { 4018 synchronized (mPackages) { 4019 checkPermissionTreeLP(name); 4020 BasePermission bp = mSettings.mPermissions.get(name); 4021 if (bp != null) { 4022 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4023 throw new SecurityException( 4024 "Not allowed to modify non-dynamic permission " 4025 + name); 4026 } 4027 mSettings.mPermissions.remove(name); 4028 mSettings.writeLPr(); 4029 } 4030 } 4031 } 4032 4033 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4034 BasePermission bp) { 4035 int index = pkg.requestedPermissions.indexOf(bp.name); 4036 if (index == -1) { 4037 throw new SecurityException("Package " + pkg.packageName 4038 + " has not requested permission " + bp.name); 4039 } 4040 if (!bp.isRuntime() && !bp.isDevelopment()) { 4041 throw new SecurityException("Permission " + bp.name 4042 + " is not a changeable permission type"); 4043 } 4044 } 4045 4046 @Override 4047 public void grantRuntimePermission(String packageName, String name, final int userId) { 4048 if (!sUserManager.exists(userId)) { 4049 Log.e(TAG, "No such user:" + userId); 4050 return; 4051 } 4052 4053 mContext.enforceCallingOrSelfPermission( 4054 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4055 "grantRuntimePermission"); 4056 4057 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4058 true /* requireFullPermission */, true /* checkShell */, 4059 "grantRuntimePermission"); 4060 4061 final int uid; 4062 final SettingBase sb; 4063 4064 synchronized (mPackages) { 4065 final PackageParser.Package pkg = mPackages.get(packageName); 4066 if (pkg == null) { 4067 throw new IllegalArgumentException("Unknown package: " + packageName); 4068 } 4069 4070 final BasePermission bp = mSettings.mPermissions.get(name); 4071 if (bp == null) { 4072 throw new IllegalArgumentException("Unknown permission: " + name); 4073 } 4074 4075 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4076 4077 // If a permission review is required for legacy apps we represent 4078 // their permissions as always granted runtime ones since we need 4079 // to keep the review required permission flag per user while an 4080 // install permission's state is shared across all users. 4081 if (Build.PERMISSIONS_REVIEW_REQUIRED 4082 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4083 && bp.isRuntime()) { 4084 return; 4085 } 4086 4087 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4088 sb = (SettingBase) pkg.mExtras; 4089 if (sb == null) { 4090 throw new IllegalArgumentException("Unknown package: " + packageName); 4091 } 4092 4093 final PermissionsState permissionsState = sb.getPermissionsState(); 4094 4095 final int flags = permissionsState.getPermissionFlags(name, userId); 4096 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4097 throw new SecurityException("Cannot grant system fixed permission " 4098 + name + " for package " + packageName); 4099 } 4100 4101 if (bp.isDevelopment()) { 4102 // Development permissions must be handled specially, since they are not 4103 // normal runtime permissions. For now they apply to all users. 4104 if (permissionsState.grantInstallPermission(bp) != 4105 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4106 scheduleWriteSettingsLocked(); 4107 } 4108 return; 4109 } 4110 4111 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4112 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4113 return; 4114 } 4115 4116 final int result = permissionsState.grantRuntimePermission(bp, userId); 4117 switch (result) { 4118 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4119 return; 4120 } 4121 4122 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4123 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4124 mHandler.post(new Runnable() { 4125 @Override 4126 public void run() { 4127 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4128 } 4129 }); 4130 } 4131 break; 4132 } 4133 4134 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4135 4136 // Not critical if that is lost - app has to request again. 4137 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4138 } 4139 4140 // Only need to do this if user is initialized. Otherwise it's a new user 4141 // and there are no processes running as the user yet and there's no need 4142 // to make an expensive call to remount processes for the changed permissions. 4143 if (READ_EXTERNAL_STORAGE.equals(name) 4144 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4145 final long token = Binder.clearCallingIdentity(); 4146 try { 4147 if (sUserManager.isInitialized(userId)) { 4148 MountServiceInternal mountServiceInternal = LocalServices.getService( 4149 MountServiceInternal.class); 4150 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4151 } 4152 } finally { 4153 Binder.restoreCallingIdentity(token); 4154 } 4155 } 4156 } 4157 4158 @Override 4159 public void revokeRuntimePermission(String packageName, String name, int userId) { 4160 if (!sUserManager.exists(userId)) { 4161 Log.e(TAG, "No such user:" + userId); 4162 return; 4163 } 4164 4165 mContext.enforceCallingOrSelfPermission( 4166 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4167 "revokeRuntimePermission"); 4168 4169 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4170 true /* requireFullPermission */, true /* checkShell */, 4171 "revokeRuntimePermission"); 4172 4173 final int appId; 4174 4175 synchronized (mPackages) { 4176 final PackageParser.Package pkg = mPackages.get(packageName); 4177 if (pkg == null) { 4178 throw new IllegalArgumentException("Unknown package: " + packageName); 4179 } 4180 4181 final BasePermission bp = mSettings.mPermissions.get(name); 4182 if (bp == null) { 4183 throw new IllegalArgumentException("Unknown permission: " + name); 4184 } 4185 4186 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4187 4188 // If a permission review is required for legacy apps we represent 4189 // their permissions as always granted runtime ones since we need 4190 // to keep the review required permission flag per user while an 4191 // install permission's state is shared across all users. 4192 if (Build.PERMISSIONS_REVIEW_REQUIRED 4193 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4194 && bp.isRuntime()) { 4195 return; 4196 } 4197 4198 SettingBase sb = (SettingBase) pkg.mExtras; 4199 if (sb == null) { 4200 throw new IllegalArgumentException("Unknown package: " + packageName); 4201 } 4202 4203 final PermissionsState permissionsState = sb.getPermissionsState(); 4204 4205 final int flags = permissionsState.getPermissionFlags(name, userId); 4206 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4207 throw new SecurityException("Cannot revoke system fixed permission " 4208 + name + " for package " + packageName); 4209 } 4210 4211 if (bp.isDevelopment()) { 4212 // Development permissions must be handled specially, since they are not 4213 // normal runtime permissions. For now they apply to all users. 4214 if (permissionsState.revokeInstallPermission(bp) != 4215 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4216 scheduleWriteSettingsLocked(); 4217 } 4218 return; 4219 } 4220 4221 if (permissionsState.revokeRuntimePermission(bp, userId) == 4222 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4223 return; 4224 } 4225 4226 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4227 4228 // Critical, after this call app should never have the permission. 4229 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4230 4231 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4232 } 4233 4234 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4235 } 4236 4237 @Override 4238 public void resetRuntimePermissions() { 4239 mContext.enforceCallingOrSelfPermission( 4240 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4241 "revokeRuntimePermission"); 4242 4243 int callingUid = Binder.getCallingUid(); 4244 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4245 mContext.enforceCallingOrSelfPermission( 4246 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4247 "resetRuntimePermissions"); 4248 } 4249 4250 synchronized (mPackages) { 4251 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4252 for (int userId : UserManagerService.getInstance().getUserIds()) { 4253 final int packageCount = mPackages.size(); 4254 for (int i = 0; i < packageCount; i++) { 4255 PackageParser.Package pkg = mPackages.valueAt(i); 4256 if (!(pkg.mExtras instanceof PackageSetting)) { 4257 continue; 4258 } 4259 PackageSetting ps = (PackageSetting) pkg.mExtras; 4260 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4261 } 4262 } 4263 } 4264 } 4265 4266 @Override 4267 public int getPermissionFlags(String name, String packageName, int userId) { 4268 if (!sUserManager.exists(userId)) { 4269 return 0; 4270 } 4271 4272 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4273 4274 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4275 true /* requireFullPermission */, false /* checkShell */, 4276 "getPermissionFlags"); 4277 4278 synchronized (mPackages) { 4279 final PackageParser.Package pkg = mPackages.get(packageName); 4280 if (pkg == null) { 4281 return 0; 4282 } 4283 4284 final BasePermission bp = mSettings.mPermissions.get(name); 4285 if (bp == null) { 4286 return 0; 4287 } 4288 4289 SettingBase sb = (SettingBase) pkg.mExtras; 4290 if (sb == null) { 4291 return 0; 4292 } 4293 4294 PermissionsState permissionsState = sb.getPermissionsState(); 4295 return permissionsState.getPermissionFlags(name, userId); 4296 } 4297 } 4298 4299 @Override 4300 public void updatePermissionFlags(String name, String packageName, int flagMask, 4301 int flagValues, int userId) { 4302 if (!sUserManager.exists(userId)) { 4303 return; 4304 } 4305 4306 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4307 4308 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4309 true /* requireFullPermission */, true /* checkShell */, 4310 "updatePermissionFlags"); 4311 4312 // Only the system can change these flags and nothing else. 4313 if (getCallingUid() != Process.SYSTEM_UID) { 4314 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4315 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4316 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4317 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4318 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4319 } 4320 4321 synchronized (mPackages) { 4322 final PackageParser.Package pkg = mPackages.get(packageName); 4323 if (pkg == null) { 4324 throw new IllegalArgumentException("Unknown package: " + packageName); 4325 } 4326 4327 final BasePermission bp = mSettings.mPermissions.get(name); 4328 if (bp == null) { 4329 throw new IllegalArgumentException("Unknown permission: " + name); 4330 } 4331 4332 SettingBase sb = (SettingBase) pkg.mExtras; 4333 if (sb == null) { 4334 throw new IllegalArgumentException("Unknown package: " + packageName); 4335 } 4336 4337 PermissionsState permissionsState = sb.getPermissionsState(); 4338 4339 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4340 4341 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4342 // Install and runtime permissions are stored in different places, 4343 // so figure out what permission changed and persist the change. 4344 if (permissionsState.getInstallPermissionState(name) != null) { 4345 scheduleWriteSettingsLocked(); 4346 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4347 || hadState) { 4348 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4349 } 4350 } 4351 } 4352 } 4353 4354 /** 4355 * Update the permission flags for all packages and runtime permissions of a user in order 4356 * to allow device or profile owner to remove POLICY_FIXED. 4357 */ 4358 @Override 4359 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4360 if (!sUserManager.exists(userId)) { 4361 return; 4362 } 4363 4364 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4365 4366 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4367 true /* requireFullPermission */, true /* checkShell */, 4368 "updatePermissionFlagsForAllApps"); 4369 4370 // Only the system can change system fixed flags. 4371 if (getCallingUid() != Process.SYSTEM_UID) { 4372 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4373 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4374 } 4375 4376 synchronized (mPackages) { 4377 boolean changed = false; 4378 final int packageCount = mPackages.size(); 4379 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4380 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4381 SettingBase sb = (SettingBase) pkg.mExtras; 4382 if (sb == null) { 4383 continue; 4384 } 4385 PermissionsState permissionsState = sb.getPermissionsState(); 4386 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4387 userId, flagMask, flagValues); 4388 } 4389 if (changed) { 4390 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4391 } 4392 } 4393 } 4394 4395 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4396 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4397 != PackageManager.PERMISSION_GRANTED 4398 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4399 != PackageManager.PERMISSION_GRANTED) { 4400 throw new SecurityException(message + " requires " 4401 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4402 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4403 } 4404 } 4405 4406 @Override 4407 public boolean shouldShowRequestPermissionRationale(String permissionName, 4408 String packageName, int userId) { 4409 if (UserHandle.getCallingUserId() != userId) { 4410 mContext.enforceCallingPermission( 4411 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4412 "canShowRequestPermissionRationale for user " + userId); 4413 } 4414 4415 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4416 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4417 return false; 4418 } 4419 4420 if (checkPermission(permissionName, packageName, userId) 4421 == PackageManager.PERMISSION_GRANTED) { 4422 return false; 4423 } 4424 4425 final int flags; 4426 4427 final long identity = Binder.clearCallingIdentity(); 4428 try { 4429 flags = getPermissionFlags(permissionName, 4430 packageName, userId); 4431 } finally { 4432 Binder.restoreCallingIdentity(identity); 4433 } 4434 4435 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4436 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4437 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4438 4439 if ((flags & fixedFlags) != 0) { 4440 return false; 4441 } 4442 4443 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4444 } 4445 4446 @Override 4447 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4448 mContext.enforceCallingOrSelfPermission( 4449 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4450 "addOnPermissionsChangeListener"); 4451 4452 synchronized (mPackages) { 4453 mOnPermissionChangeListeners.addListenerLocked(listener); 4454 } 4455 } 4456 4457 @Override 4458 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4459 synchronized (mPackages) { 4460 mOnPermissionChangeListeners.removeListenerLocked(listener); 4461 } 4462 } 4463 4464 @Override 4465 public boolean isProtectedBroadcast(String actionName) { 4466 synchronized (mPackages) { 4467 if (mProtectedBroadcasts.contains(actionName)) { 4468 return true; 4469 } else if (actionName != null) { 4470 // TODO: remove these terrible hacks 4471 if (actionName.startsWith("android.net.netmon.lingerExpired") 4472 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4473 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4474 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4475 return true; 4476 } 4477 } 4478 } 4479 return false; 4480 } 4481 4482 @Override 4483 public int checkSignatures(String pkg1, String pkg2) { 4484 synchronized (mPackages) { 4485 final PackageParser.Package p1 = mPackages.get(pkg1); 4486 final PackageParser.Package p2 = mPackages.get(pkg2); 4487 if (p1 == null || p1.mExtras == null 4488 || p2 == null || p2.mExtras == null) { 4489 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4490 } 4491 return compareSignatures(p1.mSignatures, p2.mSignatures); 4492 } 4493 } 4494 4495 @Override 4496 public int checkUidSignatures(int uid1, int uid2) { 4497 // Map to base uids. 4498 uid1 = UserHandle.getAppId(uid1); 4499 uid2 = UserHandle.getAppId(uid2); 4500 // reader 4501 synchronized (mPackages) { 4502 Signature[] s1; 4503 Signature[] s2; 4504 Object obj = mSettings.getUserIdLPr(uid1); 4505 if (obj != null) { 4506 if (obj instanceof SharedUserSetting) { 4507 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4508 } else if (obj instanceof PackageSetting) { 4509 s1 = ((PackageSetting)obj).signatures.mSignatures; 4510 } else { 4511 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4512 } 4513 } else { 4514 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4515 } 4516 obj = mSettings.getUserIdLPr(uid2); 4517 if (obj != null) { 4518 if (obj instanceof SharedUserSetting) { 4519 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4520 } else if (obj instanceof PackageSetting) { 4521 s2 = ((PackageSetting)obj).signatures.mSignatures; 4522 } else { 4523 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4524 } 4525 } else { 4526 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4527 } 4528 return compareSignatures(s1, s2); 4529 } 4530 } 4531 4532 /** 4533 * This method should typically only be used when granting or revoking 4534 * permissions, since the app may immediately restart after this call. 4535 * <p> 4536 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4537 * guard your work against the app being relaunched. 4538 */ 4539 private void killUid(int appId, int userId, String reason) { 4540 final long identity = Binder.clearCallingIdentity(); 4541 try { 4542 IActivityManager am = ActivityManagerNative.getDefault(); 4543 if (am != null) { 4544 try { 4545 am.killUid(appId, userId, reason); 4546 } catch (RemoteException e) { 4547 /* ignore - same process */ 4548 } 4549 } 4550 } finally { 4551 Binder.restoreCallingIdentity(identity); 4552 } 4553 } 4554 4555 /** 4556 * Compares two sets of signatures. Returns: 4557 * <br /> 4558 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4559 * <br /> 4560 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4561 * <br /> 4562 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4563 * <br /> 4564 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4565 * <br /> 4566 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4567 */ 4568 static int compareSignatures(Signature[] s1, Signature[] s2) { 4569 if (s1 == null) { 4570 return s2 == null 4571 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4572 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4573 } 4574 4575 if (s2 == null) { 4576 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4577 } 4578 4579 if (s1.length != s2.length) { 4580 return PackageManager.SIGNATURE_NO_MATCH; 4581 } 4582 4583 // Since both signature sets are of size 1, we can compare without HashSets. 4584 if (s1.length == 1) { 4585 return s1[0].equals(s2[0]) ? 4586 PackageManager.SIGNATURE_MATCH : 4587 PackageManager.SIGNATURE_NO_MATCH; 4588 } 4589 4590 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4591 for (Signature sig : s1) { 4592 set1.add(sig); 4593 } 4594 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4595 for (Signature sig : s2) { 4596 set2.add(sig); 4597 } 4598 // Make sure s2 contains all signatures in s1. 4599 if (set1.equals(set2)) { 4600 return PackageManager.SIGNATURE_MATCH; 4601 } 4602 return PackageManager.SIGNATURE_NO_MATCH; 4603 } 4604 4605 /** 4606 * If the database version for this type of package (internal storage or 4607 * external storage) is less than the version where package signatures 4608 * were updated, return true. 4609 */ 4610 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4611 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4612 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4613 } 4614 4615 /** 4616 * Used for backward compatibility to make sure any packages with 4617 * certificate chains get upgraded to the new style. {@code existingSigs} 4618 * will be in the old format (since they were stored on disk from before the 4619 * system upgrade) and {@code scannedSigs} will be in the newer format. 4620 */ 4621 private int compareSignaturesCompat(PackageSignatures existingSigs, 4622 PackageParser.Package scannedPkg) { 4623 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4624 return PackageManager.SIGNATURE_NO_MATCH; 4625 } 4626 4627 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4628 for (Signature sig : existingSigs.mSignatures) { 4629 existingSet.add(sig); 4630 } 4631 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4632 for (Signature sig : scannedPkg.mSignatures) { 4633 try { 4634 Signature[] chainSignatures = sig.getChainSignatures(); 4635 for (Signature chainSig : chainSignatures) { 4636 scannedCompatSet.add(chainSig); 4637 } 4638 } catch (CertificateEncodingException e) { 4639 scannedCompatSet.add(sig); 4640 } 4641 } 4642 /* 4643 * Make sure the expanded scanned set contains all signatures in the 4644 * existing one. 4645 */ 4646 if (scannedCompatSet.equals(existingSet)) { 4647 // Migrate the old signatures to the new scheme. 4648 existingSigs.assignSignatures(scannedPkg.mSignatures); 4649 // The new KeySets will be re-added later in the scanning process. 4650 synchronized (mPackages) { 4651 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4652 } 4653 return PackageManager.SIGNATURE_MATCH; 4654 } 4655 return PackageManager.SIGNATURE_NO_MATCH; 4656 } 4657 4658 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4659 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4660 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4661 } 4662 4663 private int compareSignaturesRecover(PackageSignatures existingSigs, 4664 PackageParser.Package scannedPkg) { 4665 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4666 return PackageManager.SIGNATURE_NO_MATCH; 4667 } 4668 4669 String msg = null; 4670 try { 4671 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4672 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4673 + scannedPkg.packageName); 4674 return PackageManager.SIGNATURE_MATCH; 4675 } 4676 } catch (CertificateException e) { 4677 msg = e.getMessage(); 4678 } 4679 4680 logCriticalInfo(Log.INFO, 4681 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4682 return PackageManager.SIGNATURE_NO_MATCH; 4683 } 4684 4685 @Override 4686 public List<String> getAllPackages() { 4687 synchronized (mPackages) { 4688 return new ArrayList<String>(mPackages.keySet()); 4689 } 4690 } 4691 4692 @Override 4693 public String[] getPackagesForUid(int uid) { 4694 uid = UserHandle.getAppId(uid); 4695 // reader 4696 synchronized (mPackages) { 4697 Object obj = mSettings.getUserIdLPr(uid); 4698 if (obj instanceof SharedUserSetting) { 4699 final SharedUserSetting sus = (SharedUserSetting) obj; 4700 final int N = sus.packages.size(); 4701 final String[] res = new String[N]; 4702 final Iterator<PackageSetting> it = sus.packages.iterator(); 4703 int i = 0; 4704 while (it.hasNext()) { 4705 res[i++] = it.next().name; 4706 } 4707 return res; 4708 } else if (obj instanceof PackageSetting) { 4709 final PackageSetting ps = (PackageSetting) obj; 4710 return new String[] { ps.name }; 4711 } 4712 } 4713 return null; 4714 } 4715 4716 @Override 4717 public String getNameForUid(int uid) { 4718 // reader 4719 synchronized (mPackages) { 4720 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4721 if (obj instanceof SharedUserSetting) { 4722 final SharedUserSetting sus = (SharedUserSetting) obj; 4723 return sus.name + ":" + sus.userId; 4724 } else if (obj instanceof PackageSetting) { 4725 final PackageSetting ps = (PackageSetting) obj; 4726 return ps.name; 4727 } 4728 } 4729 return null; 4730 } 4731 4732 @Override 4733 public int getUidForSharedUser(String sharedUserName) { 4734 if(sharedUserName == null) { 4735 return -1; 4736 } 4737 // reader 4738 synchronized (mPackages) { 4739 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4740 if (suid == null) { 4741 return -1; 4742 } 4743 return suid.userId; 4744 } 4745 } 4746 4747 @Override 4748 public int getFlagsForUid(int uid) { 4749 synchronized (mPackages) { 4750 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4751 if (obj instanceof SharedUserSetting) { 4752 final SharedUserSetting sus = (SharedUserSetting) obj; 4753 return sus.pkgFlags; 4754 } else if (obj instanceof PackageSetting) { 4755 final PackageSetting ps = (PackageSetting) obj; 4756 return ps.pkgFlags; 4757 } 4758 } 4759 return 0; 4760 } 4761 4762 @Override 4763 public int getPrivateFlagsForUid(int uid) { 4764 synchronized (mPackages) { 4765 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4766 if (obj instanceof SharedUserSetting) { 4767 final SharedUserSetting sus = (SharedUserSetting) obj; 4768 return sus.pkgPrivateFlags; 4769 } else if (obj instanceof PackageSetting) { 4770 final PackageSetting ps = (PackageSetting) obj; 4771 return ps.pkgPrivateFlags; 4772 } 4773 } 4774 return 0; 4775 } 4776 4777 @Override 4778 public boolean isUidPrivileged(int uid) { 4779 uid = UserHandle.getAppId(uid); 4780 // reader 4781 synchronized (mPackages) { 4782 Object obj = mSettings.getUserIdLPr(uid); 4783 if (obj instanceof SharedUserSetting) { 4784 final SharedUserSetting sus = (SharedUserSetting) obj; 4785 final Iterator<PackageSetting> it = sus.packages.iterator(); 4786 while (it.hasNext()) { 4787 if (it.next().isPrivileged()) { 4788 return true; 4789 } 4790 } 4791 } else if (obj instanceof PackageSetting) { 4792 final PackageSetting ps = (PackageSetting) obj; 4793 return ps.isPrivileged(); 4794 } 4795 } 4796 return false; 4797 } 4798 4799 @Override 4800 public String[] getAppOpPermissionPackages(String permissionName) { 4801 synchronized (mPackages) { 4802 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4803 if (pkgs == null) { 4804 return null; 4805 } 4806 return pkgs.toArray(new String[pkgs.size()]); 4807 } 4808 } 4809 4810 @Override 4811 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4812 int flags, int userId) { 4813 try { 4814 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4815 4816 if (!sUserManager.exists(userId)) return null; 4817 flags = updateFlagsForResolve(flags, userId, intent); 4818 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4819 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4820 4821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4822 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4823 flags, userId); 4824 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4825 4826 final ResolveInfo bestChoice = 4827 chooseBestActivity(intent, resolvedType, flags, query, userId); 4828 4829 if (isEphemeralAllowed(intent, query, userId)) { 4830 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4831 final EphemeralResolveInfo ai = 4832 getEphemeralResolveInfo(intent, resolvedType, userId); 4833 if (ai != null) { 4834 if (DEBUG_EPHEMERAL) { 4835 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4836 } 4837 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4838 bestChoice.ephemeralResolveInfo = ai; 4839 } 4840 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4841 } 4842 return bestChoice; 4843 } finally { 4844 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4845 } 4846 } 4847 4848 @Override 4849 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4850 IntentFilter filter, int match, ComponentName activity) { 4851 final int userId = UserHandle.getCallingUserId(); 4852 if (DEBUG_PREFERRED) { 4853 Log.v(TAG, "setLastChosenActivity intent=" + intent 4854 + " resolvedType=" + resolvedType 4855 + " flags=" + flags 4856 + " filter=" + filter 4857 + " match=" + match 4858 + " activity=" + activity); 4859 filter.dump(new PrintStreamPrinter(System.out), " "); 4860 } 4861 intent.setComponent(null); 4862 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4863 userId); 4864 // Find any earlier preferred or last chosen entries and nuke them 4865 findPreferredActivity(intent, resolvedType, 4866 flags, query, 0, false, true, false, userId); 4867 // Add the new activity as the last chosen for this filter 4868 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4869 "Setting last chosen"); 4870 } 4871 4872 @Override 4873 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4874 final int userId = UserHandle.getCallingUserId(); 4875 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4876 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4877 userId); 4878 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4879 false, false, false, userId); 4880 } 4881 4882 4883 private boolean isEphemeralAllowed( 4884 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4885 // Short circuit and return early if possible. 4886 if (DISABLE_EPHEMERAL_APPS) { 4887 return false; 4888 } 4889 final int callingUser = UserHandle.getCallingUserId(); 4890 if (callingUser != UserHandle.USER_SYSTEM) { 4891 return false; 4892 } 4893 if (mEphemeralResolverConnection == null) { 4894 return false; 4895 } 4896 if (intent.getComponent() != null) { 4897 return false; 4898 } 4899 if (intent.getPackage() != null) { 4900 return false; 4901 } 4902 final boolean isWebUri = hasWebURI(intent); 4903 if (!isWebUri) { 4904 return false; 4905 } 4906 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4907 synchronized (mPackages) { 4908 final int count = resolvedActivites.size(); 4909 for (int n = 0; n < count; n++) { 4910 ResolveInfo info = resolvedActivites.get(n); 4911 String packageName = info.activityInfo.packageName; 4912 PackageSetting ps = mSettings.mPackages.get(packageName); 4913 if (ps != null) { 4914 // Try to get the status from User settings first 4915 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4916 int status = (int) (packedStatus >> 32); 4917 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4918 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4919 if (DEBUG_EPHEMERAL) { 4920 Slog.v(TAG, "DENY ephemeral apps;" 4921 + " pkg: " + packageName + ", status: " + status); 4922 } 4923 return false; 4924 } 4925 } 4926 } 4927 } 4928 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4929 return true; 4930 } 4931 4932 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4933 int userId) { 4934 MessageDigest digest = null; 4935 try { 4936 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4937 } catch (NoSuchAlgorithmException e) { 4938 // If we can't create a digest, ignore ephemeral apps. 4939 return null; 4940 } 4941 4942 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4943 final byte[] digestBytes = digest.digest(hostBytes); 4944 int shaPrefix = 4945 digestBytes[0] << 24 4946 | digestBytes[1] << 16 4947 | digestBytes[2] << 8 4948 | digestBytes[3] << 0; 4949 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4950 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4951 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4952 // No hash prefix match; there are no ephemeral apps for this domain. 4953 return null; 4954 } 4955 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4956 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4957 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4958 continue; 4959 } 4960 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4961 // No filters; this should never happen. 4962 if (filters.isEmpty()) { 4963 continue; 4964 } 4965 // We have a domain match; resolve the filters to see if anything matches. 4966 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4967 for (int j = filters.size() - 1; j >= 0; --j) { 4968 final EphemeralResolveIntentInfo intentInfo = 4969 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4970 ephemeralResolver.addFilter(intentInfo); 4971 } 4972 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4973 intent, resolvedType, false /*defaultOnly*/, userId); 4974 if (!matchedResolveInfoList.isEmpty()) { 4975 return matchedResolveInfoList.get(0); 4976 } 4977 } 4978 // Hash or filter mis-match; no ephemeral apps for this domain. 4979 return null; 4980 } 4981 4982 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4983 int flags, List<ResolveInfo> query, int userId) { 4984 if (query != null) { 4985 final int N = query.size(); 4986 if (N == 1) { 4987 return query.get(0); 4988 } else if (N > 1) { 4989 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4990 // If there is more than one activity with the same priority, 4991 // then let the user decide between them. 4992 ResolveInfo r0 = query.get(0); 4993 ResolveInfo r1 = query.get(1); 4994 if (DEBUG_INTENT_MATCHING || debug) { 4995 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4996 + r1.activityInfo.name + "=" + r1.priority); 4997 } 4998 // If the first activity has a higher priority, or a different 4999 // default, then it is always desirable to pick it. 5000 if (r0.priority != r1.priority 5001 || r0.preferredOrder != r1.preferredOrder 5002 || r0.isDefault != r1.isDefault) { 5003 return query.get(0); 5004 } 5005 // If we have saved a preference for a preferred activity for 5006 // this Intent, use that. 5007 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5008 flags, query, r0.priority, true, false, debug, userId); 5009 if (ri != null) { 5010 return ri; 5011 } 5012 ri = new ResolveInfo(mResolveInfo); 5013 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5014 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5015 // If all of the options come from the same package, show the application's 5016 // label and icon instead of the generic resolver's. 5017 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5018 // and then throw away the ResolveInfo itself, meaning that the caller loses 5019 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5020 // a fallback for this case; we only set the target package's resources on 5021 // the ResolveInfo, not the ActivityInfo. 5022 final String intentPackage = intent.getPackage(); 5023 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5024 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5025 ri.resolvePackageName = intentPackage; 5026 if (userNeedsBadging(userId)) { 5027 ri.noResourceId = true; 5028 } else { 5029 ri.icon = appi.icon; 5030 } 5031 ri.iconResourceId = appi.icon; 5032 ri.labelRes = appi.labelRes; 5033 } 5034 ri.activityInfo.applicationInfo = new ApplicationInfo( 5035 ri.activityInfo.applicationInfo); 5036 if (userId != 0) { 5037 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5038 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5039 } 5040 // Make sure that the resolver is displayable in car mode 5041 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5042 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5043 return ri; 5044 } 5045 } 5046 return null; 5047 } 5048 5049 /** 5050 * Return true if the given list is not empty and all of its contents have 5051 * an activityInfo with the given package name. 5052 */ 5053 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5054 if (ArrayUtils.isEmpty(list)) { 5055 return false; 5056 } 5057 for (int i = 0, N = list.size(); i < N; i++) { 5058 final ResolveInfo ri = list.get(i); 5059 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5060 if (ai == null || !packageName.equals(ai.packageName)) { 5061 return false; 5062 } 5063 } 5064 return true; 5065 } 5066 5067 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5068 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5069 final int N = query.size(); 5070 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5071 .get(userId); 5072 // Get the list of persistent preferred activities that handle the intent 5073 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5074 List<PersistentPreferredActivity> pprefs = ppir != null 5075 ? ppir.queryIntent(intent, resolvedType, 5076 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5077 : null; 5078 if (pprefs != null && pprefs.size() > 0) { 5079 final int M = pprefs.size(); 5080 for (int i=0; i<M; i++) { 5081 final PersistentPreferredActivity ppa = pprefs.get(i); 5082 if (DEBUG_PREFERRED || debug) { 5083 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5084 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5085 + "\n component=" + ppa.mComponent); 5086 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5087 } 5088 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5089 flags | MATCH_DISABLED_COMPONENTS, userId); 5090 if (DEBUG_PREFERRED || debug) { 5091 Slog.v(TAG, "Found persistent preferred activity:"); 5092 if (ai != null) { 5093 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5094 } else { 5095 Slog.v(TAG, " null"); 5096 } 5097 } 5098 if (ai == null) { 5099 // This previously registered persistent preferred activity 5100 // component is no longer known. Ignore it and do NOT remove it. 5101 continue; 5102 } 5103 for (int j=0; j<N; j++) { 5104 final ResolveInfo ri = query.get(j); 5105 if (!ri.activityInfo.applicationInfo.packageName 5106 .equals(ai.applicationInfo.packageName)) { 5107 continue; 5108 } 5109 if (!ri.activityInfo.name.equals(ai.name)) { 5110 continue; 5111 } 5112 // Found a persistent preference that can handle the intent. 5113 if (DEBUG_PREFERRED || debug) { 5114 Slog.v(TAG, "Returning persistent preferred activity: " + 5115 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5116 } 5117 return ri; 5118 } 5119 } 5120 } 5121 return null; 5122 } 5123 5124 // TODO: handle preferred activities missing while user has amnesia 5125 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5126 List<ResolveInfo> query, int priority, boolean always, 5127 boolean removeMatches, boolean debug, int userId) { 5128 if (!sUserManager.exists(userId)) return null; 5129 flags = updateFlagsForResolve(flags, userId, intent); 5130 // writer 5131 synchronized (mPackages) { 5132 if (intent.getSelector() != null) { 5133 intent = intent.getSelector(); 5134 } 5135 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5136 5137 // Try to find a matching persistent preferred activity. 5138 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5139 debug, userId); 5140 5141 // If a persistent preferred activity matched, use it. 5142 if (pri != null) { 5143 return pri; 5144 } 5145 5146 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5147 // Get the list of preferred activities that handle the intent 5148 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5149 List<PreferredActivity> prefs = pir != null 5150 ? pir.queryIntent(intent, resolvedType, 5151 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5152 : null; 5153 if (prefs != null && prefs.size() > 0) { 5154 boolean changed = false; 5155 try { 5156 // First figure out how good the original match set is. 5157 // We will only allow preferred activities that came 5158 // from the same match quality. 5159 int match = 0; 5160 5161 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5162 5163 final int N = query.size(); 5164 for (int j=0; j<N; j++) { 5165 final ResolveInfo ri = query.get(j); 5166 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5167 + ": 0x" + Integer.toHexString(match)); 5168 if (ri.match > match) { 5169 match = ri.match; 5170 } 5171 } 5172 5173 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5174 + Integer.toHexString(match)); 5175 5176 match &= IntentFilter.MATCH_CATEGORY_MASK; 5177 final int M = prefs.size(); 5178 for (int i=0; i<M; i++) { 5179 final PreferredActivity pa = prefs.get(i); 5180 if (DEBUG_PREFERRED || debug) { 5181 Slog.v(TAG, "Checking PreferredActivity ds=" 5182 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5183 + "\n component=" + pa.mPref.mComponent); 5184 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5185 } 5186 if (pa.mPref.mMatch != match) { 5187 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5188 + Integer.toHexString(pa.mPref.mMatch)); 5189 continue; 5190 } 5191 // If it's not an "always" type preferred activity and that's what we're 5192 // looking for, skip it. 5193 if (always && !pa.mPref.mAlways) { 5194 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5195 continue; 5196 } 5197 final ActivityInfo ai = getActivityInfo( 5198 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5199 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5200 userId); 5201 if (DEBUG_PREFERRED || debug) { 5202 Slog.v(TAG, "Found preferred activity:"); 5203 if (ai != null) { 5204 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5205 } else { 5206 Slog.v(TAG, " null"); 5207 } 5208 } 5209 if (ai == null) { 5210 // This previously registered preferred activity 5211 // component is no longer known. Most likely an update 5212 // to the app was installed and in the new version this 5213 // component no longer exists. Clean it up by removing 5214 // it from the preferred activities list, and skip it. 5215 Slog.w(TAG, "Removing dangling preferred activity: " 5216 + pa.mPref.mComponent); 5217 pir.removeFilter(pa); 5218 changed = true; 5219 continue; 5220 } 5221 for (int j=0; j<N; j++) { 5222 final ResolveInfo ri = query.get(j); 5223 if (!ri.activityInfo.applicationInfo.packageName 5224 .equals(ai.applicationInfo.packageName)) { 5225 continue; 5226 } 5227 if (!ri.activityInfo.name.equals(ai.name)) { 5228 continue; 5229 } 5230 5231 if (removeMatches) { 5232 pir.removeFilter(pa); 5233 changed = true; 5234 if (DEBUG_PREFERRED) { 5235 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5236 } 5237 break; 5238 } 5239 5240 // Okay we found a previously set preferred or last chosen app. 5241 // If the result set is different from when this 5242 // was created, we need to clear it and re-ask the 5243 // user their preference, if we're looking for an "always" type entry. 5244 if (always && !pa.mPref.sameSet(query)) { 5245 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5246 + intent + " type " + resolvedType); 5247 if (DEBUG_PREFERRED) { 5248 Slog.v(TAG, "Removing preferred activity since set changed " 5249 + pa.mPref.mComponent); 5250 } 5251 pir.removeFilter(pa); 5252 // Re-add the filter as a "last chosen" entry (!always) 5253 PreferredActivity lastChosen = new PreferredActivity( 5254 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5255 pir.addFilter(lastChosen); 5256 changed = true; 5257 return null; 5258 } 5259 5260 // Yay! Either the set matched or we're looking for the last chosen 5261 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5262 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5263 return ri; 5264 } 5265 } 5266 } finally { 5267 if (changed) { 5268 if (DEBUG_PREFERRED) { 5269 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5270 } 5271 scheduleWritePackageRestrictionsLocked(userId); 5272 } 5273 } 5274 } 5275 } 5276 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5277 return null; 5278 } 5279 5280 /* 5281 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5282 */ 5283 @Override 5284 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5285 int targetUserId) { 5286 mContext.enforceCallingOrSelfPermission( 5287 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5288 List<CrossProfileIntentFilter> matches = 5289 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5290 if (matches != null) { 5291 int size = matches.size(); 5292 for (int i = 0; i < size; i++) { 5293 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5294 } 5295 } 5296 if (hasWebURI(intent)) { 5297 // cross-profile app linking works only towards the parent. 5298 final UserInfo parent = getProfileParent(sourceUserId); 5299 synchronized(mPackages) { 5300 int flags = updateFlagsForResolve(0, parent.id, intent); 5301 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5302 intent, resolvedType, flags, sourceUserId, parent.id); 5303 return xpDomainInfo != null; 5304 } 5305 } 5306 return false; 5307 } 5308 5309 private UserInfo getProfileParent(int userId) { 5310 final long identity = Binder.clearCallingIdentity(); 5311 try { 5312 return sUserManager.getProfileParent(userId); 5313 } finally { 5314 Binder.restoreCallingIdentity(identity); 5315 } 5316 } 5317 5318 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5319 String resolvedType, int userId) { 5320 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5321 if (resolver != null) { 5322 return resolver.queryIntent(intent, resolvedType, false, userId); 5323 } 5324 return null; 5325 } 5326 5327 @Override 5328 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5329 String resolvedType, int flags, int userId) { 5330 try { 5331 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5332 5333 return new ParceledListSlice<>( 5334 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5335 } finally { 5336 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5337 } 5338 } 5339 5340 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5341 String resolvedType, int flags, int userId) { 5342 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5343 flags = updateFlagsForResolve(flags, userId, intent); 5344 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5345 false /* requireFullPermission */, false /* checkShell */, 5346 "query intent activities"); 5347 ComponentName comp = intent.getComponent(); 5348 if (comp == null) { 5349 if (intent.getSelector() != null) { 5350 intent = intent.getSelector(); 5351 comp = intent.getComponent(); 5352 } 5353 } 5354 5355 if (comp != null) { 5356 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5357 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5358 if (ai != null) { 5359 final ResolveInfo ri = new ResolveInfo(); 5360 ri.activityInfo = ai; 5361 list.add(ri); 5362 } 5363 return list; 5364 } 5365 5366 // reader 5367 synchronized (mPackages) { 5368 final String pkgName = intent.getPackage(); 5369 if (pkgName == null) { 5370 List<CrossProfileIntentFilter> matchingFilters = 5371 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5372 // Check for results that need to skip the current profile. 5373 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5374 resolvedType, flags, userId); 5375 if (xpResolveInfo != null) { 5376 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5377 result.add(xpResolveInfo); 5378 return filterIfNotSystemUser(result, userId); 5379 } 5380 5381 // Check for results in the current profile. 5382 List<ResolveInfo> result = mActivities.queryIntent( 5383 intent, resolvedType, flags, userId); 5384 result = filterIfNotSystemUser(result, userId); 5385 5386 // Check for cross profile results. 5387 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5388 xpResolveInfo = queryCrossProfileIntents( 5389 matchingFilters, intent, resolvedType, flags, userId, 5390 hasNonNegativePriorityResult); 5391 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5392 boolean isVisibleToUser = filterIfNotSystemUser( 5393 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5394 if (isVisibleToUser) { 5395 result.add(xpResolveInfo); 5396 Collections.sort(result, mResolvePrioritySorter); 5397 } 5398 } 5399 if (hasWebURI(intent)) { 5400 CrossProfileDomainInfo xpDomainInfo = null; 5401 final UserInfo parent = getProfileParent(userId); 5402 if (parent != null) { 5403 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5404 flags, userId, parent.id); 5405 } 5406 if (xpDomainInfo != null) { 5407 if (xpResolveInfo != null) { 5408 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5409 // in the result. 5410 result.remove(xpResolveInfo); 5411 } 5412 if (result.size() == 0) { 5413 result.add(xpDomainInfo.resolveInfo); 5414 return result; 5415 } 5416 } else if (result.size() <= 1) { 5417 return result; 5418 } 5419 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5420 xpDomainInfo, userId); 5421 Collections.sort(result, mResolvePrioritySorter); 5422 } 5423 return result; 5424 } 5425 final PackageParser.Package pkg = mPackages.get(pkgName); 5426 if (pkg != null) { 5427 return filterIfNotSystemUser( 5428 mActivities.queryIntentForPackage( 5429 intent, resolvedType, flags, pkg.activities, userId), 5430 userId); 5431 } 5432 return new ArrayList<ResolveInfo>(); 5433 } 5434 } 5435 5436 private static class CrossProfileDomainInfo { 5437 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5438 ResolveInfo resolveInfo; 5439 /* Best domain verification status of the activities found in the other profile */ 5440 int bestDomainVerificationStatus; 5441 } 5442 5443 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5444 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5445 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5446 sourceUserId)) { 5447 return null; 5448 } 5449 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5450 resolvedType, flags, parentUserId); 5451 5452 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5453 return null; 5454 } 5455 CrossProfileDomainInfo result = null; 5456 int size = resultTargetUser.size(); 5457 for (int i = 0; i < size; i++) { 5458 ResolveInfo riTargetUser = resultTargetUser.get(i); 5459 // Intent filter verification is only for filters that specify a host. So don't return 5460 // those that handle all web uris. 5461 if (riTargetUser.handleAllWebDataURI) { 5462 continue; 5463 } 5464 String packageName = riTargetUser.activityInfo.packageName; 5465 PackageSetting ps = mSettings.mPackages.get(packageName); 5466 if (ps == null) { 5467 continue; 5468 } 5469 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5470 int status = (int)(verificationState >> 32); 5471 if (result == null) { 5472 result = new CrossProfileDomainInfo(); 5473 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5474 sourceUserId, parentUserId); 5475 result.bestDomainVerificationStatus = status; 5476 } else { 5477 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5478 result.bestDomainVerificationStatus); 5479 } 5480 } 5481 // Don't consider matches with status NEVER across profiles. 5482 if (result != null && result.bestDomainVerificationStatus 5483 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5484 return null; 5485 } 5486 return result; 5487 } 5488 5489 /** 5490 * Verification statuses are ordered from the worse to the best, except for 5491 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5492 */ 5493 private int bestDomainVerificationStatus(int status1, int status2) { 5494 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5495 return status2; 5496 } 5497 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5498 return status1; 5499 } 5500 return (int) MathUtils.max(status1, status2); 5501 } 5502 5503 private boolean isUserEnabled(int userId) { 5504 long callingId = Binder.clearCallingIdentity(); 5505 try { 5506 UserInfo userInfo = sUserManager.getUserInfo(userId); 5507 return userInfo != null && userInfo.isEnabled(); 5508 } finally { 5509 Binder.restoreCallingIdentity(callingId); 5510 } 5511 } 5512 5513 /** 5514 * Filter out activities with systemUserOnly flag set, when current user is not System. 5515 * 5516 * @return filtered list 5517 */ 5518 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5519 if (userId == UserHandle.USER_SYSTEM) { 5520 return resolveInfos; 5521 } 5522 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5523 ResolveInfo info = resolveInfos.get(i); 5524 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5525 resolveInfos.remove(i); 5526 } 5527 } 5528 return resolveInfos; 5529 } 5530 5531 /** 5532 * @param resolveInfos list of resolve infos in descending priority order 5533 * @return if the list contains a resolve info with non-negative priority 5534 */ 5535 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5536 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5537 } 5538 5539 private static boolean hasWebURI(Intent intent) { 5540 if (intent.getData() == null) { 5541 return false; 5542 } 5543 final String scheme = intent.getScheme(); 5544 if (TextUtils.isEmpty(scheme)) { 5545 return false; 5546 } 5547 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5548 } 5549 5550 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5551 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5552 int userId) { 5553 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5554 5555 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5556 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5557 candidates.size()); 5558 } 5559 5560 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5561 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5562 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5563 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5564 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5565 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5566 5567 synchronized (mPackages) { 5568 final int count = candidates.size(); 5569 // First, try to use linked apps. Partition the candidates into four lists: 5570 // one for the final results, one for the "do not use ever", one for "undefined status" 5571 // and finally one for "browser app type". 5572 for (int n=0; n<count; n++) { 5573 ResolveInfo info = candidates.get(n); 5574 String packageName = info.activityInfo.packageName; 5575 PackageSetting ps = mSettings.mPackages.get(packageName); 5576 if (ps != null) { 5577 // Add to the special match all list (Browser use case) 5578 if (info.handleAllWebDataURI) { 5579 matchAllList.add(info); 5580 continue; 5581 } 5582 // Try to get the status from User settings first 5583 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5584 int status = (int)(packedStatus >> 32); 5585 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5586 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5587 if (DEBUG_DOMAIN_VERIFICATION) { 5588 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5589 + " : linkgen=" + linkGeneration); 5590 } 5591 // Use link-enabled generation as preferredOrder, i.e. 5592 // prefer newly-enabled over earlier-enabled. 5593 info.preferredOrder = linkGeneration; 5594 alwaysList.add(info); 5595 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5596 if (DEBUG_DOMAIN_VERIFICATION) { 5597 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5598 } 5599 neverList.add(info); 5600 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5601 if (DEBUG_DOMAIN_VERIFICATION) { 5602 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5603 } 5604 alwaysAskList.add(info); 5605 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5606 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5607 if (DEBUG_DOMAIN_VERIFICATION) { 5608 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5609 } 5610 undefinedList.add(info); 5611 } 5612 } 5613 } 5614 5615 // We'll want to include browser possibilities in a few cases 5616 boolean includeBrowser = false; 5617 5618 // First try to add the "always" resolution(s) for the current user, if any 5619 if (alwaysList.size() > 0) { 5620 result.addAll(alwaysList); 5621 } else { 5622 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5623 result.addAll(undefinedList); 5624 // Maybe add one for the other profile. 5625 if (xpDomainInfo != null && ( 5626 xpDomainInfo.bestDomainVerificationStatus 5627 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5628 result.add(xpDomainInfo.resolveInfo); 5629 } 5630 includeBrowser = true; 5631 } 5632 5633 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5634 // If there were 'always' entries their preferred order has been set, so we also 5635 // back that off to make the alternatives equivalent 5636 if (alwaysAskList.size() > 0) { 5637 for (ResolveInfo i : result) { 5638 i.preferredOrder = 0; 5639 } 5640 result.addAll(alwaysAskList); 5641 includeBrowser = true; 5642 } 5643 5644 if (includeBrowser) { 5645 // Also add browsers (all of them or only the default one) 5646 if (DEBUG_DOMAIN_VERIFICATION) { 5647 Slog.v(TAG, " ...including browsers in candidate set"); 5648 } 5649 if ((matchFlags & MATCH_ALL) != 0) { 5650 result.addAll(matchAllList); 5651 } else { 5652 // Browser/generic handling case. If there's a default browser, go straight 5653 // to that (but only if there is no other higher-priority match). 5654 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5655 int maxMatchPrio = 0; 5656 ResolveInfo defaultBrowserMatch = null; 5657 final int numCandidates = matchAllList.size(); 5658 for (int n = 0; n < numCandidates; n++) { 5659 ResolveInfo info = matchAllList.get(n); 5660 // track the highest overall match priority... 5661 if (info.priority > maxMatchPrio) { 5662 maxMatchPrio = info.priority; 5663 } 5664 // ...and the highest-priority default browser match 5665 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5666 if (defaultBrowserMatch == null 5667 || (defaultBrowserMatch.priority < info.priority)) { 5668 if (debug) { 5669 Slog.v(TAG, "Considering default browser match " + info); 5670 } 5671 defaultBrowserMatch = info; 5672 } 5673 } 5674 } 5675 if (defaultBrowserMatch != null 5676 && defaultBrowserMatch.priority >= maxMatchPrio 5677 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5678 { 5679 if (debug) { 5680 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5681 } 5682 result.add(defaultBrowserMatch); 5683 } else { 5684 result.addAll(matchAllList); 5685 } 5686 } 5687 5688 // If there is nothing selected, add all candidates and remove the ones that the user 5689 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5690 if (result.size() == 0) { 5691 result.addAll(candidates); 5692 result.removeAll(neverList); 5693 } 5694 } 5695 } 5696 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5697 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5698 result.size()); 5699 for (ResolveInfo info : result) { 5700 Slog.v(TAG, " + " + info.activityInfo); 5701 } 5702 } 5703 return result; 5704 } 5705 5706 // Returns a packed value as a long: 5707 // 5708 // high 'int'-sized word: link status: undefined/ask/never/always. 5709 // low 'int'-sized word: relative priority among 'always' results. 5710 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5711 long result = ps.getDomainVerificationStatusForUser(userId); 5712 // if none available, get the master status 5713 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5714 if (ps.getIntentFilterVerificationInfo() != null) { 5715 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5716 } 5717 } 5718 return result; 5719 } 5720 5721 private ResolveInfo querySkipCurrentProfileIntents( 5722 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5723 int flags, int sourceUserId) { 5724 if (matchingFilters != null) { 5725 int size = matchingFilters.size(); 5726 for (int i = 0; i < size; i ++) { 5727 CrossProfileIntentFilter filter = matchingFilters.get(i); 5728 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5729 // Checking if there are activities in the target user that can handle the 5730 // intent. 5731 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5732 resolvedType, flags, sourceUserId); 5733 if (resolveInfo != null) { 5734 return resolveInfo; 5735 } 5736 } 5737 } 5738 } 5739 return null; 5740 } 5741 5742 // Return matching ResolveInfo in target user if any. 5743 private ResolveInfo queryCrossProfileIntents( 5744 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5745 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5746 if (matchingFilters != null) { 5747 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5748 // match the same intent. For performance reasons, it is better not to 5749 // run queryIntent twice for the same userId 5750 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5751 int size = matchingFilters.size(); 5752 for (int i = 0; i < size; i++) { 5753 CrossProfileIntentFilter filter = matchingFilters.get(i); 5754 int targetUserId = filter.getTargetUserId(); 5755 boolean skipCurrentProfile = 5756 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5757 boolean skipCurrentProfileIfNoMatchFound = 5758 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5759 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5760 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5761 // Checking if there are activities in the target user that can handle the 5762 // intent. 5763 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5764 resolvedType, flags, sourceUserId); 5765 if (resolveInfo != null) return resolveInfo; 5766 alreadyTriedUserIds.put(targetUserId, true); 5767 } 5768 } 5769 } 5770 return null; 5771 } 5772 5773 /** 5774 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5775 * will forward the intent to the filter's target user. 5776 * Otherwise, returns null. 5777 */ 5778 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5779 String resolvedType, int flags, int sourceUserId) { 5780 int targetUserId = filter.getTargetUserId(); 5781 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5782 resolvedType, flags, targetUserId); 5783 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5784 // If all the matches in the target profile are suspended, return null. 5785 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5786 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5787 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5788 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5789 targetUserId); 5790 } 5791 } 5792 } 5793 return null; 5794 } 5795 5796 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5797 int sourceUserId, int targetUserId) { 5798 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5799 long ident = Binder.clearCallingIdentity(); 5800 boolean targetIsProfile; 5801 try { 5802 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5803 } finally { 5804 Binder.restoreCallingIdentity(ident); 5805 } 5806 String className; 5807 if (targetIsProfile) { 5808 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5809 } else { 5810 className = FORWARD_INTENT_TO_PARENT; 5811 } 5812 ComponentName forwardingActivityComponentName = new ComponentName( 5813 mAndroidApplication.packageName, className); 5814 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5815 sourceUserId); 5816 if (!targetIsProfile) { 5817 forwardingActivityInfo.showUserIcon = targetUserId; 5818 forwardingResolveInfo.noResourceId = true; 5819 } 5820 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5821 forwardingResolveInfo.priority = 0; 5822 forwardingResolveInfo.preferredOrder = 0; 5823 forwardingResolveInfo.match = 0; 5824 forwardingResolveInfo.isDefault = true; 5825 forwardingResolveInfo.filter = filter; 5826 forwardingResolveInfo.targetUserId = targetUserId; 5827 return forwardingResolveInfo; 5828 } 5829 5830 @Override 5831 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5832 Intent[] specifics, String[] specificTypes, Intent intent, 5833 String resolvedType, int flags, int userId) { 5834 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5835 specificTypes, intent, resolvedType, flags, userId)); 5836 } 5837 5838 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5839 Intent[] specifics, String[] specificTypes, Intent intent, 5840 String resolvedType, int flags, int userId) { 5841 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5842 flags = updateFlagsForResolve(flags, userId, intent); 5843 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5844 false /* requireFullPermission */, false /* checkShell */, 5845 "query intent activity options"); 5846 final String resultsAction = intent.getAction(); 5847 5848 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5849 | PackageManager.GET_RESOLVED_FILTER, userId); 5850 5851 if (DEBUG_INTENT_MATCHING) { 5852 Log.v(TAG, "Query " + intent + ": " + results); 5853 } 5854 5855 int specificsPos = 0; 5856 int N; 5857 5858 // todo: note that the algorithm used here is O(N^2). This 5859 // isn't a problem in our current environment, but if we start running 5860 // into situations where we have more than 5 or 10 matches then this 5861 // should probably be changed to something smarter... 5862 5863 // First we go through and resolve each of the specific items 5864 // that were supplied, taking care of removing any corresponding 5865 // duplicate items in the generic resolve list. 5866 if (specifics != null) { 5867 for (int i=0; i<specifics.length; i++) { 5868 final Intent sintent = specifics[i]; 5869 if (sintent == null) { 5870 continue; 5871 } 5872 5873 if (DEBUG_INTENT_MATCHING) { 5874 Log.v(TAG, "Specific #" + i + ": " + sintent); 5875 } 5876 5877 String action = sintent.getAction(); 5878 if (resultsAction != null && resultsAction.equals(action)) { 5879 // If this action was explicitly requested, then don't 5880 // remove things that have it. 5881 action = null; 5882 } 5883 5884 ResolveInfo ri = null; 5885 ActivityInfo ai = null; 5886 5887 ComponentName comp = sintent.getComponent(); 5888 if (comp == null) { 5889 ri = resolveIntent( 5890 sintent, 5891 specificTypes != null ? specificTypes[i] : null, 5892 flags, userId); 5893 if (ri == null) { 5894 continue; 5895 } 5896 if (ri == mResolveInfo) { 5897 // ACK! Must do something better with this. 5898 } 5899 ai = ri.activityInfo; 5900 comp = new ComponentName(ai.applicationInfo.packageName, 5901 ai.name); 5902 } else { 5903 ai = getActivityInfo(comp, flags, userId); 5904 if (ai == null) { 5905 continue; 5906 } 5907 } 5908 5909 // Look for any generic query activities that are duplicates 5910 // of this specific one, and remove them from the results. 5911 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5912 N = results.size(); 5913 int j; 5914 for (j=specificsPos; j<N; j++) { 5915 ResolveInfo sri = results.get(j); 5916 if ((sri.activityInfo.name.equals(comp.getClassName()) 5917 && sri.activityInfo.applicationInfo.packageName.equals( 5918 comp.getPackageName())) 5919 || (action != null && sri.filter.matchAction(action))) { 5920 results.remove(j); 5921 if (DEBUG_INTENT_MATCHING) Log.v( 5922 TAG, "Removing duplicate item from " + j 5923 + " due to specific " + specificsPos); 5924 if (ri == null) { 5925 ri = sri; 5926 } 5927 j--; 5928 N--; 5929 } 5930 } 5931 5932 // Add this specific item to its proper place. 5933 if (ri == null) { 5934 ri = new ResolveInfo(); 5935 ri.activityInfo = ai; 5936 } 5937 results.add(specificsPos, ri); 5938 ri.specificIndex = i; 5939 specificsPos++; 5940 } 5941 } 5942 5943 // Now we go through the remaining generic results and remove any 5944 // duplicate actions that are found here. 5945 N = results.size(); 5946 for (int i=specificsPos; i<N-1; i++) { 5947 final ResolveInfo rii = results.get(i); 5948 if (rii.filter == null) { 5949 continue; 5950 } 5951 5952 // Iterate over all of the actions of this result's intent 5953 // filter... typically this should be just one. 5954 final Iterator<String> it = rii.filter.actionsIterator(); 5955 if (it == null) { 5956 continue; 5957 } 5958 while (it.hasNext()) { 5959 final String action = it.next(); 5960 if (resultsAction != null && resultsAction.equals(action)) { 5961 // If this action was explicitly requested, then don't 5962 // remove things that have it. 5963 continue; 5964 } 5965 for (int j=i+1; j<N; j++) { 5966 final ResolveInfo rij = results.get(j); 5967 if (rij.filter != null && rij.filter.hasAction(action)) { 5968 results.remove(j); 5969 if (DEBUG_INTENT_MATCHING) Log.v( 5970 TAG, "Removing duplicate item from " + j 5971 + " due to action " + action + " at " + i); 5972 j--; 5973 N--; 5974 } 5975 } 5976 } 5977 5978 // If the caller didn't request filter information, drop it now 5979 // so we don't have to marshall/unmarshall it. 5980 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5981 rii.filter = null; 5982 } 5983 } 5984 5985 // Filter out the caller activity if so requested. 5986 if (caller != null) { 5987 N = results.size(); 5988 for (int i=0; i<N; i++) { 5989 ActivityInfo ainfo = results.get(i).activityInfo; 5990 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5991 && caller.getClassName().equals(ainfo.name)) { 5992 results.remove(i); 5993 break; 5994 } 5995 } 5996 } 5997 5998 // If the caller didn't request filter information, 5999 // drop them now so we don't have to 6000 // marshall/unmarshall it. 6001 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6002 N = results.size(); 6003 for (int i=0; i<N; i++) { 6004 results.get(i).filter = null; 6005 } 6006 } 6007 6008 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6009 return results; 6010 } 6011 6012 @Override 6013 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6014 String resolvedType, int flags, int userId) { 6015 return new ParceledListSlice<>( 6016 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6017 } 6018 6019 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6020 String resolvedType, int flags, int userId) { 6021 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6022 flags = updateFlagsForResolve(flags, userId, intent); 6023 ComponentName comp = intent.getComponent(); 6024 if (comp == null) { 6025 if (intent.getSelector() != null) { 6026 intent = intent.getSelector(); 6027 comp = intent.getComponent(); 6028 } 6029 } 6030 if (comp != null) { 6031 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6032 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6033 if (ai != null) { 6034 ResolveInfo ri = new ResolveInfo(); 6035 ri.activityInfo = ai; 6036 list.add(ri); 6037 } 6038 return list; 6039 } 6040 6041 // reader 6042 synchronized (mPackages) { 6043 String pkgName = intent.getPackage(); 6044 if (pkgName == null) { 6045 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6046 } 6047 final PackageParser.Package pkg = mPackages.get(pkgName); 6048 if (pkg != null) { 6049 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6050 userId); 6051 } 6052 return Collections.emptyList(); 6053 } 6054 } 6055 6056 @Override 6057 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6058 if (!sUserManager.exists(userId)) return null; 6059 flags = updateFlagsForResolve(flags, userId, intent); 6060 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6061 if (query != null) { 6062 if (query.size() >= 1) { 6063 // If there is more than one service with the same priority, 6064 // just arbitrarily pick the first one. 6065 return query.get(0); 6066 } 6067 } 6068 return null; 6069 } 6070 6071 @Override 6072 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6073 String resolvedType, int flags, int userId) { 6074 return new ParceledListSlice<>( 6075 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6076 } 6077 6078 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6079 String resolvedType, int flags, int userId) { 6080 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6081 flags = updateFlagsForResolve(flags, userId, intent); 6082 ComponentName comp = intent.getComponent(); 6083 if (comp == null) { 6084 if (intent.getSelector() != null) { 6085 intent = intent.getSelector(); 6086 comp = intent.getComponent(); 6087 } 6088 } 6089 if (comp != null) { 6090 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6091 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6092 if (si != null) { 6093 final ResolveInfo ri = new ResolveInfo(); 6094 ri.serviceInfo = si; 6095 list.add(ri); 6096 } 6097 return list; 6098 } 6099 6100 // reader 6101 synchronized (mPackages) { 6102 String pkgName = intent.getPackage(); 6103 if (pkgName == null) { 6104 return mServices.queryIntent(intent, resolvedType, flags, userId); 6105 } 6106 final PackageParser.Package pkg = mPackages.get(pkgName); 6107 if (pkg != null) { 6108 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6109 userId); 6110 } 6111 return Collections.emptyList(); 6112 } 6113 } 6114 6115 @Override 6116 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6117 String resolvedType, int flags, int userId) { 6118 return new ParceledListSlice<>( 6119 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6120 } 6121 6122 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6123 Intent intent, String resolvedType, int flags, int userId) { 6124 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6125 flags = updateFlagsForResolve(flags, userId, intent); 6126 ComponentName comp = intent.getComponent(); 6127 if (comp == null) { 6128 if (intent.getSelector() != null) { 6129 intent = intent.getSelector(); 6130 comp = intent.getComponent(); 6131 } 6132 } 6133 if (comp != null) { 6134 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6135 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6136 if (pi != null) { 6137 final ResolveInfo ri = new ResolveInfo(); 6138 ri.providerInfo = pi; 6139 list.add(ri); 6140 } 6141 return list; 6142 } 6143 6144 // reader 6145 synchronized (mPackages) { 6146 String pkgName = intent.getPackage(); 6147 if (pkgName == null) { 6148 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6149 } 6150 final PackageParser.Package pkg = mPackages.get(pkgName); 6151 if (pkg != null) { 6152 return mProviders.queryIntentForPackage( 6153 intent, resolvedType, flags, pkg.providers, userId); 6154 } 6155 return Collections.emptyList(); 6156 } 6157 } 6158 6159 @Override 6160 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6161 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6162 flags = updateFlagsForPackage(flags, userId, null); 6163 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6164 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6165 true /* requireFullPermission */, false /* checkShell */, 6166 "get installed packages"); 6167 6168 // writer 6169 synchronized (mPackages) { 6170 ArrayList<PackageInfo> list; 6171 if (listUninstalled) { 6172 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6173 for (PackageSetting ps : mSettings.mPackages.values()) { 6174 final PackageInfo pi; 6175 if (ps.pkg != null) { 6176 pi = generatePackageInfo(ps, flags, userId); 6177 } else { 6178 pi = generatePackageInfo(ps, flags, userId); 6179 } 6180 if (pi != null) { 6181 list.add(pi); 6182 } 6183 } 6184 } else { 6185 list = new ArrayList<PackageInfo>(mPackages.size()); 6186 for (PackageParser.Package p : mPackages.values()) { 6187 final PackageInfo pi = 6188 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6189 if (pi != null) { 6190 list.add(pi); 6191 } 6192 } 6193 } 6194 6195 return new ParceledListSlice<PackageInfo>(list); 6196 } 6197 } 6198 6199 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6200 String[] permissions, boolean[] tmp, int flags, int userId) { 6201 int numMatch = 0; 6202 final PermissionsState permissionsState = ps.getPermissionsState(); 6203 for (int i=0; i<permissions.length; i++) { 6204 final String permission = permissions[i]; 6205 if (permissionsState.hasPermission(permission, userId)) { 6206 tmp[i] = true; 6207 numMatch++; 6208 } else { 6209 tmp[i] = false; 6210 } 6211 } 6212 if (numMatch == 0) { 6213 return; 6214 } 6215 final PackageInfo pi; 6216 if (ps.pkg != null) { 6217 pi = generatePackageInfo(ps, flags, userId); 6218 } else { 6219 pi = generatePackageInfo(ps, flags, userId); 6220 } 6221 // The above might return null in cases of uninstalled apps or install-state 6222 // skew across users/profiles. 6223 if (pi != null) { 6224 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6225 if (numMatch == permissions.length) { 6226 pi.requestedPermissions = permissions; 6227 } else { 6228 pi.requestedPermissions = new String[numMatch]; 6229 numMatch = 0; 6230 for (int i=0; i<permissions.length; i++) { 6231 if (tmp[i]) { 6232 pi.requestedPermissions[numMatch] = permissions[i]; 6233 numMatch++; 6234 } 6235 } 6236 } 6237 } 6238 list.add(pi); 6239 } 6240 } 6241 6242 @Override 6243 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6244 String[] permissions, int flags, int userId) { 6245 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6246 flags = updateFlagsForPackage(flags, userId, permissions); 6247 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6248 6249 // writer 6250 synchronized (mPackages) { 6251 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6252 boolean[] tmpBools = new boolean[permissions.length]; 6253 if (listUninstalled) { 6254 for (PackageSetting ps : mSettings.mPackages.values()) { 6255 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6256 } 6257 } else { 6258 for (PackageParser.Package pkg : mPackages.values()) { 6259 PackageSetting ps = (PackageSetting)pkg.mExtras; 6260 if (ps != null) { 6261 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6262 userId); 6263 } 6264 } 6265 } 6266 6267 return new ParceledListSlice<PackageInfo>(list); 6268 } 6269 } 6270 6271 @Override 6272 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6273 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6274 flags = updateFlagsForApplication(flags, userId, null); 6275 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6276 6277 // writer 6278 synchronized (mPackages) { 6279 ArrayList<ApplicationInfo> list; 6280 if (listUninstalled) { 6281 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6282 for (PackageSetting ps : mSettings.mPackages.values()) { 6283 ApplicationInfo ai; 6284 if (ps.pkg != null) { 6285 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6286 ps.readUserState(userId), userId); 6287 } else { 6288 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6289 } 6290 if (ai != null) { 6291 list.add(ai); 6292 } 6293 } 6294 } else { 6295 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6296 for (PackageParser.Package p : mPackages.values()) { 6297 if (p.mExtras != null) { 6298 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6299 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6300 if (ai != null) { 6301 list.add(ai); 6302 } 6303 } 6304 } 6305 } 6306 6307 return new ParceledListSlice<ApplicationInfo>(list); 6308 } 6309 } 6310 6311 @Override 6312 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6313 if (DISABLE_EPHEMERAL_APPS) { 6314 return null; 6315 } 6316 6317 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6318 "getEphemeralApplications"); 6319 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6320 true /* requireFullPermission */, false /* checkShell */, 6321 "getEphemeralApplications"); 6322 synchronized (mPackages) { 6323 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6324 .getEphemeralApplicationsLPw(userId); 6325 if (ephemeralApps != null) { 6326 return new ParceledListSlice<>(ephemeralApps); 6327 } 6328 } 6329 return null; 6330 } 6331 6332 @Override 6333 public boolean isEphemeralApplication(String packageName, int userId) { 6334 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6335 true /* requireFullPermission */, false /* checkShell */, 6336 "isEphemeral"); 6337 if (DISABLE_EPHEMERAL_APPS) { 6338 return false; 6339 } 6340 6341 if (!isCallerSameApp(packageName)) { 6342 return false; 6343 } 6344 synchronized (mPackages) { 6345 PackageParser.Package pkg = mPackages.get(packageName); 6346 if (pkg != null) { 6347 return pkg.applicationInfo.isEphemeralApp(); 6348 } 6349 } 6350 return false; 6351 } 6352 6353 @Override 6354 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6355 if (DISABLE_EPHEMERAL_APPS) { 6356 return null; 6357 } 6358 6359 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6360 true /* requireFullPermission */, false /* checkShell */, 6361 "getCookie"); 6362 if (!isCallerSameApp(packageName)) { 6363 return null; 6364 } 6365 synchronized (mPackages) { 6366 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6367 packageName, userId); 6368 } 6369 } 6370 6371 @Override 6372 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6373 if (DISABLE_EPHEMERAL_APPS) { 6374 return true; 6375 } 6376 6377 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6378 true /* requireFullPermission */, true /* checkShell */, 6379 "setCookie"); 6380 if (!isCallerSameApp(packageName)) { 6381 return false; 6382 } 6383 synchronized (mPackages) { 6384 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6385 packageName, cookie, userId); 6386 } 6387 } 6388 6389 @Override 6390 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6391 if (DISABLE_EPHEMERAL_APPS) { 6392 return null; 6393 } 6394 6395 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6396 "getEphemeralApplicationIcon"); 6397 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6398 true /* requireFullPermission */, false /* checkShell */, 6399 "getEphemeralApplicationIcon"); 6400 synchronized (mPackages) { 6401 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6402 packageName, userId); 6403 } 6404 } 6405 6406 private boolean isCallerSameApp(String packageName) { 6407 PackageParser.Package pkg = mPackages.get(packageName); 6408 return pkg != null 6409 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6410 } 6411 6412 @Override 6413 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6414 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6415 } 6416 6417 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6418 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6419 6420 // reader 6421 synchronized (mPackages) { 6422 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6423 final int userId = UserHandle.getCallingUserId(); 6424 while (i.hasNext()) { 6425 final PackageParser.Package p = i.next(); 6426 if (p.applicationInfo == null) continue; 6427 6428 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6429 && !p.applicationInfo.isDirectBootAware(); 6430 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6431 && p.applicationInfo.isDirectBootAware(); 6432 6433 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6434 && (!mSafeMode || isSystemApp(p)) 6435 && (matchesUnaware || matchesAware)) { 6436 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6437 if (ps != null) { 6438 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6439 ps.readUserState(userId), userId); 6440 if (ai != null) { 6441 finalList.add(ai); 6442 } 6443 } 6444 } 6445 } 6446 } 6447 6448 return finalList; 6449 } 6450 6451 @Override 6452 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6453 if (!sUserManager.exists(userId)) return null; 6454 flags = updateFlagsForComponent(flags, userId, name); 6455 // reader 6456 synchronized (mPackages) { 6457 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6458 PackageSetting ps = provider != null 6459 ? mSettings.mPackages.get(provider.owner.packageName) 6460 : null; 6461 return ps != null 6462 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6463 ? PackageParser.generateProviderInfo(provider, flags, 6464 ps.readUserState(userId), userId) 6465 : null; 6466 } 6467 } 6468 6469 /** 6470 * @deprecated 6471 */ 6472 @Deprecated 6473 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6474 // reader 6475 synchronized (mPackages) { 6476 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6477 .entrySet().iterator(); 6478 final int userId = UserHandle.getCallingUserId(); 6479 while (i.hasNext()) { 6480 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6481 PackageParser.Provider p = entry.getValue(); 6482 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6483 6484 if (ps != null && p.syncable 6485 && (!mSafeMode || (p.info.applicationInfo.flags 6486 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6487 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6488 ps.readUserState(userId), userId); 6489 if (info != null) { 6490 outNames.add(entry.getKey()); 6491 outInfo.add(info); 6492 } 6493 } 6494 } 6495 } 6496 } 6497 6498 @Override 6499 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6500 int uid, int flags) { 6501 final int userId = processName != null ? UserHandle.getUserId(uid) 6502 : UserHandle.getCallingUserId(); 6503 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6504 flags = updateFlagsForComponent(flags, userId, processName); 6505 6506 ArrayList<ProviderInfo> finalList = null; 6507 // reader 6508 synchronized (mPackages) { 6509 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6510 while (i.hasNext()) { 6511 final PackageParser.Provider p = i.next(); 6512 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6513 if (ps != null && p.info.authority != null 6514 && (processName == null 6515 || (p.info.processName.equals(processName) 6516 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6517 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6518 if (finalList == null) { 6519 finalList = new ArrayList<ProviderInfo>(3); 6520 } 6521 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6522 ps.readUserState(userId), userId); 6523 if (info != null) { 6524 finalList.add(info); 6525 } 6526 } 6527 } 6528 } 6529 6530 if (finalList != null) { 6531 Collections.sort(finalList, mProviderInitOrderSorter); 6532 return new ParceledListSlice<ProviderInfo>(finalList); 6533 } 6534 6535 return ParceledListSlice.emptyList(); 6536 } 6537 6538 @Override 6539 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6540 // reader 6541 synchronized (mPackages) { 6542 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6543 return PackageParser.generateInstrumentationInfo(i, flags); 6544 } 6545 } 6546 6547 @Override 6548 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6549 String targetPackage, int flags) { 6550 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6551 } 6552 6553 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6554 int flags) { 6555 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6556 6557 // reader 6558 synchronized (mPackages) { 6559 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6560 while (i.hasNext()) { 6561 final PackageParser.Instrumentation p = i.next(); 6562 if (targetPackage == null 6563 || targetPackage.equals(p.info.targetPackage)) { 6564 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6565 flags); 6566 if (ii != null) { 6567 finalList.add(ii); 6568 } 6569 } 6570 } 6571 } 6572 6573 return finalList; 6574 } 6575 6576 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6577 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6578 if (overlays == null) { 6579 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6580 return; 6581 } 6582 for (PackageParser.Package opkg : overlays.values()) { 6583 // Not much to do if idmap fails: we already logged the error 6584 // and we certainly don't want to abort installation of pkg simply 6585 // because an overlay didn't fit properly. For these reasons, 6586 // ignore the return value of createIdmapForPackagePairLI. 6587 createIdmapForPackagePairLI(pkg, opkg); 6588 } 6589 } 6590 6591 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6592 PackageParser.Package opkg) { 6593 if (!opkg.mTrustedOverlay) { 6594 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6595 opkg.baseCodePath + ": overlay not trusted"); 6596 return false; 6597 } 6598 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6599 if (overlaySet == null) { 6600 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6601 opkg.baseCodePath + " but target package has no known overlays"); 6602 return false; 6603 } 6604 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6605 // TODO: generate idmap for split APKs 6606 try { 6607 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6608 } catch (InstallerException e) { 6609 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6610 + opkg.baseCodePath); 6611 return false; 6612 } 6613 PackageParser.Package[] overlayArray = 6614 overlaySet.values().toArray(new PackageParser.Package[0]); 6615 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6616 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6617 return p1.mOverlayPriority - p2.mOverlayPriority; 6618 } 6619 }; 6620 Arrays.sort(overlayArray, cmp); 6621 6622 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6623 int i = 0; 6624 for (PackageParser.Package p : overlayArray) { 6625 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6626 } 6627 return true; 6628 } 6629 6630 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6631 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6632 try { 6633 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6634 } finally { 6635 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6636 } 6637 } 6638 6639 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6640 final File[] files = dir.listFiles(); 6641 if (ArrayUtils.isEmpty(files)) { 6642 Log.d(TAG, "No files in app dir " + dir); 6643 return; 6644 } 6645 6646 if (DEBUG_PACKAGE_SCANNING) { 6647 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6648 + " flags=0x" + Integer.toHexString(parseFlags)); 6649 } 6650 6651 for (File file : files) { 6652 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6653 && !PackageInstallerService.isStageName(file.getName()); 6654 if (!isPackage) { 6655 // Ignore entries which are not packages 6656 continue; 6657 } 6658 try { 6659 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6660 scanFlags, currentTime, null); 6661 } catch (PackageManagerException e) { 6662 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6663 6664 // Delete invalid userdata apps 6665 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6666 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6667 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6668 removeCodePathLI(file); 6669 } 6670 } 6671 } 6672 } 6673 6674 private static File getSettingsProblemFile() { 6675 File dataDir = Environment.getDataDirectory(); 6676 File systemDir = new File(dataDir, "system"); 6677 File fname = new File(systemDir, "uiderrors.txt"); 6678 return fname; 6679 } 6680 6681 static void reportSettingsProblem(int priority, String msg) { 6682 logCriticalInfo(priority, msg); 6683 } 6684 6685 static void logCriticalInfo(int priority, String msg) { 6686 Slog.println(priority, TAG, msg); 6687 EventLogTags.writePmCriticalInfo(msg); 6688 try { 6689 File fname = getSettingsProblemFile(); 6690 FileOutputStream out = new FileOutputStream(fname, true); 6691 PrintWriter pw = new FastPrintWriter(out); 6692 SimpleDateFormat formatter = new SimpleDateFormat(); 6693 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6694 pw.println(dateString + ": " + msg); 6695 pw.close(); 6696 FileUtils.setPermissions( 6697 fname.toString(), 6698 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6699 -1, -1); 6700 } catch (java.io.IOException e) { 6701 } 6702 } 6703 6704 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6705 final int policyFlags) throws PackageManagerException { 6706 if (ps != null 6707 && ps.codePath.equals(srcFile) 6708 && ps.timeStamp == srcFile.lastModified() 6709 && !isCompatSignatureUpdateNeeded(pkg) 6710 && !isRecoverSignatureUpdateNeeded(pkg)) { 6711 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6712 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6713 ArraySet<PublicKey> signingKs; 6714 synchronized (mPackages) { 6715 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6716 } 6717 if (ps.signatures.mSignatures != null 6718 && ps.signatures.mSignatures.length != 0 6719 && signingKs != null) { 6720 // Optimization: reuse the existing cached certificates 6721 // if the package appears to be unchanged. 6722 pkg.mSignatures = ps.signatures.mSignatures; 6723 pkg.mSigningKeys = signingKs; 6724 return; 6725 } 6726 6727 Slog.w(TAG, "PackageSetting for " + ps.name 6728 + " is missing signatures. Collecting certs again to recover them."); 6729 } else { 6730 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6731 } 6732 6733 try { 6734 PackageParser.collectCertificates(pkg, policyFlags); 6735 } catch (PackageParserException e) { 6736 throw PackageManagerException.from(e); 6737 } 6738 } 6739 6740 /** 6741 * Traces a package scan. 6742 * @see #scanPackageLI(File, int, int, long, UserHandle) 6743 */ 6744 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6745 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6746 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6747 try { 6748 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6749 } finally { 6750 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6751 } 6752 } 6753 6754 /** 6755 * Scans a package and returns the newly parsed package. 6756 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6757 */ 6758 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6759 long currentTime, UserHandle user) throws PackageManagerException { 6760 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6761 PackageParser pp = new PackageParser(); 6762 pp.setSeparateProcesses(mSeparateProcesses); 6763 pp.setOnlyCoreApps(mOnlyCore); 6764 pp.setDisplayMetrics(mMetrics); 6765 6766 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6767 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6768 } 6769 6770 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6771 final PackageParser.Package pkg; 6772 try { 6773 pkg = pp.parsePackage(scanFile, parseFlags); 6774 } catch (PackageParserException e) { 6775 throw PackageManagerException.from(e); 6776 } finally { 6777 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6778 } 6779 6780 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6781 } 6782 6783 /** 6784 * Scans a package and returns the newly parsed package. 6785 * @throws PackageManagerException on a parse error. 6786 */ 6787 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6788 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6789 throws PackageManagerException { 6790 // If the package has children and this is the first dive in the function 6791 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6792 // packages (parent and children) would be successfully scanned before the 6793 // actual scan since scanning mutates internal state and we want to atomically 6794 // install the package and its children. 6795 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6796 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6797 scanFlags |= SCAN_CHECK_ONLY; 6798 } 6799 } else { 6800 scanFlags &= ~SCAN_CHECK_ONLY; 6801 } 6802 6803 // Scan the parent 6804 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6805 scanFlags, currentTime, user); 6806 6807 // Scan the children 6808 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6809 for (int i = 0; i < childCount; i++) { 6810 PackageParser.Package childPackage = pkg.childPackages.get(i); 6811 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6812 currentTime, user); 6813 } 6814 6815 6816 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6817 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6818 } 6819 6820 return scannedPkg; 6821 } 6822 6823 /** 6824 * Scans a package and returns the newly parsed package. 6825 * @throws PackageManagerException on a parse error. 6826 */ 6827 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6828 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6829 throws PackageManagerException { 6830 PackageSetting ps = null; 6831 PackageSetting updatedPkg; 6832 // reader 6833 synchronized (mPackages) { 6834 // Look to see if we already know about this package. 6835 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6836 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6837 // This package has been renamed to its original name. Let's 6838 // use that. 6839 ps = mSettings.peekPackageLPr(oldName); 6840 } 6841 // If there was no original package, see one for the real package name. 6842 if (ps == null) { 6843 ps = mSettings.peekPackageLPr(pkg.packageName); 6844 } 6845 // Check to see if this package could be hiding/updating a system 6846 // package. Must look for it either under the original or real 6847 // package name depending on our state. 6848 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6849 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6850 6851 // If this is a package we don't know about on the system partition, we 6852 // may need to remove disabled child packages on the system partition 6853 // or may need to not add child packages if the parent apk is updated 6854 // on the data partition and no longer defines this child package. 6855 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6856 // If this is a parent package for an updated system app and this system 6857 // app got an OTA update which no longer defines some of the child packages 6858 // we have to prune them from the disabled system packages. 6859 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6860 if (disabledPs != null) { 6861 final int scannedChildCount = (pkg.childPackages != null) 6862 ? pkg.childPackages.size() : 0; 6863 final int disabledChildCount = disabledPs.childPackageNames != null 6864 ? disabledPs.childPackageNames.size() : 0; 6865 for (int i = 0; i < disabledChildCount; i++) { 6866 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6867 boolean disabledPackageAvailable = false; 6868 for (int j = 0; j < scannedChildCount; j++) { 6869 PackageParser.Package childPkg = pkg.childPackages.get(j); 6870 if (childPkg.packageName.equals(disabledChildPackageName)) { 6871 disabledPackageAvailable = true; 6872 break; 6873 } 6874 } 6875 if (!disabledPackageAvailable) { 6876 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6877 } 6878 } 6879 } 6880 } 6881 } 6882 6883 boolean updatedPkgBetter = false; 6884 // First check if this is a system package that may involve an update 6885 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6886 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6887 // it needs to drop FLAG_PRIVILEGED. 6888 if (locationIsPrivileged(scanFile)) { 6889 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6890 } else { 6891 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6892 } 6893 6894 if (ps != null && !ps.codePath.equals(scanFile)) { 6895 // The path has changed from what was last scanned... check the 6896 // version of the new path against what we have stored to determine 6897 // what to do. 6898 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6899 if (pkg.mVersionCode <= ps.versionCode) { 6900 // The system package has been updated and the code path does not match 6901 // Ignore entry. Skip it. 6902 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6903 + " ignored: updated version " + ps.versionCode 6904 + " better than this " + pkg.mVersionCode); 6905 if (!updatedPkg.codePath.equals(scanFile)) { 6906 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6907 + ps.name + " changing from " + updatedPkg.codePathString 6908 + " to " + scanFile); 6909 updatedPkg.codePath = scanFile; 6910 updatedPkg.codePathString = scanFile.toString(); 6911 updatedPkg.resourcePath = scanFile; 6912 updatedPkg.resourcePathString = scanFile.toString(); 6913 } 6914 updatedPkg.pkg = pkg; 6915 updatedPkg.versionCode = pkg.mVersionCode; 6916 6917 // Update the disabled system child packages to point to the package too. 6918 final int childCount = updatedPkg.childPackageNames != null 6919 ? updatedPkg.childPackageNames.size() : 0; 6920 for (int i = 0; i < childCount; i++) { 6921 String childPackageName = updatedPkg.childPackageNames.get(i); 6922 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6923 childPackageName); 6924 if (updatedChildPkg != null) { 6925 updatedChildPkg.pkg = pkg; 6926 updatedChildPkg.versionCode = pkg.mVersionCode; 6927 } 6928 } 6929 6930 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6931 + scanFile + " ignored: updated version " + ps.versionCode 6932 + " better than this " + pkg.mVersionCode); 6933 } else { 6934 // The current app on the system partition is better than 6935 // what we have updated to on the data partition; switch 6936 // back to the system partition version. 6937 // At this point, its safely assumed that package installation for 6938 // apps in system partition will go through. If not there won't be a working 6939 // version of the app 6940 // writer 6941 synchronized (mPackages) { 6942 // Just remove the loaded entries from package lists. 6943 mPackages.remove(ps.name); 6944 } 6945 6946 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6947 + " reverting from " + ps.codePathString 6948 + ": new version " + pkg.mVersionCode 6949 + " better than installed " + ps.versionCode); 6950 6951 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6952 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6953 synchronized (mInstallLock) { 6954 args.cleanUpResourcesLI(); 6955 } 6956 synchronized (mPackages) { 6957 mSettings.enableSystemPackageLPw(ps.name); 6958 } 6959 updatedPkgBetter = true; 6960 } 6961 } 6962 } 6963 6964 if (updatedPkg != null) { 6965 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6966 // initially 6967 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6968 6969 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6970 // flag set initially 6971 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6972 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6973 } 6974 } 6975 6976 // Verify certificates against what was last scanned 6977 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6978 6979 /* 6980 * A new system app appeared, but we already had a non-system one of the 6981 * same name installed earlier. 6982 */ 6983 boolean shouldHideSystemApp = false; 6984 if (updatedPkg == null && ps != null 6985 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6986 /* 6987 * Check to make sure the signatures match first. If they don't, 6988 * wipe the installed application and its data. 6989 */ 6990 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6991 != PackageManager.SIGNATURE_MATCH) { 6992 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6993 + " signatures don't match existing userdata copy; removing"); 6994 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6995 "scanPackageInternalLI")) { 6996 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6997 } 6998 ps = null; 6999 } else { 7000 /* 7001 * If the newly-added system app is an older version than the 7002 * already installed version, hide it. It will be scanned later 7003 * and re-added like an update. 7004 */ 7005 if (pkg.mVersionCode <= ps.versionCode) { 7006 shouldHideSystemApp = true; 7007 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7008 + " but new version " + pkg.mVersionCode + " better than installed " 7009 + ps.versionCode + "; hiding system"); 7010 } else { 7011 /* 7012 * The newly found system app is a newer version that the 7013 * one previously installed. Simply remove the 7014 * already-installed application and replace it with our own 7015 * while keeping the application data. 7016 */ 7017 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7018 + " reverting from " + ps.codePathString + ": new version " 7019 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7020 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7021 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7022 synchronized (mInstallLock) { 7023 args.cleanUpResourcesLI(); 7024 } 7025 } 7026 } 7027 } 7028 7029 // The apk is forward locked (not public) if its code and resources 7030 // are kept in different files. (except for app in either system or 7031 // vendor path). 7032 // TODO grab this value from PackageSettings 7033 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7034 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7035 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7036 } 7037 } 7038 7039 // TODO: extend to support forward-locked splits 7040 String resourcePath = null; 7041 String baseResourcePath = null; 7042 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7043 if (ps != null && ps.resourcePathString != null) { 7044 resourcePath = ps.resourcePathString; 7045 baseResourcePath = ps.resourcePathString; 7046 } else { 7047 // Should not happen at all. Just log an error. 7048 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7049 } 7050 } else { 7051 resourcePath = pkg.codePath; 7052 baseResourcePath = pkg.baseCodePath; 7053 } 7054 7055 // Set application objects path explicitly. 7056 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7057 pkg.setApplicationInfoCodePath(pkg.codePath); 7058 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7059 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7060 pkg.setApplicationInfoResourcePath(resourcePath); 7061 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7062 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7063 7064 // Note that we invoke the following method only if we are about to unpack an application 7065 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7066 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7067 7068 /* 7069 * If the system app should be overridden by a previously installed 7070 * data, hide the system app now and let the /data/app scan pick it up 7071 * again. 7072 */ 7073 if (shouldHideSystemApp) { 7074 synchronized (mPackages) { 7075 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7076 } 7077 } 7078 7079 return scannedPkg; 7080 } 7081 7082 private static String fixProcessName(String defProcessName, 7083 String processName, int uid) { 7084 if (processName == null) { 7085 return defProcessName; 7086 } 7087 return processName; 7088 } 7089 7090 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7091 throws PackageManagerException { 7092 if (pkgSetting.signatures.mSignatures != null) { 7093 // Already existing package. Make sure signatures match 7094 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7095 == PackageManager.SIGNATURE_MATCH; 7096 if (!match) { 7097 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7098 == PackageManager.SIGNATURE_MATCH; 7099 } 7100 if (!match) { 7101 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7102 == PackageManager.SIGNATURE_MATCH; 7103 } 7104 if (!match) { 7105 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7106 + pkg.packageName + " signatures do not match the " 7107 + "previously installed version; ignoring!"); 7108 } 7109 } 7110 7111 // Check for shared user signatures 7112 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7113 // Already existing package. Make sure signatures match 7114 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7115 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7116 if (!match) { 7117 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7118 == PackageManager.SIGNATURE_MATCH; 7119 } 7120 if (!match) { 7121 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7122 == PackageManager.SIGNATURE_MATCH; 7123 } 7124 if (!match) { 7125 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7126 "Package " + pkg.packageName 7127 + " has no signatures that match those in shared user " 7128 + pkgSetting.sharedUser.name + "; ignoring!"); 7129 } 7130 } 7131 } 7132 7133 /** 7134 * Enforces that only the system UID or root's UID can call a method exposed 7135 * via Binder. 7136 * 7137 * @param message used as message if SecurityException is thrown 7138 * @throws SecurityException if the caller is not system or root 7139 */ 7140 private static final void enforceSystemOrRoot(String message) { 7141 final int uid = Binder.getCallingUid(); 7142 if (uid != Process.SYSTEM_UID && uid != 0) { 7143 throw new SecurityException(message); 7144 } 7145 } 7146 7147 @Override 7148 public void performFstrimIfNeeded() { 7149 enforceSystemOrRoot("Only the system can request fstrim"); 7150 7151 // Before everything else, see whether we need to fstrim. 7152 try { 7153 IMountService ms = PackageHelper.getMountService(); 7154 if (ms != null) { 7155 final boolean isUpgrade = isUpgrade(); 7156 boolean doTrim = isUpgrade; 7157 if (doTrim) { 7158 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7159 } else { 7160 final long interval = android.provider.Settings.Global.getLong( 7161 mContext.getContentResolver(), 7162 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7163 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7164 if (interval > 0) { 7165 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7166 if (timeSinceLast > interval) { 7167 doTrim = true; 7168 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7169 + "; running immediately"); 7170 } 7171 } 7172 } 7173 if (doTrim) { 7174 if (!isFirstBoot()) { 7175 try { 7176 ActivityManagerNative.getDefault().showBootMessage( 7177 mContext.getResources().getString( 7178 R.string.android_upgrading_fstrim), true); 7179 } catch (RemoteException e) { 7180 } 7181 } 7182 ms.runMaintenance(); 7183 } 7184 } else { 7185 Slog.e(TAG, "Mount service unavailable!"); 7186 } 7187 } catch (RemoteException e) { 7188 // Can't happen; MountService is local 7189 } 7190 } 7191 7192 @Override 7193 public void updatePackagesIfNeeded() { 7194 enforceSystemOrRoot("Only the system can request package update"); 7195 7196 // We need to re-extract after an OTA. 7197 boolean causeUpgrade = isUpgrade(); 7198 7199 // First boot or factory reset. 7200 // Note: we also handle devices that are upgrading to N right now as if it is their 7201 // first boot, as they do not have profile data. 7202 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7203 7204 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7205 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7206 7207 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7208 return; 7209 } 7210 7211 List<PackageParser.Package> pkgs; 7212 synchronized (mPackages) { 7213 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7214 } 7215 7216 int numberOfPackagesVisited = 0; 7217 int numberOfPackagesOptimized = 0; 7218 int numberOfPackagesSkipped = 0; 7219 int numberOfPackagesFailed = 0; 7220 final int numberOfPackagesToDexopt = pkgs.size(); 7221 final long startTime = System.nanoTime(); 7222 7223 for (PackageParser.Package pkg : pkgs) { 7224 numberOfPackagesVisited++; 7225 7226 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7227 if (DEBUG_DEXOPT) { 7228 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7229 } 7230 numberOfPackagesSkipped++; 7231 continue; 7232 } 7233 7234 if (DEBUG_DEXOPT) { 7235 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7236 numberOfPackagesToDexopt + ": " + pkg.packageName); 7237 } 7238 7239 if (mIsPreNUpgrade) { 7240 try { 7241 ActivityManagerNative.getDefault().showBootMessage( 7242 mContext.getResources().getString(R.string.android_upgrading_apk, 7243 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7244 } catch (RemoteException e) { 7245 } 7246 } 7247 7248 // checkProfiles is false to avoid merging profiles during boot which 7249 // might interfere with background compilation (b/28612421). 7250 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7251 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7252 // trade-off worth doing to save boot time work. 7253 int dexOptStatus = performDexOptTraced(pkg.packageName, 7254 null /* instructionSet */, 7255 false /* checkProfiles */, 7256 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7257 false /* force */); 7258 switch (dexOptStatus) { 7259 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7260 numberOfPackagesOptimized++; 7261 break; 7262 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7263 numberOfPackagesSkipped++; 7264 break; 7265 case PackageDexOptimizer.DEX_OPT_FAILED: 7266 numberOfPackagesFailed++; 7267 break; 7268 default: 7269 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7270 break; 7271 } 7272 } 7273 7274 final int elapsedTimeSeconds = 7275 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7276 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7277 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7278 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7279 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7280 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7281 } 7282 7283 @Override 7284 public void notifyPackageUse(String packageName, int reason) { 7285 synchronized (mPackages) { 7286 PackageParser.Package p = mPackages.get(packageName); 7287 if (p == null) { 7288 return; 7289 } 7290 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7291 } 7292 } 7293 7294 // TODO: this is not used nor needed. Delete it. 7295 @Override 7296 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7297 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7298 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7299 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7300 } 7301 7302 @Override 7303 public boolean performDexOpt(String packageName, String instructionSet, 7304 boolean checkProfiles, int compileReason, boolean force) { 7305 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7306 getCompilerFilterForReason(compileReason), force); 7307 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7308 } 7309 7310 @Override 7311 public boolean performDexOptMode(String packageName, String instructionSet, 7312 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7313 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7314 targetCompilerFilter, force); 7315 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7316 } 7317 7318 private int performDexOptTraced(String packageName, String instructionSet, 7319 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7321 try { 7322 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7323 targetCompilerFilter, force); 7324 } finally { 7325 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7326 } 7327 } 7328 7329 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7330 // if the package can now be considered up to date for the given filter. 7331 private int performDexOptInternal(String packageName, String instructionSet, 7332 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7333 PackageParser.Package p; 7334 final String targetInstructionSet; 7335 synchronized (mPackages) { 7336 p = mPackages.get(packageName); 7337 if (p == null) { 7338 // Package could not be found. Report failure. 7339 return PackageDexOptimizer.DEX_OPT_FAILED; 7340 } 7341 mPackageUsage.write(false); 7342 7343 targetInstructionSet = instructionSet != null ? instructionSet : 7344 getPrimaryInstructionSet(p.applicationInfo); 7345 } 7346 long callingId = Binder.clearCallingIdentity(); 7347 try { 7348 synchronized (mInstallLock) { 7349 final String[] instructionSets = new String[] { targetInstructionSet }; 7350 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7351 targetCompilerFilter, force); 7352 } 7353 } finally { 7354 Binder.restoreCallingIdentity(callingId); 7355 } 7356 } 7357 7358 public ArraySet<String> getOptimizablePackages() { 7359 ArraySet<String> pkgs = new ArraySet<String>(); 7360 synchronized (mPackages) { 7361 for (PackageParser.Package p : mPackages.values()) { 7362 if (PackageDexOptimizer.canOptimizePackage(p)) { 7363 pkgs.add(p.packageName); 7364 } 7365 } 7366 } 7367 return pkgs; 7368 } 7369 7370 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7371 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7372 boolean force) { 7373 // Select the dex optimizer based on the force parameter. 7374 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7375 // allocate an object here. 7376 PackageDexOptimizer pdo = force 7377 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7378 : mPackageDexOptimizer; 7379 7380 // Optimize all dependencies first. Note: we ignore the return value and march on 7381 // on errors. 7382 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7383 if (!deps.isEmpty()) { 7384 for (PackageParser.Package depPackage : deps) { 7385 // TODO: Analyze and investigate if we (should) profile libraries. 7386 // Currently this will do a full compilation of the library by default. 7387 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7388 false /* checkProfiles */, 7389 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7390 } 7391 } 7392 7393 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7394 targetCompilerFilter); 7395 } 7396 7397 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7398 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7399 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7400 Set<String> collectedNames = new HashSet<>(); 7401 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7402 7403 retValue.remove(p); 7404 7405 return retValue; 7406 } else { 7407 return Collections.emptyList(); 7408 } 7409 } 7410 7411 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7412 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7413 if (!collectedNames.contains(p.packageName)) { 7414 collectedNames.add(p.packageName); 7415 collected.add(p); 7416 7417 if (p.usesLibraries != null) { 7418 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7419 } 7420 if (p.usesOptionalLibraries != null) { 7421 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7422 collectedNames); 7423 } 7424 } 7425 } 7426 7427 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7428 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7429 for (String libName : libs) { 7430 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7431 if (libPkg != null) { 7432 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7433 } 7434 } 7435 } 7436 7437 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7438 synchronized (mPackages) { 7439 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7440 if (lib != null && lib.apk != null) { 7441 return mPackages.get(lib.apk); 7442 } 7443 } 7444 return null; 7445 } 7446 7447 public void shutdown() { 7448 mPackageUsage.write(true); 7449 } 7450 7451 @Override 7452 public void forceDexOpt(String packageName) { 7453 enforceSystemOrRoot("forceDexOpt"); 7454 7455 PackageParser.Package pkg; 7456 synchronized (mPackages) { 7457 pkg = mPackages.get(packageName); 7458 if (pkg == null) { 7459 throw new IllegalArgumentException("Unknown package: " + packageName); 7460 } 7461 } 7462 7463 synchronized (mInstallLock) { 7464 final String[] instructionSets = new String[] { 7465 getPrimaryInstructionSet(pkg.applicationInfo) }; 7466 7467 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7468 7469 // Whoever is calling forceDexOpt wants a fully compiled package. 7470 // Don't use profiles since that may cause compilation to be skipped. 7471 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7472 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7473 true /* force */); 7474 7475 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7476 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7477 throw new IllegalStateException("Failed to dexopt: " + res); 7478 } 7479 } 7480 } 7481 7482 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7483 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7484 Slog.w(TAG, "Unable to update from " + oldPkg.name 7485 + " to " + newPkg.packageName 7486 + ": old package not in system partition"); 7487 return false; 7488 } else if (mPackages.get(oldPkg.name) != null) { 7489 Slog.w(TAG, "Unable to update from " + oldPkg.name 7490 + " to " + newPkg.packageName 7491 + ": old package still exists"); 7492 return false; 7493 } 7494 return true; 7495 } 7496 7497 void removeCodePathLI(File codePath) { 7498 if (codePath.isDirectory()) { 7499 try { 7500 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7501 } catch (InstallerException e) { 7502 Slog.w(TAG, "Failed to remove code path", e); 7503 } 7504 } else { 7505 codePath.delete(); 7506 } 7507 } 7508 7509 private int[] resolveUserIds(int userId) { 7510 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7511 } 7512 7513 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7514 if (pkg == null) { 7515 Slog.wtf(TAG, "Package was null!", new Throwable()); 7516 return; 7517 } 7518 clearAppDataLeafLIF(pkg, userId, flags); 7519 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7520 for (int i = 0; i < childCount; i++) { 7521 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7522 } 7523 } 7524 7525 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7526 final PackageSetting ps; 7527 synchronized (mPackages) { 7528 ps = mSettings.mPackages.get(pkg.packageName); 7529 } 7530 for (int realUserId : resolveUserIds(userId)) { 7531 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7532 try { 7533 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7534 ceDataInode); 7535 } catch (InstallerException e) { 7536 Slog.w(TAG, String.valueOf(e)); 7537 } 7538 } 7539 } 7540 7541 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7542 if (pkg == null) { 7543 Slog.wtf(TAG, "Package was null!", new Throwable()); 7544 return; 7545 } 7546 destroyAppDataLeafLIF(pkg, userId, flags); 7547 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7548 for (int i = 0; i < childCount; i++) { 7549 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7550 } 7551 } 7552 7553 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7554 final PackageSetting ps; 7555 synchronized (mPackages) { 7556 ps = mSettings.mPackages.get(pkg.packageName); 7557 } 7558 for (int realUserId : resolveUserIds(userId)) { 7559 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7560 try { 7561 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7562 ceDataInode); 7563 } catch (InstallerException e) { 7564 Slog.w(TAG, String.valueOf(e)); 7565 } 7566 } 7567 } 7568 7569 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7570 if (pkg == null) { 7571 Slog.wtf(TAG, "Package was null!", new Throwable()); 7572 return; 7573 } 7574 destroyAppProfilesLeafLIF(pkg); 7575 destroyAppReferenceProfileLeafLIF(pkg, userId); 7576 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7577 for (int i = 0; i < childCount; i++) { 7578 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7579 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId); 7580 } 7581 } 7582 7583 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId) { 7584 if (pkg.isForwardLocked()) { 7585 return; 7586 } 7587 7588 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7589 try { 7590 path = new File(path).getCanonicalPath(); 7591 } catch (IOException e) { 7592 // TODO: Should we return early here ? 7593 Slog.w(TAG, "Failed to get canonical path", e); 7594 } 7595 7596 final String useMarker = path.replace('/', '@'); 7597 for (int realUserId : resolveUserIds(userId)) { 7598 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7599 File foreignUseMark = new File(profileDir, useMarker); 7600 if (foreignUseMark.exists()) { 7601 if (!foreignUseMark.delete()) { 7602 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7603 + pkg.packageName); 7604 } 7605 } 7606 7607 File[] markers = profileDir.listFiles(); 7608 if (markers != null) { 7609 final String searchString = "@" + pkg.packageName + "@"; 7610 // We also delete all markers that contain the package name we're 7611 // uninstalling. These are associated with secondary dex-files belonging 7612 // to the package. Reconstructing the path of these dex files is messy 7613 // in general. 7614 for (File marker : markers) { 7615 if (marker.getName().indexOf(searchString) > 0) { 7616 if (!marker.delete()) { 7617 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7618 + pkg.packageName); 7619 } 7620 } 7621 } 7622 } 7623 } 7624 } 7625 } 7626 7627 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7628 try { 7629 mInstaller.destroyAppProfiles(pkg.packageName); 7630 } catch (InstallerException e) { 7631 Slog.w(TAG, String.valueOf(e)); 7632 } 7633 } 7634 7635 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7636 if (pkg == null) { 7637 Slog.wtf(TAG, "Package was null!", new Throwable()); 7638 return; 7639 } 7640 clearAppProfilesLeafLIF(pkg); 7641 destroyAppReferenceProfileLeafLIF(pkg, userId); 7642 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7643 for (int i = 0; i < childCount; i++) { 7644 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7645 } 7646 } 7647 7648 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7649 try { 7650 mInstaller.clearAppProfiles(pkg.packageName); 7651 } catch (InstallerException e) { 7652 Slog.w(TAG, String.valueOf(e)); 7653 } 7654 } 7655 7656 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7657 long lastUpdateTime) { 7658 // Set parent install/update time 7659 PackageSetting ps = (PackageSetting) pkg.mExtras; 7660 if (ps != null) { 7661 ps.firstInstallTime = firstInstallTime; 7662 ps.lastUpdateTime = lastUpdateTime; 7663 } 7664 // Set children install/update time 7665 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7666 for (int i = 0; i < childCount; i++) { 7667 PackageParser.Package childPkg = pkg.childPackages.get(i); 7668 ps = (PackageSetting) childPkg.mExtras; 7669 if (ps != null) { 7670 ps.firstInstallTime = firstInstallTime; 7671 ps.lastUpdateTime = lastUpdateTime; 7672 } 7673 } 7674 } 7675 7676 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7677 PackageParser.Package changingLib) { 7678 if (file.path != null) { 7679 usesLibraryFiles.add(file.path); 7680 return; 7681 } 7682 PackageParser.Package p = mPackages.get(file.apk); 7683 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7684 // If we are doing this while in the middle of updating a library apk, 7685 // then we need to make sure to use that new apk for determining the 7686 // dependencies here. (We haven't yet finished committing the new apk 7687 // to the package manager state.) 7688 if (p == null || p.packageName.equals(changingLib.packageName)) { 7689 p = changingLib; 7690 } 7691 } 7692 if (p != null) { 7693 usesLibraryFiles.addAll(p.getAllCodePaths()); 7694 } 7695 } 7696 7697 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7698 PackageParser.Package changingLib) throws PackageManagerException { 7699 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7700 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7701 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7702 for (int i=0; i<N; i++) { 7703 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7704 if (file == null) { 7705 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7706 "Package " + pkg.packageName + " requires unavailable shared library " 7707 + pkg.usesLibraries.get(i) + "; failing!"); 7708 } 7709 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7710 } 7711 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7712 for (int i=0; i<N; i++) { 7713 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7714 if (file == null) { 7715 Slog.w(TAG, "Package " + pkg.packageName 7716 + " desires unavailable shared library " 7717 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7718 } else { 7719 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7720 } 7721 } 7722 N = usesLibraryFiles.size(); 7723 if (N > 0) { 7724 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7725 } else { 7726 pkg.usesLibraryFiles = null; 7727 } 7728 } 7729 } 7730 7731 private static boolean hasString(List<String> list, List<String> which) { 7732 if (list == null) { 7733 return false; 7734 } 7735 for (int i=list.size()-1; i>=0; i--) { 7736 for (int j=which.size()-1; j>=0; j--) { 7737 if (which.get(j).equals(list.get(i))) { 7738 return true; 7739 } 7740 } 7741 } 7742 return false; 7743 } 7744 7745 private void updateAllSharedLibrariesLPw() { 7746 for (PackageParser.Package pkg : mPackages.values()) { 7747 try { 7748 updateSharedLibrariesLPw(pkg, null); 7749 } catch (PackageManagerException e) { 7750 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7751 } 7752 } 7753 } 7754 7755 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7756 PackageParser.Package changingPkg) { 7757 ArrayList<PackageParser.Package> res = null; 7758 for (PackageParser.Package pkg : mPackages.values()) { 7759 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7760 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7761 if (res == null) { 7762 res = new ArrayList<PackageParser.Package>(); 7763 } 7764 res.add(pkg); 7765 try { 7766 updateSharedLibrariesLPw(pkg, changingPkg); 7767 } catch (PackageManagerException e) { 7768 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7769 } 7770 } 7771 } 7772 return res; 7773 } 7774 7775 /** 7776 * Derive the value of the {@code cpuAbiOverride} based on the provided 7777 * value and an optional stored value from the package settings. 7778 */ 7779 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7780 String cpuAbiOverride = null; 7781 7782 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7783 cpuAbiOverride = null; 7784 } else if (abiOverride != null) { 7785 cpuAbiOverride = abiOverride; 7786 } else if (settings != null) { 7787 cpuAbiOverride = settings.cpuAbiOverrideString; 7788 } 7789 7790 return cpuAbiOverride; 7791 } 7792 7793 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7794 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7795 throws PackageManagerException { 7796 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7797 // If the package has children and this is the first dive in the function 7798 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7799 // whether all packages (parent and children) would be successfully scanned 7800 // before the actual scan since scanning mutates internal state and we want 7801 // to atomically install the package and its children. 7802 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7803 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7804 scanFlags |= SCAN_CHECK_ONLY; 7805 } 7806 } else { 7807 scanFlags &= ~SCAN_CHECK_ONLY; 7808 } 7809 7810 final PackageParser.Package scannedPkg; 7811 try { 7812 // Scan the parent 7813 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7814 // Scan the children 7815 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7816 for (int i = 0; i < childCount; i++) { 7817 PackageParser.Package childPkg = pkg.childPackages.get(i); 7818 scanPackageLI(childPkg, policyFlags, 7819 scanFlags, currentTime, user); 7820 } 7821 } finally { 7822 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7823 } 7824 7825 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7826 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7827 } 7828 7829 return scannedPkg; 7830 } 7831 7832 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7833 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7834 boolean success = false; 7835 try { 7836 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7837 currentTime, user); 7838 success = true; 7839 return res; 7840 } finally { 7841 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7842 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7843 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7844 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7845 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7846 } 7847 } 7848 } 7849 7850 /** 7851 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7852 */ 7853 private static boolean apkHasCode(String fileName) { 7854 StrictJarFile jarFile = null; 7855 try { 7856 jarFile = new StrictJarFile(fileName, 7857 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7858 return jarFile.findEntry("classes.dex") != null; 7859 } catch (IOException ignore) { 7860 } finally { 7861 try { 7862 jarFile.close(); 7863 } catch (IOException ignore) {} 7864 } 7865 return false; 7866 } 7867 7868 /** 7869 * Enforces code policy for the package. This ensures that if an APK has 7870 * declared hasCode="true" in its manifest that the APK actually contains 7871 * code. 7872 * 7873 * @throws PackageManagerException If bytecode could not be found when it should exist 7874 */ 7875 private static void enforceCodePolicy(PackageParser.Package pkg) 7876 throws PackageManagerException { 7877 final boolean shouldHaveCode = 7878 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7879 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7880 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7881 "Package " + pkg.baseCodePath + " code is missing"); 7882 } 7883 7884 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7885 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7886 final boolean splitShouldHaveCode = 7887 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7888 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7889 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7890 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7891 } 7892 } 7893 } 7894 } 7895 7896 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7897 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7898 throws PackageManagerException { 7899 final File scanFile = new File(pkg.codePath); 7900 if (pkg.applicationInfo.getCodePath() == null || 7901 pkg.applicationInfo.getResourcePath() == null) { 7902 // Bail out. The resource and code paths haven't been set. 7903 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7904 "Code and resource paths haven't been set correctly"); 7905 } 7906 7907 // Apply policy 7908 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7909 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7910 if (pkg.applicationInfo.isDirectBootAware()) { 7911 // we're direct boot aware; set for all components 7912 for (PackageParser.Service s : pkg.services) { 7913 s.info.encryptionAware = s.info.directBootAware = true; 7914 } 7915 for (PackageParser.Provider p : pkg.providers) { 7916 p.info.encryptionAware = p.info.directBootAware = true; 7917 } 7918 for (PackageParser.Activity a : pkg.activities) { 7919 a.info.encryptionAware = a.info.directBootAware = true; 7920 } 7921 for (PackageParser.Activity r : pkg.receivers) { 7922 r.info.encryptionAware = r.info.directBootAware = true; 7923 } 7924 } 7925 } else { 7926 // Only allow system apps to be flagged as core apps. 7927 pkg.coreApp = false; 7928 // clear flags not applicable to regular apps 7929 pkg.applicationInfo.privateFlags &= 7930 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7931 pkg.applicationInfo.privateFlags &= 7932 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7933 } 7934 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7935 7936 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7937 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7938 } 7939 7940 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7941 enforceCodePolicy(pkg); 7942 } 7943 7944 if (mCustomResolverComponentName != null && 7945 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7946 setUpCustomResolverActivity(pkg); 7947 } 7948 7949 if (pkg.packageName.equals("android")) { 7950 synchronized (mPackages) { 7951 if (mAndroidApplication != null) { 7952 Slog.w(TAG, "*************************************************"); 7953 Slog.w(TAG, "Core android package being redefined. Skipping."); 7954 Slog.w(TAG, " file=" + scanFile); 7955 Slog.w(TAG, "*************************************************"); 7956 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7957 "Core android package being redefined. Skipping."); 7958 } 7959 7960 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7961 // Set up information for our fall-back user intent resolution activity. 7962 mPlatformPackage = pkg; 7963 pkg.mVersionCode = mSdkVersion; 7964 mAndroidApplication = pkg.applicationInfo; 7965 7966 if (!mResolverReplaced) { 7967 mResolveActivity.applicationInfo = mAndroidApplication; 7968 mResolveActivity.name = ResolverActivity.class.getName(); 7969 mResolveActivity.packageName = mAndroidApplication.packageName; 7970 mResolveActivity.processName = "system:ui"; 7971 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7972 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7973 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7974 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7975 mResolveActivity.exported = true; 7976 mResolveActivity.enabled = true; 7977 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7978 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7979 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7980 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7981 | ActivityInfo.CONFIG_ORIENTATION 7982 | ActivityInfo.CONFIG_KEYBOARD 7983 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7984 mResolveInfo.activityInfo = mResolveActivity; 7985 mResolveInfo.priority = 0; 7986 mResolveInfo.preferredOrder = 0; 7987 mResolveInfo.match = 0; 7988 mResolveComponentName = new ComponentName( 7989 mAndroidApplication.packageName, mResolveActivity.name); 7990 } 7991 } 7992 } 7993 } 7994 7995 if (DEBUG_PACKAGE_SCANNING) { 7996 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7997 Log.d(TAG, "Scanning package " + pkg.packageName); 7998 } 7999 8000 synchronized (mPackages) { 8001 if (mPackages.containsKey(pkg.packageName) 8002 || mSharedLibraries.containsKey(pkg.packageName)) { 8003 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8004 "Application package " + pkg.packageName 8005 + " already installed. Skipping duplicate."); 8006 } 8007 8008 // If we're only installing presumed-existing packages, require that the 8009 // scanned APK is both already known and at the path previously established 8010 // for it. Previously unknown packages we pick up normally, but if we have an 8011 // a priori expectation about this package's install presence, enforce it. 8012 // With a singular exception for new system packages. When an OTA contains 8013 // a new system package, we allow the codepath to change from a system location 8014 // to the user-installed location. If we don't allow this change, any newer, 8015 // user-installed version of the application will be ignored. 8016 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8017 if (mExpectingBetter.containsKey(pkg.packageName)) { 8018 logCriticalInfo(Log.WARN, 8019 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8020 } else { 8021 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8022 if (known != null) { 8023 if (DEBUG_PACKAGE_SCANNING) { 8024 Log.d(TAG, "Examining " + pkg.codePath 8025 + " and requiring known paths " + known.codePathString 8026 + " & " + known.resourcePathString); 8027 } 8028 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8029 || !pkg.applicationInfo.getResourcePath().equals( 8030 known.resourcePathString)) { 8031 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8032 "Application package " + pkg.packageName 8033 + " found at " + pkg.applicationInfo.getCodePath() 8034 + " but expected at " + known.codePathString 8035 + "; ignoring."); 8036 } 8037 } 8038 } 8039 } 8040 } 8041 8042 // Initialize package source and resource directories 8043 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8044 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8045 8046 SharedUserSetting suid = null; 8047 PackageSetting pkgSetting = null; 8048 8049 if (!isSystemApp(pkg)) { 8050 // Only system apps can use these features. 8051 pkg.mOriginalPackages = null; 8052 pkg.mRealPackage = null; 8053 pkg.mAdoptPermissions = null; 8054 } 8055 8056 // Getting the package setting may have a side-effect, so if we 8057 // are only checking if scan would succeed, stash a copy of the 8058 // old setting to restore at the end. 8059 PackageSetting nonMutatedPs = null; 8060 8061 // writer 8062 synchronized (mPackages) { 8063 if (pkg.mSharedUserId != null) { 8064 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8065 if (suid == null) { 8066 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8067 "Creating application package " + pkg.packageName 8068 + " for shared user failed"); 8069 } 8070 if (DEBUG_PACKAGE_SCANNING) { 8071 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8072 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8073 + "): packages=" + suid.packages); 8074 } 8075 } 8076 8077 // Check if we are renaming from an original package name. 8078 PackageSetting origPackage = null; 8079 String realName = null; 8080 if (pkg.mOriginalPackages != null) { 8081 // This package may need to be renamed to a previously 8082 // installed name. Let's check on that... 8083 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8084 if (pkg.mOriginalPackages.contains(renamed)) { 8085 // This package had originally been installed as the 8086 // original name, and we have already taken care of 8087 // transitioning to the new one. Just update the new 8088 // one to continue using the old name. 8089 realName = pkg.mRealPackage; 8090 if (!pkg.packageName.equals(renamed)) { 8091 // Callers into this function may have already taken 8092 // care of renaming the package; only do it here if 8093 // it is not already done. 8094 pkg.setPackageName(renamed); 8095 } 8096 8097 } else { 8098 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8099 if ((origPackage = mSettings.peekPackageLPr( 8100 pkg.mOriginalPackages.get(i))) != null) { 8101 // We do have the package already installed under its 8102 // original name... should we use it? 8103 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8104 // New package is not compatible with original. 8105 origPackage = null; 8106 continue; 8107 } else if (origPackage.sharedUser != null) { 8108 // Make sure uid is compatible between packages. 8109 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8110 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8111 + " to " + pkg.packageName + ": old uid " 8112 + origPackage.sharedUser.name 8113 + " differs from " + pkg.mSharedUserId); 8114 origPackage = null; 8115 continue; 8116 } 8117 // TODO: Add case when shared user id is added [b/28144775] 8118 } else { 8119 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8120 + pkg.packageName + " to old name " + origPackage.name); 8121 } 8122 break; 8123 } 8124 } 8125 } 8126 } 8127 8128 if (mTransferedPackages.contains(pkg.packageName)) { 8129 Slog.w(TAG, "Package " + pkg.packageName 8130 + " was transferred to another, but its .apk remains"); 8131 } 8132 8133 // See comments in nonMutatedPs declaration 8134 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8135 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8136 if (foundPs != null) { 8137 nonMutatedPs = new PackageSetting(foundPs); 8138 } 8139 } 8140 8141 // Just create the setting, don't add it yet. For already existing packages 8142 // the PkgSetting exists already and doesn't have to be created. 8143 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8144 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8145 pkg.applicationInfo.primaryCpuAbi, 8146 pkg.applicationInfo.secondaryCpuAbi, 8147 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8148 user, false); 8149 if (pkgSetting == null) { 8150 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8151 "Creating application package " + pkg.packageName + " failed"); 8152 } 8153 8154 if (pkgSetting.origPackage != null) { 8155 // If we are first transitioning from an original package, 8156 // fix up the new package's name now. We need to do this after 8157 // looking up the package under its new name, so getPackageLP 8158 // can take care of fiddling things correctly. 8159 pkg.setPackageName(origPackage.name); 8160 8161 // File a report about this. 8162 String msg = "New package " + pkgSetting.realName 8163 + " renamed to replace old package " + pkgSetting.name; 8164 reportSettingsProblem(Log.WARN, msg); 8165 8166 // Make a note of it. 8167 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8168 mTransferedPackages.add(origPackage.name); 8169 } 8170 8171 // No longer need to retain this. 8172 pkgSetting.origPackage = null; 8173 } 8174 8175 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8176 // Make a note of it. 8177 mTransferedPackages.add(pkg.packageName); 8178 } 8179 8180 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8181 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8182 } 8183 8184 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8185 // Check all shared libraries and map to their actual file path. 8186 // We only do this here for apps not on a system dir, because those 8187 // are the only ones that can fail an install due to this. We 8188 // will take care of the system apps by updating all of their 8189 // library paths after the scan is done. 8190 updateSharedLibrariesLPw(pkg, null); 8191 } 8192 8193 if (mFoundPolicyFile) { 8194 SELinuxMMAC.assignSeinfoValue(pkg); 8195 } 8196 8197 pkg.applicationInfo.uid = pkgSetting.appId; 8198 pkg.mExtras = pkgSetting; 8199 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8200 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8201 // We just determined the app is signed correctly, so bring 8202 // over the latest parsed certs. 8203 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8204 } else { 8205 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8206 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8207 "Package " + pkg.packageName + " upgrade keys do not match the " 8208 + "previously installed version"); 8209 } else { 8210 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8211 String msg = "System package " + pkg.packageName 8212 + " signature changed; retaining data."; 8213 reportSettingsProblem(Log.WARN, msg); 8214 } 8215 } 8216 } else { 8217 try { 8218 verifySignaturesLP(pkgSetting, pkg); 8219 // We just determined the app is signed correctly, so bring 8220 // over the latest parsed certs. 8221 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8222 } catch (PackageManagerException e) { 8223 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8224 throw e; 8225 } 8226 // The signature has changed, but this package is in the system 8227 // image... let's recover! 8228 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8229 // However... if this package is part of a shared user, but it 8230 // doesn't match the signature of the shared user, let's fail. 8231 // What this means is that you can't change the signatures 8232 // associated with an overall shared user, which doesn't seem all 8233 // that unreasonable. 8234 if (pkgSetting.sharedUser != null) { 8235 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8236 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8237 throw new PackageManagerException( 8238 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8239 "Signature mismatch for shared user: " 8240 + pkgSetting.sharedUser); 8241 } 8242 } 8243 // File a report about this. 8244 String msg = "System package " + pkg.packageName 8245 + " signature changed; retaining data."; 8246 reportSettingsProblem(Log.WARN, msg); 8247 } 8248 } 8249 // Verify that this new package doesn't have any content providers 8250 // that conflict with existing packages. Only do this if the 8251 // package isn't already installed, since we don't want to break 8252 // things that are installed. 8253 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8254 final int N = pkg.providers.size(); 8255 int i; 8256 for (i=0; i<N; i++) { 8257 PackageParser.Provider p = pkg.providers.get(i); 8258 if (p.info.authority != null) { 8259 String names[] = p.info.authority.split(";"); 8260 for (int j = 0; j < names.length; j++) { 8261 if (mProvidersByAuthority.containsKey(names[j])) { 8262 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8263 final String otherPackageName = 8264 ((other != null && other.getComponentName() != null) ? 8265 other.getComponentName().getPackageName() : "?"); 8266 throw new PackageManagerException( 8267 INSTALL_FAILED_CONFLICTING_PROVIDER, 8268 "Can't install because provider name " + names[j] 8269 + " (in package " + pkg.applicationInfo.packageName 8270 + ") is already used by " + otherPackageName); 8271 } 8272 } 8273 } 8274 } 8275 } 8276 8277 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8278 // This package wants to adopt ownership of permissions from 8279 // another package. 8280 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8281 final String origName = pkg.mAdoptPermissions.get(i); 8282 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8283 if (orig != null) { 8284 if (verifyPackageUpdateLPr(orig, pkg)) { 8285 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8286 + pkg.packageName); 8287 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8288 } 8289 } 8290 } 8291 } 8292 } 8293 8294 final String pkgName = pkg.packageName; 8295 8296 final long scanFileTime = scanFile.lastModified(); 8297 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8298 pkg.applicationInfo.processName = fixProcessName( 8299 pkg.applicationInfo.packageName, 8300 pkg.applicationInfo.processName, 8301 pkg.applicationInfo.uid); 8302 8303 if (pkg != mPlatformPackage) { 8304 // Get all of our default paths setup 8305 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8306 } 8307 8308 final String path = scanFile.getPath(); 8309 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8310 8311 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8312 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8313 8314 // Some system apps still use directory structure for native libraries 8315 // in which case we might end up not detecting abi solely based on apk 8316 // structure. Try to detect abi based on directory structure. 8317 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8318 pkg.applicationInfo.primaryCpuAbi == null) { 8319 setBundledAppAbisAndRoots(pkg, pkgSetting); 8320 setNativeLibraryPaths(pkg); 8321 } 8322 8323 } else { 8324 if ((scanFlags & SCAN_MOVE) != 0) { 8325 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8326 // but we already have this packages package info in the PackageSetting. We just 8327 // use that and derive the native library path based on the new codepath. 8328 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8329 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8330 } 8331 8332 // Set native library paths again. For moves, the path will be updated based on the 8333 // ABIs we've determined above. For non-moves, the path will be updated based on the 8334 // ABIs we determined during compilation, but the path will depend on the final 8335 // package path (after the rename away from the stage path). 8336 setNativeLibraryPaths(pkg); 8337 } 8338 8339 // This is a special case for the "system" package, where the ABI is 8340 // dictated by the zygote configuration (and init.rc). We should keep track 8341 // of this ABI so that we can deal with "normal" applications that run under 8342 // the same UID correctly. 8343 if (mPlatformPackage == pkg) { 8344 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8345 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8346 } 8347 8348 // If there's a mismatch between the abi-override in the package setting 8349 // and the abiOverride specified for the install. Warn about this because we 8350 // would've already compiled the app without taking the package setting into 8351 // account. 8352 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8353 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8354 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8355 " for package " + pkg.packageName); 8356 } 8357 } 8358 8359 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8360 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8361 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8362 8363 // Copy the derived override back to the parsed package, so that we can 8364 // update the package settings accordingly. 8365 pkg.cpuAbiOverride = cpuAbiOverride; 8366 8367 if (DEBUG_ABI_SELECTION) { 8368 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8369 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8370 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8371 } 8372 8373 // Push the derived path down into PackageSettings so we know what to 8374 // clean up at uninstall time. 8375 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8376 8377 if (DEBUG_ABI_SELECTION) { 8378 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8379 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8380 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8381 } 8382 8383 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8384 // We don't do this here during boot because we can do it all 8385 // at once after scanning all existing packages. 8386 // 8387 // We also do this *before* we perform dexopt on this package, so that 8388 // we can avoid redundant dexopts, and also to make sure we've got the 8389 // code and package path correct. 8390 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8391 pkg, true /* boot complete */); 8392 } 8393 8394 if (mFactoryTest && pkg.requestedPermissions.contains( 8395 android.Manifest.permission.FACTORY_TEST)) { 8396 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8397 } 8398 8399 ArrayList<PackageParser.Package> clientLibPkgs = null; 8400 8401 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8402 if (nonMutatedPs != null) { 8403 synchronized (mPackages) { 8404 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8405 } 8406 } 8407 return pkg; 8408 } 8409 8410 // Only privileged apps and updated privileged apps can add child packages. 8411 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8412 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8413 throw new PackageManagerException("Only privileged apps and updated " 8414 + "privileged apps can add child packages. Ignoring package " 8415 + pkg.packageName); 8416 } 8417 final int childCount = pkg.childPackages.size(); 8418 for (int i = 0; i < childCount; i++) { 8419 PackageParser.Package childPkg = pkg.childPackages.get(i); 8420 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8421 childPkg.packageName)) { 8422 throw new PackageManagerException("Cannot override a child package of " 8423 + "another disabled system app. Ignoring package " + pkg.packageName); 8424 } 8425 } 8426 } 8427 8428 // writer 8429 synchronized (mPackages) { 8430 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8431 // Only system apps can add new shared libraries. 8432 if (pkg.libraryNames != null) { 8433 for (int i=0; i<pkg.libraryNames.size(); i++) { 8434 String name = pkg.libraryNames.get(i); 8435 boolean allowed = false; 8436 if (pkg.isUpdatedSystemApp()) { 8437 // New library entries can only be added through the 8438 // system image. This is important to get rid of a lot 8439 // of nasty edge cases: for example if we allowed a non- 8440 // system update of the app to add a library, then uninstalling 8441 // the update would make the library go away, and assumptions 8442 // we made such as through app install filtering would now 8443 // have allowed apps on the device which aren't compatible 8444 // with it. Better to just have the restriction here, be 8445 // conservative, and create many fewer cases that can negatively 8446 // impact the user experience. 8447 final PackageSetting sysPs = mSettings 8448 .getDisabledSystemPkgLPr(pkg.packageName); 8449 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8450 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8451 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8452 allowed = true; 8453 break; 8454 } 8455 } 8456 } 8457 } else { 8458 allowed = true; 8459 } 8460 if (allowed) { 8461 if (!mSharedLibraries.containsKey(name)) { 8462 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8463 } else if (!name.equals(pkg.packageName)) { 8464 Slog.w(TAG, "Package " + pkg.packageName + " library " 8465 + name + " already exists; skipping"); 8466 } 8467 } else { 8468 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8469 + name + " that is not declared on system image; skipping"); 8470 } 8471 } 8472 if ((scanFlags & SCAN_BOOTING) == 0) { 8473 // If we are not booting, we need to update any applications 8474 // that are clients of our shared library. If we are booting, 8475 // this will all be done once the scan is complete. 8476 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8477 } 8478 } 8479 } 8480 } 8481 8482 if ((scanFlags & SCAN_BOOTING) != 0) { 8483 // No apps can run during boot scan, so they don't need to be frozen 8484 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8485 // Caller asked to not kill app, so it's probably not frozen 8486 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8487 // Caller asked us to ignore frozen check for some reason; they 8488 // probably didn't know the package name 8489 } else { 8490 // We're doing major surgery on this package, so it better be frozen 8491 // right now to keep it from launching 8492 checkPackageFrozen(pkgName); 8493 } 8494 8495 // Also need to kill any apps that are dependent on the library. 8496 if (clientLibPkgs != null) { 8497 for (int i=0; i<clientLibPkgs.size(); i++) { 8498 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8499 killApplication(clientPkg.applicationInfo.packageName, 8500 clientPkg.applicationInfo.uid, "update lib"); 8501 } 8502 } 8503 8504 // Make sure we're not adding any bogus keyset info 8505 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8506 ksms.assertScannedPackageValid(pkg); 8507 8508 // writer 8509 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8510 8511 boolean createIdmapFailed = false; 8512 synchronized (mPackages) { 8513 // We don't expect installation to fail beyond this point 8514 8515 // Add the new setting to mSettings 8516 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8517 // Add the new setting to mPackages 8518 mPackages.put(pkg.applicationInfo.packageName, pkg); 8519 // Make sure we don't accidentally delete its data. 8520 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8521 while (iter.hasNext()) { 8522 PackageCleanItem item = iter.next(); 8523 if (pkgName.equals(item.packageName)) { 8524 iter.remove(); 8525 } 8526 } 8527 8528 // Take care of first install / last update times. 8529 if (currentTime != 0) { 8530 if (pkgSetting.firstInstallTime == 0) { 8531 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8532 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8533 pkgSetting.lastUpdateTime = currentTime; 8534 } 8535 } else if (pkgSetting.firstInstallTime == 0) { 8536 // We need *something*. Take time time stamp of the file. 8537 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8538 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8539 if (scanFileTime != pkgSetting.timeStamp) { 8540 // A package on the system image has changed; consider this 8541 // to be an update. 8542 pkgSetting.lastUpdateTime = scanFileTime; 8543 } 8544 } 8545 8546 // Add the package's KeySets to the global KeySetManagerService 8547 ksms.addScannedPackageLPw(pkg); 8548 8549 int N = pkg.providers.size(); 8550 StringBuilder r = null; 8551 int i; 8552 for (i=0; i<N; i++) { 8553 PackageParser.Provider p = pkg.providers.get(i); 8554 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8555 p.info.processName, pkg.applicationInfo.uid); 8556 mProviders.addProvider(p); 8557 p.syncable = p.info.isSyncable; 8558 if (p.info.authority != null) { 8559 String names[] = p.info.authority.split(";"); 8560 p.info.authority = null; 8561 for (int j = 0; j < names.length; j++) { 8562 if (j == 1 && p.syncable) { 8563 // We only want the first authority for a provider to possibly be 8564 // syncable, so if we already added this provider using a different 8565 // authority clear the syncable flag. We copy the provider before 8566 // changing it because the mProviders object contains a reference 8567 // to a provider that we don't want to change. 8568 // Only do this for the second authority since the resulting provider 8569 // object can be the same for all future authorities for this provider. 8570 p = new PackageParser.Provider(p); 8571 p.syncable = false; 8572 } 8573 if (!mProvidersByAuthority.containsKey(names[j])) { 8574 mProvidersByAuthority.put(names[j], p); 8575 if (p.info.authority == null) { 8576 p.info.authority = names[j]; 8577 } else { 8578 p.info.authority = p.info.authority + ";" + names[j]; 8579 } 8580 if (DEBUG_PACKAGE_SCANNING) { 8581 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8582 Log.d(TAG, "Registered content provider: " + names[j] 8583 + ", className = " + p.info.name + ", isSyncable = " 8584 + p.info.isSyncable); 8585 } 8586 } else { 8587 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8588 Slog.w(TAG, "Skipping provider name " + names[j] + 8589 " (in package " + pkg.applicationInfo.packageName + 8590 "): name already used by " 8591 + ((other != null && other.getComponentName() != null) 8592 ? other.getComponentName().getPackageName() : "?")); 8593 } 8594 } 8595 } 8596 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8597 if (r == null) { 8598 r = new StringBuilder(256); 8599 } else { 8600 r.append(' '); 8601 } 8602 r.append(p.info.name); 8603 } 8604 } 8605 if (r != null) { 8606 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8607 } 8608 8609 N = pkg.services.size(); 8610 r = null; 8611 for (i=0; i<N; i++) { 8612 PackageParser.Service s = pkg.services.get(i); 8613 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8614 s.info.processName, pkg.applicationInfo.uid); 8615 mServices.addService(s); 8616 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8617 if (r == null) { 8618 r = new StringBuilder(256); 8619 } else { 8620 r.append(' '); 8621 } 8622 r.append(s.info.name); 8623 } 8624 } 8625 if (r != null) { 8626 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8627 } 8628 8629 N = pkg.receivers.size(); 8630 r = null; 8631 for (i=0; i<N; i++) { 8632 PackageParser.Activity a = pkg.receivers.get(i); 8633 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8634 a.info.processName, pkg.applicationInfo.uid); 8635 mReceivers.addActivity(a, "receiver"); 8636 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8637 if (r == null) { 8638 r = new StringBuilder(256); 8639 } else { 8640 r.append(' '); 8641 } 8642 r.append(a.info.name); 8643 } 8644 } 8645 if (r != null) { 8646 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8647 } 8648 8649 N = pkg.activities.size(); 8650 r = null; 8651 for (i=0; i<N; i++) { 8652 PackageParser.Activity a = pkg.activities.get(i); 8653 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8654 a.info.processName, pkg.applicationInfo.uid); 8655 mActivities.addActivity(a, "activity"); 8656 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8657 if (r == null) { 8658 r = new StringBuilder(256); 8659 } else { 8660 r.append(' '); 8661 } 8662 r.append(a.info.name); 8663 } 8664 } 8665 if (r != null) { 8666 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8667 } 8668 8669 N = pkg.permissionGroups.size(); 8670 r = null; 8671 for (i=0; i<N; i++) { 8672 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8673 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8674 if (cur == null) { 8675 mPermissionGroups.put(pg.info.name, pg); 8676 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8677 if (r == null) { 8678 r = new StringBuilder(256); 8679 } else { 8680 r.append(' '); 8681 } 8682 r.append(pg.info.name); 8683 } 8684 } else { 8685 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8686 + pg.info.packageName + " ignored: original from " 8687 + cur.info.packageName); 8688 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8689 if (r == null) { 8690 r = new StringBuilder(256); 8691 } else { 8692 r.append(' '); 8693 } 8694 r.append("DUP:"); 8695 r.append(pg.info.name); 8696 } 8697 } 8698 } 8699 if (r != null) { 8700 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8701 } 8702 8703 N = pkg.permissions.size(); 8704 r = null; 8705 for (i=0; i<N; i++) { 8706 PackageParser.Permission p = pkg.permissions.get(i); 8707 8708 // Assume by default that we did not install this permission into the system. 8709 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8710 8711 // Now that permission groups have a special meaning, we ignore permission 8712 // groups for legacy apps to prevent unexpected behavior. In particular, 8713 // permissions for one app being granted to someone just becase they happen 8714 // to be in a group defined by another app (before this had no implications). 8715 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8716 p.group = mPermissionGroups.get(p.info.group); 8717 // Warn for a permission in an unknown group. 8718 if (p.info.group != null && p.group == null) { 8719 Slog.w(TAG, "Permission " + p.info.name + " from package " 8720 + p.info.packageName + " in an unknown group " + p.info.group); 8721 } 8722 } 8723 8724 ArrayMap<String, BasePermission> permissionMap = 8725 p.tree ? mSettings.mPermissionTrees 8726 : mSettings.mPermissions; 8727 BasePermission bp = permissionMap.get(p.info.name); 8728 8729 // Allow system apps to redefine non-system permissions 8730 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8731 final boolean currentOwnerIsSystem = (bp.perm != null 8732 && isSystemApp(bp.perm.owner)); 8733 if (isSystemApp(p.owner)) { 8734 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8735 // It's a built-in permission and no owner, take ownership now 8736 bp.packageSetting = pkgSetting; 8737 bp.perm = p; 8738 bp.uid = pkg.applicationInfo.uid; 8739 bp.sourcePackage = p.info.packageName; 8740 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8741 } else if (!currentOwnerIsSystem) { 8742 String msg = "New decl " + p.owner + " of permission " 8743 + p.info.name + " is system; overriding " + bp.sourcePackage; 8744 reportSettingsProblem(Log.WARN, msg); 8745 bp = null; 8746 } 8747 } 8748 } 8749 8750 if (bp == null) { 8751 bp = new BasePermission(p.info.name, p.info.packageName, 8752 BasePermission.TYPE_NORMAL); 8753 permissionMap.put(p.info.name, bp); 8754 } 8755 8756 if (bp.perm == null) { 8757 if (bp.sourcePackage == null 8758 || bp.sourcePackage.equals(p.info.packageName)) { 8759 BasePermission tree = findPermissionTreeLP(p.info.name); 8760 if (tree == null 8761 || tree.sourcePackage.equals(p.info.packageName)) { 8762 bp.packageSetting = pkgSetting; 8763 bp.perm = p; 8764 bp.uid = pkg.applicationInfo.uid; 8765 bp.sourcePackage = p.info.packageName; 8766 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8767 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8768 if (r == null) { 8769 r = new StringBuilder(256); 8770 } else { 8771 r.append(' '); 8772 } 8773 r.append(p.info.name); 8774 } 8775 } else { 8776 Slog.w(TAG, "Permission " + p.info.name + " from package " 8777 + p.info.packageName + " ignored: base tree " 8778 + tree.name + " is from package " 8779 + tree.sourcePackage); 8780 } 8781 } else { 8782 Slog.w(TAG, "Permission " + p.info.name + " from package " 8783 + p.info.packageName + " ignored: original from " 8784 + bp.sourcePackage); 8785 } 8786 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8787 if (r == null) { 8788 r = new StringBuilder(256); 8789 } else { 8790 r.append(' '); 8791 } 8792 r.append("DUP:"); 8793 r.append(p.info.name); 8794 } 8795 if (bp.perm == p) { 8796 bp.protectionLevel = p.info.protectionLevel; 8797 } 8798 } 8799 8800 if (r != null) { 8801 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8802 } 8803 8804 N = pkg.instrumentation.size(); 8805 r = null; 8806 for (i=0; i<N; i++) { 8807 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8808 a.info.packageName = pkg.applicationInfo.packageName; 8809 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8810 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8811 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8812 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8813 a.info.dataDir = pkg.applicationInfo.dataDir; 8814 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8815 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8816 8817 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8818 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8819 mInstrumentation.put(a.getComponentName(), a); 8820 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8821 if (r == null) { 8822 r = new StringBuilder(256); 8823 } else { 8824 r.append(' '); 8825 } 8826 r.append(a.info.name); 8827 } 8828 } 8829 if (r != null) { 8830 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8831 } 8832 8833 if (pkg.protectedBroadcasts != null) { 8834 N = pkg.protectedBroadcasts.size(); 8835 for (i=0; i<N; i++) { 8836 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8837 } 8838 } 8839 8840 pkgSetting.setTimeStamp(scanFileTime); 8841 8842 // Create idmap files for pairs of (packages, overlay packages). 8843 // Note: "android", ie framework-res.apk, is handled by native layers. 8844 if (pkg.mOverlayTarget != null) { 8845 // This is an overlay package. 8846 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8847 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8848 mOverlays.put(pkg.mOverlayTarget, 8849 new ArrayMap<String, PackageParser.Package>()); 8850 } 8851 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8852 map.put(pkg.packageName, pkg); 8853 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8854 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8855 createIdmapFailed = true; 8856 } 8857 } 8858 } else if (mOverlays.containsKey(pkg.packageName) && 8859 !pkg.packageName.equals("android")) { 8860 // This is a regular package, with one or more known overlay packages. 8861 createIdmapsForPackageLI(pkg); 8862 } 8863 } 8864 8865 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8866 8867 if (createIdmapFailed) { 8868 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8869 "scanPackageLI failed to createIdmap"); 8870 } 8871 return pkg; 8872 } 8873 8874 /** 8875 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8876 * is derived purely on the basis of the contents of {@code scanFile} and 8877 * {@code cpuAbiOverride}. 8878 * 8879 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8880 */ 8881 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8882 String cpuAbiOverride, boolean extractLibs) 8883 throws PackageManagerException { 8884 // TODO: We can probably be smarter about this stuff. For installed apps, 8885 // we can calculate this information at install time once and for all. For 8886 // system apps, we can probably assume that this information doesn't change 8887 // after the first boot scan. As things stand, we do lots of unnecessary work. 8888 8889 // Give ourselves some initial paths; we'll come back for another 8890 // pass once we've determined ABI below. 8891 setNativeLibraryPaths(pkg); 8892 8893 // We would never need to extract libs for forward-locked and external packages, 8894 // since the container service will do it for us. We shouldn't attempt to 8895 // extract libs from system app when it was not updated. 8896 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8897 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8898 extractLibs = false; 8899 } 8900 8901 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8902 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8903 8904 NativeLibraryHelper.Handle handle = null; 8905 try { 8906 handle = NativeLibraryHelper.Handle.create(pkg); 8907 // TODO(multiArch): This can be null for apps that didn't go through the 8908 // usual installation process. We can calculate it again, like we 8909 // do during install time. 8910 // 8911 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8912 // unnecessary. 8913 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8914 8915 // Null out the abis so that they can be recalculated. 8916 pkg.applicationInfo.primaryCpuAbi = null; 8917 pkg.applicationInfo.secondaryCpuAbi = null; 8918 if (isMultiArch(pkg.applicationInfo)) { 8919 // Warn if we've set an abiOverride for multi-lib packages.. 8920 // By definition, we need to copy both 32 and 64 bit libraries for 8921 // such packages. 8922 if (pkg.cpuAbiOverride != null 8923 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8924 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8925 } 8926 8927 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8928 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8929 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8930 if (extractLibs) { 8931 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8932 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8933 useIsaSpecificSubdirs); 8934 } else { 8935 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8936 } 8937 } 8938 8939 maybeThrowExceptionForMultiArchCopy( 8940 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8941 8942 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8943 if (extractLibs) { 8944 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8945 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8946 useIsaSpecificSubdirs); 8947 } else { 8948 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8949 } 8950 } 8951 8952 maybeThrowExceptionForMultiArchCopy( 8953 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8954 8955 if (abi64 >= 0) { 8956 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8957 } 8958 8959 if (abi32 >= 0) { 8960 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8961 if (abi64 >= 0) { 8962 if (pkg.use32bitAbi) { 8963 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8964 pkg.applicationInfo.primaryCpuAbi = abi; 8965 } else { 8966 pkg.applicationInfo.secondaryCpuAbi = abi; 8967 } 8968 } else { 8969 pkg.applicationInfo.primaryCpuAbi = abi; 8970 } 8971 } 8972 8973 } else { 8974 String[] abiList = (cpuAbiOverride != null) ? 8975 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8976 8977 // Enable gross and lame hacks for apps that are built with old 8978 // SDK tools. We must scan their APKs for renderscript bitcode and 8979 // not launch them if it's present. Don't bother checking on devices 8980 // that don't have 64 bit support. 8981 boolean needsRenderScriptOverride = false; 8982 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8983 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8984 abiList = Build.SUPPORTED_32_BIT_ABIS; 8985 needsRenderScriptOverride = true; 8986 } 8987 8988 final int copyRet; 8989 if (extractLibs) { 8990 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8991 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8992 } else { 8993 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8994 } 8995 8996 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8997 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8998 "Error unpackaging native libs for app, errorCode=" + copyRet); 8999 } 9000 9001 if (copyRet >= 0) { 9002 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9003 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9004 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9005 } else if (needsRenderScriptOverride) { 9006 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9007 } 9008 } 9009 } catch (IOException ioe) { 9010 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9011 } finally { 9012 IoUtils.closeQuietly(handle); 9013 } 9014 9015 // Now that we've calculated the ABIs and determined if it's an internal app, 9016 // we will go ahead and populate the nativeLibraryPath. 9017 setNativeLibraryPaths(pkg); 9018 } 9019 9020 /** 9021 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9022 * i.e, so that all packages can be run inside a single process if required. 9023 * 9024 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9025 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9026 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9027 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9028 * updating a package that belongs to a shared user. 9029 * 9030 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9031 * adds unnecessary complexity. 9032 */ 9033 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9034 PackageParser.Package scannedPackage, boolean bootComplete) { 9035 String requiredInstructionSet = null; 9036 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9037 requiredInstructionSet = VMRuntime.getInstructionSet( 9038 scannedPackage.applicationInfo.primaryCpuAbi); 9039 } 9040 9041 PackageSetting requirer = null; 9042 for (PackageSetting ps : packagesForUser) { 9043 // If packagesForUser contains scannedPackage, we skip it. This will happen 9044 // when scannedPackage is an update of an existing package. Without this check, 9045 // we will never be able to change the ABI of any package belonging to a shared 9046 // user, even if it's compatible with other packages. 9047 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9048 if (ps.primaryCpuAbiString == null) { 9049 continue; 9050 } 9051 9052 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9053 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9054 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9055 // this but there's not much we can do. 9056 String errorMessage = "Instruction set mismatch, " 9057 + ((requirer == null) ? "[caller]" : requirer) 9058 + " requires " + requiredInstructionSet + " whereas " + ps 9059 + " requires " + instructionSet; 9060 Slog.w(TAG, errorMessage); 9061 } 9062 9063 if (requiredInstructionSet == null) { 9064 requiredInstructionSet = instructionSet; 9065 requirer = ps; 9066 } 9067 } 9068 } 9069 9070 if (requiredInstructionSet != null) { 9071 String adjustedAbi; 9072 if (requirer != null) { 9073 // requirer != null implies that either scannedPackage was null or that scannedPackage 9074 // did not require an ABI, in which case we have to adjust scannedPackage to match 9075 // the ABI of the set (which is the same as requirer's ABI) 9076 adjustedAbi = requirer.primaryCpuAbiString; 9077 if (scannedPackage != null) { 9078 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9079 } 9080 } else { 9081 // requirer == null implies that we're updating all ABIs in the set to 9082 // match scannedPackage. 9083 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9084 } 9085 9086 for (PackageSetting ps : packagesForUser) { 9087 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9088 if (ps.primaryCpuAbiString != null) { 9089 continue; 9090 } 9091 9092 ps.primaryCpuAbiString = adjustedAbi; 9093 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9094 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9095 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9096 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9097 + " (requirer=" 9098 + (requirer == null ? "null" : requirer.pkg.packageName) 9099 + ", scannedPackage=" 9100 + (scannedPackage != null ? scannedPackage.packageName : "null") 9101 + ")"); 9102 try { 9103 mInstaller.rmdex(ps.codePathString, 9104 getDexCodeInstructionSet(getPreferredInstructionSet())); 9105 } catch (InstallerException ignored) { 9106 } 9107 } 9108 } 9109 } 9110 } 9111 } 9112 9113 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9114 synchronized (mPackages) { 9115 mResolverReplaced = true; 9116 // Set up information for custom user intent resolution activity. 9117 mResolveActivity.applicationInfo = pkg.applicationInfo; 9118 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9119 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9120 mResolveActivity.processName = pkg.applicationInfo.packageName; 9121 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9122 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9123 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9124 mResolveActivity.theme = 0; 9125 mResolveActivity.exported = true; 9126 mResolveActivity.enabled = true; 9127 mResolveInfo.activityInfo = mResolveActivity; 9128 mResolveInfo.priority = 0; 9129 mResolveInfo.preferredOrder = 0; 9130 mResolveInfo.match = 0; 9131 mResolveComponentName = mCustomResolverComponentName; 9132 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9133 mResolveComponentName); 9134 } 9135 } 9136 9137 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9138 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9139 9140 // Set up information for ephemeral installer activity 9141 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9142 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9143 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9144 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9145 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9146 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9147 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9148 mEphemeralInstallerActivity.theme = 0; 9149 mEphemeralInstallerActivity.exported = true; 9150 mEphemeralInstallerActivity.enabled = true; 9151 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9152 mEphemeralInstallerInfo.priority = 0; 9153 mEphemeralInstallerInfo.preferredOrder = 0; 9154 mEphemeralInstallerInfo.match = 0; 9155 9156 if (DEBUG_EPHEMERAL) { 9157 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9158 } 9159 } 9160 9161 private static String calculateBundledApkRoot(final String codePathString) { 9162 final File codePath = new File(codePathString); 9163 final File codeRoot; 9164 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9165 codeRoot = Environment.getRootDirectory(); 9166 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9167 codeRoot = Environment.getOemDirectory(); 9168 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9169 codeRoot = Environment.getVendorDirectory(); 9170 } else { 9171 // Unrecognized code path; take its top real segment as the apk root: 9172 // e.g. /something/app/blah.apk => /something 9173 try { 9174 File f = codePath.getCanonicalFile(); 9175 File parent = f.getParentFile(); // non-null because codePath is a file 9176 File tmp; 9177 while ((tmp = parent.getParentFile()) != null) { 9178 f = parent; 9179 parent = tmp; 9180 } 9181 codeRoot = f; 9182 Slog.w(TAG, "Unrecognized code path " 9183 + codePath + " - using " + codeRoot); 9184 } catch (IOException e) { 9185 // Can't canonicalize the code path -- shenanigans? 9186 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9187 return Environment.getRootDirectory().getPath(); 9188 } 9189 } 9190 return codeRoot.getPath(); 9191 } 9192 9193 /** 9194 * Derive and set the location of native libraries for the given package, 9195 * which varies depending on where and how the package was installed. 9196 */ 9197 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9198 final ApplicationInfo info = pkg.applicationInfo; 9199 final String codePath = pkg.codePath; 9200 final File codeFile = new File(codePath); 9201 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9202 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9203 9204 info.nativeLibraryRootDir = null; 9205 info.nativeLibraryRootRequiresIsa = false; 9206 info.nativeLibraryDir = null; 9207 info.secondaryNativeLibraryDir = null; 9208 9209 if (isApkFile(codeFile)) { 9210 // Monolithic install 9211 if (bundledApp) { 9212 // If "/system/lib64/apkname" exists, assume that is the per-package 9213 // native library directory to use; otherwise use "/system/lib/apkname". 9214 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9215 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9216 getPrimaryInstructionSet(info)); 9217 9218 // This is a bundled system app so choose the path based on the ABI. 9219 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9220 // is just the default path. 9221 final String apkName = deriveCodePathName(codePath); 9222 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9223 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9224 apkName).getAbsolutePath(); 9225 9226 if (info.secondaryCpuAbi != null) { 9227 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9228 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9229 secondaryLibDir, apkName).getAbsolutePath(); 9230 } 9231 } else if (asecApp) { 9232 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9233 .getAbsolutePath(); 9234 } else { 9235 final String apkName = deriveCodePathName(codePath); 9236 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9237 .getAbsolutePath(); 9238 } 9239 9240 info.nativeLibraryRootRequiresIsa = false; 9241 info.nativeLibraryDir = info.nativeLibraryRootDir; 9242 } else { 9243 // Cluster install 9244 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9245 info.nativeLibraryRootRequiresIsa = true; 9246 9247 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9248 getPrimaryInstructionSet(info)).getAbsolutePath(); 9249 9250 if (info.secondaryCpuAbi != null) { 9251 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9252 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9253 } 9254 } 9255 } 9256 9257 /** 9258 * Calculate the abis and roots for a bundled app. These can uniquely 9259 * be determined from the contents of the system partition, i.e whether 9260 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9261 * of this information, and instead assume that the system was built 9262 * sensibly. 9263 */ 9264 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9265 PackageSetting pkgSetting) { 9266 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9267 9268 // If "/system/lib64/apkname" exists, assume that is the per-package 9269 // native library directory to use; otherwise use "/system/lib/apkname". 9270 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9271 setBundledAppAbi(pkg, apkRoot, apkName); 9272 // pkgSetting might be null during rescan following uninstall of updates 9273 // to a bundled app, so accommodate that possibility. The settings in 9274 // that case will be established later from the parsed package. 9275 // 9276 // If the settings aren't null, sync them up with what we've just derived. 9277 // note that apkRoot isn't stored in the package settings. 9278 if (pkgSetting != null) { 9279 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9280 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9281 } 9282 } 9283 9284 /** 9285 * Deduces the ABI of a bundled app and sets the relevant fields on the 9286 * parsed pkg object. 9287 * 9288 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9289 * under which system libraries are installed. 9290 * @param apkName the name of the installed package. 9291 */ 9292 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9293 final File codeFile = new File(pkg.codePath); 9294 9295 final boolean has64BitLibs; 9296 final boolean has32BitLibs; 9297 if (isApkFile(codeFile)) { 9298 // Monolithic install 9299 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9300 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9301 } else { 9302 // Cluster install 9303 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9304 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9305 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9306 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9307 has64BitLibs = (new File(rootDir, isa)).exists(); 9308 } else { 9309 has64BitLibs = false; 9310 } 9311 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9312 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9313 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9314 has32BitLibs = (new File(rootDir, isa)).exists(); 9315 } else { 9316 has32BitLibs = false; 9317 } 9318 } 9319 9320 if (has64BitLibs && !has32BitLibs) { 9321 // The package has 64 bit libs, but not 32 bit libs. Its primary 9322 // ABI should be 64 bit. We can safely assume here that the bundled 9323 // native libraries correspond to the most preferred ABI in the list. 9324 9325 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9326 pkg.applicationInfo.secondaryCpuAbi = null; 9327 } else if (has32BitLibs && !has64BitLibs) { 9328 // The package has 32 bit libs but not 64 bit libs. Its primary 9329 // ABI should be 32 bit. 9330 9331 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9332 pkg.applicationInfo.secondaryCpuAbi = null; 9333 } else if (has32BitLibs && has64BitLibs) { 9334 // The application has both 64 and 32 bit bundled libraries. We check 9335 // here that the app declares multiArch support, and warn if it doesn't. 9336 // 9337 // We will be lenient here and record both ABIs. The primary will be the 9338 // ABI that's higher on the list, i.e, a device that's configured to prefer 9339 // 64 bit apps will see a 64 bit primary ABI, 9340 9341 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9342 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9343 } 9344 9345 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9346 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9347 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9348 } else { 9349 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9350 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9351 } 9352 } else { 9353 pkg.applicationInfo.primaryCpuAbi = null; 9354 pkg.applicationInfo.secondaryCpuAbi = null; 9355 } 9356 } 9357 9358 private void killApplication(String pkgName, int appId, String reason) { 9359 // Request the ActivityManager to kill the process(only for existing packages) 9360 // so that we do not end up in a confused state while the user is still using the older 9361 // version of the application while the new one gets installed. 9362 final long token = Binder.clearCallingIdentity(); 9363 try { 9364 IActivityManager am = ActivityManagerNative.getDefault(); 9365 if (am != null) { 9366 try { 9367 am.killApplicationWithAppId(pkgName, appId, reason); 9368 } catch (RemoteException e) { 9369 } 9370 } 9371 } finally { 9372 Binder.restoreCallingIdentity(token); 9373 } 9374 } 9375 9376 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9377 // Remove the parent package setting 9378 PackageSetting ps = (PackageSetting) pkg.mExtras; 9379 if (ps != null) { 9380 removePackageLI(ps, chatty); 9381 } 9382 // Remove the child package setting 9383 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9384 for (int i = 0; i < childCount; i++) { 9385 PackageParser.Package childPkg = pkg.childPackages.get(i); 9386 ps = (PackageSetting) childPkg.mExtras; 9387 if (ps != null) { 9388 removePackageLI(ps, chatty); 9389 } 9390 } 9391 } 9392 9393 void removePackageLI(PackageSetting ps, boolean chatty) { 9394 if (DEBUG_INSTALL) { 9395 if (chatty) 9396 Log.d(TAG, "Removing package " + ps.name); 9397 } 9398 9399 // writer 9400 synchronized (mPackages) { 9401 mPackages.remove(ps.name); 9402 final PackageParser.Package pkg = ps.pkg; 9403 if (pkg != null) { 9404 cleanPackageDataStructuresLILPw(pkg, chatty); 9405 } 9406 } 9407 } 9408 9409 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9410 if (DEBUG_INSTALL) { 9411 if (chatty) 9412 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9413 } 9414 9415 // writer 9416 synchronized (mPackages) { 9417 // Remove the parent package 9418 mPackages.remove(pkg.applicationInfo.packageName); 9419 cleanPackageDataStructuresLILPw(pkg, chatty); 9420 9421 // Remove the child packages 9422 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9423 for (int i = 0; i < childCount; i++) { 9424 PackageParser.Package childPkg = pkg.childPackages.get(i); 9425 mPackages.remove(childPkg.applicationInfo.packageName); 9426 cleanPackageDataStructuresLILPw(childPkg, chatty); 9427 } 9428 } 9429 } 9430 9431 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9432 int N = pkg.providers.size(); 9433 StringBuilder r = null; 9434 int i; 9435 for (i=0; i<N; i++) { 9436 PackageParser.Provider p = pkg.providers.get(i); 9437 mProviders.removeProvider(p); 9438 if (p.info.authority == null) { 9439 9440 /* There was another ContentProvider with this authority when 9441 * this app was installed so this authority is null, 9442 * Ignore it as we don't have to unregister the provider. 9443 */ 9444 continue; 9445 } 9446 String names[] = p.info.authority.split(";"); 9447 for (int j = 0; j < names.length; j++) { 9448 if (mProvidersByAuthority.get(names[j]) == p) { 9449 mProvidersByAuthority.remove(names[j]); 9450 if (DEBUG_REMOVE) { 9451 if (chatty) 9452 Log.d(TAG, "Unregistered content provider: " + names[j] 9453 + ", className = " + p.info.name + ", isSyncable = " 9454 + p.info.isSyncable); 9455 } 9456 } 9457 } 9458 if (DEBUG_REMOVE && chatty) { 9459 if (r == null) { 9460 r = new StringBuilder(256); 9461 } else { 9462 r.append(' '); 9463 } 9464 r.append(p.info.name); 9465 } 9466 } 9467 if (r != null) { 9468 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9469 } 9470 9471 N = pkg.services.size(); 9472 r = null; 9473 for (i=0; i<N; i++) { 9474 PackageParser.Service s = pkg.services.get(i); 9475 mServices.removeService(s); 9476 if (chatty) { 9477 if (r == null) { 9478 r = new StringBuilder(256); 9479 } else { 9480 r.append(' '); 9481 } 9482 r.append(s.info.name); 9483 } 9484 } 9485 if (r != null) { 9486 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9487 } 9488 9489 N = pkg.receivers.size(); 9490 r = null; 9491 for (i=0; i<N; i++) { 9492 PackageParser.Activity a = pkg.receivers.get(i); 9493 mReceivers.removeActivity(a, "receiver"); 9494 if (DEBUG_REMOVE && chatty) { 9495 if (r == null) { 9496 r = new StringBuilder(256); 9497 } else { 9498 r.append(' '); 9499 } 9500 r.append(a.info.name); 9501 } 9502 } 9503 if (r != null) { 9504 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9505 } 9506 9507 N = pkg.activities.size(); 9508 r = null; 9509 for (i=0; i<N; i++) { 9510 PackageParser.Activity a = pkg.activities.get(i); 9511 mActivities.removeActivity(a, "activity"); 9512 if (DEBUG_REMOVE && chatty) { 9513 if (r == null) { 9514 r = new StringBuilder(256); 9515 } else { 9516 r.append(' '); 9517 } 9518 r.append(a.info.name); 9519 } 9520 } 9521 if (r != null) { 9522 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9523 } 9524 9525 N = pkg.permissions.size(); 9526 r = null; 9527 for (i=0; i<N; i++) { 9528 PackageParser.Permission p = pkg.permissions.get(i); 9529 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9530 if (bp == null) { 9531 bp = mSettings.mPermissionTrees.get(p.info.name); 9532 } 9533 if (bp != null && bp.perm == p) { 9534 bp.perm = null; 9535 if (DEBUG_REMOVE && chatty) { 9536 if (r == null) { 9537 r = new StringBuilder(256); 9538 } else { 9539 r.append(' '); 9540 } 9541 r.append(p.info.name); 9542 } 9543 } 9544 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9545 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9546 if (appOpPkgs != null) { 9547 appOpPkgs.remove(pkg.packageName); 9548 } 9549 } 9550 } 9551 if (r != null) { 9552 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9553 } 9554 9555 N = pkg.requestedPermissions.size(); 9556 r = null; 9557 for (i=0; i<N; i++) { 9558 String perm = pkg.requestedPermissions.get(i); 9559 BasePermission bp = mSettings.mPermissions.get(perm); 9560 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9561 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9562 if (appOpPkgs != null) { 9563 appOpPkgs.remove(pkg.packageName); 9564 if (appOpPkgs.isEmpty()) { 9565 mAppOpPermissionPackages.remove(perm); 9566 } 9567 } 9568 } 9569 } 9570 if (r != null) { 9571 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9572 } 9573 9574 N = pkg.instrumentation.size(); 9575 r = null; 9576 for (i=0; i<N; i++) { 9577 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9578 mInstrumentation.remove(a.getComponentName()); 9579 if (DEBUG_REMOVE && chatty) { 9580 if (r == null) { 9581 r = new StringBuilder(256); 9582 } else { 9583 r.append(' '); 9584 } 9585 r.append(a.info.name); 9586 } 9587 } 9588 if (r != null) { 9589 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9590 } 9591 9592 r = null; 9593 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9594 // Only system apps can hold shared libraries. 9595 if (pkg.libraryNames != null) { 9596 for (i=0; i<pkg.libraryNames.size(); i++) { 9597 String name = pkg.libraryNames.get(i); 9598 SharedLibraryEntry cur = mSharedLibraries.get(name); 9599 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9600 mSharedLibraries.remove(name); 9601 if (DEBUG_REMOVE && chatty) { 9602 if (r == null) { 9603 r = new StringBuilder(256); 9604 } else { 9605 r.append(' '); 9606 } 9607 r.append(name); 9608 } 9609 } 9610 } 9611 } 9612 } 9613 if (r != null) { 9614 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9615 } 9616 } 9617 9618 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9619 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9620 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9621 return true; 9622 } 9623 } 9624 return false; 9625 } 9626 9627 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9628 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9629 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9630 9631 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9632 // Update the parent permissions 9633 updatePermissionsLPw(pkg.packageName, pkg, flags); 9634 // Update the child permissions 9635 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9636 for (int i = 0; i < childCount; i++) { 9637 PackageParser.Package childPkg = pkg.childPackages.get(i); 9638 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9639 } 9640 } 9641 9642 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9643 int flags) { 9644 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9645 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9646 } 9647 9648 private void updatePermissionsLPw(String changingPkg, 9649 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9650 // Make sure there are no dangling permission trees. 9651 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9652 while (it.hasNext()) { 9653 final BasePermission bp = it.next(); 9654 if (bp.packageSetting == null) { 9655 // We may not yet have parsed the package, so just see if 9656 // we still know about its settings. 9657 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9658 } 9659 if (bp.packageSetting == null) { 9660 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9661 + " from package " + bp.sourcePackage); 9662 it.remove(); 9663 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9664 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9665 Slog.i(TAG, "Removing old permission tree: " + bp.name 9666 + " from package " + bp.sourcePackage); 9667 flags |= UPDATE_PERMISSIONS_ALL; 9668 it.remove(); 9669 } 9670 } 9671 } 9672 9673 // Make sure all dynamic permissions have been assigned to a package, 9674 // and make sure there are no dangling permissions. 9675 it = mSettings.mPermissions.values().iterator(); 9676 while (it.hasNext()) { 9677 final BasePermission bp = it.next(); 9678 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9679 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9680 + bp.name + " pkg=" + bp.sourcePackage 9681 + " info=" + bp.pendingInfo); 9682 if (bp.packageSetting == null && bp.pendingInfo != null) { 9683 final BasePermission tree = findPermissionTreeLP(bp.name); 9684 if (tree != null && tree.perm != null) { 9685 bp.packageSetting = tree.packageSetting; 9686 bp.perm = new PackageParser.Permission(tree.perm.owner, 9687 new PermissionInfo(bp.pendingInfo)); 9688 bp.perm.info.packageName = tree.perm.info.packageName; 9689 bp.perm.info.name = bp.name; 9690 bp.uid = tree.uid; 9691 } 9692 } 9693 } 9694 if (bp.packageSetting == null) { 9695 // We may not yet have parsed the package, so just see if 9696 // we still know about its settings. 9697 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9698 } 9699 if (bp.packageSetting == null) { 9700 Slog.w(TAG, "Removing dangling permission: " + bp.name 9701 + " from package " + bp.sourcePackage); 9702 it.remove(); 9703 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9704 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9705 Slog.i(TAG, "Removing old permission: " + bp.name 9706 + " from package " + bp.sourcePackage); 9707 flags |= UPDATE_PERMISSIONS_ALL; 9708 it.remove(); 9709 } 9710 } 9711 } 9712 9713 // Now update the permissions for all packages, in particular 9714 // replace the granted permissions of the system packages. 9715 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9716 for (PackageParser.Package pkg : mPackages.values()) { 9717 if (pkg != pkgInfo) { 9718 // Only replace for packages on requested volume 9719 final String volumeUuid = getVolumeUuidForPackage(pkg); 9720 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9721 && Objects.equals(replaceVolumeUuid, volumeUuid); 9722 grantPermissionsLPw(pkg, replace, changingPkg); 9723 } 9724 } 9725 } 9726 9727 if (pkgInfo != null) { 9728 // Only replace for packages on requested volume 9729 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9730 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9731 && Objects.equals(replaceVolumeUuid, volumeUuid); 9732 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9733 } 9734 } 9735 9736 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9737 String packageOfInterest) { 9738 // IMPORTANT: There are two types of permissions: install and runtime. 9739 // Install time permissions are granted when the app is installed to 9740 // all device users and users added in the future. Runtime permissions 9741 // are granted at runtime explicitly to specific users. Normal and signature 9742 // protected permissions are install time permissions. Dangerous permissions 9743 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9744 // otherwise they are runtime permissions. This function does not manage 9745 // runtime permissions except for the case an app targeting Lollipop MR1 9746 // being upgraded to target a newer SDK, in which case dangerous permissions 9747 // are transformed from install time to runtime ones. 9748 9749 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9750 if (ps == null) { 9751 return; 9752 } 9753 9754 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9755 9756 PermissionsState permissionsState = ps.getPermissionsState(); 9757 PermissionsState origPermissions = permissionsState; 9758 9759 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9760 9761 boolean runtimePermissionsRevoked = false; 9762 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9763 9764 boolean changedInstallPermission = false; 9765 9766 if (replace) { 9767 ps.installPermissionsFixed = false; 9768 if (!ps.isSharedUser()) { 9769 origPermissions = new PermissionsState(permissionsState); 9770 permissionsState.reset(); 9771 } else { 9772 // We need to know only about runtime permission changes since the 9773 // calling code always writes the install permissions state but 9774 // the runtime ones are written only if changed. The only cases of 9775 // changed runtime permissions here are promotion of an install to 9776 // runtime and revocation of a runtime from a shared user. 9777 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9778 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9779 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9780 runtimePermissionsRevoked = true; 9781 } 9782 } 9783 } 9784 9785 permissionsState.setGlobalGids(mGlobalGids); 9786 9787 final int N = pkg.requestedPermissions.size(); 9788 for (int i=0; i<N; i++) { 9789 final String name = pkg.requestedPermissions.get(i); 9790 final BasePermission bp = mSettings.mPermissions.get(name); 9791 9792 if (DEBUG_INSTALL) { 9793 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9794 } 9795 9796 if (bp == null || bp.packageSetting == null) { 9797 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9798 Slog.w(TAG, "Unknown permission " + name 9799 + " in package " + pkg.packageName); 9800 } 9801 continue; 9802 } 9803 9804 final String perm = bp.name; 9805 boolean allowedSig = false; 9806 int grant = GRANT_DENIED; 9807 9808 // Keep track of app op permissions. 9809 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9810 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9811 if (pkgs == null) { 9812 pkgs = new ArraySet<>(); 9813 mAppOpPermissionPackages.put(bp.name, pkgs); 9814 } 9815 pkgs.add(pkg.packageName); 9816 } 9817 9818 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9819 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9820 >= Build.VERSION_CODES.M; 9821 switch (level) { 9822 case PermissionInfo.PROTECTION_NORMAL: { 9823 // For all apps normal permissions are install time ones. 9824 grant = GRANT_INSTALL; 9825 } break; 9826 9827 case PermissionInfo.PROTECTION_DANGEROUS: { 9828 // If a permission review is required for legacy apps we represent 9829 // their permissions as always granted runtime ones since we need 9830 // to keep the review required permission flag per user while an 9831 // install permission's state is shared across all users. 9832 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9833 // For legacy apps dangerous permissions are install time ones. 9834 grant = GRANT_INSTALL; 9835 } else if (origPermissions.hasInstallPermission(bp.name)) { 9836 // For legacy apps that became modern, install becomes runtime. 9837 grant = GRANT_UPGRADE; 9838 } else if (mPromoteSystemApps 9839 && isSystemApp(ps) 9840 && mExistingSystemPackages.contains(ps.name)) { 9841 // For legacy system apps, install becomes runtime. 9842 // We cannot check hasInstallPermission() for system apps since those 9843 // permissions were granted implicitly and not persisted pre-M. 9844 grant = GRANT_UPGRADE; 9845 } else { 9846 // For modern apps keep runtime permissions unchanged. 9847 grant = GRANT_RUNTIME; 9848 } 9849 } break; 9850 9851 case PermissionInfo.PROTECTION_SIGNATURE: { 9852 // For all apps signature permissions are install time ones. 9853 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9854 if (allowedSig) { 9855 grant = GRANT_INSTALL; 9856 } 9857 } break; 9858 } 9859 9860 if (DEBUG_INSTALL) { 9861 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9862 } 9863 9864 if (grant != GRANT_DENIED) { 9865 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9866 // If this is an existing, non-system package, then 9867 // we can't add any new permissions to it. 9868 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9869 // Except... if this is a permission that was added 9870 // to the platform (note: need to only do this when 9871 // updating the platform). 9872 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9873 grant = GRANT_DENIED; 9874 } 9875 } 9876 } 9877 9878 switch (grant) { 9879 case GRANT_INSTALL: { 9880 // Revoke this as runtime permission to handle the case of 9881 // a runtime permission being downgraded to an install one. 9882 // Also in permission review mode we keep dangerous permissions 9883 // for legacy apps 9884 for (int userId : UserManagerService.getInstance().getUserIds()) { 9885 if (origPermissions.getRuntimePermissionState( 9886 bp.name, userId) != null) { 9887 // Revoke the runtime permission and clear the flags. 9888 origPermissions.revokeRuntimePermission(bp, userId); 9889 origPermissions.updatePermissionFlags(bp, userId, 9890 PackageManager.MASK_PERMISSION_FLAGS, 0); 9891 // If we revoked a permission permission, we have to write. 9892 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9893 changedRuntimePermissionUserIds, userId); 9894 } 9895 } 9896 // Grant an install permission. 9897 if (permissionsState.grantInstallPermission(bp) != 9898 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9899 changedInstallPermission = true; 9900 } 9901 } break; 9902 9903 case GRANT_RUNTIME: { 9904 // Grant previously granted runtime permissions. 9905 for (int userId : UserManagerService.getInstance().getUserIds()) { 9906 PermissionState permissionState = origPermissions 9907 .getRuntimePermissionState(bp.name, userId); 9908 int flags = permissionState != null 9909 ? permissionState.getFlags() : 0; 9910 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9911 if (permissionsState.grantRuntimePermission(bp, userId) == 9912 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9913 // If we cannot put the permission as it was, we have to write. 9914 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9915 changedRuntimePermissionUserIds, userId); 9916 } 9917 // If the app supports runtime permissions no need for a review. 9918 if (Build.PERMISSIONS_REVIEW_REQUIRED 9919 && appSupportsRuntimePermissions 9920 && (flags & PackageManager 9921 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9922 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9923 // Since we changed the flags, we have to write. 9924 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9925 changedRuntimePermissionUserIds, userId); 9926 } 9927 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9928 && !appSupportsRuntimePermissions) { 9929 // For legacy apps that need a permission review, every new 9930 // runtime permission is granted but it is pending a review. 9931 // We also need to review only platform defined runtime 9932 // permissions as these are the only ones the platform knows 9933 // how to disable the API to simulate revocation as legacy 9934 // apps don't expect to run with revoked permissions. 9935 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9936 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9937 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9938 // We changed the flags, hence have to write. 9939 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9940 changedRuntimePermissionUserIds, userId); 9941 } 9942 } 9943 if (permissionsState.grantRuntimePermission(bp, userId) 9944 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9945 // We changed the permission, hence have to write. 9946 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9947 changedRuntimePermissionUserIds, userId); 9948 } 9949 } 9950 // Propagate the permission flags. 9951 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9952 } 9953 } break; 9954 9955 case GRANT_UPGRADE: { 9956 // Grant runtime permissions for a previously held install permission. 9957 PermissionState permissionState = origPermissions 9958 .getInstallPermissionState(bp.name); 9959 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9960 9961 if (origPermissions.revokeInstallPermission(bp) 9962 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9963 // We will be transferring the permission flags, so clear them. 9964 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9965 PackageManager.MASK_PERMISSION_FLAGS, 0); 9966 changedInstallPermission = true; 9967 } 9968 9969 // If the permission is not to be promoted to runtime we ignore it and 9970 // also its other flags as they are not applicable to install permissions. 9971 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9972 for (int userId : currentUserIds) { 9973 if (permissionsState.grantRuntimePermission(bp, userId) != 9974 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9975 // Transfer the permission flags. 9976 permissionsState.updatePermissionFlags(bp, userId, 9977 flags, flags); 9978 // If we granted the permission, we have to write. 9979 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9980 changedRuntimePermissionUserIds, userId); 9981 } 9982 } 9983 } 9984 } break; 9985 9986 default: { 9987 if (packageOfInterest == null 9988 || packageOfInterest.equals(pkg.packageName)) { 9989 Slog.w(TAG, "Not granting permission " + perm 9990 + " to package " + pkg.packageName 9991 + " because it was previously installed without"); 9992 } 9993 } break; 9994 } 9995 } else { 9996 if (permissionsState.revokeInstallPermission(bp) != 9997 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9998 // Also drop the permission flags. 9999 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10000 PackageManager.MASK_PERMISSION_FLAGS, 0); 10001 changedInstallPermission = true; 10002 Slog.i(TAG, "Un-granting permission " + perm 10003 + " from package " + pkg.packageName 10004 + " (protectionLevel=" + bp.protectionLevel 10005 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10006 + ")"); 10007 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10008 // Don't print warning for app op permissions, since it is fine for them 10009 // not to be granted, there is a UI for the user to decide. 10010 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10011 Slog.w(TAG, "Not granting permission " + perm 10012 + " to package " + pkg.packageName 10013 + " (protectionLevel=" + bp.protectionLevel 10014 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10015 + ")"); 10016 } 10017 } 10018 } 10019 } 10020 10021 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10022 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10023 // This is the first that we have heard about this package, so the 10024 // permissions we have now selected are fixed until explicitly 10025 // changed. 10026 ps.installPermissionsFixed = true; 10027 } 10028 10029 // Persist the runtime permissions state for users with changes. If permissions 10030 // were revoked because no app in the shared user declares them we have to 10031 // write synchronously to avoid losing runtime permissions state. 10032 for (int userId : changedRuntimePermissionUserIds) { 10033 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10034 } 10035 10036 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10037 } 10038 10039 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10040 boolean allowed = false; 10041 final int NP = PackageParser.NEW_PERMISSIONS.length; 10042 for (int ip=0; ip<NP; ip++) { 10043 final PackageParser.NewPermissionInfo npi 10044 = PackageParser.NEW_PERMISSIONS[ip]; 10045 if (npi.name.equals(perm) 10046 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10047 allowed = true; 10048 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10049 + pkg.packageName); 10050 break; 10051 } 10052 } 10053 return allowed; 10054 } 10055 10056 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10057 BasePermission bp, PermissionsState origPermissions) { 10058 boolean allowed; 10059 allowed = (compareSignatures( 10060 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10061 == PackageManager.SIGNATURE_MATCH) 10062 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10063 == PackageManager.SIGNATURE_MATCH); 10064 if (!allowed && (bp.protectionLevel 10065 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10066 if (isSystemApp(pkg)) { 10067 // For updated system applications, a system permission 10068 // is granted only if it had been defined by the original application. 10069 if (pkg.isUpdatedSystemApp()) { 10070 final PackageSetting sysPs = mSettings 10071 .getDisabledSystemPkgLPr(pkg.packageName); 10072 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10073 // If the original was granted this permission, we take 10074 // that grant decision as read and propagate it to the 10075 // update. 10076 if (sysPs.isPrivileged()) { 10077 allowed = true; 10078 } 10079 } else { 10080 // The system apk may have been updated with an older 10081 // version of the one on the data partition, but which 10082 // granted a new system permission that it didn't have 10083 // before. In this case we do want to allow the app to 10084 // now get the new permission if the ancestral apk is 10085 // privileged to get it. 10086 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10087 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10088 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10089 allowed = true; 10090 break; 10091 } 10092 } 10093 } 10094 // Also if a privileged parent package on the system image or any of 10095 // its children requested a privileged permission, the updated child 10096 // packages can also get the permission. 10097 if (pkg.parentPackage != null) { 10098 final PackageSetting disabledSysParentPs = mSettings 10099 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10100 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10101 && disabledSysParentPs.isPrivileged()) { 10102 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10103 allowed = true; 10104 } else if (disabledSysParentPs.pkg.childPackages != null) { 10105 final int count = disabledSysParentPs.pkg.childPackages.size(); 10106 for (int i = 0; i < count; i++) { 10107 PackageParser.Package disabledSysChildPkg = 10108 disabledSysParentPs.pkg.childPackages.get(i); 10109 if (isPackageRequestingPermission(disabledSysChildPkg, 10110 perm)) { 10111 allowed = true; 10112 break; 10113 } 10114 } 10115 } 10116 } 10117 } 10118 } 10119 } else { 10120 allowed = isPrivilegedApp(pkg); 10121 } 10122 } 10123 } 10124 if (!allowed) { 10125 if (!allowed && (bp.protectionLevel 10126 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10127 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10128 // If this was a previously normal/dangerous permission that got moved 10129 // to a system permission as part of the runtime permission redesign, then 10130 // we still want to blindly grant it to old apps. 10131 allowed = true; 10132 } 10133 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10134 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10135 // If this permission is to be granted to the system installer and 10136 // this app is an installer, then it gets the permission. 10137 allowed = true; 10138 } 10139 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10140 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10141 // If this permission is to be granted to the system verifier and 10142 // this app is a verifier, then it gets the permission. 10143 allowed = true; 10144 } 10145 if (!allowed && (bp.protectionLevel 10146 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10147 && isSystemApp(pkg)) { 10148 // Any pre-installed system app is allowed to get this permission. 10149 allowed = true; 10150 } 10151 if (!allowed && (bp.protectionLevel 10152 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10153 // For development permissions, a development permission 10154 // is granted only if it was already granted. 10155 allowed = origPermissions.hasInstallPermission(perm); 10156 } 10157 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10158 && pkg.packageName.equals(mSetupWizardPackage)) { 10159 // If this permission is to be granted to the system setup wizard and 10160 // this app is a setup wizard, then it gets the permission. 10161 allowed = true; 10162 } 10163 } 10164 return allowed; 10165 } 10166 10167 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10168 final int permCount = pkg.requestedPermissions.size(); 10169 for (int j = 0; j < permCount; j++) { 10170 String requestedPermission = pkg.requestedPermissions.get(j); 10171 if (permission.equals(requestedPermission)) { 10172 return true; 10173 } 10174 } 10175 return false; 10176 } 10177 10178 final class ActivityIntentResolver 10179 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10180 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10181 boolean defaultOnly, int userId) { 10182 if (!sUserManager.exists(userId)) return null; 10183 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10184 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10185 } 10186 10187 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10188 int userId) { 10189 if (!sUserManager.exists(userId)) return null; 10190 mFlags = flags; 10191 return super.queryIntent(intent, resolvedType, 10192 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10193 } 10194 10195 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10196 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10197 if (!sUserManager.exists(userId)) return null; 10198 if (packageActivities == null) { 10199 return null; 10200 } 10201 mFlags = flags; 10202 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10203 final int N = packageActivities.size(); 10204 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10205 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10206 10207 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10208 for (int i = 0; i < N; ++i) { 10209 intentFilters = packageActivities.get(i).intents; 10210 if (intentFilters != null && intentFilters.size() > 0) { 10211 PackageParser.ActivityIntentInfo[] array = 10212 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10213 intentFilters.toArray(array); 10214 listCut.add(array); 10215 } 10216 } 10217 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10218 } 10219 10220 /** 10221 * Finds a privileged activity that matches the specified activity names. 10222 */ 10223 private PackageParser.Activity findMatchingActivity( 10224 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10225 for (PackageParser.Activity sysActivity : activityList) { 10226 if (sysActivity.info.name.equals(activityInfo.name)) { 10227 return sysActivity; 10228 } 10229 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10230 return sysActivity; 10231 } 10232 if (sysActivity.info.targetActivity != null) { 10233 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10234 return sysActivity; 10235 } 10236 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10237 return sysActivity; 10238 } 10239 } 10240 } 10241 return null; 10242 } 10243 10244 public class IterGenerator<E> { 10245 public Iterator<E> generate(ActivityIntentInfo info) { 10246 return null; 10247 } 10248 } 10249 10250 public class ActionIterGenerator extends IterGenerator<String> { 10251 @Override 10252 public Iterator<String> generate(ActivityIntentInfo info) { 10253 return info.actionsIterator(); 10254 } 10255 } 10256 10257 public class CategoriesIterGenerator extends IterGenerator<String> { 10258 @Override 10259 public Iterator<String> generate(ActivityIntentInfo info) { 10260 return info.categoriesIterator(); 10261 } 10262 } 10263 10264 public class SchemesIterGenerator extends IterGenerator<String> { 10265 @Override 10266 public Iterator<String> generate(ActivityIntentInfo info) { 10267 return info.schemesIterator(); 10268 } 10269 } 10270 10271 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10272 @Override 10273 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10274 return info.authoritiesIterator(); 10275 } 10276 } 10277 10278 /** 10279 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10280 * MODIFIED. Do not pass in a list that should not be changed. 10281 */ 10282 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10283 IterGenerator<T> generator, Iterator<T> searchIterator) { 10284 // loop through the set of actions; every one must be found in the intent filter 10285 while (searchIterator.hasNext()) { 10286 // we must have at least one filter in the list to consider a match 10287 if (intentList.size() == 0) { 10288 break; 10289 } 10290 10291 final T searchAction = searchIterator.next(); 10292 10293 // loop through the set of intent filters 10294 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10295 while (intentIter.hasNext()) { 10296 final ActivityIntentInfo intentInfo = intentIter.next(); 10297 boolean selectionFound = false; 10298 10299 // loop through the intent filter's selection criteria; at least one 10300 // of them must match the searched criteria 10301 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10302 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10303 final T intentSelection = intentSelectionIter.next(); 10304 if (intentSelection != null && intentSelection.equals(searchAction)) { 10305 selectionFound = true; 10306 break; 10307 } 10308 } 10309 10310 // the selection criteria wasn't found in this filter's set; this filter 10311 // is not a potential match 10312 if (!selectionFound) { 10313 intentIter.remove(); 10314 } 10315 } 10316 } 10317 } 10318 10319 private boolean isProtectedAction(ActivityIntentInfo filter) { 10320 final Iterator<String> actionsIter = filter.actionsIterator(); 10321 while (actionsIter != null && actionsIter.hasNext()) { 10322 final String filterAction = actionsIter.next(); 10323 if (PROTECTED_ACTIONS.contains(filterAction)) { 10324 return true; 10325 } 10326 } 10327 return false; 10328 } 10329 10330 /** 10331 * Adjusts the priority of the given intent filter according to policy. 10332 * <p> 10333 * <ul> 10334 * <li>The priority for non privileged applications is capped to '0'</li> 10335 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10336 * <li>The priority for unbundled updates to privileged applications is capped to the 10337 * priority defined on the system partition</li> 10338 * </ul> 10339 * <p> 10340 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10341 * allowed to obtain any priority on any action. 10342 */ 10343 private void adjustPriority( 10344 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10345 // nothing to do; priority is fine as-is 10346 if (intent.getPriority() <= 0) { 10347 return; 10348 } 10349 10350 final ActivityInfo activityInfo = intent.activity.info; 10351 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10352 10353 final boolean privilegedApp = 10354 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10355 if (!privilegedApp) { 10356 // non-privileged applications can never define a priority >0 10357 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10358 + " package: " + applicationInfo.packageName 10359 + " activity: " + intent.activity.className 10360 + " origPrio: " + intent.getPriority()); 10361 intent.setPriority(0); 10362 return; 10363 } 10364 10365 if (systemActivities == null) { 10366 // the system package is not disabled; we're parsing the system partition 10367 if (isProtectedAction(intent)) { 10368 if (mDeferProtectedFilters) { 10369 // We can't deal with these just yet. No component should ever obtain a 10370 // >0 priority for a protected actions, with ONE exception -- the setup 10371 // wizard. The setup wizard, however, cannot be known until we're able to 10372 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10373 // until all intent filters have been processed. Chicken, meet egg. 10374 // Let the filter temporarily have a high priority and rectify the 10375 // priorities after all system packages have been scanned. 10376 mProtectedFilters.add(intent); 10377 if (DEBUG_FILTERS) { 10378 Slog.i(TAG, "Protected action; save for later;" 10379 + " package: " + applicationInfo.packageName 10380 + " activity: " + intent.activity.className 10381 + " origPrio: " + intent.getPriority()); 10382 } 10383 return; 10384 } else { 10385 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10386 Slog.i(TAG, "No setup wizard;" 10387 + " All protected intents capped to priority 0"); 10388 } 10389 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10390 if (DEBUG_FILTERS) { 10391 Slog.i(TAG, "Found setup wizard;" 10392 + " allow priority " + intent.getPriority() + ";" 10393 + " package: " + intent.activity.info.packageName 10394 + " activity: " + intent.activity.className 10395 + " priority: " + intent.getPriority()); 10396 } 10397 // setup wizard gets whatever it wants 10398 return; 10399 } 10400 Slog.w(TAG, "Protected action; cap priority to 0;" 10401 + " package: " + intent.activity.info.packageName 10402 + " activity: " + intent.activity.className 10403 + " origPrio: " + intent.getPriority()); 10404 intent.setPriority(0); 10405 return; 10406 } 10407 } 10408 // privileged apps on the system image get whatever priority they request 10409 return; 10410 } 10411 10412 // privileged app unbundled update ... try to find the same activity 10413 final PackageParser.Activity foundActivity = 10414 findMatchingActivity(systemActivities, activityInfo); 10415 if (foundActivity == null) { 10416 // this is a new activity; it cannot obtain >0 priority 10417 if (DEBUG_FILTERS) { 10418 Slog.i(TAG, "New activity; cap priority to 0;" 10419 + " package: " + applicationInfo.packageName 10420 + " activity: " + intent.activity.className 10421 + " origPrio: " + intent.getPriority()); 10422 } 10423 intent.setPriority(0); 10424 return; 10425 } 10426 10427 // found activity, now check for filter equivalence 10428 10429 // a shallow copy is enough; we modify the list, not its contents 10430 final List<ActivityIntentInfo> intentListCopy = 10431 new ArrayList<>(foundActivity.intents); 10432 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10433 10434 // find matching action subsets 10435 final Iterator<String> actionsIterator = intent.actionsIterator(); 10436 if (actionsIterator != null) { 10437 getIntentListSubset( 10438 intentListCopy, new ActionIterGenerator(), actionsIterator); 10439 if (intentListCopy.size() == 0) { 10440 // no more intents to match; we're not equivalent 10441 if (DEBUG_FILTERS) { 10442 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10443 + " package: " + applicationInfo.packageName 10444 + " activity: " + intent.activity.className 10445 + " origPrio: " + intent.getPriority()); 10446 } 10447 intent.setPriority(0); 10448 return; 10449 } 10450 } 10451 10452 // find matching category subsets 10453 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10454 if (categoriesIterator != null) { 10455 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10456 categoriesIterator); 10457 if (intentListCopy.size() == 0) { 10458 // no more intents to match; we're not equivalent 10459 if (DEBUG_FILTERS) { 10460 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10461 + " package: " + applicationInfo.packageName 10462 + " activity: " + intent.activity.className 10463 + " origPrio: " + intent.getPriority()); 10464 } 10465 intent.setPriority(0); 10466 return; 10467 } 10468 } 10469 10470 // find matching schemes subsets 10471 final Iterator<String> schemesIterator = intent.schemesIterator(); 10472 if (schemesIterator != null) { 10473 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10474 schemesIterator); 10475 if (intentListCopy.size() == 0) { 10476 // no more intents to match; we're not equivalent 10477 if (DEBUG_FILTERS) { 10478 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10479 + " package: " + applicationInfo.packageName 10480 + " activity: " + intent.activity.className 10481 + " origPrio: " + intent.getPriority()); 10482 } 10483 intent.setPriority(0); 10484 return; 10485 } 10486 } 10487 10488 // find matching authorities subsets 10489 final Iterator<IntentFilter.AuthorityEntry> 10490 authoritiesIterator = intent.authoritiesIterator(); 10491 if (authoritiesIterator != null) { 10492 getIntentListSubset(intentListCopy, 10493 new AuthoritiesIterGenerator(), 10494 authoritiesIterator); 10495 if (intentListCopy.size() == 0) { 10496 // no more intents to match; we're not equivalent 10497 if (DEBUG_FILTERS) { 10498 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10499 + " package: " + applicationInfo.packageName 10500 + " activity: " + intent.activity.className 10501 + " origPrio: " + intent.getPriority()); 10502 } 10503 intent.setPriority(0); 10504 return; 10505 } 10506 } 10507 10508 // we found matching filter(s); app gets the max priority of all intents 10509 int cappedPriority = 0; 10510 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10511 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10512 } 10513 if (intent.getPriority() > cappedPriority) { 10514 if (DEBUG_FILTERS) { 10515 Slog.i(TAG, "Found matching filter(s);" 10516 + " cap priority to " + cappedPriority + ";" 10517 + " package: " + applicationInfo.packageName 10518 + " activity: " + intent.activity.className 10519 + " origPrio: " + intent.getPriority()); 10520 } 10521 intent.setPriority(cappedPriority); 10522 return; 10523 } 10524 // all this for nothing; the requested priority was <= what was on the system 10525 } 10526 10527 public final void addActivity(PackageParser.Activity a, String type) { 10528 mActivities.put(a.getComponentName(), a); 10529 if (DEBUG_SHOW_INFO) 10530 Log.v( 10531 TAG, " " + type + " " + 10532 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10533 if (DEBUG_SHOW_INFO) 10534 Log.v(TAG, " Class=" + a.info.name); 10535 final int NI = a.intents.size(); 10536 for (int j=0; j<NI; j++) { 10537 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10538 if ("activity".equals(type)) { 10539 final PackageSetting ps = 10540 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10541 final List<PackageParser.Activity> systemActivities = 10542 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10543 adjustPriority(systemActivities, intent); 10544 } 10545 if (DEBUG_SHOW_INFO) { 10546 Log.v(TAG, " IntentFilter:"); 10547 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10548 } 10549 if (!intent.debugCheck()) { 10550 Log.w(TAG, "==> For Activity " + a.info.name); 10551 } 10552 addFilter(intent); 10553 } 10554 } 10555 10556 public final void removeActivity(PackageParser.Activity a, String type) { 10557 mActivities.remove(a.getComponentName()); 10558 if (DEBUG_SHOW_INFO) { 10559 Log.v(TAG, " " + type + " " 10560 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10561 : a.info.name) + ":"); 10562 Log.v(TAG, " Class=" + a.info.name); 10563 } 10564 final int NI = a.intents.size(); 10565 for (int j=0; j<NI; j++) { 10566 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10567 if (DEBUG_SHOW_INFO) { 10568 Log.v(TAG, " IntentFilter:"); 10569 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10570 } 10571 removeFilter(intent); 10572 } 10573 } 10574 10575 @Override 10576 protected boolean allowFilterResult( 10577 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10578 ActivityInfo filterAi = filter.activity.info; 10579 for (int i=dest.size()-1; i>=0; i--) { 10580 ActivityInfo destAi = dest.get(i).activityInfo; 10581 if (destAi.name == filterAi.name 10582 && destAi.packageName == filterAi.packageName) { 10583 return false; 10584 } 10585 } 10586 return true; 10587 } 10588 10589 @Override 10590 protected ActivityIntentInfo[] newArray(int size) { 10591 return new ActivityIntentInfo[size]; 10592 } 10593 10594 @Override 10595 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10596 if (!sUserManager.exists(userId)) return true; 10597 PackageParser.Package p = filter.activity.owner; 10598 if (p != null) { 10599 PackageSetting ps = (PackageSetting)p.mExtras; 10600 if (ps != null) { 10601 // System apps are never considered stopped for purposes of 10602 // filtering, because there may be no way for the user to 10603 // actually re-launch them. 10604 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10605 && ps.getStopped(userId); 10606 } 10607 } 10608 return false; 10609 } 10610 10611 @Override 10612 protected boolean isPackageForFilter(String packageName, 10613 PackageParser.ActivityIntentInfo info) { 10614 return packageName.equals(info.activity.owner.packageName); 10615 } 10616 10617 @Override 10618 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10619 int match, int userId) { 10620 if (!sUserManager.exists(userId)) return null; 10621 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10622 return null; 10623 } 10624 final PackageParser.Activity activity = info.activity; 10625 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10626 if (ps == null) { 10627 return null; 10628 } 10629 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10630 ps.readUserState(userId), userId); 10631 if (ai == null) { 10632 return null; 10633 } 10634 final ResolveInfo res = new ResolveInfo(); 10635 res.activityInfo = ai; 10636 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10637 res.filter = info; 10638 } 10639 if (info != null) { 10640 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10641 } 10642 res.priority = info.getPriority(); 10643 res.preferredOrder = activity.owner.mPreferredOrder; 10644 //System.out.println("Result: " + res.activityInfo.className + 10645 // " = " + res.priority); 10646 res.match = match; 10647 res.isDefault = info.hasDefault; 10648 res.labelRes = info.labelRes; 10649 res.nonLocalizedLabel = info.nonLocalizedLabel; 10650 if (userNeedsBadging(userId)) { 10651 res.noResourceId = true; 10652 } else { 10653 res.icon = info.icon; 10654 } 10655 res.iconResourceId = info.icon; 10656 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10657 return res; 10658 } 10659 10660 @Override 10661 protected void sortResults(List<ResolveInfo> results) { 10662 Collections.sort(results, mResolvePrioritySorter); 10663 } 10664 10665 @Override 10666 protected void dumpFilter(PrintWriter out, String prefix, 10667 PackageParser.ActivityIntentInfo filter) { 10668 out.print(prefix); out.print( 10669 Integer.toHexString(System.identityHashCode(filter.activity))); 10670 out.print(' '); 10671 filter.activity.printComponentShortName(out); 10672 out.print(" filter "); 10673 out.println(Integer.toHexString(System.identityHashCode(filter))); 10674 } 10675 10676 @Override 10677 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10678 return filter.activity; 10679 } 10680 10681 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10682 PackageParser.Activity activity = (PackageParser.Activity)label; 10683 out.print(prefix); out.print( 10684 Integer.toHexString(System.identityHashCode(activity))); 10685 out.print(' '); 10686 activity.printComponentShortName(out); 10687 if (count > 1) { 10688 out.print(" ("); out.print(count); out.print(" filters)"); 10689 } 10690 out.println(); 10691 } 10692 10693 // Keys are String (activity class name), values are Activity. 10694 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10695 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10696 private int mFlags; 10697 } 10698 10699 private final class ServiceIntentResolver 10700 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10701 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10702 boolean defaultOnly, int userId) { 10703 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10704 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10705 } 10706 10707 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10708 int userId) { 10709 if (!sUserManager.exists(userId)) return null; 10710 mFlags = flags; 10711 return super.queryIntent(intent, resolvedType, 10712 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10713 } 10714 10715 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10716 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10717 if (!sUserManager.exists(userId)) return null; 10718 if (packageServices == null) { 10719 return null; 10720 } 10721 mFlags = flags; 10722 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10723 final int N = packageServices.size(); 10724 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10725 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10726 10727 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10728 for (int i = 0; i < N; ++i) { 10729 intentFilters = packageServices.get(i).intents; 10730 if (intentFilters != null && intentFilters.size() > 0) { 10731 PackageParser.ServiceIntentInfo[] array = 10732 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10733 intentFilters.toArray(array); 10734 listCut.add(array); 10735 } 10736 } 10737 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10738 } 10739 10740 public final void addService(PackageParser.Service s) { 10741 mServices.put(s.getComponentName(), s); 10742 if (DEBUG_SHOW_INFO) { 10743 Log.v(TAG, " " 10744 + (s.info.nonLocalizedLabel != null 10745 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10746 Log.v(TAG, " Class=" + s.info.name); 10747 } 10748 final int NI = s.intents.size(); 10749 int j; 10750 for (j=0; j<NI; j++) { 10751 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10752 if (DEBUG_SHOW_INFO) { 10753 Log.v(TAG, " IntentFilter:"); 10754 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10755 } 10756 if (!intent.debugCheck()) { 10757 Log.w(TAG, "==> For Service " + s.info.name); 10758 } 10759 addFilter(intent); 10760 } 10761 } 10762 10763 public final void removeService(PackageParser.Service s) { 10764 mServices.remove(s.getComponentName()); 10765 if (DEBUG_SHOW_INFO) { 10766 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10767 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10768 Log.v(TAG, " Class=" + s.info.name); 10769 } 10770 final int NI = s.intents.size(); 10771 int j; 10772 for (j=0; j<NI; j++) { 10773 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10774 if (DEBUG_SHOW_INFO) { 10775 Log.v(TAG, " IntentFilter:"); 10776 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10777 } 10778 removeFilter(intent); 10779 } 10780 } 10781 10782 @Override 10783 protected boolean allowFilterResult( 10784 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10785 ServiceInfo filterSi = filter.service.info; 10786 for (int i=dest.size()-1; i>=0; i--) { 10787 ServiceInfo destAi = dest.get(i).serviceInfo; 10788 if (destAi.name == filterSi.name 10789 && destAi.packageName == filterSi.packageName) { 10790 return false; 10791 } 10792 } 10793 return true; 10794 } 10795 10796 @Override 10797 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10798 return new PackageParser.ServiceIntentInfo[size]; 10799 } 10800 10801 @Override 10802 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10803 if (!sUserManager.exists(userId)) return true; 10804 PackageParser.Package p = filter.service.owner; 10805 if (p != null) { 10806 PackageSetting ps = (PackageSetting)p.mExtras; 10807 if (ps != null) { 10808 // System apps are never considered stopped for purposes of 10809 // filtering, because there may be no way for the user to 10810 // actually re-launch them. 10811 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10812 && ps.getStopped(userId); 10813 } 10814 } 10815 return false; 10816 } 10817 10818 @Override 10819 protected boolean isPackageForFilter(String packageName, 10820 PackageParser.ServiceIntentInfo info) { 10821 return packageName.equals(info.service.owner.packageName); 10822 } 10823 10824 @Override 10825 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10826 int match, int userId) { 10827 if (!sUserManager.exists(userId)) return null; 10828 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10829 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10830 return null; 10831 } 10832 final PackageParser.Service service = info.service; 10833 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10834 if (ps == null) { 10835 return null; 10836 } 10837 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10838 ps.readUserState(userId), userId); 10839 if (si == null) { 10840 return null; 10841 } 10842 final ResolveInfo res = new ResolveInfo(); 10843 res.serviceInfo = si; 10844 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10845 res.filter = filter; 10846 } 10847 res.priority = info.getPriority(); 10848 res.preferredOrder = service.owner.mPreferredOrder; 10849 res.match = match; 10850 res.isDefault = info.hasDefault; 10851 res.labelRes = info.labelRes; 10852 res.nonLocalizedLabel = info.nonLocalizedLabel; 10853 res.icon = info.icon; 10854 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10855 return res; 10856 } 10857 10858 @Override 10859 protected void sortResults(List<ResolveInfo> results) { 10860 Collections.sort(results, mResolvePrioritySorter); 10861 } 10862 10863 @Override 10864 protected void dumpFilter(PrintWriter out, String prefix, 10865 PackageParser.ServiceIntentInfo filter) { 10866 out.print(prefix); out.print( 10867 Integer.toHexString(System.identityHashCode(filter.service))); 10868 out.print(' '); 10869 filter.service.printComponentShortName(out); 10870 out.print(" filter "); 10871 out.println(Integer.toHexString(System.identityHashCode(filter))); 10872 } 10873 10874 @Override 10875 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10876 return filter.service; 10877 } 10878 10879 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10880 PackageParser.Service service = (PackageParser.Service)label; 10881 out.print(prefix); out.print( 10882 Integer.toHexString(System.identityHashCode(service))); 10883 out.print(' '); 10884 service.printComponentShortName(out); 10885 if (count > 1) { 10886 out.print(" ("); out.print(count); out.print(" filters)"); 10887 } 10888 out.println(); 10889 } 10890 10891// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10892// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10893// final List<ResolveInfo> retList = Lists.newArrayList(); 10894// while (i.hasNext()) { 10895// final ResolveInfo resolveInfo = (ResolveInfo) i; 10896// if (isEnabledLP(resolveInfo.serviceInfo)) { 10897// retList.add(resolveInfo); 10898// } 10899// } 10900// return retList; 10901// } 10902 10903 // Keys are String (activity class name), values are Activity. 10904 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10905 = new ArrayMap<ComponentName, PackageParser.Service>(); 10906 private int mFlags; 10907 }; 10908 10909 private final class ProviderIntentResolver 10910 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10911 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10912 boolean defaultOnly, int userId) { 10913 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10914 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10915 } 10916 10917 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10918 int userId) { 10919 if (!sUserManager.exists(userId)) 10920 return null; 10921 mFlags = flags; 10922 return super.queryIntent(intent, resolvedType, 10923 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10924 } 10925 10926 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10927 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10928 if (!sUserManager.exists(userId)) 10929 return null; 10930 if (packageProviders == null) { 10931 return null; 10932 } 10933 mFlags = flags; 10934 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10935 final int N = packageProviders.size(); 10936 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10937 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10938 10939 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10940 for (int i = 0; i < N; ++i) { 10941 intentFilters = packageProviders.get(i).intents; 10942 if (intentFilters != null && intentFilters.size() > 0) { 10943 PackageParser.ProviderIntentInfo[] array = 10944 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10945 intentFilters.toArray(array); 10946 listCut.add(array); 10947 } 10948 } 10949 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10950 } 10951 10952 public final void addProvider(PackageParser.Provider p) { 10953 if (mProviders.containsKey(p.getComponentName())) { 10954 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10955 return; 10956 } 10957 10958 mProviders.put(p.getComponentName(), p); 10959 if (DEBUG_SHOW_INFO) { 10960 Log.v(TAG, " " 10961 + (p.info.nonLocalizedLabel != null 10962 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10963 Log.v(TAG, " Class=" + p.info.name); 10964 } 10965 final int NI = p.intents.size(); 10966 int j; 10967 for (j = 0; j < NI; j++) { 10968 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10969 if (DEBUG_SHOW_INFO) { 10970 Log.v(TAG, " IntentFilter:"); 10971 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10972 } 10973 if (!intent.debugCheck()) { 10974 Log.w(TAG, "==> For Provider " + p.info.name); 10975 } 10976 addFilter(intent); 10977 } 10978 } 10979 10980 public final void removeProvider(PackageParser.Provider p) { 10981 mProviders.remove(p.getComponentName()); 10982 if (DEBUG_SHOW_INFO) { 10983 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10984 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10985 Log.v(TAG, " Class=" + p.info.name); 10986 } 10987 final int NI = p.intents.size(); 10988 int j; 10989 for (j = 0; j < NI; j++) { 10990 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10991 if (DEBUG_SHOW_INFO) { 10992 Log.v(TAG, " IntentFilter:"); 10993 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10994 } 10995 removeFilter(intent); 10996 } 10997 } 10998 10999 @Override 11000 protected boolean allowFilterResult( 11001 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11002 ProviderInfo filterPi = filter.provider.info; 11003 for (int i = dest.size() - 1; i >= 0; i--) { 11004 ProviderInfo destPi = dest.get(i).providerInfo; 11005 if (destPi.name == filterPi.name 11006 && destPi.packageName == filterPi.packageName) { 11007 return false; 11008 } 11009 } 11010 return true; 11011 } 11012 11013 @Override 11014 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11015 return new PackageParser.ProviderIntentInfo[size]; 11016 } 11017 11018 @Override 11019 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11020 if (!sUserManager.exists(userId)) 11021 return true; 11022 PackageParser.Package p = filter.provider.owner; 11023 if (p != null) { 11024 PackageSetting ps = (PackageSetting) p.mExtras; 11025 if (ps != null) { 11026 // System apps are never considered stopped for purposes of 11027 // filtering, because there may be no way for the user to 11028 // actually re-launch them. 11029 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11030 && ps.getStopped(userId); 11031 } 11032 } 11033 return false; 11034 } 11035 11036 @Override 11037 protected boolean isPackageForFilter(String packageName, 11038 PackageParser.ProviderIntentInfo info) { 11039 return packageName.equals(info.provider.owner.packageName); 11040 } 11041 11042 @Override 11043 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11044 int match, int userId) { 11045 if (!sUserManager.exists(userId)) 11046 return null; 11047 final PackageParser.ProviderIntentInfo info = filter; 11048 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11049 return null; 11050 } 11051 final PackageParser.Provider provider = info.provider; 11052 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11053 if (ps == null) { 11054 return null; 11055 } 11056 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11057 ps.readUserState(userId), userId); 11058 if (pi == null) { 11059 return null; 11060 } 11061 final ResolveInfo res = new ResolveInfo(); 11062 res.providerInfo = pi; 11063 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11064 res.filter = filter; 11065 } 11066 res.priority = info.getPriority(); 11067 res.preferredOrder = provider.owner.mPreferredOrder; 11068 res.match = match; 11069 res.isDefault = info.hasDefault; 11070 res.labelRes = info.labelRes; 11071 res.nonLocalizedLabel = info.nonLocalizedLabel; 11072 res.icon = info.icon; 11073 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11074 return res; 11075 } 11076 11077 @Override 11078 protected void sortResults(List<ResolveInfo> results) { 11079 Collections.sort(results, mResolvePrioritySorter); 11080 } 11081 11082 @Override 11083 protected void dumpFilter(PrintWriter out, String prefix, 11084 PackageParser.ProviderIntentInfo filter) { 11085 out.print(prefix); 11086 out.print( 11087 Integer.toHexString(System.identityHashCode(filter.provider))); 11088 out.print(' '); 11089 filter.provider.printComponentShortName(out); 11090 out.print(" filter "); 11091 out.println(Integer.toHexString(System.identityHashCode(filter))); 11092 } 11093 11094 @Override 11095 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11096 return filter.provider; 11097 } 11098 11099 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11100 PackageParser.Provider provider = (PackageParser.Provider)label; 11101 out.print(prefix); out.print( 11102 Integer.toHexString(System.identityHashCode(provider))); 11103 out.print(' '); 11104 provider.printComponentShortName(out); 11105 if (count > 1) { 11106 out.print(" ("); out.print(count); out.print(" filters)"); 11107 } 11108 out.println(); 11109 } 11110 11111 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11112 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11113 private int mFlags; 11114 } 11115 11116 private static final class EphemeralIntentResolver 11117 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11118 @Override 11119 protected EphemeralResolveIntentInfo[] newArray(int size) { 11120 return new EphemeralResolveIntentInfo[size]; 11121 } 11122 11123 @Override 11124 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11125 return true; 11126 } 11127 11128 @Override 11129 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11130 int userId) { 11131 if (!sUserManager.exists(userId)) { 11132 return null; 11133 } 11134 return info.getEphemeralResolveInfo(); 11135 } 11136 } 11137 11138 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11139 new Comparator<ResolveInfo>() { 11140 public int compare(ResolveInfo r1, ResolveInfo r2) { 11141 int v1 = r1.priority; 11142 int v2 = r2.priority; 11143 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11144 if (v1 != v2) { 11145 return (v1 > v2) ? -1 : 1; 11146 } 11147 v1 = r1.preferredOrder; 11148 v2 = r2.preferredOrder; 11149 if (v1 != v2) { 11150 return (v1 > v2) ? -1 : 1; 11151 } 11152 if (r1.isDefault != r2.isDefault) { 11153 return r1.isDefault ? -1 : 1; 11154 } 11155 v1 = r1.match; 11156 v2 = r2.match; 11157 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11158 if (v1 != v2) { 11159 return (v1 > v2) ? -1 : 1; 11160 } 11161 if (r1.system != r2.system) { 11162 return r1.system ? -1 : 1; 11163 } 11164 if (r1.activityInfo != null) { 11165 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11166 } 11167 if (r1.serviceInfo != null) { 11168 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11169 } 11170 if (r1.providerInfo != null) { 11171 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11172 } 11173 return 0; 11174 } 11175 }; 11176 11177 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11178 new Comparator<ProviderInfo>() { 11179 public int compare(ProviderInfo p1, ProviderInfo p2) { 11180 final int v1 = p1.initOrder; 11181 final int v2 = p2.initOrder; 11182 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11183 } 11184 }; 11185 11186 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11187 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11188 final int[] userIds) { 11189 mHandler.post(new Runnable() { 11190 @Override 11191 public void run() { 11192 try { 11193 final IActivityManager am = ActivityManagerNative.getDefault(); 11194 if (am == null) return; 11195 final int[] resolvedUserIds; 11196 if (userIds == null) { 11197 resolvedUserIds = am.getRunningUserIds(); 11198 } else { 11199 resolvedUserIds = userIds; 11200 } 11201 for (int id : resolvedUserIds) { 11202 final Intent intent = new Intent(action, 11203 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11204 if (extras != null) { 11205 intent.putExtras(extras); 11206 } 11207 if (targetPkg != null) { 11208 intent.setPackage(targetPkg); 11209 } 11210 // Modify the UID when posting to other users 11211 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11212 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11213 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11214 intent.putExtra(Intent.EXTRA_UID, uid); 11215 } 11216 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11217 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11218 if (DEBUG_BROADCASTS) { 11219 RuntimeException here = new RuntimeException("here"); 11220 here.fillInStackTrace(); 11221 Slog.d(TAG, "Sending to user " + id + ": " 11222 + intent.toShortString(false, true, false, false) 11223 + " " + intent.getExtras(), here); 11224 } 11225 am.broadcastIntent(null, intent, null, finishedReceiver, 11226 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11227 null, finishedReceiver != null, false, id); 11228 } 11229 } catch (RemoteException ex) { 11230 } 11231 } 11232 }); 11233 } 11234 11235 /** 11236 * Check if the external storage media is available. This is true if there 11237 * is a mounted external storage medium or if the external storage is 11238 * emulated. 11239 */ 11240 private boolean isExternalMediaAvailable() { 11241 return mMediaMounted || Environment.isExternalStorageEmulated(); 11242 } 11243 11244 @Override 11245 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11246 // writer 11247 synchronized (mPackages) { 11248 if (!isExternalMediaAvailable()) { 11249 // If the external storage is no longer mounted at this point, 11250 // the caller may not have been able to delete all of this 11251 // packages files and can not delete any more. Bail. 11252 return null; 11253 } 11254 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11255 if (lastPackage != null) { 11256 pkgs.remove(lastPackage); 11257 } 11258 if (pkgs.size() > 0) { 11259 return pkgs.get(0); 11260 } 11261 } 11262 return null; 11263 } 11264 11265 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11266 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11267 userId, andCode ? 1 : 0, packageName); 11268 if (mSystemReady) { 11269 msg.sendToTarget(); 11270 } else { 11271 if (mPostSystemReadyMessages == null) { 11272 mPostSystemReadyMessages = new ArrayList<>(); 11273 } 11274 mPostSystemReadyMessages.add(msg); 11275 } 11276 } 11277 11278 void startCleaningPackages() { 11279 // reader 11280 if (!isExternalMediaAvailable()) { 11281 return; 11282 } 11283 synchronized (mPackages) { 11284 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11285 return; 11286 } 11287 } 11288 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11289 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11290 IActivityManager am = ActivityManagerNative.getDefault(); 11291 if (am != null) { 11292 try { 11293 am.startService(null, intent, null, mContext.getOpPackageName(), 11294 UserHandle.USER_SYSTEM); 11295 } catch (RemoteException e) { 11296 } 11297 } 11298 } 11299 11300 @Override 11301 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11302 int installFlags, String installerPackageName, int userId) { 11303 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11304 11305 final int callingUid = Binder.getCallingUid(); 11306 enforceCrossUserPermission(callingUid, userId, 11307 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11308 11309 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11310 try { 11311 if (observer != null) { 11312 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11313 } 11314 } catch (RemoteException re) { 11315 } 11316 return; 11317 } 11318 11319 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11320 installFlags |= PackageManager.INSTALL_FROM_ADB; 11321 11322 } else { 11323 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11324 // about installerPackageName. 11325 11326 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11327 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11328 } 11329 11330 UserHandle user; 11331 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11332 user = UserHandle.ALL; 11333 } else { 11334 user = new UserHandle(userId); 11335 } 11336 11337 // Only system components can circumvent runtime permissions when installing. 11338 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11339 && mContext.checkCallingOrSelfPermission(Manifest.permission 11340 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11341 throw new SecurityException("You need the " 11342 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11343 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11344 } 11345 11346 final File originFile = new File(originPath); 11347 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11348 11349 final Message msg = mHandler.obtainMessage(INIT_COPY); 11350 final VerificationInfo verificationInfo = new VerificationInfo( 11351 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11352 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11353 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11354 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11355 null /*certificates*/); 11356 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11357 msg.obj = params; 11358 11359 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11360 System.identityHashCode(msg.obj)); 11361 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11362 System.identityHashCode(msg.obj)); 11363 11364 mHandler.sendMessage(msg); 11365 } 11366 11367 void installStage(String packageName, File stagedDir, String stagedCid, 11368 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11369 String installerPackageName, int installerUid, UserHandle user, 11370 Certificate[][] certificates) { 11371 if (DEBUG_EPHEMERAL) { 11372 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11373 Slog.d(TAG, "Ephemeral install of " + packageName); 11374 } 11375 } 11376 final VerificationInfo verificationInfo = new VerificationInfo( 11377 sessionParams.originatingUri, sessionParams.referrerUri, 11378 sessionParams.originatingUid, installerUid); 11379 11380 final OriginInfo origin; 11381 if (stagedDir != null) { 11382 origin = OriginInfo.fromStagedFile(stagedDir); 11383 } else { 11384 origin = OriginInfo.fromStagedContainer(stagedCid); 11385 } 11386 11387 final Message msg = mHandler.obtainMessage(INIT_COPY); 11388 final InstallParams params = new InstallParams(origin, null, observer, 11389 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11390 verificationInfo, user, sessionParams.abiOverride, 11391 sessionParams.grantedRuntimePermissions, certificates); 11392 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11393 msg.obj = params; 11394 11395 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11396 System.identityHashCode(msg.obj)); 11397 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11398 System.identityHashCode(msg.obj)); 11399 11400 mHandler.sendMessage(msg); 11401 } 11402 11403 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11404 int userId) { 11405 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11406 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11407 } 11408 11409 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11410 int appId, int userId) { 11411 Bundle extras = new Bundle(1); 11412 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11413 11414 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11415 packageName, extras, 0, null, null, new int[] {userId}); 11416 try { 11417 IActivityManager am = ActivityManagerNative.getDefault(); 11418 if (isSystem && am.isUserRunning(userId, 0)) { 11419 // The just-installed/enabled app is bundled on the system, so presumed 11420 // to be able to run automatically without needing an explicit launch. 11421 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11422 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11423 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11424 .setPackage(packageName); 11425 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11426 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11427 } 11428 } catch (RemoteException e) { 11429 // shouldn't happen 11430 Slog.w(TAG, "Unable to bootstrap installed package", e); 11431 } 11432 } 11433 11434 @Override 11435 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11436 int userId) { 11437 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11438 PackageSetting pkgSetting; 11439 final int uid = Binder.getCallingUid(); 11440 enforceCrossUserPermission(uid, userId, 11441 true /* requireFullPermission */, true /* checkShell */, 11442 "setApplicationHiddenSetting for user " + userId); 11443 11444 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11445 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11446 return false; 11447 } 11448 11449 long callingId = Binder.clearCallingIdentity(); 11450 try { 11451 boolean sendAdded = false; 11452 boolean sendRemoved = false; 11453 // writer 11454 synchronized (mPackages) { 11455 pkgSetting = mSettings.mPackages.get(packageName); 11456 if (pkgSetting == null) { 11457 return false; 11458 } 11459 if (pkgSetting.getHidden(userId) != hidden) { 11460 pkgSetting.setHidden(hidden, userId); 11461 mSettings.writePackageRestrictionsLPr(userId); 11462 if (hidden) { 11463 sendRemoved = true; 11464 } else { 11465 sendAdded = true; 11466 } 11467 } 11468 } 11469 if (sendAdded) { 11470 sendPackageAddedForUser(packageName, pkgSetting, userId); 11471 return true; 11472 } 11473 if (sendRemoved) { 11474 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11475 "hiding pkg"); 11476 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11477 return true; 11478 } 11479 } finally { 11480 Binder.restoreCallingIdentity(callingId); 11481 } 11482 return false; 11483 } 11484 11485 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11486 int userId) { 11487 final PackageRemovedInfo info = new PackageRemovedInfo(); 11488 info.removedPackage = packageName; 11489 info.removedUsers = new int[] {userId}; 11490 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11491 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11492 } 11493 11494 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11495 if (pkgList.length > 0) { 11496 Bundle extras = new Bundle(1); 11497 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11498 11499 sendPackageBroadcast( 11500 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11501 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11502 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11503 new int[] {userId}); 11504 } 11505 } 11506 11507 /** 11508 * Returns true if application is not found or there was an error. Otherwise it returns 11509 * the hidden state of the package for the given user. 11510 */ 11511 @Override 11512 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11513 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11514 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11515 true /* requireFullPermission */, false /* checkShell */, 11516 "getApplicationHidden for user " + userId); 11517 PackageSetting pkgSetting; 11518 long callingId = Binder.clearCallingIdentity(); 11519 try { 11520 // writer 11521 synchronized (mPackages) { 11522 pkgSetting = mSettings.mPackages.get(packageName); 11523 if (pkgSetting == null) { 11524 return true; 11525 } 11526 return pkgSetting.getHidden(userId); 11527 } 11528 } finally { 11529 Binder.restoreCallingIdentity(callingId); 11530 } 11531 } 11532 11533 /** 11534 * @hide 11535 */ 11536 @Override 11537 public int installExistingPackageAsUser(String packageName, int userId) { 11538 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11539 null); 11540 PackageSetting pkgSetting; 11541 final int uid = Binder.getCallingUid(); 11542 enforceCrossUserPermission(uid, userId, 11543 true /* requireFullPermission */, true /* checkShell */, 11544 "installExistingPackage for user " + userId); 11545 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11546 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11547 } 11548 11549 long callingId = Binder.clearCallingIdentity(); 11550 try { 11551 boolean installed = false; 11552 11553 // writer 11554 synchronized (mPackages) { 11555 pkgSetting = mSettings.mPackages.get(packageName); 11556 if (pkgSetting == null) { 11557 return PackageManager.INSTALL_FAILED_INVALID_URI; 11558 } 11559 if (!pkgSetting.getInstalled(userId)) { 11560 pkgSetting.setInstalled(true, userId); 11561 pkgSetting.setHidden(false, userId); 11562 mSettings.writePackageRestrictionsLPr(userId); 11563 installed = true; 11564 } 11565 } 11566 11567 if (installed) { 11568 if (pkgSetting.pkg != null) { 11569 synchronized (mInstallLock) { 11570 // We don't need to freeze for a brand new install 11571 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11572 } 11573 } 11574 sendPackageAddedForUser(packageName, pkgSetting, userId); 11575 } 11576 } finally { 11577 Binder.restoreCallingIdentity(callingId); 11578 } 11579 11580 return PackageManager.INSTALL_SUCCEEDED; 11581 } 11582 11583 boolean isUserRestricted(int userId, String restrictionKey) { 11584 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11585 if (restrictions.getBoolean(restrictionKey, false)) { 11586 Log.w(TAG, "User is restricted: " + restrictionKey); 11587 return true; 11588 } 11589 return false; 11590 } 11591 11592 @Override 11593 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11594 int userId) { 11595 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11596 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11597 true /* requireFullPermission */, true /* checkShell */, 11598 "setPackagesSuspended for user " + userId); 11599 11600 if (ArrayUtils.isEmpty(packageNames)) { 11601 return packageNames; 11602 } 11603 11604 // List of package names for whom the suspended state has changed. 11605 List<String> changedPackages = new ArrayList<>(packageNames.length); 11606 // List of package names for whom the suspended state is not set as requested in this 11607 // method. 11608 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11609 long callingId = Binder.clearCallingIdentity(); 11610 try { 11611 for (int i = 0; i < packageNames.length; i++) { 11612 String packageName = packageNames[i]; 11613 boolean changed = false; 11614 final int appId; 11615 synchronized (mPackages) { 11616 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11617 if (pkgSetting == null) { 11618 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11619 + "\". Skipping suspending/un-suspending."); 11620 unactionedPackages.add(packageName); 11621 continue; 11622 } 11623 appId = pkgSetting.appId; 11624 if (pkgSetting.getSuspended(userId) != suspended) { 11625 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11626 unactionedPackages.add(packageName); 11627 continue; 11628 } 11629 pkgSetting.setSuspended(suspended, userId); 11630 mSettings.writePackageRestrictionsLPr(userId); 11631 changed = true; 11632 changedPackages.add(packageName); 11633 } 11634 } 11635 11636 if (changed && suspended) { 11637 killApplication(packageName, UserHandle.getUid(userId, appId), 11638 "suspending package"); 11639 } 11640 } 11641 } finally { 11642 Binder.restoreCallingIdentity(callingId); 11643 } 11644 11645 if (!changedPackages.isEmpty()) { 11646 sendPackagesSuspendedForUser(changedPackages.toArray( 11647 new String[changedPackages.size()]), userId, suspended); 11648 } 11649 11650 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11651 } 11652 11653 @Override 11654 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11655 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11656 true /* requireFullPermission */, false /* checkShell */, 11657 "isPackageSuspendedForUser for user " + userId); 11658 synchronized (mPackages) { 11659 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11660 if (pkgSetting == null) { 11661 throw new IllegalArgumentException("Unknown target package: " + packageName); 11662 } 11663 return pkgSetting.getSuspended(userId); 11664 } 11665 } 11666 11667 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11668 if (isPackageDeviceAdmin(packageName, userId)) { 11669 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11670 + "\": has an active device admin"); 11671 return false; 11672 } 11673 11674 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11675 if (packageName.equals(activeLauncherPackageName)) { 11676 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11677 + "\": contains the active launcher"); 11678 return false; 11679 } 11680 11681 if (packageName.equals(mRequiredInstallerPackage)) { 11682 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11683 + "\": required for package installation"); 11684 return false; 11685 } 11686 11687 if (packageName.equals(mRequiredVerifierPackage)) { 11688 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11689 + "\": required for package verification"); 11690 return false; 11691 } 11692 11693 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11694 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11695 + "\": is the default dialer"); 11696 return false; 11697 } 11698 11699 return true; 11700 } 11701 11702 private String getActiveLauncherPackageName(int userId) { 11703 Intent intent = new Intent(Intent.ACTION_MAIN); 11704 intent.addCategory(Intent.CATEGORY_HOME); 11705 ResolveInfo resolveInfo = resolveIntent( 11706 intent, 11707 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11708 PackageManager.MATCH_DEFAULT_ONLY, 11709 userId); 11710 11711 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11712 } 11713 11714 private String getDefaultDialerPackageName(int userId) { 11715 synchronized (mPackages) { 11716 return mSettings.getDefaultDialerPackageNameLPw(userId); 11717 } 11718 } 11719 11720 @Override 11721 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11722 mContext.enforceCallingOrSelfPermission( 11723 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11724 "Only package verification agents can verify applications"); 11725 11726 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11727 final PackageVerificationResponse response = new PackageVerificationResponse( 11728 verificationCode, Binder.getCallingUid()); 11729 msg.arg1 = id; 11730 msg.obj = response; 11731 mHandler.sendMessage(msg); 11732 } 11733 11734 @Override 11735 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11736 long millisecondsToDelay) { 11737 mContext.enforceCallingOrSelfPermission( 11738 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11739 "Only package verification agents can extend verification timeouts"); 11740 11741 final PackageVerificationState state = mPendingVerification.get(id); 11742 final PackageVerificationResponse response = new PackageVerificationResponse( 11743 verificationCodeAtTimeout, Binder.getCallingUid()); 11744 11745 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11746 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11747 } 11748 if (millisecondsToDelay < 0) { 11749 millisecondsToDelay = 0; 11750 } 11751 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11752 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11753 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11754 } 11755 11756 if ((state != null) && !state.timeoutExtended()) { 11757 state.extendTimeout(); 11758 11759 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11760 msg.arg1 = id; 11761 msg.obj = response; 11762 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11763 } 11764 } 11765 11766 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11767 int verificationCode, UserHandle user) { 11768 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11769 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11770 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11771 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11772 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11773 11774 mContext.sendBroadcastAsUser(intent, user, 11775 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11776 } 11777 11778 private ComponentName matchComponentForVerifier(String packageName, 11779 List<ResolveInfo> receivers) { 11780 ActivityInfo targetReceiver = null; 11781 11782 final int NR = receivers.size(); 11783 for (int i = 0; i < NR; i++) { 11784 final ResolveInfo info = receivers.get(i); 11785 if (info.activityInfo == null) { 11786 continue; 11787 } 11788 11789 if (packageName.equals(info.activityInfo.packageName)) { 11790 targetReceiver = info.activityInfo; 11791 break; 11792 } 11793 } 11794 11795 if (targetReceiver == null) { 11796 return null; 11797 } 11798 11799 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11800 } 11801 11802 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11803 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11804 if (pkgInfo.verifiers.length == 0) { 11805 return null; 11806 } 11807 11808 final int N = pkgInfo.verifiers.length; 11809 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11810 for (int i = 0; i < N; i++) { 11811 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11812 11813 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11814 receivers); 11815 if (comp == null) { 11816 continue; 11817 } 11818 11819 final int verifierUid = getUidForVerifier(verifierInfo); 11820 if (verifierUid == -1) { 11821 continue; 11822 } 11823 11824 if (DEBUG_VERIFY) { 11825 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11826 + " with the correct signature"); 11827 } 11828 sufficientVerifiers.add(comp); 11829 verificationState.addSufficientVerifier(verifierUid); 11830 } 11831 11832 return sufficientVerifiers; 11833 } 11834 11835 private int getUidForVerifier(VerifierInfo verifierInfo) { 11836 synchronized (mPackages) { 11837 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11838 if (pkg == null) { 11839 return -1; 11840 } else if (pkg.mSignatures.length != 1) { 11841 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11842 + " has more than one signature; ignoring"); 11843 return -1; 11844 } 11845 11846 /* 11847 * If the public key of the package's signature does not match 11848 * our expected public key, then this is a different package and 11849 * we should skip. 11850 */ 11851 11852 final byte[] expectedPublicKey; 11853 try { 11854 final Signature verifierSig = pkg.mSignatures[0]; 11855 final PublicKey publicKey = verifierSig.getPublicKey(); 11856 expectedPublicKey = publicKey.getEncoded(); 11857 } catch (CertificateException e) { 11858 return -1; 11859 } 11860 11861 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11862 11863 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11864 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11865 + " does not have the expected public key; ignoring"); 11866 return -1; 11867 } 11868 11869 return pkg.applicationInfo.uid; 11870 } 11871 } 11872 11873 @Override 11874 public void finishPackageInstall(int token, boolean didLaunch) { 11875 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11876 11877 if (DEBUG_INSTALL) { 11878 Slog.v(TAG, "BM finishing package install for " + token); 11879 } 11880 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11881 11882 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11883 mHandler.sendMessage(msg); 11884 } 11885 11886 /** 11887 * Get the verification agent timeout. 11888 * 11889 * @return verification timeout in milliseconds 11890 */ 11891 private long getVerificationTimeout() { 11892 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11893 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11894 DEFAULT_VERIFICATION_TIMEOUT); 11895 } 11896 11897 /** 11898 * Get the default verification agent response code. 11899 * 11900 * @return default verification response code 11901 */ 11902 private int getDefaultVerificationResponse() { 11903 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11904 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11905 DEFAULT_VERIFICATION_RESPONSE); 11906 } 11907 11908 /** 11909 * Check whether or not package verification has been enabled. 11910 * 11911 * @return true if verification should be performed 11912 */ 11913 private boolean isVerificationEnabled(int userId, int installFlags) { 11914 if (!DEFAULT_VERIFY_ENABLE) { 11915 return false; 11916 } 11917 // Ephemeral apps don't get the full verification treatment 11918 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11919 if (DEBUG_EPHEMERAL) { 11920 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11921 } 11922 return false; 11923 } 11924 11925 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11926 11927 // Check if installing from ADB 11928 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11929 // Do not run verification in a test harness environment 11930 if (ActivityManager.isRunningInTestHarness()) { 11931 return false; 11932 } 11933 if (ensureVerifyAppsEnabled) { 11934 return true; 11935 } 11936 // Check if the developer does not want package verification for ADB installs 11937 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11938 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11939 return false; 11940 } 11941 } 11942 11943 if (ensureVerifyAppsEnabled) { 11944 return true; 11945 } 11946 11947 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11948 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11949 } 11950 11951 @Override 11952 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11953 throws RemoteException { 11954 mContext.enforceCallingOrSelfPermission( 11955 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11956 "Only intentfilter verification agents can verify applications"); 11957 11958 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11959 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11960 Binder.getCallingUid(), verificationCode, failedDomains); 11961 msg.arg1 = id; 11962 msg.obj = response; 11963 mHandler.sendMessage(msg); 11964 } 11965 11966 @Override 11967 public int getIntentVerificationStatus(String packageName, int userId) { 11968 synchronized (mPackages) { 11969 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11970 } 11971 } 11972 11973 @Override 11974 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11975 mContext.enforceCallingOrSelfPermission( 11976 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11977 11978 boolean result = false; 11979 synchronized (mPackages) { 11980 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11981 } 11982 if (result) { 11983 scheduleWritePackageRestrictionsLocked(userId); 11984 } 11985 return result; 11986 } 11987 11988 @Override 11989 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11990 String packageName) { 11991 synchronized (mPackages) { 11992 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11993 } 11994 } 11995 11996 @Override 11997 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11998 if (TextUtils.isEmpty(packageName)) { 11999 return ParceledListSlice.emptyList(); 12000 } 12001 synchronized (mPackages) { 12002 PackageParser.Package pkg = mPackages.get(packageName); 12003 if (pkg == null || pkg.activities == null) { 12004 return ParceledListSlice.emptyList(); 12005 } 12006 final int count = pkg.activities.size(); 12007 ArrayList<IntentFilter> result = new ArrayList<>(); 12008 for (int n=0; n<count; n++) { 12009 PackageParser.Activity activity = pkg.activities.get(n); 12010 if (activity.intents != null && activity.intents.size() > 0) { 12011 result.addAll(activity.intents); 12012 } 12013 } 12014 return new ParceledListSlice<>(result); 12015 } 12016 } 12017 12018 @Override 12019 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12020 mContext.enforceCallingOrSelfPermission( 12021 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12022 12023 synchronized (mPackages) { 12024 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12025 if (packageName != null) { 12026 result |= updateIntentVerificationStatus(packageName, 12027 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12028 userId); 12029 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12030 packageName, userId); 12031 } 12032 return result; 12033 } 12034 } 12035 12036 @Override 12037 public String getDefaultBrowserPackageName(int userId) { 12038 synchronized (mPackages) { 12039 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12040 } 12041 } 12042 12043 /** 12044 * Get the "allow unknown sources" setting. 12045 * 12046 * @return the current "allow unknown sources" setting 12047 */ 12048 private int getUnknownSourcesSettings() { 12049 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12050 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12051 -1); 12052 } 12053 12054 @Override 12055 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12056 final int uid = Binder.getCallingUid(); 12057 // writer 12058 synchronized (mPackages) { 12059 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12060 if (targetPackageSetting == null) { 12061 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12062 } 12063 12064 PackageSetting installerPackageSetting; 12065 if (installerPackageName != null) { 12066 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12067 if (installerPackageSetting == null) { 12068 throw new IllegalArgumentException("Unknown installer package: " 12069 + installerPackageName); 12070 } 12071 } else { 12072 installerPackageSetting = null; 12073 } 12074 12075 Signature[] callerSignature; 12076 Object obj = mSettings.getUserIdLPr(uid); 12077 if (obj != null) { 12078 if (obj instanceof SharedUserSetting) { 12079 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12080 } else if (obj instanceof PackageSetting) { 12081 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12082 } else { 12083 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12084 } 12085 } else { 12086 throw new SecurityException("Unknown calling UID: " + uid); 12087 } 12088 12089 // Verify: can't set installerPackageName to a package that is 12090 // not signed with the same cert as the caller. 12091 if (installerPackageSetting != null) { 12092 if (compareSignatures(callerSignature, 12093 installerPackageSetting.signatures.mSignatures) 12094 != PackageManager.SIGNATURE_MATCH) { 12095 throw new SecurityException( 12096 "Caller does not have same cert as new installer package " 12097 + installerPackageName); 12098 } 12099 } 12100 12101 // Verify: if target already has an installer package, it must 12102 // be signed with the same cert as the caller. 12103 if (targetPackageSetting.installerPackageName != null) { 12104 PackageSetting setting = mSettings.mPackages.get( 12105 targetPackageSetting.installerPackageName); 12106 // If the currently set package isn't valid, then it's always 12107 // okay to change it. 12108 if (setting != null) { 12109 if (compareSignatures(callerSignature, 12110 setting.signatures.mSignatures) 12111 != PackageManager.SIGNATURE_MATCH) { 12112 throw new SecurityException( 12113 "Caller does not have same cert as old installer package " 12114 + targetPackageSetting.installerPackageName); 12115 } 12116 } 12117 } 12118 12119 // Okay! 12120 targetPackageSetting.installerPackageName = installerPackageName; 12121 if (installerPackageName != null) { 12122 mSettings.mInstallerPackages.add(installerPackageName); 12123 } 12124 scheduleWriteSettingsLocked(); 12125 } 12126 } 12127 12128 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12129 // Queue up an async operation since the package installation may take a little while. 12130 mHandler.post(new Runnable() { 12131 public void run() { 12132 mHandler.removeCallbacks(this); 12133 // Result object to be returned 12134 PackageInstalledInfo res = new PackageInstalledInfo(); 12135 res.setReturnCode(currentStatus); 12136 res.uid = -1; 12137 res.pkg = null; 12138 res.removedInfo = null; 12139 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12140 args.doPreInstall(res.returnCode); 12141 synchronized (mInstallLock) { 12142 installPackageTracedLI(args, res); 12143 } 12144 args.doPostInstall(res.returnCode, res.uid); 12145 } 12146 12147 // A restore should be performed at this point if (a) the install 12148 // succeeded, (b) the operation is not an update, and (c) the new 12149 // package has not opted out of backup participation. 12150 final boolean update = res.removedInfo != null 12151 && res.removedInfo.removedPackage != null; 12152 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12153 boolean doRestore = !update 12154 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12155 12156 // Set up the post-install work request bookkeeping. This will be used 12157 // and cleaned up by the post-install event handling regardless of whether 12158 // there's a restore pass performed. Token values are >= 1. 12159 int token; 12160 if (mNextInstallToken < 0) mNextInstallToken = 1; 12161 token = mNextInstallToken++; 12162 12163 PostInstallData data = new PostInstallData(args, res); 12164 mRunningInstalls.put(token, data); 12165 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12166 12167 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12168 // Pass responsibility to the Backup Manager. It will perform a 12169 // restore if appropriate, then pass responsibility back to the 12170 // Package Manager to run the post-install observer callbacks 12171 // and broadcasts. 12172 IBackupManager bm = IBackupManager.Stub.asInterface( 12173 ServiceManager.getService(Context.BACKUP_SERVICE)); 12174 if (bm != null) { 12175 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12176 + " to BM for possible restore"); 12177 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12178 try { 12179 // TODO: http://b/22388012 12180 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12181 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12182 } else { 12183 doRestore = false; 12184 } 12185 } catch (RemoteException e) { 12186 // can't happen; the backup manager is local 12187 } catch (Exception e) { 12188 Slog.e(TAG, "Exception trying to enqueue restore", e); 12189 doRestore = false; 12190 } 12191 } else { 12192 Slog.e(TAG, "Backup Manager not found!"); 12193 doRestore = false; 12194 } 12195 } 12196 12197 if (!doRestore) { 12198 // No restore possible, or the Backup Manager was mysteriously not 12199 // available -- just fire the post-install work request directly. 12200 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12201 12202 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12203 12204 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12205 mHandler.sendMessage(msg); 12206 } 12207 } 12208 }); 12209 } 12210 12211 /** 12212 * Callback from PackageSettings whenever an app is first transitioned out of the 12213 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12214 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12215 * here whether the app is the target of an ongoing install, and only send the 12216 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12217 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12218 * handling. 12219 */ 12220 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12221 // Serialize this with the rest of the install-process message chain. In the 12222 // restore-at-install case, this Runnable will necessarily run before the 12223 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12224 // are coherent. In the non-restore case, the app has already completed install 12225 // and been launched through some other means, so it is not in a problematic 12226 // state for observers to see the FIRST_LAUNCH signal. 12227 mHandler.post(new Runnable() { 12228 @Override 12229 public void run() { 12230 for (int i = 0; i < mRunningInstalls.size(); i++) { 12231 final PostInstallData data = mRunningInstalls.valueAt(i); 12232 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12233 // right package; but is it for the right user? 12234 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12235 if (userId == data.res.newUsers[uIndex]) { 12236 if (DEBUG_BACKUP) { 12237 Slog.i(TAG, "Package " + pkgName 12238 + " being restored so deferring FIRST_LAUNCH"); 12239 } 12240 return; 12241 } 12242 } 12243 } 12244 } 12245 // didn't find it, so not being restored 12246 if (DEBUG_BACKUP) { 12247 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12248 } 12249 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12250 } 12251 }); 12252 } 12253 12254 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12255 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12256 installerPkg, null, userIds); 12257 } 12258 12259 private abstract class HandlerParams { 12260 private static final int MAX_RETRIES = 4; 12261 12262 /** 12263 * Number of times startCopy() has been attempted and had a non-fatal 12264 * error. 12265 */ 12266 private int mRetries = 0; 12267 12268 /** User handle for the user requesting the information or installation. */ 12269 private final UserHandle mUser; 12270 String traceMethod; 12271 int traceCookie; 12272 12273 HandlerParams(UserHandle user) { 12274 mUser = user; 12275 } 12276 12277 UserHandle getUser() { 12278 return mUser; 12279 } 12280 12281 HandlerParams setTraceMethod(String traceMethod) { 12282 this.traceMethod = traceMethod; 12283 return this; 12284 } 12285 12286 HandlerParams setTraceCookie(int traceCookie) { 12287 this.traceCookie = traceCookie; 12288 return this; 12289 } 12290 12291 final boolean startCopy() { 12292 boolean res; 12293 try { 12294 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12295 12296 if (++mRetries > MAX_RETRIES) { 12297 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12298 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12299 handleServiceError(); 12300 return false; 12301 } else { 12302 handleStartCopy(); 12303 res = true; 12304 } 12305 } catch (RemoteException e) { 12306 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12307 mHandler.sendEmptyMessage(MCS_RECONNECT); 12308 res = false; 12309 } 12310 handleReturnCode(); 12311 return res; 12312 } 12313 12314 final void serviceError() { 12315 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12316 handleServiceError(); 12317 handleReturnCode(); 12318 } 12319 12320 abstract void handleStartCopy() throws RemoteException; 12321 abstract void handleServiceError(); 12322 abstract void handleReturnCode(); 12323 } 12324 12325 class MeasureParams extends HandlerParams { 12326 private final PackageStats mStats; 12327 private boolean mSuccess; 12328 12329 private final IPackageStatsObserver mObserver; 12330 12331 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12332 super(new UserHandle(stats.userHandle)); 12333 mObserver = observer; 12334 mStats = stats; 12335 } 12336 12337 @Override 12338 public String toString() { 12339 return "MeasureParams{" 12340 + Integer.toHexString(System.identityHashCode(this)) 12341 + " " + mStats.packageName + "}"; 12342 } 12343 12344 @Override 12345 void handleStartCopy() throws RemoteException { 12346 synchronized (mInstallLock) { 12347 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12348 } 12349 12350 if (mSuccess) { 12351 final boolean mounted; 12352 if (Environment.isExternalStorageEmulated()) { 12353 mounted = true; 12354 } else { 12355 final String status = Environment.getExternalStorageState(); 12356 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12357 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12358 } 12359 12360 if (mounted) { 12361 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12362 12363 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12364 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12365 12366 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12367 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12368 12369 // Always subtract cache size, since it's a subdirectory 12370 mStats.externalDataSize -= mStats.externalCacheSize; 12371 12372 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12373 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12374 12375 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12376 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12377 } 12378 } 12379 } 12380 12381 @Override 12382 void handleReturnCode() { 12383 if (mObserver != null) { 12384 try { 12385 mObserver.onGetStatsCompleted(mStats, mSuccess); 12386 } catch (RemoteException e) { 12387 Slog.i(TAG, "Observer no longer exists."); 12388 } 12389 } 12390 } 12391 12392 @Override 12393 void handleServiceError() { 12394 Slog.e(TAG, "Could not measure application " + mStats.packageName 12395 + " external storage"); 12396 } 12397 } 12398 12399 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12400 throws RemoteException { 12401 long result = 0; 12402 for (File path : paths) { 12403 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12404 } 12405 return result; 12406 } 12407 12408 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12409 for (File path : paths) { 12410 try { 12411 mcs.clearDirectory(path.getAbsolutePath()); 12412 } catch (RemoteException e) { 12413 } 12414 } 12415 } 12416 12417 static class OriginInfo { 12418 /** 12419 * Location where install is coming from, before it has been 12420 * copied/renamed into place. This could be a single monolithic APK 12421 * file, or a cluster directory. This location may be untrusted. 12422 */ 12423 final File file; 12424 final String cid; 12425 12426 /** 12427 * Flag indicating that {@link #file} or {@link #cid} has already been 12428 * staged, meaning downstream users don't need to defensively copy the 12429 * contents. 12430 */ 12431 final boolean staged; 12432 12433 /** 12434 * Flag indicating that {@link #file} or {@link #cid} is an already 12435 * installed app that is being moved. 12436 */ 12437 final boolean existing; 12438 12439 final String resolvedPath; 12440 final File resolvedFile; 12441 12442 static OriginInfo fromNothing() { 12443 return new OriginInfo(null, null, false, false); 12444 } 12445 12446 static OriginInfo fromUntrustedFile(File file) { 12447 return new OriginInfo(file, null, false, false); 12448 } 12449 12450 static OriginInfo fromExistingFile(File file) { 12451 return new OriginInfo(file, null, false, true); 12452 } 12453 12454 static OriginInfo fromStagedFile(File file) { 12455 return new OriginInfo(file, null, true, false); 12456 } 12457 12458 static OriginInfo fromStagedContainer(String cid) { 12459 return new OriginInfo(null, cid, true, false); 12460 } 12461 12462 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12463 this.file = file; 12464 this.cid = cid; 12465 this.staged = staged; 12466 this.existing = existing; 12467 12468 if (cid != null) { 12469 resolvedPath = PackageHelper.getSdDir(cid); 12470 resolvedFile = new File(resolvedPath); 12471 } else if (file != null) { 12472 resolvedPath = file.getAbsolutePath(); 12473 resolvedFile = file; 12474 } else { 12475 resolvedPath = null; 12476 resolvedFile = null; 12477 } 12478 } 12479 } 12480 12481 static class MoveInfo { 12482 final int moveId; 12483 final String fromUuid; 12484 final String toUuid; 12485 final String packageName; 12486 final String dataAppName; 12487 final int appId; 12488 final String seinfo; 12489 final int targetSdkVersion; 12490 12491 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12492 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12493 this.moveId = moveId; 12494 this.fromUuid = fromUuid; 12495 this.toUuid = toUuid; 12496 this.packageName = packageName; 12497 this.dataAppName = dataAppName; 12498 this.appId = appId; 12499 this.seinfo = seinfo; 12500 this.targetSdkVersion = targetSdkVersion; 12501 } 12502 } 12503 12504 static class VerificationInfo { 12505 /** A constant used to indicate that a uid value is not present. */ 12506 public static final int NO_UID = -1; 12507 12508 /** URI referencing where the package was downloaded from. */ 12509 final Uri originatingUri; 12510 12511 /** HTTP referrer URI associated with the originatingURI. */ 12512 final Uri referrer; 12513 12514 /** UID of the application that the install request originated from. */ 12515 final int originatingUid; 12516 12517 /** UID of application requesting the install */ 12518 final int installerUid; 12519 12520 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12521 this.originatingUri = originatingUri; 12522 this.referrer = referrer; 12523 this.originatingUid = originatingUid; 12524 this.installerUid = installerUid; 12525 } 12526 } 12527 12528 class InstallParams extends HandlerParams { 12529 final OriginInfo origin; 12530 final MoveInfo move; 12531 final IPackageInstallObserver2 observer; 12532 int installFlags; 12533 final String installerPackageName; 12534 final String volumeUuid; 12535 private InstallArgs mArgs; 12536 private int mRet; 12537 final String packageAbiOverride; 12538 final String[] grantedRuntimePermissions; 12539 final VerificationInfo verificationInfo; 12540 final Certificate[][] certificates; 12541 12542 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12543 int installFlags, String installerPackageName, String volumeUuid, 12544 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12545 String[] grantedPermissions, Certificate[][] certificates) { 12546 super(user); 12547 this.origin = origin; 12548 this.move = move; 12549 this.observer = observer; 12550 this.installFlags = installFlags; 12551 this.installerPackageName = installerPackageName; 12552 this.volumeUuid = volumeUuid; 12553 this.verificationInfo = verificationInfo; 12554 this.packageAbiOverride = packageAbiOverride; 12555 this.grantedRuntimePermissions = grantedPermissions; 12556 this.certificates = certificates; 12557 } 12558 12559 @Override 12560 public String toString() { 12561 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12562 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12563 } 12564 12565 private int installLocationPolicy(PackageInfoLite pkgLite) { 12566 String packageName = pkgLite.packageName; 12567 int installLocation = pkgLite.installLocation; 12568 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12569 // reader 12570 synchronized (mPackages) { 12571 // Currently installed package which the new package is attempting to replace or 12572 // null if no such package is installed. 12573 PackageParser.Package installedPkg = mPackages.get(packageName); 12574 // Package which currently owns the data which the new package will own if installed. 12575 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12576 // will be null whereas dataOwnerPkg will contain information about the package 12577 // which was uninstalled while keeping its data. 12578 PackageParser.Package dataOwnerPkg = installedPkg; 12579 if (dataOwnerPkg == null) { 12580 PackageSetting ps = mSettings.mPackages.get(packageName); 12581 if (ps != null) { 12582 dataOwnerPkg = ps.pkg; 12583 } 12584 } 12585 12586 if (dataOwnerPkg != null) { 12587 // If installed, the package will get access to data left on the device by its 12588 // predecessor. As a security measure, this is permited only if this is not a 12589 // version downgrade or if the predecessor package is marked as debuggable and 12590 // a downgrade is explicitly requested. 12591 // 12592 // On debuggable platform builds, downgrades are permitted even for 12593 // non-debuggable packages to make testing easier. Debuggable platform builds do 12594 // not offer security guarantees and thus it's OK to disable some security 12595 // mechanisms to make debugging/testing easier on those builds. However, even on 12596 // debuggable builds downgrades of packages are permitted only if requested via 12597 // installFlags. This is because we aim to keep the behavior of debuggable 12598 // platform builds as close as possible to the behavior of non-debuggable 12599 // platform builds. 12600 final boolean downgradeRequested = 12601 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12602 final boolean packageDebuggable = 12603 (dataOwnerPkg.applicationInfo.flags 12604 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12605 final boolean downgradePermitted = 12606 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12607 if (!downgradePermitted) { 12608 try { 12609 checkDowngrade(dataOwnerPkg, pkgLite); 12610 } catch (PackageManagerException e) { 12611 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12612 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12613 } 12614 } 12615 } 12616 12617 if (installedPkg != null) { 12618 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12619 // Check for updated system application. 12620 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12621 if (onSd) { 12622 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12623 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12624 } 12625 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12626 } else { 12627 if (onSd) { 12628 // Install flag overrides everything. 12629 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12630 } 12631 // If current upgrade specifies particular preference 12632 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12633 // Application explicitly specified internal. 12634 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12635 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12636 // App explictly prefers external. Let policy decide 12637 } else { 12638 // Prefer previous location 12639 if (isExternal(installedPkg)) { 12640 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12641 } 12642 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12643 } 12644 } 12645 } else { 12646 // Invalid install. Return error code 12647 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12648 } 12649 } 12650 } 12651 // All the special cases have been taken care of. 12652 // Return result based on recommended install location. 12653 if (onSd) { 12654 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12655 } 12656 return pkgLite.recommendedInstallLocation; 12657 } 12658 12659 /* 12660 * Invoke remote method to get package information and install 12661 * location values. Override install location based on default 12662 * policy if needed and then create install arguments based 12663 * on the install location. 12664 */ 12665 public void handleStartCopy() throws RemoteException { 12666 int ret = PackageManager.INSTALL_SUCCEEDED; 12667 12668 // If we're already staged, we've firmly committed to an install location 12669 if (origin.staged) { 12670 if (origin.file != null) { 12671 installFlags |= PackageManager.INSTALL_INTERNAL; 12672 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12673 } else if (origin.cid != null) { 12674 installFlags |= PackageManager.INSTALL_EXTERNAL; 12675 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12676 } else { 12677 throw new IllegalStateException("Invalid stage location"); 12678 } 12679 } 12680 12681 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12682 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12683 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12684 PackageInfoLite pkgLite = null; 12685 12686 if (onInt && onSd) { 12687 // Check if both bits are set. 12688 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12689 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12690 } else if (onSd && ephemeral) { 12691 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12692 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12693 } else { 12694 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12695 packageAbiOverride); 12696 12697 if (DEBUG_EPHEMERAL && ephemeral) { 12698 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12699 } 12700 12701 /* 12702 * If we have too little free space, try to free cache 12703 * before giving up. 12704 */ 12705 if (!origin.staged && pkgLite.recommendedInstallLocation 12706 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12707 // TODO: focus freeing disk space on the target device 12708 final StorageManager storage = StorageManager.from(mContext); 12709 final long lowThreshold = storage.getStorageLowBytes( 12710 Environment.getDataDirectory()); 12711 12712 final long sizeBytes = mContainerService.calculateInstalledSize( 12713 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12714 12715 try { 12716 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12717 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12718 installFlags, packageAbiOverride); 12719 } catch (InstallerException e) { 12720 Slog.w(TAG, "Failed to free cache", e); 12721 } 12722 12723 /* 12724 * The cache free must have deleted the file we 12725 * downloaded to install. 12726 * 12727 * TODO: fix the "freeCache" call to not delete 12728 * the file we care about. 12729 */ 12730 if (pkgLite.recommendedInstallLocation 12731 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12732 pkgLite.recommendedInstallLocation 12733 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12734 } 12735 } 12736 } 12737 12738 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12739 int loc = pkgLite.recommendedInstallLocation; 12740 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12741 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12742 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12743 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12744 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12745 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12746 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12747 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12748 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12749 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12750 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12751 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12752 } else { 12753 // Override with defaults if needed. 12754 loc = installLocationPolicy(pkgLite); 12755 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12756 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12757 } else if (!onSd && !onInt) { 12758 // Override install location with flags 12759 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12760 // Set the flag to install on external media. 12761 installFlags |= PackageManager.INSTALL_EXTERNAL; 12762 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12763 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12764 if (DEBUG_EPHEMERAL) { 12765 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12766 } 12767 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12768 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12769 |PackageManager.INSTALL_INTERNAL); 12770 } else { 12771 // Make sure the flag for installing on external 12772 // media is unset 12773 installFlags |= PackageManager.INSTALL_INTERNAL; 12774 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12775 } 12776 } 12777 } 12778 } 12779 12780 final InstallArgs args = createInstallArgs(this); 12781 mArgs = args; 12782 12783 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12784 // TODO: http://b/22976637 12785 // Apps installed for "all" users use the device owner to verify the app 12786 UserHandle verifierUser = getUser(); 12787 if (verifierUser == UserHandle.ALL) { 12788 verifierUser = UserHandle.SYSTEM; 12789 } 12790 12791 /* 12792 * Determine if we have any installed package verifiers. If we 12793 * do, then we'll defer to them to verify the packages. 12794 */ 12795 final int requiredUid = mRequiredVerifierPackage == null ? -1 12796 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12797 verifierUser.getIdentifier()); 12798 if (!origin.existing && requiredUid != -1 12799 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12800 final Intent verification = new Intent( 12801 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12802 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12803 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12804 PACKAGE_MIME_TYPE); 12805 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12806 12807 // Query all live verifiers based on current user state 12808 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12809 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12810 12811 if (DEBUG_VERIFY) { 12812 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12813 + verification.toString() + " with " + pkgLite.verifiers.length 12814 + " optional verifiers"); 12815 } 12816 12817 final int verificationId = mPendingVerificationToken++; 12818 12819 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12820 12821 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12822 installerPackageName); 12823 12824 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12825 installFlags); 12826 12827 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12828 pkgLite.packageName); 12829 12830 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12831 pkgLite.versionCode); 12832 12833 if (verificationInfo != null) { 12834 if (verificationInfo.originatingUri != null) { 12835 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12836 verificationInfo.originatingUri); 12837 } 12838 if (verificationInfo.referrer != null) { 12839 verification.putExtra(Intent.EXTRA_REFERRER, 12840 verificationInfo.referrer); 12841 } 12842 if (verificationInfo.originatingUid >= 0) { 12843 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12844 verificationInfo.originatingUid); 12845 } 12846 if (verificationInfo.installerUid >= 0) { 12847 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12848 verificationInfo.installerUid); 12849 } 12850 } 12851 12852 final PackageVerificationState verificationState = new PackageVerificationState( 12853 requiredUid, args); 12854 12855 mPendingVerification.append(verificationId, verificationState); 12856 12857 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12858 receivers, verificationState); 12859 12860 /* 12861 * If any sufficient verifiers were listed in the package 12862 * manifest, attempt to ask them. 12863 */ 12864 if (sufficientVerifiers != null) { 12865 final int N = sufficientVerifiers.size(); 12866 if (N == 0) { 12867 Slog.i(TAG, "Additional verifiers required, but none installed."); 12868 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12869 } else { 12870 for (int i = 0; i < N; i++) { 12871 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12872 12873 final Intent sufficientIntent = new Intent(verification); 12874 sufficientIntent.setComponent(verifierComponent); 12875 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12876 } 12877 } 12878 } 12879 12880 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12881 mRequiredVerifierPackage, receivers); 12882 if (ret == PackageManager.INSTALL_SUCCEEDED 12883 && mRequiredVerifierPackage != null) { 12884 Trace.asyncTraceBegin( 12885 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12886 /* 12887 * Send the intent to the required verification agent, 12888 * but only start the verification timeout after the 12889 * target BroadcastReceivers have run. 12890 */ 12891 verification.setComponent(requiredVerifierComponent); 12892 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12893 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12894 new BroadcastReceiver() { 12895 @Override 12896 public void onReceive(Context context, Intent intent) { 12897 final Message msg = mHandler 12898 .obtainMessage(CHECK_PENDING_VERIFICATION); 12899 msg.arg1 = verificationId; 12900 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12901 } 12902 }, null, 0, null, null); 12903 12904 /* 12905 * We don't want the copy to proceed until verification 12906 * succeeds, so null out this field. 12907 */ 12908 mArgs = null; 12909 } 12910 } else { 12911 /* 12912 * No package verification is enabled, so immediately start 12913 * the remote call to initiate copy using temporary file. 12914 */ 12915 ret = args.copyApk(mContainerService, true); 12916 } 12917 } 12918 12919 mRet = ret; 12920 } 12921 12922 @Override 12923 void handleReturnCode() { 12924 // If mArgs is null, then MCS couldn't be reached. When it 12925 // reconnects, it will try again to install. At that point, this 12926 // will succeed. 12927 if (mArgs != null) { 12928 processPendingInstall(mArgs, mRet); 12929 } 12930 } 12931 12932 @Override 12933 void handleServiceError() { 12934 mArgs = createInstallArgs(this); 12935 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12936 } 12937 12938 public boolean isForwardLocked() { 12939 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12940 } 12941 } 12942 12943 /** 12944 * Used during creation of InstallArgs 12945 * 12946 * @param installFlags package installation flags 12947 * @return true if should be installed on external storage 12948 */ 12949 private static boolean installOnExternalAsec(int installFlags) { 12950 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12951 return false; 12952 } 12953 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12954 return true; 12955 } 12956 return false; 12957 } 12958 12959 /** 12960 * Used during creation of InstallArgs 12961 * 12962 * @param installFlags package installation flags 12963 * @return true if should be installed as forward locked 12964 */ 12965 private static boolean installForwardLocked(int installFlags) { 12966 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12967 } 12968 12969 private InstallArgs createInstallArgs(InstallParams params) { 12970 if (params.move != null) { 12971 return new MoveInstallArgs(params); 12972 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12973 return new AsecInstallArgs(params); 12974 } else { 12975 return new FileInstallArgs(params); 12976 } 12977 } 12978 12979 /** 12980 * Create args that describe an existing installed package. Typically used 12981 * when cleaning up old installs, or used as a move source. 12982 */ 12983 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12984 String resourcePath, String[] instructionSets) { 12985 final boolean isInAsec; 12986 if (installOnExternalAsec(installFlags)) { 12987 /* Apps on SD card are always in ASEC containers. */ 12988 isInAsec = true; 12989 } else if (installForwardLocked(installFlags) 12990 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12991 /* 12992 * Forward-locked apps are only in ASEC containers if they're the 12993 * new style 12994 */ 12995 isInAsec = true; 12996 } else { 12997 isInAsec = false; 12998 } 12999 13000 if (isInAsec) { 13001 return new AsecInstallArgs(codePath, instructionSets, 13002 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13003 } else { 13004 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13005 } 13006 } 13007 13008 static abstract class InstallArgs { 13009 /** @see InstallParams#origin */ 13010 final OriginInfo origin; 13011 /** @see InstallParams#move */ 13012 final MoveInfo move; 13013 13014 final IPackageInstallObserver2 observer; 13015 // Always refers to PackageManager flags only 13016 final int installFlags; 13017 final String installerPackageName; 13018 final String volumeUuid; 13019 final UserHandle user; 13020 final String abiOverride; 13021 final String[] installGrantPermissions; 13022 /** If non-null, drop an async trace when the install completes */ 13023 final String traceMethod; 13024 final int traceCookie; 13025 final Certificate[][] certificates; 13026 13027 // The list of instruction sets supported by this app. This is currently 13028 // only used during the rmdex() phase to clean up resources. We can get rid of this 13029 // if we move dex files under the common app path. 13030 /* nullable */ String[] instructionSets; 13031 13032 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13033 int installFlags, String installerPackageName, String volumeUuid, 13034 UserHandle user, String[] instructionSets, 13035 String abiOverride, String[] installGrantPermissions, 13036 String traceMethod, int traceCookie, Certificate[][] certificates) { 13037 this.origin = origin; 13038 this.move = move; 13039 this.installFlags = installFlags; 13040 this.observer = observer; 13041 this.installerPackageName = installerPackageName; 13042 this.volumeUuid = volumeUuid; 13043 this.user = user; 13044 this.instructionSets = instructionSets; 13045 this.abiOverride = abiOverride; 13046 this.installGrantPermissions = installGrantPermissions; 13047 this.traceMethod = traceMethod; 13048 this.traceCookie = traceCookie; 13049 this.certificates = certificates; 13050 } 13051 13052 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13053 abstract int doPreInstall(int status); 13054 13055 /** 13056 * Rename package into final resting place. All paths on the given 13057 * scanned package should be updated to reflect the rename. 13058 */ 13059 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13060 abstract int doPostInstall(int status, int uid); 13061 13062 /** @see PackageSettingBase#codePathString */ 13063 abstract String getCodePath(); 13064 /** @see PackageSettingBase#resourcePathString */ 13065 abstract String getResourcePath(); 13066 13067 // Need installer lock especially for dex file removal. 13068 abstract void cleanUpResourcesLI(); 13069 abstract boolean doPostDeleteLI(boolean delete); 13070 13071 /** 13072 * Called before the source arguments are copied. This is used mostly 13073 * for MoveParams when it needs to read the source file to put it in the 13074 * destination. 13075 */ 13076 int doPreCopy() { 13077 return PackageManager.INSTALL_SUCCEEDED; 13078 } 13079 13080 /** 13081 * Called after the source arguments are copied. This is used mostly for 13082 * MoveParams when it needs to read the source file to put it in the 13083 * destination. 13084 */ 13085 int doPostCopy(int uid) { 13086 return PackageManager.INSTALL_SUCCEEDED; 13087 } 13088 13089 protected boolean isFwdLocked() { 13090 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13091 } 13092 13093 protected boolean isExternalAsec() { 13094 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13095 } 13096 13097 protected boolean isEphemeral() { 13098 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13099 } 13100 13101 UserHandle getUser() { 13102 return user; 13103 } 13104 } 13105 13106 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13107 if (!allCodePaths.isEmpty()) { 13108 if (instructionSets == null) { 13109 throw new IllegalStateException("instructionSet == null"); 13110 } 13111 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13112 for (String codePath : allCodePaths) { 13113 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13114 try { 13115 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13116 } catch (InstallerException ignored) { 13117 } 13118 } 13119 } 13120 } 13121 } 13122 13123 /** 13124 * Logic to handle installation of non-ASEC applications, including copying 13125 * and renaming logic. 13126 */ 13127 class FileInstallArgs extends InstallArgs { 13128 private File codeFile; 13129 private File resourceFile; 13130 13131 // Example topology: 13132 // /data/app/com.example/base.apk 13133 // /data/app/com.example/split_foo.apk 13134 // /data/app/com.example/lib/arm/libfoo.so 13135 // /data/app/com.example/lib/arm64/libfoo.so 13136 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13137 13138 /** New install */ 13139 FileInstallArgs(InstallParams params) { 13140 super(params.origin, params.move, params.observer, params.installFlags, 13141 params.installerPackageName, params.volumeUuid, 13142 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13143 params.grantedRuntimePermissions, 13144 params.traceMethod, params.traceCookie, params.certificates); 13145 if (isFwdLocked()) { 13146 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13147 } 13148 } 13149 13150 /** Existing install */ 13151 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13152 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13153 null, null, null, 0, null /*certificates*/); 13154 this.codeFile = (codePath != null) ? new File(codePath) : null; 13155 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13156 } 13157 13158 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13159 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13160 try { 13161 return doCopyApk(imcs, temp); 13162 } finally { 13163 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13164 } 13165 } 13166 13167 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13168 if (origin.staged) { 13169 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13170 codeFile = origin.file; 13171 resourceFile = origin.file; 13172 return PackageManager.INSTALL_SUCCEEDED; 13173 } 13174 13175 try { 13176 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13177 final File tempDir = 13178 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13179 codeFile = tempDir; 13180 resourceFile = tempDir; 13181 } catch (IOException e) { 13182 Slog.w(TAG, "Failed to create copy file: " + e); 13183 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13184 } 13185 13186 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13187 @Override 13188 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13189 if (!FileUtils.isValidExtFilename(name)) { 13190 throw new IllegalArgumentException("Invalid filename: " + name); 13191 } 13192 try { 13193 final File file = new File(codeFile, name); 13194 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13195 O_RDWR | O_CREAT, 0644); 13196 Os.chmod(file.getAbsolutePath(), 0644); 13197 return new ParcelFileDescriptor(fd); 13198 } catch (ErrnoException e) { 13199 throw new RemoteException("Failed to open: " + e.getMessage()); 13200 } 13201 } 13202 }; 13203 13204 int ret = PackageManager.INSTALL_SUCCEEDED; 13205 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13206 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13207 Slog.e(TAG, "Failed to copy package"); 13208 return ret; 13209 } 13210 13211 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13212 NativeLibraryHelper.Handle handle = null; 13213 try { 13214 handle = NativeLibraryHelper.Handle.create(codeFile); 13215 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13216 abiOverride); 13217 } catch (IOException e) { 13218 Slog.e(TAG, "Copying native libraries failed", e); 13219 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13220 } finally { 13221 IoUtils.closeQuietly(handle); 13222 } 13223 13224 return ret; 13225 } 13226 13227 int doPreInstall(int status) { 13228 if (status != PackageManager.INSTALL_SUCCEEDED) { 13229 cleanUp(); 13230 } 13231 return status; 13232 } 13233 13234 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13235 if (status != PackageManager.INSTALL_SUCCEEDED) { 13236 cleanUp(); 13237 return false; 13238 } 13239 13240 final File targetDir = codeFile.getParentFile(); 13241 final File beforeCodeFile = codeFile; 13242 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13243 13244 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13245 try { 13246 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13247 } catch (ErrnoException e) { 13248 Slog.w(TAG, "Failed to rename", e); 13249 return false; 13250 } 13251 13252 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13253 Slog.w(TAG, "Failed to restorecon"); 13254 return false; 13255 } 13256 13257 // Reflect the rename internally 13258 codeFile = afterCodeFile; 13259 resourceFile = afterCodeFile; 13260 13261 // Reflect the rename in scanned details 13262 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13263 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13264 afterCodeFile, pkg.baseCodePath)); 13265 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13266 afterCodeFile, pkg.splitCodePaths)); 13267 13268 // Reflect the rename in app info 13269 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13270 pkg.setApplicationInfoCodePath(pkg.codePath); 13271 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13272 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13273 pkg.setApplicationInfoResourcePath(pkg.codePath); 13274 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13275 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13276 13277 return true; 13278 } 13279 13280 int doPostInstall(int status, int uid) { 13281 if (status != PackageManager.INSTALL_SUCCEEDED) { 13282 cleanUp(); 13283 } 13284 return status; 13285 } 13286 13287 @Override 13288 String getCodePath() { 13289 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13290 } 13291 13292 @Override 13293 String getResourcePath() { 13294 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13295 } 13296 13297 private boolean cleanUp() { 13298 if (codeFile == null || !codeFile.exists()) { 13299 return false; 13300 } 13301 13302 removeCodePathLI(codeFile); 13303 13304 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13305 resourceFile.delete(); 13306 } 13307 13308 return true; 13309 } 13310 13311 void cleanUpResourcesLI() { 13312 // Try enumerating all code paths before deleting 13313 List<String> allCodePaths = Collections.EMPTY_LIST; 13314 if (codeFile != null && codeFile.exists()) { 13315 try { 13316 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13317 allCodePaths = pkg.getAllCodePaths(); 13318 } catch (PackageParserException e) { 13319 // Ignored; we tried our best 13320 } 13321 } 13322 13323 cleanUp(); 13324 removeDexFiles(allCodePaths, instructionSets); 13325 } 13326 13327 boolean doPostDeleteLI(boolean delete) { 13328 // XXX err, shouldn't we respect the delete flag? 13329 cleanUpResourcesLI(); 13330 return true; 13331 } 13332 } 13333 13334 private boolean isAsecExternal(String cid) { 13335 final String asecPath = PackageHelper.getSdFilesystem(cid); 13336 return !asecPath.startsWith(mAsecInternalPath); 13337 } 13338 13339 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13340 PackageManagerException { 13341 if (copyRet < 0) { 13342 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13343 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13344 throw new PackageManagerException(copyRet, message); 13345 } 13346 } 13347 } 13348 13349 /** 13350 * Extract the MountService "container ID" from the full code path of an 13351 * .apk. 13352 */ 13353 static String cidFromCodePath(String fullCodePath) { 13354 int eidx = fullCodePath.lastIndexOf("/"); 13355 String subStr1 = fullCodePath.substring(0, eidx); 13356 int sidx = subStr1.lastIndexOf("/"); 13357 return subStr1.substring(sidx+1, eidx); 13358 } 13359 13360 /** 13361 * Logic to handle installation of ASEC applications, including copying and 13362 * renaming logic. 13363 */ 13364 class AsecInstallArgs extends InstallArgs { 13365 static final String RES_FILE_NAME = "pkg.apk"; 13366 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13367 13368 String cid; 13369 String packagePath; 13370 String resourcePath; 13371 13372 /** New install */ 13373 AsecInstallArgs(InstallParams params) { 13374 super(params.origin, params.move, params.observer, params.installFlags, 13375 params.installerPackageName, params.volumeUuid, 13376 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13377 params.grantedRuntimePermissions, 13378 params.traceMethod, params.traceCookie, params.certificates); 13379 } 13380 13381 /** Existing install */ 13382 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13383 boolean isExternal, boolean isForwardLocked) { 13384 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13385 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13386 instructionSets, null, null, null, 0, null /*certificates*/); 13387 // Hackily pretend we're still looking at a full code path 13388 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13389 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13390 } 13391 13392 // Extract cid from fullCodePath 13393 int eidx = fullCodePath.lastIndexOf("/"); 13394 String subStr1 = fullCodePath.substring(0, eidx); 13395 int sidx = subStr1.lastIndexOf("/"); 13396 cid = subStr1.substring(sidx+1, eidx); 13397 setMountPath(subStr1); 13398 } 13399 13400 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13401 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13402 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13403 instructionSets, null, null, null, 0, null /*certificates*/); 13404 this.cid = cid; 13405 setMountPath(PackageHelper.getSdDir(cid)); 13406 } 13407 13408 void createCopyFile() { 13409 cid = mInstallerService.allocateExternalStageCidLegacy(); 13410 } 13411 13412 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13413 if (origin.staged && origin.cid != null) { 13414 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13415 cid = origin.cid; 13416 setMountPath(PackageHelper.getSdDir(cid)); 13417 return PackageManager.INSTALL_SUCCEEDED; 13418 } 13419 13420 if (temp) { 13421 createCopyFile(); 13422 } else { 13423 /* 13424 * Pre-emptively destroy the container since it's destroyed if 13425 * copying fails due to it existing anyway. 13426 */ 13427 PackageHelper.destroySdDir(cid); 13428 } 13429 13430 final String newMountPath = imcs.copyPackageToContainer( 13431 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13432 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13433 13434 if (newMountPath != null) { 13435 setMountPath(newMountPath); 13436 return PackageManager.INSTALL_SUCCEEDED; 13437 } else { 13438 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13439 } 13440 } 13441 13442 @Override 13443 String getCodePath() { 13444 return packagePath; 13445 } 13446 13447 @Override 13448 String getResourcePath() { 13449 return resourcePath; 13450 } 13451 13452 int doPreInstall(int status) { 13453 if (status != PackageManager.INSTALL_SUCCEEDED) { 13454 // Destroy container 13455 PackageHelper.destroySdDir(cid); 13456 } else { 13457 boolean mounted = PackageHelper.isContainerMounted(cid); 13458 if (!mounted) { 13459 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13460 Process.SYSTEM_UID); 13461 if (newMountPath != null) { 13462 setMountPath(newMountPath); 13463 } else { 13464 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13465 } 13466 } 13467 } 13468 return status; 13469 } 13470 13471 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13472 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13473 String newMountPath = null; 13474 if (PackageHelper.isContainerMounted(cid)) { 13475 // Unmount the container 13476 if (!PackageHelper.unMountSdDir(cid)) { 13477 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13478 return false; 13479 } 13480 } 13481 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13482 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13483 " which might be stale. Will try to clean up."); 13484 // Clean up the stale container and proceed to recreate. 13485 if (!PackageHelper.destroySdDir(newCacheId)) { 13486 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13487 return false; 13488 } 13489 // Successfully cleaned up stale container. Try to rename again. 13490 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13491 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13492 + " inspite of cleaning it up."); 13493 return false; 13494 } 13495 } 13496 if (!PackageHelper.isContainerMounted(newCacheId)) { 13497 Slog.w(TAG, "Mounting container " + newCacheId); 13498 newMountPath = PackageHelper.mountSdDir(newCacheId, 13499 getEncryptKey(), Process.SYSTEM_UID); 13500 } else { 13501 newMountPath = PackageHelper.getSdDir(newCacheId); 13502 } 13503 if (newMountPath == null) { 13504 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13505 return false; 13506 } 13507 Log.i(TAG, "Succesfully renamed " + cid + 13508 " to " + newCacheId + 13509 " at new path: " + newMountPath); 13510 cid = newCacheId; 13511 13512 final File beforeCodeFile = new File(packagePath); 13513 setMountPath(newMountPath); 13514 final File afterCodeFile = new File(packagePath); 13515 13516 // Reflect the rename in scanned details 13517 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13518 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13519 afterCodeFile, pkg.baseCodePath)); 13520 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13521 afterCodeFile, pkg.splitCodePaths)); 13522 13523 // Reflect the rename in app info 13524 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13525 pkg.setApplicationInfoCodePath(pkg.codePath); 13526 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13527 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13528 pkg.setApplicationInfoResourcePath(pkg.codePath); 13529 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13530 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13531 13532 return true; 13533 } 13534 13535 private void setMountPath(String mountPath) { 13536 final File mountFile = new File(mountPath); 13537 13538 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13539 if (monolithicFile.exists()) { 13540 packagePath = monolithicFile.getAbsolutePath(); 13541 if (isFwdLocked()) { 13542 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13543 } else { 13544 resourcePath = packagePath; 13545 } 13546 } else { 13547 packagePath = mountFile.getAbsolutePath(); 13548 resourcePath = packagePath; 13549 } 13550 } 13551 13552 int doPostInstall(int status, int uid) { 13553 if (status != PackageManager.INSTALL_SUCCEEDED) { 13554 cleanUp(); 13555 } else { 13556 final int groupOwner; 13557 final String protectedFile; 13558 if (isFwdLocked()) { 13559 groupOwner = UserHandle.getSharedAppGid(uid); 13560 protectedFile = RES_FILE_NAME; 13561 } else { 13562 groupOwner = -1; 13563 protectedFile = null; 13564 } 13565 13566 if (uid < Process.FIRST_APPLICATION_UID 13567 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13568 Slog.e(TAG, "Failed to finalize " + cid); 13569 PackageHelper.destroySdDir(cid); 13570 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13571 } 13572 13573 boolean mounted = PackageHelper.isContainerMounted(cid); 13574 if (!mounted) { 13575 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13576 } 13577 } 13578 return status; 13579 } 13580 13581 private void cleanUp() { 13582 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13583 13584 // Destroy secure container 13585 PackageHelper.destroySdDir(cid); 13586 } 13587 13588 private List<String> getAllCodePaths() { 13589 final File codeFile = new File(getCodePath()); 13590 if (codeFile != null && codeFile.exists()) { 13591 try { 13592 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13593 return pkg.getAllCodePaths(); 13594 } catch (PackageParserException e) { 13595 // Ignored; we tried our best 13596 } 13597 } 13598 return Collections.EMPTY_LIST; 13599 } 13600 13601 void cleanUpResourcesLI() { 13602 // Enumerate all code paths before deleting 13603 cleanUpResourcesLI(getAllCodePaths()); 13604 } 13605 13606 private void cleanUpResourcesLI(List<String> allCodePaths) { 13607 cleanUp(); 13608 removeDexFiles(allCodePaths, instructionSets); 13609 } 13610 13611 String getPackageName() { 13612 return getAsecPackageName(cid); 13613 } 13614 13615 boolean doPostDeleteLI(boolean delete) { 13616 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13617 final List<String> allCodePaths = getAllCodePaths(); 13618 boolean mounted = PackageHelper.isContainerMounted(cid); 13619 if (mounted) { 13620 // Unmount first 13621 if (PackageHelper.unMountSdDir(cid)) { 13622 mounted = false; 13623 } 13624 } 13625 if (!mounted && delete) { 13626 cleanUpResourcesLI(allCodePaths); 13627 } 13628 return !mounted; 13629 } 13630 13631 @Override 13632 int doPreCopy() { 13633 if (isFwdLocked()) { 13634 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13635 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13636 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13637 } 13638 } 13639 13640 return PackageManager.INSTALL_SUCCEEDED; 13641 } 13642 13643 @Override 13644 int doPostCopy(int uid) { 13645 if (isFwdLocked()) { 13646 if (uid < Process.FIRST_APPLICATION_UID 13647 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13648 RES_FILE_NAME)) { 13649 Slog.e(TAG, "Failed to finalize " + cid); 13650 PackageHelper.destroySdDir(cid); 13651 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13652 } 13653 } 13654 13655 return PackageManager.INSTALL_SUCCEEDED; 13656 } 13657 } 13658 13659 /** 13660 * Logic to handle movement of existing installed applications. 13661 */ 13662 class MoveInstallArgs extends InstallArgs { 13663 private File codeFile; 13664 private File resourceFile; 13665 13666 /** New install */ 13667 MoveInstallArgs(InstallParams params) { 13668 super(params.origin, params.move, params.observer, params.installFlags, 13669 params.installerPackageName, params.volumeUuid, 13670 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13671 params.grantedRuntimePermissions, 13672 params.traceMethod, params.traceCookie, params.certificates); 13673 } 13674 13675 int copyApk(IMediaContainerService imcs, boolean temp) { 13676 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13677 + move.fromUuid + " to " + move.toUuid); 13678 synchronized (mInstaller) { 13679 try { 13680 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13681 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13682 } catch (InstallerException e) { 13683 Slog.w(TAG, "Failed to move app", e); 13684 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13685 } 13686 } 13687 13688 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13689 resourceFile = codeFile; 13690 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13691 13692 return PackageManager.INSTALL_SUCCEEDED; 13693 } 13694 13695 int doPreInstall(int status) { 13696 if (status != PackageManager.INSTALL_SUCCEEDED) { 13697 cleanUp(move.toUuid); 13698 } 13699 return status; 13700 } 13701 13702 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13703 if (status != PackageManager.INSTALL_SUCCEEDED) { 13704 cleanUp(move.toUuid); 13705 return false; 13706 } 13707 13708 // Reflect the move in app info 13709 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13710 pkg.setApplicationInfoCodePath(pkg.codePath); 13711 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13712 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13713 pkg.setApplicationInfoResourcePath(pkg.codePath); 13714 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13715 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13716 13717 return true; 13718 } 13719 13720 int doPostInstall(int status, int uid) { 13721 if (status == PackageManager.INSTALL_SUCCEEDED) { 13722 cleanUp(move.fromUuid); 13723 } else { 13724 cleanUp(move.toUuid); 13725 } 13726 return status; 13727 } 13728 13729 @Override 13730 String getCodePath() { 13731 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13732 } 13733 13734 @Override 13735 String getResourcePath() { 13736 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13737 } 13738 13739 private boolean cleanUp(String volumeUuid) { 13740 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13741 move.dataAppName); 13742 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13743 final int[] userIds = sUserManager.getUserIds(); 13744 synchronized (mInstallLock) { 13745 // Clean up both app data and code 13746 // All package moves are frozen until finished 13747 for (int userId : userIds) { 13748 try { 13749 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13750 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13751 } catch (InstallerException e) { 13752 Slog.w(TAG, String.valueOf(e)); 13753 } 13754 } 13755 removeCodePathLI(codeFile); 13756 } 13757 return true; 13758 } 13759 13760 void cleanUpResourcesLI() { 13761 throw new UnsupportedOperationException(); 13762 } 13763 13764 boolean doPostDeleteLI(boolean delete) { 13765 throw new UnsupportedOperationException(); 13766 } 13767 } 13768 13769 static String getAsecPackageName(String packageCid) { 13770 int idx = packageCid.lastIndexOf("-"); 13771 if (idx == -1) { 13772 return packageCid; 13773 } 13774 return packageCid.substring(0, idx); 13775 } 13776 13777 // Utility method used to create code paths based on package name and available index. 13778 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13779 String idxStr = ""; 13780 int idx = 1; 13781 // Fall back to default value of idx=1 if prefix is not 13782 // part of oldCodePath 13783 if (oldCodePath != null) { 13784 String subStr = oldCodePath; 13785 // Drop the suffix right away 13786 if (suffix != null && subStr.endsWith(suffix)) { 13787 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13788 } 13789 // If oldCodePath already contains prefix find out the 13790 // ending index to either increment or decrement. 13791 int sidx = subStr.lastIndexOf(prefix); 13792 if (sidx != -1) { 13793 subStr = subStr.substring(sidx + prefix.length()); 13794 if (subStr != null) { 13795 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13796 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13797 } 13798 try { 13799 idx = Integer.parseInt(subStr); 13800 if (idx <= 1) { 13801 idx++; 13802 } else { 13803 idx--; 13804 } 13805 } catch(NumberFormatException e) { 13806 } 13807 } 13808 } 13809 } 13810 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13811 return prefix + idxStr; 13812 } 13813 13814 private File getNextCodePath(File targetDir, String packageName) { 13815 int suffix = 1; 13816 File result; 13817 do { 13818 result = new File(targetDir, packageName + "-" + suffix); 13819 suffix++; 13820 } while (result.exists()); 13821 return result; 13822 } 13823 13824 // Utility method that returns the relative package path with respect 13825 // to the installation directory. Like say for /data/data/com.test-1.apk 13826 // string com.test-1 is returned. 13827 static String deriveCodePathName(String codePath) { 13828 if (codePath == null) { 13829 return null; 13830 } 13831 final File codeFile = new File(codePath); 13832 final String name = codeFile.getName(); 13833 if (codeFile.isDirectory()) { 13834 return name; 13835 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13836 final int lastDot = name.lastIndexOf('.'); 13837 return name.substring(0, lastDot); 13838 } else { 13839 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13840 return null; 13841 } 13842 } 13843 13844 static class PackageInstalledInfo { 13845 String name; 13846 int uid; 13847 // The set of users that originally had this package installed. 13848 int[] origUsers; 13849 // The set of users that now have this package installed. 13850 int[] newUsers; 13851 PackageParser.Package pkg; 13852 int returnCode; 13853 String returnMsg; 13854 PackageRemovedInfo removedInfo; 13855 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13856 13857 public void setError(int code, String msg) { 13858 setReturnCode(code); 13859 setReturnMessage(msg); 13860 Slog.w(TAG, msg); 13861 } 13862 13863 public void setError(String msg, PackageParserException e) { 13864 setReturnCode(e.error); 13865 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13866 Slog.w(TAG, msg, e); 13867 } 13868 13869 public void setError(String msg, PackageManagerException e) { 13870 returnCode = e.error; 13871 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13872 Slog.w(TAG, msg, e); 13873 } 13874 13875 public void setReturnCode(int returnCode) { 13876 this.returnCode = returnCode; 13877 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13878 for (int i = 0; i < childCount; i++) { 13879 addedChildPackages.valueAt(i).returnCode = returnCode; 13880 } 13881 } 13882 13883 private void setReturnMessage(String returnMsg) { 13884 this.returnMsg = returnMsg; 13885 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13886 for (int i = 0; i < childCount; i++) { 13887 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13888 } 13889 } 13890 13891 // In some error cases we want to convey more info back to the observer 13892 String origPackage; 13893 String origPermission; 13894 } 13895 13896 /* 13897 * Install a non-existing package. 13898 */ 13899 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13900 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13901 PackageInstalledInfo res) { 13902 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13903 13904 // Remember this for later, in case we need to rollback this install 13905 String pkgName = pkg.packageName; 13906 13907 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13908 13909 synchronized(mPackages) { 13910 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13911 // A package with the same name is already installed, though 13912 // it has been renamed to an older name. The package we 13913 // are trying to install should be installed as an update to 13914 // the existing one, but that has not been requested, so bail. 13915 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13916 + " without first uninstalling package running as " 13917 + mSettings.mRenamedPackages.get(pkgName)); 13918 return; 13919 } 13920 if (mPackages.containsKey(pkgName)) { 13921 // Don't allow installation over an existing package with the same name. 13922 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13923 + " without first uninstalling."); 13924 return; 13925 } 13926 } 13927 13928 try { 13929 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13930 System.currentTimeMillis(), user); 13931 13932 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13933 13934 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13935 prepareAppDataAfterInstallLIF(newPackage); 13936 13937 } else { 13938 // Remove package from internal structures, but keep around any 13939 // data that might have already existed 13940 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13941 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13942 } 13943 } catch (PackageManagerException e) { 13944 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13945 } 13946 13947 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13948 } 13949 13950 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13951 // Can't rotate keys during boot or if sharedUser. 13952 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13953 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13954 return false; 13955 } 13956 // app is using upgradeKeySets; make sure all are valid 13957 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13958 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13959 for (int i = 0; i < upgradeKeySets.length; i++) { 13960 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13961 Slog.wtf(TAG, "Package " 13962 + (oldPs.name != null ? oldPs.name : "<null>") 13963 + " contains upgrade-key-set reference to unknown key-set: " 13964 + upgradeKeySets[i] 13965 + " reverting to signatures check."); 13966 return false; 13967 } 13968 } 13969 return true; 13970 } 13971 13972 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13973 // Upgrade keysets are being used. Determine if new package has a superset of the 13974 // required keys. 13975 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13976 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13977 for (int i = 0; i < upgradeKeySets.length; i++) { 13978 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13979 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13980 return true; 13981 } 13982 } 13983 return false; 13984 } 13985 13986 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13987 try (DigestInputStream digestStream = 13988 new DigestInputStream(new FileInputStream(file), digest)) { 13989 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13990 } 13991 } 13992 13993 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13994 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13995 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13996 13997 final PackageParser.Package oldPackage; 13998 final String pkgName = pkg.packageName; 13999 final int[] allUsers; 14000 final int[] installedUsers; 14001 14002 synchronized(mPackages) { 14003 oldPackage = mPackages.get(pkgName); 14004 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14005 14006 // don't allow upgrade to target a release SDK from a pre-release SDK 14007 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14008 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14009 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14010 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14011 if (oldTargetsPreRelease 14012 && !newTargetsPreRelease 14013 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14014 Slog.w(TAG, "Can't install package targeting released sdk"); 14015 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14016 return; 14017 } 14018 14019 // don't allow an upgrade from full to ephemeral 14020 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14021 if (isEphemeral && !oldIsEphemeral) { 14022 // can't downgrade from full to ephemeral 14023 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14024 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14025 return; 14026 } 14027 14028 // verify signatures are valid 14029 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14030 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14031 if (!checkUpgradeKeySetLP(ps, pkg)) { 14032 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14033 "New package not signed by keys specified by upgrade-keysets: " 14034 + pkgName); 14035 return; 14036 } 14037 } else { 14038 // default to original signature matching 14039 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14040 != PackageManager.SIGNATURE_MATCH) { 14041 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14042 "New package has a different signature: " + pkgName); 14043 return; 14044 } 14045 } 14046 14047 // don't allow a system upgrade unless the upgrade hash matches 14048 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14049 byte[] digestBytes = null; 14050 try { 14051 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14052 updateDigest(digest, new File(pkg.baseCodePath)); 14053 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14054 for (String path : pkg.splitCodePaths) { 14055 updateDigest(digest, new File(path)); 14056 } 14057 } 14058 digestBytes = digest.digest(); 14059 } catch (NoSuchAlgorithmException | IOException e) { 14060 res.setError(INSTALL_FAILED_INVALID_APK, 14061 "Could not compute hash: " + pkgName); 14062 return; 14063 } 14064 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14065 res.setError(INSTALL_FAILED_INVALID_APK, 14066 "New package fails restrict-update check: " + pkgName); 14067 return; 14068 } 14069 // retain upgrade restriction 14070 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14071 } 14072 14073 // Check for shared user id changes 14074 String invalidPackageName = 14075 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14076 if (invalidPackageName != null) { 14077 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14078 "Package " + invalidPackageName + " tried to change user " 14079 + oldPackage.mSharedUserId); 14080 return; 14081 } 14082 14083 // In case of rollback, remember per-user/profile install state 14084 allUsers = sUserManager.getUserIds(); 14085 installedUsers = ps.queryInstalledUsers(allUsers, true); 14086 } 14087 14088 // Update what is removed 14089 res.removedInfo = new PackageRemovedInfo(); 14090 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14091 res.removedInfo.removedPackage = oldPackage.packageName; 14092 res.removedInfo.isUpdate = true; 14093 res.removedInfo.origUsers = installedUsers; 14094 final int childCount = (oldPackage.childPackages != null) 14095 ? oldPackage.childPackages.size() : 0; 14096 for (int i = 0; i < childCount; i++) { 14097 boolean childPackageUpdated = false; 14098 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14099 if (res.addedChildPackages != null) { 14100 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14101 if (childRes != null) { 14102 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14103 childRes.removedInfo.removedPackage = childPkg.packageName; 14104 childRes.removedInfo.isUpdate = true; 14105 childPackageUpdated = true; 14106 } 14107 } 14108 if (!childPackageUpdated) { 14109 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14110 childRemovedRes.removedPackage = childPkg.packageName; 14111 childRemovedRes.isUpdate = false; 14112 childRemovedRes.dataRemoved = true; 14113 synchronized (mPackages) { 14114 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14115 if (childPs != null) { 14116 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14117 } 14118 } 14119 if (res.removedInfo.removedChildPackages == null) { 14120 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14121 } 14122 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14123 } 14124 } 14125 14126 boolean sysPkg = (isSystemApp(oldPackage)); 14127 if (sysPkg) { 14128 // Set the system/privileged flags as needed 14129 final boolean privileged = 14130 (oldPackage.applicationInfo.privateFlags 14131 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14132 final int systemPolicyFlags = policyFlags 14133 | PackageParser.PARSE_IS_SYSTEM 14134 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14135 14136 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14137 user, allUsers, installerPackageName, res); 14138 } else { 14139 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14140 user, allUsers, installerPackageName, res); 14141 } 14142 } 14143 14144 public List<String> getPreviousCodePaths(String packageName) { 14145 final PackageSetting ps = mSettings.mPackages.get(packageName); 14146 final List<String> result = new ArrayList<String>(); 14147 if (ps != null && ps.oldCodePaths != null) { 14148 result.addAll(ps.oldCodePaths); 14149 } 14150 return result; 14151 } 14152 14153 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14154 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14155 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14156 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14157 + deletedPackage); 14158 14159 String pkgName = deletedPackage.packageName; 14160 boolean deletedPkg = true; 14161 boolean addedPkg = false; 14162 boolean updatedSettings = false; 14163 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14164 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14165 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14166 14167 final long origUpdateTime = (pkg.mExtras != null) 14168 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14169 14170 // First delete the existing package while retaining the data directory 14171 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14172 res.removedInfo, true, pkg)) { 14173 // If the existing package wasn't successfully deleted 14174 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14175 deletedPkg = false; 14176 } else { 14177 // Successfully deleted the old package; proceed with replace. 14178 14179 // If deleted package lived in a container, give users a chance to 14180 // relinquish resources before killing. 14181 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14182 if (DEBUG_INSTALL) { 14183 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14184 } 14185 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14186 final ArrayList<String> pkgList = new ArrayList<String>(1); 14187 pkgList.add(deletedPackage.applicationInfo.packageName); 14188 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14189 } 14190 14191 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14192 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14193 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14194 14195 try { 14196 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14197 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14198 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14199 14200 // Update the in-memory copy of the previous code paths. 14201 PackageSetting ps = mSettings.mPackages.get(pkgName); 14202 if (!killApp) { 14203 if (ps.oldCodePaths == null) { 14204 ps.oldCodePaths = new ArraySet<>(); 14205 } 14206 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14207 if (deletedPackage.splitCodePaths != null) { 14208 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14209 } 14210 } else { 14211 ps.oldCodePaths = null; 14212 } 14213 if (ps.childPackageNames != null) { 14214 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14215 final String childPkgName = ps.childPackageNames.get(i); 14216 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14217 childPs.oldCodePaths = ps.oldCodePaths; 14218 } 14219 } 14220 prepareAppDataAfterInstallLIF(newPackage); 14221 addedPkg = true; 14222 } catch (PackageManagerException e) { 14223 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14224 } 14225 } 14226 14227 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14228 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14229 14230 // Revert all internal state mutations and added folders for the failed install 14231 if (addedPkg) { 14232 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14233 res.removedInfo, true, null); 14234 } 14235 14236 // Restore the old package 14237 if (deletedPkg) { 14238 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14239 File restoreFile = new File(deletedPackage.codePath); 14240 // Parse old package 14241 boolean oldExternal = isExternal(deletedPackage); 14242 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14243 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14244 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14245 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14246 try { 14247 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14248 null); 14249 } catch (PackageManagerException e) { 14250 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14251 + e.getMessage()); 14252 return; 14253 } 14254 14255 synchronized (mPackages) { 14256 // Ensure the installer package name up to date 14257 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14258 14259 // Update permissions for restored package 14260 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14261 14262 mSettings.writeLPr(); 14263 } 14264 14265 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14266 } 14267 } else { 14268 synchronized (mPackages) { 14269 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14270 if (ps != null) { 14271 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14272 if (res.removedInfo.removedChildPackages != null) { 14273 final int childCount = res.removedInfo.removedChildPackages.size(); 14274 // Iterate in reverse as we may modify the collection 14275 for (int i = childCount - 1; i >= 0; i--) { 14276 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14277 if (res.addedChildPackages.containsKey(childPackageName)) { 14278 res.removedInfo.removedChildPackages.removeAt(i); 14279 } else { 14280 PackageRemovedInfo childInfo = res.removedInfo 14281 .removedChildPackages.valueAt(i); 14282 childInfo.removedForAllUsers = mPackages.get( 14283 childInfo.removedPackage) == null; 14284 } 14285 } 14286 } 14287 } 14288 } 14289 } 14290 } 14291 14292 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14293 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14294 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14295 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14296 + ", old=" + deletedPackage); 14297 14298 final boolean disabledSystem; 14299 14300 // Remove existing system package 14301 removePackageLI(deletedPackage, true); 14302 14303 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14304 if (!disabledSystem) { 14305 // We didn't need to disable the .apk as a current system package, 14306 // which means we are replacing another update that is already 14307 // installed. We need to make sure to delete the older one's .apk. 14308 res.removedInfo.args = createInstallArgsForExisting(0, 14309 deletedPackage.applicationInfo.getCodePath(), 14310 deletedPackage.applicationInfo.getResourcePath(), 14311 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14312 } else { 14313 res.removedInfo.args = null; 14314 } 14315 14316 // Successfully disabled the old package. Now proceed with re-installation 14317 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14318 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14319 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14320 14321 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14322 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14323 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14324 14325 PackageParser.Package newPackage = null; 14326 try { 14327 // Add the package to the internal data structures 14328 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14329 14330 // Set the update and install times 14331 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14332 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14333 System.currentTimeMillis()); 14334 14335 // Update the package dynamic state if succeeded 14336 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14337 // Now that the install succeeded make sure we remove data 14338 // directories for any child package the update removed. 14339 final int deletedChildCount = (deletedPackage.childPackages != null) 14340 ? deletedPackage.childPackages.size() : 0; 14341 final int newChildCount = (newPackage.childPackages != null) 14342 ? newPackage.childPackages.size() : 0; 14343 for (int i = 0; i < deletedChildCount; i++) { 14344 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14345 boolean childPackageDeleted = true; 14346 for (int j = 0; j < newChildCount; j++) { 14347 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14348 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14349 childPackageDeleted = false; 14350 break; 14351 } 14352 } 14353 if (childPackageDeleted) { 14354 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14355 deletedChildPkg.packageName); 14356 if (ps != null && res.removedInfo.removedChildPackages != null) { 14357 PackageRemovedInfo removedChildRes = res.removedInfo 14358 .removedChildPackages.get(deletedChildPkg.packageName); 14359 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14360 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14361 } 14362 } 14363 } 14364 14365 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14366 prepareAppDataAfterInstallLIF(newPackage); 14367 } 14368 } catch (PackageManagerException e) { 14369 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14370 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14371 } 14372 14373 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14374 // Re installation failed. Restore old information 14375 // Remove new pkg information 14376 if (newPackage != null) { 14377 removeInstalledPackageLI(newPackage, true); 14378 } 14379 // Add back the old system package 14380 try { 14381 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14382 } catch (PackageManagerException e) { 14383 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14384 } 14385 14386 synchronized (mPackages) { 14387 if (disabledSystem) { 14388 enableSystemPackageLPw(deletedPackage); 14389 } 14390 14391 // Ensure the installer package name up to date 14392 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14393 14394 // Update permissions for restored package 14395 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14396 14397 mSettings.writeLPr(); 14398 } 14399 14400 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14401 + " after failed upgrade"); 14402 } 14403 } 14404 14405 /** 14406 * Checks whether the parent or any of the child packages have a change shared 14407 * user. For a package to be a valid update the shred users of the parent and 14408 * the children should match. We may later support changing child shared users. 14409 * @param oldPkg The updated package. 14410 * @param newPkg The update package. 14411 * @return The shared user that change between the versions. 14412 */ 14413 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14414 PackageParser.Package newPkg) { 14415 // Check parent shared user 14416 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14417 return newPkg.packageName; 14418 } 14419 // Check child shared users 14420 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14421 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14422 for (int i = 0; i < newChildCount; i++) { 14423 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14424 // If this child was present, did it have the same shared user? 14425 for (int j = 0; j < oldChildCount; j++) { 14426 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14427 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14428 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14429 return newChildPkg.packageName; 14430 } 14431 } 14432 } 14433 return null; 14434 } 14435 14436 private void removeNativeBinariesLI(PackageSetting ps) { 14437 // Remove the lib path for the parent package 14438 if (ps != null) { 14439 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14440 // Remove the lib path for the child packages 14441 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14442 for (int i = 0; i < childCount; i++) { 14443 PackageSetting childPs = null; 14444 synchronized (mPackages) { 14445 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14446 } 14447 if (childPs != null) { 14448 NativeLibraryHelper.removeNativeBinariesLI(childPs 14449 .legacyNativeLibraryPathString); 14450 } 14451 } 14452 } 14453 } 14454 14455 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14456 // Enable the parent package 14457 mSettings.enableSystemPackageLPw(pkg.packageName); 14458 // Enable the child packages 14459 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14460 for (int i = 0; i < childCount; i++) { 14461 PackageParser.Package childPkg = pkg.childPackages.get(i); 14462 mSettings.enableSystemPackageLPw(childPkg.packageName); 14463 } 14464 } 14465 14466 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14467 PackageParser.Package newPkg) { 14468 // Disable the parent package (parent always replaced) 14469 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14470 // Disable the child packages 14471 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14472 for (int i = 0; i < childCount; i++) { 14473 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14474 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14475 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14476 } 14477 return disabled; 14478 } 14479 14480 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14481 String installerPackageName) { 14482 // Enable the parent package 14483 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14484 // Enable the child packages 14485 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14486 for (int i = 0; i < childCount; i++) { 14487 PackageParser.Package childPkg = pkg.childPackages.get(i); 14488 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14489 } 14490 } 14491 14492 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14493 // Collect all used permissions in the UID 14494 ArraySet<String> usedPermissions = new ArraySet<>(); 14495 final int packageCount = su.packages.size(); 14496 for (int i = 0; i < packageCount; i++) { 14497 PackageSetting ps = su.packages.valueAt(i); 14498 if (ps.pkg == null) { 14499 continue; 14500 } 14501 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14502 for (int j = 0; j < requestedPermCount; j++) { 14503 String permission = ps.pkg.requestedPermissions.get(j); 14504 BasePermission bp = mSettings.mPermissions.get(permission); 14505 if (bp != null) { 14506 usedPermissions.add(permission); 14507 } 14508 } 14509 } 14510 14511 PermissionsState permissionsState = su.getPermissionsState(); 14512 // Prune install permissions 14513 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14514 final int installPermCount = installPermStates.size(); 14515 for (int i = installPermCount - 1; i >= 0; i--) { 14516 PermissionState permissionState = installPermStates.get(i); 14517 if (!usedPermissions.contains(permissionState.getName())) { 14518 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14519 if (bp != null) { 14520 permissionsState.revokeInstallPermission(bp); 14521 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14522 PackageManager.MASK_PERMISSION_FLAGS, 0); 14523 } 14524 } 14525 } 14526 14527 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14528 14529 // Prune runtime permissions 14530 for (int userId : allUserIds) { 14531 List<PermissionState> runtimePermStates = permissionsState 14532 .getRuntimePermissionStates(userId); 14533 final int runtimePermCount = runtimePermStates.size(); 14534 for (int i = runtimePermCount - 1; i >= 0; i--) { 14535 PermissionState permissionState = runtimePermStates.get(i); 14536 if (!usedPermissions.contains(permissionState.getName())) { 14537 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14538 if (bp != null) { 14539 permissionsState.revokeRuntimePermission(bp, userId); 14540 permissionsState.updatePermissionFlags(bp, userId, 14541 PackageManager.MASK_PERMISSION_FLAGS, 0); 14542 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14543 runtimePermissionChangedUserIds, userId); 14544 } 14545 } 14546 } 14547 } 14548 14549 return runtimePermissionChangedUserIds; 14550 } 14551 14552 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14553 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14554 // Update the parent package setting 14555 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14556 res, user); 14557 // Update the child packages setting 14558 final int childCount = (newPackage.childPackages != null) 14559 ? newPackage.childPackages.size() : 0; 14560 for (int i = 0; i < childCount; i++) { 14561 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14562 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14563 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14564 childRes.origUsers, childRes, user); 14565 } 14566 } 14567 14568 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14569 String installerPackageName, int[] allUsers, int[] installedForUsers, 14570 PackageInstalledInfo res, UserHandle user) { 14571 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14572 14573 String pkgName = newPackage.packageName; 14574 synchronized (mPackages) { 14575 //write settings. the installStatus will be incomplete at this stage. 14576 //note that the new package setting would have already been 14577 //added to mPackages. It hasn't been persisted yet. 14578 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14579 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14580 mSettings.writeLPr(); 14581 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14582 } 14583 14584 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14585 synchronized (mPackages) { 14586 updatePermissionsLPw(newPackage.packageName, newPackage, 14587 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14588 ? UPDATE_PERMISSIONS_ALL : 0)); 14589 // For system-bundled packages, we assume that installing an upgraded version 14590 // of the package implies that the user actually wants to run that new code, 14591 // so we enable the package. 14592 PackageSetting ps = mSettings.mPackages.get(pkgName); 14593 final int userId = user.getIdentifier(); 14594 if (ps != null) { 14595 if (isSystemApp(newPackage)) { 14596 if (DEBUG_INSTALL) { 14597 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14598 } 14599 // Enable system package for requested users 14600 if (res.origUsers != null) { 14601 for (int origUserId : res.origUsers) { 14602 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14603 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14604 origUserId, installerPackageName); 14605 } 14606 } 14607 } 14608 // Also convey the prior install/uninstall state 14609 if (allUsers != null && installedForUsers != null) { 14610 for (int currentUserId : allUsers) { 14611 final boolean installed = ArrayUtils.contains( 14612 installedForUsers, currentUserId); 14613 if (DEBUG_INSTALL) { 14614 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14615 } 14616 ps.setInstalled(installed, currentUserId); 14617 } 14618 // these install state changes will be persisted in the 14619 // upcoming call to mSettings.writeLPr(). 14620 } 14621 } 14622 // It's implied that when a user requests installation, they want the app to be 14623 // installed and enabled. 14624 if (userId != UserHandle.USER_ALL) { 14625 ps.setInstalled(true, userId); 14626 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14627 } 14628 } 14629 res.name = pkgName; 14630 res.uid = newPackage.applicationInfo.uid; 14631 res.pkg = newPackage; 14632 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14633 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14634 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14635 //to update install status 14636 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14637 mSettings.writeLPr(); 14638 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14639 } 14640 14641 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14642 } 14643 14644 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14645 try { 14646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14647 installPackageLI(args, res); 14648 } finally { 14649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14650 } 14651 } 14652 14653 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14654 final int installFlags = args.installFlags; 14655 final String installerPackageName = args.installerPackageName; 14656 final String volumeUuid = args.volumeUuid; 14657 final File tmpPackageFile = new File(args.getCodePath()); 14658 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14659 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14660 || (args.volumeUuid != null)); 14661 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14662 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14663 boolean replace = false; 14664 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14665 if (args.move != null) { 14666 // moving a complete application; perform an initial scan on the new install location 14667 scanFlags |= SCAN_INITIAL; 14668 } 14669 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14670 scanFlags |= SCAN_DONT_KILL_APP; 14671 } 14672 14673 // Result object to be returned 14674 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14675 14676 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14677 14678 // Sanity check 14679 if (ephemeral && (forwardLocked || onExternal)) { 14680 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14681 + " external=" + onExternal); 14682 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14683 return; 14684 } 14685 14686 // Retrieve PackageSettings and parse package 14687 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14688 | PackageParser.PARSE_ENFORCE_CODE 14689 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14690 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14691 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14692 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14693 PackageParser pp = new PackageParser(); 14694 pp.setSeparateProcesses(mSeparateProcesses); 14695 pp.setDisplayMetrics(mMetrics); 14696 14697 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14698 final PackageParser.Package pkg; 14699 try { 14700 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14701 } catch (PackageParserException e) { 14702 res.setError("Failed parse during installPackageLI", e); 14703 return; 14704 } finally { 14705 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14706 } 14707 14708 // If we are installing a clustered package add results for the children 14709 if (pkg.childPackages != null) { 14710 synchronized (mPackages) { 14711 final int childCount = pkg.childPackages.size(); 14712 for (int i = 0; i < childCount; i++) { 14713 PackageParser.Package childPkg = pkg.childPackages.get(i); 14714 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14715 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14716 childRes.pkg = childPkg; 14717 childRes.name = childPkg.packageName; 14718 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14719 if (childPs != null) { 14720 childRes.origUsers = childPs.queryInstalledUsers( 14721 sUserManager.getUserIds(), true); 14722 } 14723 if ((mPackages.containsKey(childPkg.packageName))) { 14724 childRes.removedInfo = new PackageRemovedInfo(); 14725 childRes.removedInfo.removedPackage = childPkg.packageName; 14726 } 14727 if (res.addedChildPackages == null) { 14728 res.addedChildPackages = new ArrayMap<>(); 14729 } 14730 res.addedChildPackages.put(childPkg.packageName, childRes); 14731 } 14732 } 14733 } 14734 14735 // If package doesn't declare API override, mark that we have an install 14736 // time CPU ABI override. 14737 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14738 pkg.cpuAbiOverride = args.abiOverride; 14739 } 14740 14741 String pkgName = res.name = pkg.packageName; 14742 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14743 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14744 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14745 return; 14746 } 14747 } 14748 14749 try { 14750 // either use what we've been given or parse directly from the APK 14751 if (args.certificates != null) { 14752 try { 14753 PackageParser.populateCertificates(pkg, args.certificates); 14754 } catch (PackageParserException e) { 14755 // there was something wrong with the certificates we were given; 14756 // try to pull them from the APK 14757 PackageParser.collectCertificates(pkg, parseFlags); 14758 } 14759 } else { 14760 PackageParser.collectCertificates(pkg, parseFlags); 14761 } 14762 } catch (PackageParserException e) { 14763 res.setError("Failed collect during installPackageLI", e); 14764 return; 14765 } 14766 14767 // Get rid of all references to package scan path via parser. 14768 pp = null; 14769 String oldCodePath = null; 14770 boolean systemApp = false; 14771 synchronized (mPackages) { 14772 // Check if installing already existing package 14773 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14774 String oldName = mSettings.mRenamedPackages.get(pkgName); 14775 if (pkg.mOriginalPackages != null 14776 && pkg.mOriginalPackages.contains(oldName) 14777 && mPackages.containsKey(oldName)) { 14778 // This package is derived from an original package, 14779 // and this device has been updating from that original 14780 // name. We must continue using the original name, so 14781 // rename the new package here. 14782 pkg.setPackageName(oldName); 14783 pkgName = pkg.packageName; 14784 replace = true; 14785 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14786 + oldName + " pkgName=" + pkgName); 14787 } else if (mPackages.containsKey(pkgName)) { 14788 // This package, under its official name, already exists 14789 // on the device; we should replace it. 14790 replace = true; 14791 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14792 } 14793 14794 // Child packages are installed through the parent package 14795 if (pkg.parentPackage != null) { 14796 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14797 "Package " + pkg.packageName + " is child of package " 14798 + pkg.parentPackage.parentPackage + ". Child packages " 14799 + "can be updated only through the parent package."); 14800 return; 14801 } 14802 14803 if (replace) { 14804 // Prevent apps opting out from runtime permissions 14805 PackageParser.Package oldPackage = mPackages.get(pkgName); 14806 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14807 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14808 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14809 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14810 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14811 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14812 + " doesn't support runtime permissions but the old" 14813 + " target SDK " + oldTargetSdk + " does."); 14814 return; 14815 } 14816 14817 // Prevent installing of child packages 14818 if (oldPackage.parentPackage != null) { 14819 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14820 "Package " + pkg.packageName + " is child of package " 14821 + oldPackage.parentPackage + ". Child packages " 14822 + "can be updated only through the parent package."); 14823 return; 14824 } 14825 } 14826 } 14827 14828 PackageSetting ps = mSettings.mPackages.get(pkgName); 14829 if (ps != null) { 14830 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14831 14832 // Quick sanity check that we're signed correctly if updating; 14833 // we'll check this again later when scanning, but we want to 14834 // bail early here before tripping over redefined permissions. 14835 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14836 if (!checkUpgradeKeySetLP(ps, pkg)) { 14837 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14838 + pkg.packageName + " upgrade keys do not match the " 14839 + "previously installed version"); 14840 return; 14841 } 14842 } else { 14843 try { 14844 verifySignaturesLP(ps, pkg); 14845 } catch (PackageManagerException e) { 14846 res.setError(e.error, e.getMessage()); 14847 return; 14848 } 14849 } 14850 14851 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14852 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14853 systemApp = (ps.pkg.applicationInfo.flags & 14854 ApplicationInfo.FLAG_SYSTEM) != 0; 14855 } 14856 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14857 } 14858 14859 // Check whether the newly-scanned package wants to define an already-defined perm 14860 int N = pkg.permissions.size(); 14861 for (int i = N-1; i >= 0; i--) { 14862 PackageParser.Permission perm = pkg.permissions.get(i); 14863 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14864 if (bp != null) { 14865 // If the defining package is signed with our cert, it's okay. This 14866 // also includes the "updating the same package" case, of course. 14867 // "updating same package" could also involve key-rotation. 14868 final boolean sigsOk; 14869 if (bp.sourcePackage.equals(pkg.packageName) 14870 && (bp.packageSetting instanceof PackageSetting) 14871 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14872 scanFlags))) { 14873 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14874 } else { 14875 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14876 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14877 } 14878 if (!sigsOk) { 14879 // If the owning package is the system itself, we log but allow 14880 // install to proceed; we fail the install on all other permission 14881 // redefinitions. 14882 if (!bp.sourcePackage.equals("android")) { 14883 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14884 + pkg.packageName + " attempting to redeclare permission " 14885 + perm.info.name + " already owned by " + bp.sourcePackage); 14886 res.origPermission = perm.info.name; 14887 res.origPackage = bp.sourcePackage; 14888 return; 14889 } else { 14890 Slog.w(TAG, "Package " + pkg.packageName 14891 + " attempting to redeclare system permission " 14892 + perm.info.name + "; ignoring new declaration"); 14893 pkg.permissions.remove(i); 14894 } 14895 } 14896 } 14897 } 14898 } 14899 14900 if (systemApp) { 14901 if (onExternal) { 14902 // Abort update; system app can't be replaced with app on sdcard 14903 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14904 "Cannot install updates to system apps on sdcard"); 14905 return; 14906 } else if (ephemeral) { 14907 // Abort update; system app can't be replaced with an ephemeral app 14908 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14909 "Cannot update a system app with an ephemeral app"); 14910 return; 14911 } 14912 } 14913 14914 if (args.move != null) { 14915 // We did an in-place move, so dex is ready to roll 14916 scanFlags |= SCAN_NO_DEX; 14917 scanFlags |= SCAN_MOVE; 14918 14919 synchronized (mPackages) { 14920 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14921 if (ps == null) { 14922 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14923 "Missing settings for moved package " + pkgName); 14924 } 14925 14926 // We moved the entire application as-is, so bring over the 14927 // previously derived ABI information. 14928 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14929 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14930 } 14931 14932 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14933 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14934 scanFlags |= SCAN_NO_DEX; 14935 14936 try { 14937 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14938 args.abiOverride : pkg.cpuAbiOverride); 14939 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14940 true /* extract libs */); 14941 } catch (PackageManagerException pme) { 14942 Slog.e(TAG, "Error deriving application ABI", pme); 14943 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14944 return; 14945 } 14946 14947 // Shared libraries for the package need to be updated. 14948 synchronized (mPackages) { 14949 try { 14950 updateSharedLibrariesLPw(pkg, null); 14951 } catch (PackageManagerException e) { 14952 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14953 } 14954 } 14955 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14956 // Do not run PackageDexOptimizer through the local performDexOpt 14957 // method because `pkg` is not in `mPackages` yet. 14958 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14959 null /* instructionSets */, false /* checkProfiles */, 14960 getCompilerFilterForReason(REASON_INSTALL)); 14961 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14962 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14963 String msg = "Extracting package failed for " + pkgName; 14964 res.setError(INSTALL_FAILED_DEXOPT, msg); 14965 return; 14966 } 14967 14968 // Notify BackgroundDexOptService that the package has been changed. 14969 // If this is an update of a package which used to fail to compile, 14970 // BDOS will remove it from its blacklist. 14971 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14972 } 14973 14974 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14975 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14976 return; 14977 } 14978 14979 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14980 14981 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14982 "installPackageLI")) { 14983 if (replace) { 14984 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14985 installerPackageName, res); 14986 } else { 14987 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14988 args.user, installerPackageName, volumeUuid, res); 14989 } 14990 } 14991 synchronized (mPackages) { 14992 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14993 if (ps != null) { 14994 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14995 } 14996 14997 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14998 for (int i = 0; i < childCount; i++) { 14999 PackageParser.Package childPkg = pkg.childPackages.get(i); 15000 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15001 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15002 if (childPs != null) { 15003 childRes.newUsers = childPs.queryInstalledUsers( 15004 sUserManager.getUserIds(), true); 15005 } 15006 } 15007 } 15008 } 15009 15010 private void startIntentFilterVerifications(int userId, boolean replacing, 15011 PackageParser.Package pkg) { 15012 if (mIntentFilterVerifierComponent == null) { 15013 Slog.w(TAG, "No IntentFilter verification will not be done as " 15014 + "there is no IntentFilterVerifier available!"); 15015 return; 15016 } 15017 15018 final int verifierUid = getPackageUid( 15019 mIntentFilterVerifierComponent.getPackageName(), 15020 MATCH_DEBUG_TRIAGED_MISSING, 15021 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15022 15023 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15024 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15025 mHandler.sendMessage(msg); 15026 15027 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15028 for (int i = 0; i < childCount; i++) { 15029 PackageParser.Package childPkg = pkg.childPackages.get(i); 15030 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15031 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15032 mHandler.sendMessage(msg); 15033 } 15034 } 15035 15036 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15037 PackageParser.Package pkg) { 15038 int size = pkg.activities.size(); 15039 if (size == 0) { 15040 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15041 "No activity, so no need to verify any IntentFilter!"); 15042 return; 15043 } 15044 15045 final boolean hasDomainURLs = hasDomainURLs(pkg); 15046 if (!hasDomainURLs) { 15047 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15048 "No domain URLs, so no need to verify any IntentFilter!"); 15049 return; 15050 } 15051 15052 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15053 + " if any IntentFilter from the " + size 15054 + " Activities needs verification ..."); 15055 15056 int count = 0; 15057 final String packageName = pkg.packageName; 15058 15059 synchronized (mPackages) { 15060 // If this is a new install and we see that we've already run verification for this 15061 // package, we have nothing to do: it means the state was restored from backup. 15062 if (!replacing) { 15063 IntentFilterVerificationInfo ivi = 15064 mSettings.getIntentFilterVerificationLPr(packageName); 15065 if (ivi != null) { 15066 if (DEBUG_DOMAIN_VERIFICATION) { 15067 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15068 + ivi.getStatusString()); 15069 } 15070 return; 15071 } 15072 } 15073 15074 // If any filters need to be verified, then all need to be. 15075 boolean needToVerify = false; 15076 for (PackageParser.Activity a : pkg.activities) { 15077 for (ActivityIntentInfo filter : a.intents) { 15078 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15079 if (DEBUG_DOMAIN_VERIFICATION) { 15080 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15081 } 15082 needToVerify = true; 15083 break; 15084 } 15085 } 15086 } 15087 15088 if (needToVerify) { 15089 final int verificationId = mIntentFilterVerificationToken++; 15090 for (PackageParser.Activity a : pkg.activities) { 15091 for (ActivityIntentInfo filter : a.intents) { 15092 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15093 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15094 "Verification needed for IntentFilter:" + filter.toString()); 15095 mIntentFilterVerifier.addOneIntentFilterVerification( 15096 verifierUid, userId, verificationId, filter, packageName); 15097 count++; 15098 } 15099 } 15100 } 15101 } 15102 } 15103 15104 if (count > 0) { 15105 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15106 + " IntentFilter verification" + (count > 1 ? "s" : "") 15107 + " for userId:" + userId); 15108 mIntentFilterVerifier.startVerifications(userId); 15109 } else { 15110 if (DEBUG_DOMAIN_VERIFICATION) { 15111 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15112 } 15113 } 15114 } 15115 15116 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15117 final ComponentName cn = filter.activity.getComponentName(); 15118 final String packageName = cn.getPackageName(); 15119 15120 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15121 packageName); 15122 if (ivi == null) { 15123 return true; 15124 } 15125 int status = ivi.getStatus(); 15126 switch (status) { 15127 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15128 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15129 return true; 15130 15131 default: 15132 // Nothing to do 15133 return false; 15134 } 15135 } 15136 15137 private static boolean isMultiArch(ApplicationInfo info) { 15138 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15139 } 15140 15141 private static boolean isExternal(PackageParser.Package pkg) { 15142 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15143 } 15144 15145 private static boolean isExternal(PackageSetting ps) { 15146 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15147 } 15148 15149 private static boolean isEphemeral(PackageParser.Package pkg) { 15150 return pkg.applicationInfo.isEphemeralApp(); 15151 } 15152 15153 private static boolean isEphemeral(PackageSetting ps) { 15154 return ps.pkg != null && isEphemeral(ps.pkg); 15155 } 15156 15157 private static boolean isSystemApp(PackageParser.Package pkg) { 15158 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15159 } 15160 15161 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15162 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15163 } 15164 15165 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15166 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15167 } 15168 15169 private static boolean isSystemApp(PackageSetting ps) { 15170 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15171 } 15172 15173 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15174 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15175 } 15176 15177 private int packageFlagsToInstallFlags(PackageSetting ps) { 15178 int installFlags = 0; 15179 if (isEphemeral(ps)) { 15180 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15181 } 15182 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15183 // This existing package was an external ASEC install when we have 15184 // the external flag without a UUID 15185 installFlags |= PackageManager.INSTALL_EXTERNAL; 15186 } 15187 if (ps.isForwardLocked()) { 15188 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15189 } 15190 return installFlags; 15191 } 15192 15193 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15194 if (isExternal(pkg)) { 15195 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15196 return StorageManager.UUID_PRIMARY_PHYSICAL; 15197 } else { 15198 return pkg.volumeUuid; 15199 } 15200 } else { 15201 return StorageManager.UUID_PRIVATE_INTERNAL; 15202 } 15203 } 15204 15205 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15206 if (isExternal(pkg)) { 15207 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15208 return mSettings.getExternalVersion(); 15209 } else { 15210 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15211 } 15212 } else { 15213 return mSettings.getInternalVersion(); 15214 } 15215 } 15216 15217 private void deleteTempPackageFiles() { 15218 final FilenameFilter filter = new FilenameFilter() { 15219 public boolean accept(File dir, String name) { 15220 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15221 } 15222 }; 15223 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15224 file.delete(); 15225 } 15226 } 15227 15228 @Override 15229 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15230 int flags) { 15231 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15232 flags); 15233 } 15234 15235 @Override 15236 public void deletePackage(final String packageName, 15237 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15238 mContext.enforceCallingOrSelfPermission( 15239 android.Manifest.permission.DELETE_PACKAGES, null); 15240 Preconditions.checkNotNull(packageName); 15241 Preconditions.checkNotNull(observer); 15242 final int uid = Binder.getCallingUid(); 15243 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15244 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15245 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15246 mContext.enforceCallingOrSelfPermission( 15247 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15248 "deletePackage for user " + userId); 15249 } 15250 15251 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15252 try { 15253 observer.onPackageDeleted(packageName, 15254 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15255 } catch (RemoteException re) { 15256 } 15257 return; 15258 } 15259 15260 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15261 try { 15262 observer.onPackageDeleted(packageName, 15263 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15264 } catch (RemoteException re) { 15265 } 15266 return; 15267 } 15268 15269 if (DEBUG_REMOVE) { 15270 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15271 + " deleteAllUsers: " + deleteAllUsers ); 15272 } 15273 // Queue up an async operation since the package deletion may take a little while. 15274 mHandler.post(new Runnable() { 15275 public void run() { 15276 mHandler.removeCallbacks(this); 15277 int returnCode; 15278 if (!deleteAllUsers) { 15279 returnCode = deletePackageX(packageName, userId, deleteFlags); 15280 } else { 15281 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15282 // If nobody is blocking uninstall, proceed with delete for all users 15283 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15284 returnCode = deletePackageX(packageName, userId, deleteFlags); 15285 } else { 15286 // Otherwise uninstall individually for users with blockUninstalls=false 15287 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15288 for (int userId : users) { 15289 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15290 returnCode = deletePackageX(packageName, userId, userFlags); 15291 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15292 Slog.w(TAG, "Package delete failed for user " + userId 15293 + ", returnCode " + returnCode); 15294 } 15295 } 15296 } 15297 // The app has only been marked uninstalled for certain users. 15298 // We still need to report that delete was blocked 15299 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15300 } 15301 } 15302 try { 15303 observer.onPackageDeleted(packageName, returnCode, null); 15304 } catch (RemoteException e) { 15305 Log.i(TAG, "Observer no longer exists."); 15306 } //end catch 15307 } //end run 15308 }); 15309 } 15310 15311 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15312 int[] result = EMPTY_INT_ARRAY; 15313 for (int userId : userIds) { 15314 if (getBlockUninstallForUser(packageName, userId)) { 15315 result = ArrayUtils.appendInt(result, userId); 15316 } 15317 } 15318 return result; 15319 } 15320 15321 @Override 15322 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15323 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15324 } 15325 15326 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15327 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15328 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15329 try { 15330 if (dpm != null) { 15331 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15332 /* callingUserOnly =*/ false); 15333 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15334 : deviceOwnerComponentName.getPackageName(); 15335 // Does the package contains the device owner? 15336 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15337 // this check is probably not needed, since DO should be registered as a device 15338 // admin on some user too. (Original bug for this: b/17657954) 15339 if (packageName.equals(deviceOwnerPackageName)) { 15340 return true; 15341 } 15342 // Does it contain a device admin for any user? 15343 int[] users; 15344 if (userId == UserHandle.USER_ALL) { 15345 users = sUserManager.getUserIds(); 15346 } else { 15347 users = new int[]{userId}; 15348 } 15349 for (int i = 0; i < users.length; ++i) { 15350 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15351 return true; 15352 } 15353 } 15354 } 15355 } catch (RemoteException e) { 15356 } 15357 return false; 15358 } 15359 15360 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15361 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15362 } 15363 15364 /** 15365 * This method is an internal method that could be get invoked either 15366 * to delete an installed package or to clean up a failed installation. 15367 * After deleting an installed package, a broadcast is sent to notify any 15368 * listeners that the package has been removed. For cleaning up a failed 15369 * installation, the broadcast is not necessary since the package's 15370 * installation wouldn't have sent the initial broadcast either 15371 * The key steps in deleting a package are 15372 * deleting the package information in internal structures like mPackages, 15373 * deleting the packages base directories through installd 15374 * updating mSettings to reflect current status 15375 * persisting settings for later use 15376 * sending a broadcast if necessary 15377 */ 15378 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15379 final PackageRemovedInfo info = new PackageRemovedInfo(); 15380 final boolean res; 15381 15382 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15383 ? UserHandle.ALL : new UserHandle(userId); 15384 15385 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15386 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15387 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15388 } 15389 15390 PackageSetting uninstalledPs = null; 15391 15392 // for the uninstall-updates case and restricted profiles, remember the per- 15393 // user handle installed state 15394 int[] allUsers; 15395 synchronized (mPackages) { 15396 uninstalledPs = mSettings.mPackages.get(packageName); 15397 if (uninstalledPs == null) { 15398 Slog.w(TAG, "Not removing non-existent package " + packageName); 15399 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15400 } 15401 allUsers = sUserManager.getUserIds(); 15402 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15403 } 15404 15405 synchronized (mInstallLock) { 15406 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15407 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15408 "deletePackageX")) { 15409 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15410 deleteFlags | REMOVE_CHATTY, info, true, null); 15411 } 15412 synchronized (mPackages) { 15413 if (res) { 15414 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15415 } 15416 } 15417 } 15418 15419 if (res) { 15420 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15421 info.sendPackageRemovedBroadcasts(killApp); 15422 info.sendSystemPackageUpdatedBroadcasts(); 15423 info.sendSystemPackageAppearedBroadcasts(); 15424 } 15425 // Force a gc here. 15426 Runtime.getRuntime().gc(); 15427 // Delete the resources here after sending the broadcast to let 15428 // other processes clean up before deleting resources. 15429 if (info.args != null) { 15430 synchronized (mInstallLock) { 15431 info.args.doPostDeleteLI(true); 15432 } 15433 } 15434 15435 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15436 } 15437 15438 class PackageRemovedInfo { 15439 String removedPackage; 15440 int uid = -1; 15441 int removedAppId = -1; 15442 int[] origUsers; 15443 int[] removedUsers = null; 15444 boolean isRemovedPackageSystemUpdate = false; 15445 boolean isUpdate; 15446 boolean dataRemoved; 15447 boolean removedForAllUsers; 15448 // Clean up resources deleted packages. 15449 InstallArgs args = null; 15450 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15451 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15452 15453 void sendPackageRemovedBroadcasts(boolean killApp) { 15454 sendPackageRemovedBroadcastInternal(killApp); 15455 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15456 for (int i = 0; i < childCount; i++) { 15457 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15458 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15459 } 15460 } 15461 15462 void sendSystemPackageUpdatedBroadcasts() { 15463 if (isRemovedPackageSystemUpdate) { 15464 sendSystemPackageUpdatedBroadcastsInternal(); 15465 final int childCount = (removedChildPackages != null) 15466 ? removedChildPackages.size() : 0; 15467 for (int i = 0; i < childCount; i++) { 15468 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15469 if (childInfo.isRemovedPackageSystemUpdate) { 15470 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15471 } 15472 } 15473 } 15474 } 15475 15476 void sendSystemPackageAppearedBroadcasts() { 15477 final int packageCount = (appearedChildPackages != null) 15478 ? appearedChildPackages.size() : 0; 15479 for (int i = 0; i < packageCount; i++) { 15480 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15481 for (int userId : installedInfo.newUsers) { 15482 sendPackageAddedForUser(installedInfo.name, true, 15483 UserHandle.getAppId(installedInfo.uid), userId); 15484 } 15485 } 15486 } 15487 15488 private void sendSystemPackageUpdatedBroadcastsInternal() { 15489 Bundle extras = new Bundle(2); 15490 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15491 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15492 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15493 extras, 0, null, null, null); 15494 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15495 extras, 0, null, null, null); 15496 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15497 null, 0, removedPackage, null, null); 15498 } 15499 15500 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15501 Bundle extras = new Bundle(2); 15502 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15503 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15504 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15505 if (isUpdate || isRemovedPackageSystemUpdate) { 15506 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15507 } 15508 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15509 if (removedPackage != null) { 15510 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15511 extras, 0, null, null, removedUsers); 15512 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15513 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15514 removedPackage, extras, 0, null, null, removedUsers); 15515 } 15516 } 15517 if (removedAppId >= 0) { 15518 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15519 removedUsers); 15520 } 15521 } 15522 } 15523 15524 /* 15525 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15526 * flag is not set, the data directory is removed as well. 15527 * make sure this flag is set for partially installed apps. If not its meaningless to 15528 * delete a partially installed application. 15529 */ 15530 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15531 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15532 String packageName = ps.name; 15533 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15534 // Retrieve object to delete permissions for shared user later on 15535 final PackageParser.Package deletedPkg; 15536 final PackageSetting deletedPs; 15537 // reader 15538 synchronized (mPackages) { 15539 deletedPkg = mPackages.get(packageName); 15540 deletedPs = mSettings.mPackages.get(packageName); 15541 if (outInfo != null) { 15542 outInfo.removedPackage = packageName; 15543 outInfo.removedUsers = deletedPs != null 15544 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15545 : null; 15546 } 15547 } 15548 15549 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15550 15551 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15552 final PackageParser.Package resolvedPkg; 15553 if (deletedPkg != null) { 15554 resolvedPkg = deletedPkg; 15555 } else { 15556 // We don't have a parsed package when it lives on an ejected 15557 // adopted storage device, so fake something together 15558 resolvedPkg = new PackageParser.Package(ps.name); 15559 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15560 } 15561 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15562 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15563 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15564 if (outInfo != null) { 15565 outInfo.dataRemoved = true; 15566 } 15567 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15568 } 15569 15570 // writer 15571 synchronized (mPackages) { 15572 if (deletedPs != null) { 15573 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15574 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15575 clearDefaultBrowserIfNeeded(packageName); 15576 if (outInfo != null) { 15577 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15578 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15579 } 15580 updatePermissionsLPw(deletedPs.name, null, 0); 15581 if (deletedPs.sharedUser != null) { 15582 // Remove permissions associated with package. Since runtime 15583 // permissions are per user we have to kill the removed package 15584 // or packages running under the shared user of the removed 15585 // package if revoking the permissions requested only by the removed 15586 // package is successful and this causes a change in gids. 15587 for (int userId : UserManagerService.getInstance().getUserIds()) { 15588 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15589 userId); 15590 if (userIdToKill == UserHandle.USER_ALL 15591 || userIdToKill >= UserHandle.USER_SYSTEM) { 15592 // If gids changed for this user, kill all affected packages. 15593 mHandler.post(new Runnable() { 15594 @Override 15595 public void run() { 15596 // This has to happen with no lock held. 15597 killApplication(deletedPs.name, deletedPs.appId, 15598 KILL_APP_REASON_GIDS_CHANGED); 15599 } 15600 }); 15601 break; 15602 } 15603 } 15604 } 15605 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15606 } 15607 // make sure to preserve per-user disabled state if this removal was just 15608 // a downgrade of a system app to the factory package 15609 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15610 if (DEBUG_REMOVE) { 15611 Slog.d(TAG, "Propagating install state across downgrade"); 15612 } 15613 for (int userId : allUserHandles) { 15614 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15615 if (DEBUG_REMOVE) { 15616 Slog.d(TAG, " user " + userId + " => " + installed); 15617 } 15618 ps.setInstalled(installed, userId); 15619 } 15620 } 15621 } 15622 // can downgrade to reader 15623 if (writeSettings) { 15624 // Save settings now 15625 mSettings.writeLPr(); 15626 } 15627 } 15628 if (outInfo != null) { 15629 // A user ID was deleted here. Go through all users and remove it 15630 // from KeyStore. 15631 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15632 } 15633 } 15634 15635 static boolean locationIsPrivileged(File path) { 15636 try { 15637 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15638 .getCanonicalPath(); 15639 return path.getCanonicalPath().startsWith(privilegedAppDir); 15640 } catch (IOException e) { 15641 Slog.e(TAG, "Unable to access code path " + path); 15642 } 15643 return false; 15644 } 15645 15646 /* 15647 * Tries to delete system package. 15648 */ 15649 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15650 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15651 boolean writeSettings) { 15652 if (deletedPs.parentPackageName != null) { 15653 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15654 return false; 15655 } 15656 15657 final boolean applyUserRestrictions 15658 = (allUserHandles != null) && (outInfo.origUsers != null); 15659 final PackageSetting disabledPs; 15660 // Confirm if the system package has been updated 15661 // An updated system app can be deleted. This will also have to restore 15662 // the system pkg from system partition 15663 // reader 15664 synchronized (mPackages) { 15665 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15666 } 15667 15668 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15669 + " disabledPs=" + disabledPs); 15670 15671 if (disabledPs == null) { 15672 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15673 return false; 15674 } else if (DEBUG_REMOVE) { 15675 Slog.d(TAG, "Deleting system pkg from data partition"); 15676 } 15677 15678 if (DEBUG_REMOVE) { 15679 if (applyUserRestrictions) { 15680 Slog.d(TAG, "Remembering install states:"); 15681 for (int userId : allUserHandles) { 15682 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15683 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15684 } 15685 } 15686 } 15687 15688 // Delete the updated package 15689 outInfo.isRemovedPackageSystemUpdate = true; 15690 if (outInfo.removedChildPackages != null) { 15691 final int childCount = (deletedPs.childPackageNames != null) 15692 ? deletedPs.childPackageNames.size() : 0; 15693 for (int i = 0; i < childCount; i++) { 15694 String childPackageName = deletedPs.childPackageNames.get(i); 15695 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15696 .contains(childPackageName)) { 15697 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15698 childPackageName); 15699 if (childInfo != null) { 15700 childInfo.isRemovedPackageSystemUpdate = true; 15701 } 15702 } 15703 } 15704 } 15705 15706 if (disabledPs.versionCode < deletedPs.versionCode) { 15707 // Delete data for downgrades 15708 flags &= ~PackageManager.DELETE_KEEP_DATA; 15709 } else { 15710 // Preserve data by setting flag 15711 flags |= PackageManager.DELETE_KEEP_DATA; 15712 } 15713 15714 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15715 outInfo, writeSettings, disabledPs.pkg); 15716 if (!ret) { 15717 return false; 15718 } 15719 15720 // writer 15721 synchronized (mPackages) { 15722 // Reinstate the old system package 15723 enableSystemPackageLPw(disabledPs.pkg); 15724 // Remove any native libraries from the upgraded package. 15725 removeNativeBinariesLI(deletedPs); 15726 } 15727 15728 // Install the system package 15729 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15730 int parseFlags = mDefParseFlags 15731 | PackageParser.PARSE_MUST_BE_APK 15732 | PackageParser.PARSE_IS_SYSTEM 15733 | PackageParser.PARSE_IS_SYSTEM_DIR; 15734 if (locationIsPrivileged(disabledPs.codePath)) { 15735 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15736 } 15737 15738 final PackageParser.Package newPkg; 15739 try { 15740 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15741 } catch (PackageManagerException e) { 15742 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15743 + e.getMessage()); 15744 return false; 15745 } 15746 15747 prepareAppDataAfterInstallLIF(newPkg); 15748 15749 // writer 15750 synchronized (mPackages) { 15751 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15752 15753 // Propagate the permissions state as we do not want to drop on the floor 15754 // runtime permissions. The update permissions method below will take 15755 // care of removing obsolete permissions and grant install permissions. 15756 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15757 updatePermissionsLPw(newPkg.packageName, newPkg, 15758 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15759 15760 if (applyUserRestrictions) { 15761 if (DEBUG_REMOVE) { 15762 Slog.d(TAG, "Propagating install state across reinstall"); 15763 } 15764 for (int userId : allUserHandles) { 15765 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15766 if (DEBUG_REMOVE) { 15767 Slog.d(TAG, " user " + userId + " => " + installed); 15768 } 15769 ps.setInstalled(installed, userId); 15770 15771 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15772 } 15773 // Regardless of writeSettings we need to ensure that this restriction 15774 // state propagation is persisted 15775 mSettings.writeAllUsersPackageRestrictionsLPr(); 15776 } 15777 // can downgrade to reader here 15778 if (writeSettings) { 15779 mSettings.writeLPr(); 15780 } 15781 } 15782 return true; 15783 } 15784 15785 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15786 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15787 PackageRemovedInfo outInfo, boolean writeSettings, 15788 PackageParser.Package replacingPackage) { 15789 synchronized (mPackages) { 15790 if (outInfo != null) { 15791 outInfo.uid = ps.appId; 15792 } 15793 15794 if (outInfo != null && outInfo.removedChildPackages != null) { 15795 final int childCount = (ps.childPackageNames != null) 15796 ? ps.childPackageNames.size() : 0; 15797 for (int i = 0; i < childCount; i++) { 15798 String childPackageName = ps.childPackageNames.get(i); 15799 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15800 if (childPs == null) { 15801 return false; 15802 } 15803 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15804 childPackageName); 15805 if (childInfo != null) { 15806 childInfo.uid = childPs.appId; 15807 } 15808 } 15809 } 15810 } 15811 15812 // Delete package data from internal structures and also remove data if flag is set 15813 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15814 15815 // Delete the child packages data 15816 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15817 for (int i = 0; i < childCount; i++) { 15818 PackageSetting childPs; 15819 synchronized (mPackages) { 15820 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15821 } 15822 if (childPs != null) { 15823 PackageRemovedInfo childOutInfo = (outInfo != null 15824 && outInfo.removedChildPackages != null) 15825 ? outInfo.removedChildPackages.get(childPs.name) : null; 15826 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15827 && (replacingPackage != null 15828 && !replacingPackage.hasChildPackage(childPs.name)) 15829 ? flags & ~DELETE_KEEP_DATA : flags; 15830 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15831 deleteFlags, writeSettings); 15832 } 15833 } 15834 15835 // Delete application code and resources only for parent packages 15836 if (ps.parentPackageName == null) { 15837 if (deleteCodeAndResources && (outInfo != null)) { 15838 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15839 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15840 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15841 } 15842 } 15843 15844 return true; 15845 } 15846 15847 @Override 15848 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15849 int userId) { 15850 mContext.enforceCallingOrSelfPermission( 15851 android.Manifest.permission.DELETE_PACKAGES, null); 15852 synchronized (mPackages) { 15853 PackageSetting ps = mSettings.mPackages.get(packageName); 15854 if (ps == null) { 15855 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15856 return false; 15857 } 15858 if (!ps.getInstalled(userId)) { 15859 // Can't block uninstall for an app that is not installed or enabled. 15860 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15861 return false; 15862 } 15863 ps.setBlockUninstall(blockUninstall, userId); 15864 mSettings.writePackageRestrictionsLPr(userId); 15865 } 15866 return true; 15867 } 15868 15869 @Override 15870 public boolean getBlockUninstallForUser(String packageName, int userId) { 15871 synchronized (mPackages) { 15872 PackageSetting ps = mSettings.mPackages.get(packageName); 15873 if (ps == null) { 15874 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15875 return false; 15876 } 15877 return ps.getBlockUninstall(userId); 15878 } 15879 } 15880 15881 @Override 15882 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15883 int callingUid = Binder.getCallingUid(); 15884 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15885 throw new SecurityException( 15886 "setRequiredForSystemUser can only be run by the system or root"); 15887 } 15888 synchronized (mPackages) { 15889 PackageSetting ps = mSettings.mPackages.get(packageName); 15890 if (ps == null) { 15891 Log.w(TAG, "Package doesn't exist: " + packageName); 15892 return false; 15893 } 15894 if (systemUserApp) { 15895 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15896 } else { 15897 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15898 } 15899 mSettings.writeLPr(); 15900 } 15901 return true; 15902 } 15903 15904 /* 15905 * This method handles package deletion in general 15906 */ 15907 private boolean deletePackageLIF(String packageName, UserHandle user, 15908 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15909 PackageRemovedInfo outInfo, boolean writeSettings, 15910 PackageParser.Package replacingPackage) { 15911 if (packageName == null) { 15912 Slog.w(TAG, "Attempt to delete null packageName."); 15913 return false; 15914 } 15915 15916 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15917 15918 PackageSetting ps; 15919 15920 synchronized (mPackages) { 15921 ps = mSettings.mPackages.get(packageName); 15922 if (ps == null) { 15923 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15924 return false; 15925 } 15926 15927 if (ps.parentPackageName != null && (!isSystemApp(ps) 15928 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15929 if (DEBUG_REMOVE) { 15930 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15931 + ((user == null) ? UserHandle.USER_ALL : user)); 15932 } 15933 final int removedUserId = (user != null) ? user.getIdentifier() 15934 : UserHandle.USER_ALL; 15935 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15936 return false; 15937 } 15938 markPackageUninstalledForUserLPw(ps, user); 15939 scheduleWritePackageRestrictionsLocked(user); 15940 return true; 15941 } 15942 } 15943 15944 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15945 && user.getIdentifier() != UserHandle.USER_ALL)) { 15946 // The caller is asking that the package only be deleted for a single 15947 // user. To do this, we just mark its uninstalled state and delete 15948 // its data. If this is a system app, we only allow this to happen if 15949 // they have set the special DELETE_SYSTEM_APP which requests different 15950 // semantics than normal for uninstalling system apps. 15951 markPackageUninstalledForUserLPw(ps, user); 15952 15953 if (!isSystemApp(ps)) { 15954 // Do not uninstall the APK if an app should be cached 15955 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15956 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15957 // Other user still have this package installed, so all 15958 // we need to do is clear this user's data and save that 15959 // it is uninstalled. 15960 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15961 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15962 return false; 15963 } 15964 scheduleWritePackageRestrictionsLocked(user); 15965 return true; 15966 } else { 15967 // We need to set it back to 'installed' so the uninstall 15968 // broadcasts will be sent correctly. 15969 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15970 ps.setInstalled(true, user.getIdentifier()); 15971 } 15972 } else { 15973 // This is a system app, so we assume that the 15974 // other users still have this package installed, so all 15975 // we need to do is clear this user's data and save that 15976 // it is uninstalled. 15977 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15978 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15979 return false; 15980 } 15981 scheduleWritePackageRestrictionsLocked(user); 15982 return true; 15983 } 15984 } 15985 15986 // If we are deleting a composite package for all users, keep track 15987 // of result for each child. 15988 if (ps.childPackageNames != null && outInfo != null) { 15989 synchronized (mPackages) { 15990 final int childCount = ps.childPackageNames.size(); 15991 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15992 for (int i = 0; i < childCount; i++) { 15993 String childPackageName = ps.childPackageNames.get(i); 15994 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15995 childInfo.removedPackage = childPackageName; 15996 outInfo.removedChildPackages.put(childPackageName, childInfo); 15997 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15998 if (childPs != null) { 15999 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16000 } 16001 } 16002 } 16003 } 16004 16005 boolean ret = false; 16006 if (isSystemApp(ps)) { 16007 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16008 // When an updated system application is deleted we delete the existing resources 16009 // as well and fall back to existing code in system partition 16010 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16011 } else { 16012 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16013 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16014 outInfo, writeSettings, replacingPackage); 16015 } 16016 16017 // Take a note whether we deleted the package for all users 16018 if (outInfo != null) { 16019 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16020 if (outInfo.removedChildPackages != null) { 16021 synchronized (mPackages) { 16022 final int childCount = outInfo.removedChildPackages.size(); 16023 for (int i = 0; i < childCount; i++) { 16024 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16025 if (childInfo != null) { 16026 childInfo.removedForAllUsers = mPackages.get( 16027 childInfo.removedPackage) == null; 16028 } 16029 } 16030 } 16031 } 16032 // If we uninstalled an update to a system app there may be some 16033 // child packages that appeared as they are declared in the system 16034 // app but were not declared in the update. 16035 if (isSystemApp(ps)) { 16036 synchronized (mPackages) { 16037 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16038 final int childCount = (updatedPs.childPackageNames != null) 16039 ? updatedPs.childPackageNames.size() : 0; 16040 for (int i = 0; i < childCount; i++) { 16041 String childPackageName = updatedPs.childPackageNames.get(i); 16042 if (outInfo.removedChildPackages == null 16043 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16044 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16045 if (childPs == null) { 16046 continue; 16047 } 16048 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16049 installRes.name = childPackageName; 16050 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16051 installRes.pkg = mPackages.get(childPackageName); 16052 installRes.uid = childPs.pkg.applicationInfo.uid; 16053 if (outInfo.appearedChildPackages == null) { 16054 outInfo.appearedChildPackages = new ArrayMap<>(); 16055 } 16056 outInfo.appearedChildPackages.put(childPackageName, installRes); 16057 } 16058 } 16059 } 16060 } 16061 } 16062 16063 return ret; 16064 } 16065 16066 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16067 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16068 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16069 for (int nextUserId : userIds) { 16070 if (DEBUG_REMOVE) { 16071 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16072 } 16073 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16074 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16075 false /*hidden*/, false /*suspended*/, null, null, null, 16076 false /*blockUninstall*/, 16077 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16078 } 16079 } 16080 16081 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16082 PackageRemovedInfo outInfo) { 16083 final PackageParser.Package pkg; 16084 synchronized (mPackages) { 16085 pkg = mPackages.get(ps.name); 16086 } 16087 16088 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16089 : new int[] {userId}; 16090 for (int nextUserId : userIds) { 16091 if (DEBUG_REMOVE) { 16092 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16093 + nextUserId); 16094 } 16095 16096 destroyAppDataLIF(pkg, userId, 16097 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16098 destroyAppProfilesLIF(pkg, userId); 16099 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16100 schedulePackageCleaning(ps.name, nextUserId, false); 16101 synchronized (mPackages) { 16102 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16103 scheduleWritePackageRestrictionsLocked(nextUserId); 16104 } 16105 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16106 } 16107 } 16108 16109 if (outInfo != null) { 16110 outInfo.removedPackage = ps.name; 16111 outInfo.removedAppId = ps.appId; 16112 outInfo.removedUsers = userIds; 16113 } 16114 16115 return true; 16116 } 16117 16118 private final class ClearStorageConnection implements ServiceConnection { 16119 IMediaContainerService mContainerService; 16120 16121 @Override 16122 public void onServiceConnected(ComponentName name, IBinder service) { 16123 synchronized (this) { 16124 mContainerService = IMediaContainerService.Stub.asInterface(service); 16125 notifyAll(); 16126 } 16127 } 16128 16129 @Override 16130 public void onServiceDisconnected(ComponentName name) { 16131 } 16132 } 16133 16134 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16135 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16136 16137 final boolean mounted; 16138 if (Environment.isExternalStorageEmulated()) { 16139 mounted = true; 16140 } else { 16141 final String status = Environment.getExternalStorageState(); 16142 16143 mounted = status.equals(Environment.MEDIA_MOUNTED) 16144 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16145 } 16146 16147 if (!mounted) { 16148 return; 16149 } 16150 16151 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16152 int[] users; 16153 if (userId == UserHandle.USER_ALL) { 16154 users = sUserManager.getUserIds(); 16155 } else { 16156 users = new int[] { userId }; 16157 } 16158 final ClearStorageConnection conn = new ClearStorageConnection(); 16159 if (mContext.bindServiceAsUser( 16160 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16161 try { 16162 for (int curUser : users) { 16163 long timeout = SystemClock.uptimeMillis() + 5000; 16164 synchronized (conn) { 16165 long now = SystemClock.uptimeMillis(); 16166 while (conn.mContainerService == null && now < timeout) { 16167 try { 16168 conn.wait(timeout - now); 16169 } catch (InterruptedException e) { 16170 } 16171 } 16172 } 16173 if (conn.mContainerService == null) { 16174 return; 16175 } 16176 16177 final UserEnvironment userEnv = new UserEnvironment(curUser); 16178 clearDirectory(conn.mContainerService, 16179 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16180 if (allData) { 16181 clearDirectory(conn.mContainerService, 16182 userEnv.buildExternalStorageAppDataDirs(packageName)); 16183 clearDirectory(conn.mContainerService, 16184 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16185 } 16186 } 16187 } finally { 16188 mContext.unbindService(conn); 16189 } 16190 } 16191 } 16192 16193 @Override 16194 public void clearApplicationProfileData(String packageName) { 16195 enforceSystemOrRoot("Only the system can clear all profile data"); 16196 16197 final PackageParser.Package pkg; 16198 synchronized (mPackages) { 16199 pkg = mPackages.get(packageName); 16200 } 16201 16202 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16203 synchronized (mInstallLock) { 16204 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16205 } 16206 } 16207 } 16208 16209 @Override 16210 public void clearApplicationUserData(final String packageName, 16211 final IPackageDataObserver observer, final int userId) { 16212 mContext.enforceCallingOrSelfPermission( 16213 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16214 16215 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16216 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16217 16218 final DevicePolicyManagerInternal dpmi = LocalServices 16219 .getService(DevicePolicyManagerInternal.class); 16220 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16221 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16222 } 16223 // Queue up an async operation since the package deletion may take a little while. 16224 mHandler.post(new Runnable() { 16225 public void run() { 16226 mHandler.removeCallbacks(this); 16227 final boolean succeeded; 16228 try (PackageFreezer freezer = freezePackage(packageName, 16229 "clearApplicationUserData")) { 16230 synchronized (mInstallLock) { 16231 succeeded = clearApplicationUserDataLIF(packageName, userId); 16232 } 16233 clearExternalStorageDataSync(packageName, userId, true); 16234 } 16235 if (succeeded) { 16236 // invoke DeviceStorageMonitor's update method to clear any notifications 16237 DeviceStorageMonitorInternal dsm = LocalServices 16238 .getService(DeviceStorageMonitorInternal.class); 16239 if (dsm != null) { 16240 dsm.checkMemory(); 16241 } 16242 } 16243 if(observer != null) { 16244 try { 16245 observer.onRemoveCompleted(packageName, succeeded); 16246 } catch (RemoteException e) { 16247 Log.i(TAG, "Observer no longer exists."); 16248 } 16249 } //end if observer 16250 } //end run 16251 }); 16252 } 16253 16254 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16255 if (packageName == null) { 16256 Slog.w(TAG, "Attempt to delete null packageName."); 16257 return false; 16258 } 16259 16260 // Try finding details about the requested package 16261 PackageParser.Package pkg; 16262 synchronized (mPackages) { 16263 pkg = mPackages.get(packageName); 16264 if (pkg == null) { 16265 final PackageSetting ps = mSettings.mPackages.get(packageName); 16266 if (ps != null) { 16267 pkg = ps.pkg; 16268 } 16269 } 16270 16271 if (pkg == null) { 16272 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16273 return false; 16274 } 16275 16276 PackageSetting ps = (PackageSetting) pkg.mExtras; 16277 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16278 } 16279 16280 clearAppDataLIF(pkg, userId, 16281 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16282 16283 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16284 removeKeystoreDataIfNeeded(userId, appId); 16285 16286 final UserManager um = mContext.getSystemService(UserManager.class); 16287 final int flags; 16288 if (um.isUserUnlockingOrUnlocked(userId)) { 16289 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16290 } else if (um.isUserRunning(userId)) { 16291 flags = StorageManager.FLAG_STORAGE_DE; 16292 } else { 16293 flags = 0; 16294 } 16295 prepareAppDataContentsLIF(pkg, userId, flags); 16296 16297 return true; 16298 } 16299 16300 /** 16301 * Reverts user permission state changes (permissions and flags) in 16302 * all packages for a given user. 16303 * 16304 * @param userId The device user for which to do a reset. 16305 */ 16306 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16307 final int packageCount = mPackages.size(); 16308 for (int i = 0; i < packageCount; i++) { 16309 PackageParser.Package pkg = mPackages.valueAt(i); 16310 PackageSetting ps = (PackageSetting) pkg.mExtras; 16311 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16312 } 16313 } 16314 16315 private void resetNetworkPolicies(int userId) { 16316 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16317 } 16318 16319 /** 16320 * Reverts user permission state changes (permissions and flags). 16321 * 16322 * @param ps The package for which to reset. 16323 * @param userId The device user for which to do a reset. 16324 */ 16325 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16326 final PackageSetting ps, final int userId) { 16327 if (ps.pkg == null) { 16328 return; 16329 } 16330 16331 // These are flags that can change base on user actions. 16332 final int userSettableMask = FLAG_PERMISSION_USER_SET 16333 | FLAG_PERMISSION_USER_FIXED 16334 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16335 | FLAG_PERMISSION_REVIEW_REQUIRED; 16336 16337 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16338 | FLAG_PERMISSION_POLICY_FIXED; 16339 16340 boolean writeInstallPermissions = false; 16341 boolean writeRuntimePermissions = false; 16342 16343 final int permissionCount = ps.pkg.requestedPermissions.size(); 16344 for (int i = 0; i < permissionCount; i++) { 16345 String permission = ps.pkg.requestedPermissions.get(i); 16346 16347 BasePermission bp = mSettings.mPermissions.get(permission); 16348 if (bp == null) { 16349 continue; 16350 } 16351 16352 // If shared user we just reset the state to which only this app contributed. 16353 if (ps.sharedUser != null) { 16354 boolean used = false; 16355 final int packageCount = ps.sharedUser.packages.size(); 16356 for (int j = 0; j < packageCount; j++) { 16357 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16358 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16359 && pkg.pkg.requestedPermissions.contains(permission)) { 16360 used = true; 16361 break; 16362 } 16363 } 16364 if (used) { 16365 continue; 16366 } 16367 } 16368 16369 PermissionsState permissionsState = ps.getPermissionsState(); 16370 16371 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16372 16373 // Always clear the user settable flags. 16374 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16375 bp.name) != null; 16376 // If permission review is enabled and this is a legacy app, mark the 16377 // permission as requiring a review as this is the initial state. 16378 int flags = 0; 16379 if (Build.PERMISSIONS_REVIEW_REQUIRED 16380 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16381 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16382 } 16383 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16384 if (hasInstallState) { 16385 writeInstallPermissions = true; 16386 } else { 16387 writeRuntimePermissions = true; 16388 } 16389 } 16390 16391 // Below is only runtime permission handling. 16392 if (!bp.isRuntime()) { 16393 continue; 16394 } 16395 16396 // Never clobber system or policy. 16397 if ((oldFlags & policyOrSystemFlags) != 0) { 16398 continue; 16399 } 16400 16401 // If this permission was granted by default, make sure it is. 16402 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16403 if (permissionsState.grantRuntimePermission(bp, userId) 16404 != PERMISSION_OPERATION_FAILURE) { 16405 writeRuntimePermissions = true; 16406 } 16407 // If permission review is enabled the permissions for a legacy apps 16408 // are represented as constantly granted runtime ones, so don't revoke. 16409 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16410 // Otherwise, reset the permission. 16411 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16412 switch (revokeResult) { 16413 case PERMISSION_OPERATION_SUCCESS: 16414 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16415 writeRuntimePermissions = true; 16416 final int appId = ps.appId; 16417 mHandler.post(new Runnable() { 16418 @Override 16419 public void run() { 16420 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16421 } 16422 }); 16423 } break; 16424 } 16425 } 16426 } 16427 16428 // Synchronously write as we are taking permissions away. 16429 if (writeRuntimePermissions) { 16430 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16431 } 16432 16433 // Synchronously write as we are taking permissions away. 16434 if (writeInstallPermissions) { 16435 mSettings.writeLPr(); 16436 } 16437 } 16438 16439 /** 16440 * Remove entries from the keystore daemon. Will only remove it if the 16441 * {@code appId} is valid. 16442 */ 16443 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16444 if (appId < 0) { 16445 return; 16446 } 16447 16448 final KeyStore keyStore = KeyStore.getInstance(); 16449 if (keyStore != null) { 16450 if (userId == UserHandle.USER_ALL) { 16451 for (final int individual : sUserManager.getUserIds()) { 16452 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16453 } 16454 } else { 16455 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16456 } 16457 } else { 16458 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16459 } 16460 } 16461 16462 @Override 16463 public void deleteApplicationCacheFiles(final String packageName, 16464 final IPackageDataObserver observer) { 16465 final int userId = UserHandle.getCallingUserId(); 16466 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16467 } 16468 16469 @Override 16470 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16471 final IPackageDataObserver observer) { 16472 mContext.enforceCallingOrSelfPermission( 16473 android.Manifest.permission.DELETE_CACHE_FILES, null); 16474 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16475 /* requireFullPermission= */ true, /* checkShell= */ false, 16476 "delete application cache files"); 16477 16478 final PackageParser.Package pkg; 16479 synchronized (mPackages) { 16480 pkg = mPackages.get(packageName); 16481 } 16482 16483 // Queue up an async operation since the package deletion may take a little while. 16484 mHandler.post(new Runnable() { 16485 public void run() { 16486 synchronized (mInstallLock) { 16487 final int flags = StorageManager.FLAG_STORAGE_DE 16488 | StorageManager.FLAG_STORAGE_CE; 16489 // We're only clearing cache files, so we don't care if the 16490 // app is unfrozen and still able to run 16491 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16492 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16493 } 16494 clearExternalStorageDataSync(packageName, userId, false); 16495 if (observer != null) { 16496 try { 16497 observer.onRemoveCompleted(packageName, true); 16498 } catch (RemoteException e) { 16499 Log.i(TAG, "Observer no longer exists."); 16500 } 16501 } 16502 } 16503 }); 16504 } 16505 16506 @Override 16507 public void getPackageSizeInfo(final String packageName, int userHandle, 16508 final IPackageStatsObserver observer) { 16509 mContext.enforceCallingOrSelfPermission( 16510 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16511 if (packageName == null) { 16512 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16513 } 16514 16515 PackageStats stats = new PackageStats(packageName, userHandle); 16516 16517 /* 16518 * Queue up an async operation since the package measurement may take a 16519 * little while. 16520 */ 16521 Message msg = mHandler.obtainMessage(INIT_COPY); 16522 msg.obj = new MeasureParams(stats, observer); 16523 mHandler.sendMessage(msg); 16524 } 16525 16526 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16527 final PackageSetting ps; 16528 synchronized (mPackages) { 16529 ps = mSettings.mPackages.get(packageName); 16530 if (ps == null) { 16531 Slog.w(TAG, "Failed to find settings for " + packageName); 16532 return false; 16533 } 16534 } 16535 try { 16536 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16537 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16538 ps.getCeDataInode(userId), ps.codePathString, stats); 16539 } catch (InstallerException e) { 16540 Slog.w(TAG, String.valueOf(e)); 16541 return false; 16542 } 16543 16544 // For now, ignore code size of packages on system partition 16545 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16546 stats.codeSize = 0; 16547 } 16548 16549 return true; 16550 } 16551 16552 private int getUidTargetSdkVersionLockedLPr(int uid) { 16553 Object obj = mSettings.getUserIdLPr(uid); 16554 if (obj instanceof SharedUserSetting) { 16555 final SharedUserSetting sus = (SharedUserSetting) obj; 16556 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16557 final Iterator<PackageSetting> it = sus.packages.iterator(); 16558 while (it.hasNext()) { 16559 final PackageSetting ps = it.next(); 16560 if (ps.pkg != null) { 16561 int v = ps.pkg.applicationInfo.targetSdkVersion; 16562 if (v < vers) vers = v; 16563 } 16564 } 16565 return vers; 16566 } else if (obj instanceof PackageSetting) { 16567 final PackageSetting ps = (PackageSetting) obj; 16568 if (ps.pkg != null) { 16569 return ps.pkg.applicationInfo.targetSdkVersion; 16570 } 16571 } 16572 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16573 } 16574 16575 @Override 16576 public void addPreferredActivity(IntentFilter filter, int match, 16577 ComponentName[] set, ComponentName activity, int userId) { 16578 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16579 "Adding preferred"); 16580 } 16581 16582 private void addPreferredActivityInternal(IntentFilter filter, int match, 16583 ComponentName[] set, ComponentName activity, boolean always, int userId, 16584 String opname) { 16585 // writer 16586 int callingUid = Binder.getCallingUid(); 16587 enforceCrossUserPermission(callingUid, userId, 16588 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16589 if (filter.countActions() == 0) { 16590 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16591 return; 16592 } 16593 synchronized (mPackages) { 16594 if (mContext.checkCallingOrSelfPermission( 16595 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16596 != PackageManager.PERMISSION_GRANTED) { 16597 if (getUidTargetSdkVersionLockedLPr(callingUid) 16598 < Build.VERSION_CODES.FROYO) { 16599 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16600 + callingUid); 16601 return; 16602 } 16603 mContext.enforceCallingOrSelfPermission( 16604 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16605 } 16606 16607 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16608 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16609 + userId + ":"); 16610 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16611 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16612 scheduleWritePackageRestrictionsLocked(userId); 16613 } 16614 } 16615 16616 @Override 16617 public void replacePreferredActivity(IntentFilter filter, int match, 16618 ComponentName[] set, ComponentName activity, int userId) { 16619 if (filter.countActions() != 1) { 16620 throw new IllegalArgumentException( 16621 "replacePreferredActivity expects filter to have only 1 action."); 16622 } 16623 if (filter.countDataAuthorities() != 0 16624 || filter.countDataPaths() != 0 16625 || filter.countDataSchemes() > 1 16626 || filter.countDataTypes() != 0) { 16627 throw new IllegalArgumentException( 16628 "replacePreferredActivity expects filter to have no data authorities, " + 16629 "paths, or types; and at most one scheme."); 16630 } 16631 16632 final int callingUid = Binder.getCallingUid(); 16633 enforceCrossUserPermission(callingUid, userId, 16634 true /* requireFullPermission */, false /* checkShell */, 16635 "replace preferred activity"); 16636 synchronized (mPackages) { 16637 if (mContext.checkCallingOrSelfPermission( 16638 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16639 != PackageManager.PERMISSION_GRANTED) { 16640 if (getUidTargetSdkVersionLockedLPr(callingUid) 16641 < Build.VERSION_CODES.FROYO) { 16642 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16643 + Binder.getCallingUid()); 16644 return; 16645 } 16646 mContext.enforceCallingOrSelfPermission( 16647 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16648 } 16649 16650 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16651 if (pir != null) { 16652 // Get all of the existing entries that exactly match this filter. 16653 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16654 if (existing != null && existing.size() == 1) { 16655 PreferredActivity cur = existing.get(0); 16656 if (DEBUG_PREFERRED) { 16657 Slog.i(TAG, "Checking replace of preferred:"); 16658 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16659 if (!cur.mPref.mAlways) { 16660 Slog.i(TAG, " -- CUR; not mAlways!"); 16661 } else { 16662 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16663 Slog.i(TAG, " -- CUR: mSet=" 16664 + Arrays.toString(cur.mPref.mSetComponents)); 16665 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16666 Slog.i(TAG, " -- NEW: mMatch=" 16667 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16668 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16669 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16670 } 16671 } 16672 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16673 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16674 && cur.mPref.sameSet(set)) { 16675 // Setting the preferred activity to what it happens to be already 16676 if (DEBUG_PREFERRED) { 16677 Slog.i(TAG, "Replacing with same preferred activity " 16678 + cur.mPref.mShortComponent + " for user " 16679 + userId + ":"); 16680 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16681 } 16682 return; 16683 } 16684 } 16685 16686 if (existing != null) { 16687 if (DEBUG_PREFERRED) { 16688 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16689 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16690 } 16691 for (int i = 0; i < existing.size(); i++) { 16692 PreferredActivity pa = existing.get(i); 16693 if (DEBUG_PREFERRED) { 16694 Slog.i(TAG, "Removing existing preferred activity " 16695 + pa.mPref.mComponent + ":"); 16696 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16697 } 16698 pir.removeFilter(pa); 16699 } 16700 } 16701 } 16702 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16703 "Replacing preferred"); 16704 } 16705 } 16706 16707 @Override 16708 public void clearPackagePreferredActivities(String packageName) { 16709 final int uid = Binder.getCallingUid(); 16710 // writer 16711 synchronized (mPackages) { 16712 PackageParser.Package pkg = mPackages.get(packageName); 16713 if (pkg == null || pkg.applicationInfo.uid != uid) { 16714 if (mContext.checkCallingOrSelfPermission( 16715 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16716 != PackageManager.PERMISSION_GRANTED) { 16717 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16718 < Build.VERSION_CODES.FROYO) { 16719 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16720 + Binder.getCallingUid()); 16721 return; 16722 } 16723 mContext.enforceCallingOrSelfPermission( 16724 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16725 } 16726 } 16727 16728 int user = UserHandle.getCallingUserId(); 16729 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16730 scheduleWritePackageRestrictionsLocked(user); 16731 } 16732 } 16733 } 16734 16735 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16736 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16737 ArrayList<PreferredActivity> removed = null; 16738 boolean changed = false; 16739 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16740 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16741 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16742 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16743 continue; 16744 } 16745 Iterator<PreferredActivity> it = pir.filterIterator(); 16746 while (it.hasNext()) { 16747 PreferredActivity pa = it.next(); 16748 // Mark entry for removal only if it matches the package name 16749 // and the entry is of type "always". 16750 if (packageName == null || 16751 (pa.mPref.mComponent.getPackageName().equals(packageName) 16752 && pa.mPref.mAlways)) { 16753 if (removed == null) { 16754 removed = new ArrayList<PreferredActivity>(); 16755 } 16756 removed.add(pa); 16757 } 16758 } 16759 if (removed != null) { 16760 for (int j=0; j<removed.size(); j++) { 16761 PreferredActivity pa = removed.get(j); 16762 pir.removeFilter(pa); 16763 } 16764 changed = true; 16765 } 16766 } 16767 return changed; 16768 } 16769 16770 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16771 private void clearIntentFilterVerificationsLPw(int userId) { 16772 final int packageCount = mPackages.size(); 16773 for (int i = 0; i < packageCount; i++) { 16774 PackageParser.Package pkg = mPackages.valueAt(i); 16775 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16776 } 16777 } 16778 16779 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16780 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16781 if (userId == UserHandle.USER_ALL) { 16782 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16783 sUserManager.getUserIds())) { 16784 for (int oneUserId : sUserManager.getUserIds()) { 16785 scheduleWritePackageRestrictionsLocked(oneUserId); 16786 } 16787 } 16788 } else { 16789 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16790 scheduleWritePackageRestrictionsLocked(userId); 16791 } 16792 } 16793 } 16794 16795 void clearDefaultBrowserIfNeeded(String packageName) { 16796 for (int oneUserId : sUserManager.getUserIds()) { 16797 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16798 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16799 if (packageName.equals(defaultBrowserPackageName)) { 16800 setDefaultBrowserPackageName(null, oneUserId); 16801 } 16802 } 16803 } 16804 16805 @Override 16806 public void resetApplicationPreferences(int userId) { 16807 mContext.enforceCallingOrSelfPermission( 16808 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16809 final long identity = Binder.clearCallingIdentity(); 16810 // writer 16811 try { 16812 synchronized (mPackages) { 16813 clearPackagePreferredActivitiesLPw(null, userId); 16814 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16815 // TODO: We have to reset the default SMS and Phone. This requires 16816 // significant refactoring to keep all default apps in the package 16817 // manager (cleaner but more work) or have the services provide 16818 // callbacks to the package manager to request a default app reset. 16819 applyFactoryDefaultBrowserLPw(userId); 16820 clearIntentFilterVerificationsLPw(userId); 16821 primeDomainVerificationsLPw(userId); 16822 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16823 scheduleWritePackageRestrictionsLocked(userId); 16824 } 16825 resetNetworkPolicies(userId); 16826 } finally { 16827 Binder.restoreCallingIdentity(identity); 16828 } 16829 } 16830 16831 @Override 16832 public int getPreferredActivities(List<IntentFilter> outFilters, 16833 List<ComponentName> outActivities, String packageName) { 16834 16835 int num = 0; 16836 final int userId = UserHandle.getCallingUserId(); 16837 // reader 16838 synchronized (mPackages) { 16839 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16840 if (pir != null) { 16841 final Iterator<PreferredActivity> it = pir.filterIterator(); 16842 while (it.hasNext()) { 16843 final PreferredActivity pa = it.next(); 16844 if (packageName == null 16845 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16846 && pa.mPref.mAlways)) { 16847 if (outFilters != null) { 16848 outFilters.add(new IntentFilter(pa)); 16849 } 16850 if (outActivities != null) { 16851 outActivities.add(pa.mPref.mComponent); 16852 } 16853 } 16854 } 16855 } 16856 } 16857 16858 return num; 16859 } 16860 16861 @Override 16862 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16863 int userId) { 16864 int callingUid = Binder.getCallingUid(); 16865 if (callingUid != Process.SYSTEM_UID) { 16866 throw new SecurityException( 16867 "addPersistentPreferredActivity can only be run by the system"); 16868 } 16869 if (filter.countActions() == 0) { 16870 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16871 return; 16872 } 16873 synchronized (mPackages) { 16874 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16875 ":"); 16876 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16877 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16878 new PersistentPreferredActivity(filter, activity)); 16879 scheduleWritePackageRestrictionsLocked(userId); 16880 } 16881 } 16882 16883 @Override 16884 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16885 int callingUid = Binder.getCallingUid(); 16886 if (callingUid != Process.SYSTEM_UID) { 16887 throw new SecurityException( 16888 "clearPackagePersistentPreferredActivities can only be run by the system"); 16889 } 16890 ArrayList<PersistentPreferredActivity> removed = null; 16891 boolean changed = false; 16892 synchronized (mPackages) { 16893 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16894 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16895 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16896 .valueAt(i); 16897 if (userId != thisUserId) { 16898 continue; 16899 } 16900 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16901 while (it.hasNext()) { 16902 PersistentPreferredActivity ppa = it.next(); 16903 // Mark entry for removal only if it matches the package name. 16904 if (ppa.mComponent.getPackageName().equals(packageName)) { 16905 if (removed == null) { 16906 removed = new ArrayList<PersistentPreferredActivity>(); 16907 } 16908 removed.add(ppa); 16909 } 16910 } 16911 if (removed != null) { 16912 for (int j=0; j<removed.size(); j++) { 16913 PersistentPreferredActivity ppa = removed.get(j); 16914 ppir.removeFilter(ppa); 16915 } 16916 changed = true; 16917 } 16918 } 16919 16920 if (changed) { 16921 scheduleWritePackageRestrictionsLocked(userId); 16922 } 16923 } 16924 } 16925 16926 /** 16927 * Common machinery for picking apart a restored XML blob and passing 16928 * it to a caller-supplied functor to be applied to the running system. 16929 */ 16930 private void restoreFromXml(XmlPullParser parser, int userId, 16931 String expectedStartTag, BlobXmlRestorer functor) 16932 throws IOException, XmlPullParserException { 16933 int type; 16934 while ((type = parser.next()) != XmlPullParser.START_TAG 16935 && type != XmlPullParser.END_DOCUMENT) { 16936 } 16937 if (type != XmlPullParser.START_TAG) { 16938 // oops didn't find a start tag?! 16939 if (DEBUG_BACKUP) { 16940 Slog.e(TAG, "Didn't find start tag during restore"); 16941 } 16942 return; 16943 } 16944Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16945 // this is supposed to be TAG_PREFERRED_BACKUP 16946 if (!expectedStartTag.equals(parser.getName())) { 16947 if (DEBUG_BACKUP) { 16948 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16949 } 16950 return; 16951 } 16952 16953 // skip interfering stuff, then we're aligned with the backing implementation 16954 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16955Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16956 functor.apply(parser, userId); 16957 } 16958 16959 private interface BlobXmlRestorer { 16960 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16961 } 16962 16963 /** 16964 * Non-Binder method, support for the backup/restore mechanism: write the 16965 * full set of preferred activities in its canonical XML format. Returns the 16966 * XML output as a byte array, or null if there is none. 16967 */ 16968 @Override 16969 public byte[] getPreferredActivityBackup(int userId) { 16970 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16971 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16972 } 16973 16974 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16975 try { 16976 final XmlSerializer serializer = new FastXmlSerializer(); 16977 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16978 serializer.startDocument(null, true); 16979 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16980 16981 synchronized (mPackages) { 16982 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16983 } 16984 16985 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16986 serializer.endDocument(); 16987 serializer.flush(); 16988 } catch (Exception e) { 16989 if (DEBUG_BACKUP) { 16990 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16991 } 16992 return null; 16993 } 16994 16995 return dataStream.toByteArray(); 16996 } 16997 16998 @Override 16999 public void restorePreferredActivities(byte[] backup, int userId) { 17000 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17001 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17002 } 17003 17004 try { 17005 final XmlPullParser parser = Xml.newPullParser(); 17006 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17007 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17008 new BlobXmlRestorer() { 17009 @Override 17010 public void apply(XmlPullParser parser, int userId) 17011 throws XmlPullParserException, IOException { 17012 synchronized (mPackages) { 17013 mSettings.readPreferredActivitiesLPw(parser, userId); 17014 } 17015 } 17016 } ); 17017 } catch (Exception e) { 17018 if (DEBUG_BACKUP) { 17019 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17020 } 17021 } 17022 } 17023 17024 /** 17025 * Non-Binder method, support for the backup/restore mechanism: write the 17026 * default browser (etc) settings in its canonical XML format. Returns the default 17027 * browser XML representation as a byte array, or null if there is none. 17028 */ 17029 @Override 17030 public byte[] getDefaultAppsBackup(int userId) { 17031 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17032 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 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_DEFAULT_APPS); 17041 17042 synchronized (mPackages) { 17043 mSettings.writeDefaultAppsLPr(serializer, userId); 17044 } 17045 17046 serializer.endTag(null, TAG_DEFAULT_APPS); 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 restoreDefaultApps(byte[] backup, int userId) { 17061 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17062 throw new SecurityException("Only the system may call restoreDefaultApps()"); 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_DEFAULT_APPS, 17069 new BlobXmlRestorer() { 17070 @Override 17071 public void apply(XmlPullParser parser, int userId) 17072 throws XmlPullParserException, IOException { 17073 synchronized (mPackages) { 17074 mSettings.readDefaultAppsLPw(parser, userId); 17075 } 17076 } 17077 } ); 17078 } catch (Exception e) { 17079 if (DEBUG_BACKUP) { 17080 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17081 } 17082 } 17083 } 17084 17085 @Override 17086 public byte[] getIntentFilterVerificationBackup(int userId) { 17087 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17088 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17089 } 17090 17091 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17092 try { 17093 final XmlSerializer serializer = new FastXmlSerializer(); 17094 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17095 serializer.startDocument(null, true); 17096 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17097 17098 synchronized (mPackages) { 17099 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17100 } 17101 17102 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17103 serializer.endDocument(); 17104 serializer.flush(); 17105 } catch (Exception e) { 17106 if (DEBUG_BACKUP) { 17107 Slog.e(TAG, "Unable to write default apps for backup", e); 17108 } 17109 return null; 17110 } 17111 17112 return dataStream.toByteArray(); 17113 } 17114 17115 @Override 17116 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17117 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17118 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17119 } 17120 17121 try { 17122 final XmlPullParser parser = Xml.newPullParser(); 17123 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17124 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17125 new BlobXmlRestorer() { 17126 @Override 17127 public void apply(XmlPullParser parser, int userId) 17128 throws XmlPullParserException, IOException { 17129 synchronized (mPackages) { 17130 mSettings.readAllDomainVerificationsLPr(parser, userId); 17131 mSettings.writeLPr(); 17132 } 17133 } 17134 } ); 17135 } catch (Exception e) { 17136 if (DEBUG_BACKUP) { 17137 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17138 } 17139 } 17140 } 17141 17142 @Override 17143 public byte[] getPermissionGrantBackup(int userId) { 17144 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17145 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17146 } 17147 17148 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17149 try { 17150 final XmlSerializer serializer = new FastXmlSerializer(); 17151 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17152 serializer.startDocument(null, true); 17153 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17154 17155 synchronized (mPackages) { 17156 serializeRuntimePermissionGrantsLPr(serializer, userId); 17157 } 17158 17159 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17160 serializer.endDocument(); 17161 serializer.flush(); 17162 } catch (Exception e) { 17163 if (DEBUG_BACKUP) { 17164 Slog.e(TAG, "Unable to write default apps for backup", e); 17165 } 17166 return null; 17167 } 17168 17169 return dataStream.toByteArray(); 17170 } 17171 17172 @Override 17173 public void restorePermissionGrants(byte[] backup, int userId) { 17174 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17175 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17176 } 17177 17178 try { 17179 final XmlPullParser parser = Xml.newPullParser(); 17180 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17181 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17182 new BlobXmlRestorer() { 17183 @Override 17184 public void apply(XmlPullParser parser, int userId) 17185 throws XmlPullParserException, IOException { 17186 synchronized (mPackages) { 17187 processRestoredPermissionGrantsLPr(parser, userId); 17188 } 17189 } 17190 } ); 17191 } catch (Exception e) { 17192 if (DEBUG_BACKUP) { 17193 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17194 } 17195 } 17196 } 17197 17198 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17199 throws IOException { 17200 serializer.startTag(null, TAG_ALL_GRANTS); 17201 17202 final int N = mSettings.mPackages.size(); 17203 for (int i = 0; i < N; i++) { 17204 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17205 boolean pkgGrantsKnown = false; 17206 17207 PermissionsState packagePerms = ps.getPermissionsState(); 17208 17209 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17210 final int grantFlags = state.getFlags(); 17211 // only look at grants that are not system/policy fixed 17212 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17213 final boolean isGranted = state.isGranted(); 17214 // And only back up the user-twiddled state bits 17215 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17216 final String packageName = mSettings.mPackages.keyAt(i); 17217 if (!pkgGrantsKnown) { 17218 serializer.startTag(null, TAG_GRANT); 17219 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17220 pkgGrantsKnown = true; 17221 } 17222 17223 final boolean userSet = 17224 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17225 final boolean userFixed = 17226 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17227 final boolean revoke = 17228 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17229 17230 serializer.startTag(null, TAG_PERMISSION); 17231 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17232 if (isGranted) { 17233 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17234 } 17235 if (userSet) { 17236 serializer.attribute(null, ATTR_USER_SET, "true"); 17237 } 17238 if (userFixed) { 17239 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17240 } 17241 if (revoke) { 17242 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17243 } 17244 serializer.endTag(null, TAG_PERMISSION); 17245 } 17246 } 17247 } 17248 17249 if (pkgGrantsKnown) { 17250 serializer.endTag(null, TAG_GRANT); 17251 } 17252 } 17253 17254 serializer.endTag(null, TAG_ALL_GRANTS); 17255 } 17256 17257 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17258 throws XmlPullParserException, IOException { 17259 String pkgName = null; 17260 int outerDepth = parser.getDepth(); 17261 int type; 17262 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17263 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17264 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17265 continue; 17266 } 17267 17268 final String tagName = parser.getName(); 17269 if (tagName.equals(TAG_GRANT)) { 17270 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17271 if (DEBUG_BACKUP) { 17272 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17273 } 17274 } else if (tagName.equals(TAG_PERMISSION)) { 17275 17276 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17277 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17278 17279 int newFlagSet = 0; 17280 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17281 newFlagSet |= FLAG_PERMISSION_USER_SET; 17282 } 17283 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17284 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17285 } 17286 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17287 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17288 } 17289 if (DEBUG_BACKUP) { 17290 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17291 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17292 } 17293 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17294 if (ps != null) { 17295 // Already installed so we apply the grant immediately 17296 if (DEBUG_BACKUP) { 17297 Slog.v(TAG, " + already installed; applying"); 17298 } 17299 PermissionsState perms = ps.getPermissionsState(); 17300 BasePermission bp = mSettings.mPermissions.get(permName); 17301 if (bp != null) { 17302 if (isGranted) { 17303 perms.grantRuntimePermission(bp, userId); 17304 } 17305 if (newFlagSet != 0) { 17306 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17307 } 17308 } 17309 } else { 17310 // Need to wait for post-restore install to apply the grant 17311 if (DEBUG_BACKUP) { 17312 Slog.v(TAG, " - not yet installed; saving for later"); 17313 } 17314 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17315 isGranted, newFlagSet, userId); 17316 } 17317 } else { 17318 PackageManagerService.reportSettingsProblem(Log.WARN, 17319 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17320 XmlUtils.skipCurrentTag(parser); 17321 } 17322 } 17323 17324 scheduleWriteSettingsLocked(); 17325 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17326 } 17327 17328 @Override 17329 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17330 int sourceUserId, int targetUserId, int flags) { 17331 mContext.enforceCallingOrSelfPermission( 17332 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17333 int callingUid = Binder.getCallingUid(); 17334 enforceOwnerRights(ownerPackage, callingUid); 17335 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17336 if (intentFilter.countActions() == 0) { 17337 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17338 return; 17339 } 17340 synchronized (mPackages) { 17341 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17342 ownerPackage, targetUserId, flags); 17343 CrossProfileIntentResolver resolver = 17344 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17345 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17346 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17347 if (existing != null) { 17348 int size = existing.size(); 17349 for (int i = 0; i < size; i++) { 17350 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17351 return; 17352 } 17353 } 17354 } 17355 resolver.addFilter(newFilter); 17356 scheduleWritePackageRestrictionsLocked(sourceUserId); 17357 } 17358 } 17359 17360 @Override 17361 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17362 mContext.enforceCallingOrSelfPermission( 17363 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17364 int callingUid = Binder.getCallingUid(); 17365 enforceOwnerRights(ownerPackage, callingUid); 17366 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17367 synchronized (mPackages) { 17368 CrossProfileIntentResolver resolver = 17369 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17370 ArraySet<CrossProfileIntentFilter> set = 17371 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17372 for (CrossProfileIntentFilter filter : set) { 17373 if (filter.getOwnerPackage().equals(ownerPackage)) { 17374 resolver.removeFilter(filter); 17375 } 17376 } 17377 scheduleWritePackageRestrictionsLocked(sourceUserId); 17378 } 17379 } 17380 17381 // Enforcing that callingUid is owning pkg on userId 17382 private void enforceOwnerRights(String pkg, int callingUid) { 17383 // The system owns everything. 17384 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17385 return; 17386 } 17387 int callingUserId = UserHandle.getUserId(callingUid); 17388 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17389 if (pi == null) { 17390 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17391 + callingUserId); 17392 } 17393 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17394 throw new SecurityException("Calling uid " + callingUid 17395 + " does not own package " + pkg); 17396 } 17397 } 17398 17399 @Override 17400 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17401 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17402 } 17403 17404 private Intent getHomeIntent() { 17405 Intent intent = new Intent(Intent.ACTION_MAIN); 17406 intent.addCategory(Intent.CATEGORY_HOME); 17407 return intent; 17408 } 17409 17410 private IntentFilter getHomeFilter() { 17411 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17412 filter.addCategory(Intent.CATEGORY_HOME); 17413 filter.addCategory(Intent.CATEGORY_DEFAULT); 17414 return filter; 17415 } 17416 17417 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17418 int userId) { 17419 Intent intent = getHomeIntent(); 17420 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17421 PackageManager.GET_META_DATA, userId); 17422 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17423 true, false, false, userId); 17424 17425 allHomeCandidates.clear(); 17426 if (list != null) { 17427 for (ResolveInfo ri : list) { 17428 allHomeCandidates.add(ri); 17429 } 17430 } 17431 return (preferred == null || preferred.activityInfo == null) 17432 ? null 17433 : new ComponentName(preferred.activityInfo.packageName, 17434 preferred.activityInfo.name); 17435 } 17436 17437 @Override 17438 public void setHomeActivity(ComponentName comp, int userId) { 17439 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17440 getHomeActivitiesAsUser(homeActivities, userId); 17441 17442 boolean found = false; 17443 17444 final int size = homeActivities.size(); 17445 final ComponentName[] set = new ComponentName[size]; 17446 for (int i = 0; i < size; i++) { 17447 final ResolveInfo candidate = homeActivities.get(i); 17448 final ActivityInfo info = candidate.activityInfo; 17449 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17450 set[i] = activityName; 17451 if (!found && activityName.equals(comp)) { 17452 found = true; 17453 } 17454 } 17455 if (!found) { 17456 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17457 + userId); 17458 } 17459 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17460 set, comp, userId); 17461 } 17462 17463 private @Nullable String getSetupWizardPackageName() { 17464 final Intent intent = new Intent(Intent.ACTION_MAIN); 17465 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17466 17467 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17468 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17469 | MATCH_DISABLED_COMPONENTS, 17470 UserHandle.myUserId()); 17471 if (matches.size() == 1) { 17472 return matches.get(0).getComponentInfo().packageName; 17473 } else { 17474 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17475 + ": matches=" + matches); 17476 return null; 17477 } 17478 } 17479 17480 @Override 17481 public void setApplicationEnabledSetting(String appPackageName, 17482 int newState, int flags, int userId, String callingPackage) { 17483 if (!sUserManager.exists(userId)) return; 17484 if (callingPackage == null) { 17485 callingPackage = Integer.toString(Binder.getCallingUid()); 17486 } 17487 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17488 } 17489 17490 @Override 17491 public void setComponentEnabledSetting(ComponentName componentName, 17492 int newState, int flags, int userId) { 17493 if (!sUserManager.exists(userId)) return; 17494 setEnabledSetting(componentName.getPackageName(), 17495 componentName.getClassName(), newState, flags, userId, null); 17496 } 17497 17498 private void setEnabledSetting(final String packageName, String className, int newState, 17499 final int flags, int userId, String callingPackage) { 17500 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17501 || newState == COMPONENT_ENABLED_STATE_ENABLED 17502 || newState == COMPONENT_ENABLED_STATE_DISABLED 17503 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17504 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17505 throw new IllegalArgumentException("Invalid new component state: " 17506 + newState); 17507 } 17508 PackageSetting pkgSetting; 17509 final int uid = Binder.getCallingUid(); 17510 final int permission; 17511 if (uid == Process.SYSTEM_UID) { 17512 permission = PackageManager.PERMISSION_GRANTED; 17513 } else { 17514 permission = mContext.checkCallingOrSelfPermission( 17515 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17516 } 17517 enforceCrossUserPermission(uid, userId, 17518 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17519 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17520 boolean sendNow = false; 17521 boolean isApp = (className == null); 17522 String componentName = isApp ? packageName : className; 17523 int packageUid = -1; 17524 ArrayList<String> components; 17525 17526 // writer 17527 synchronized (mPackages) { 17528 pkgSetting = mSettings.mPackages.get(packageName); 17529 if (pkgSetting == null) { 17530 if (className == null) { 17531 throw new IllegalArgumentException("Unknown package: " + packageName); 17532 } 17533 throw new IllegalArgumentException( 17534 "Unknown component: " + packageName + "/" + className); 17535 } 17536 // Allow root and verify that userId is not being specified by a different user 17537 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17538 throw new SecurityException( 17539 "Permission Denial: attempt to change component state from pid=" 17540 + Binder.getCallingPid() 17541 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17542 } 17543 if (className == null) { 17544 // We're dealing with an application/package level state change 17545 if (pkgSetting.getEnabled(userId) == newState) { 17546 // Nothing to do 17547 return; 17548 } 17549 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17550 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17551 // Don't care about who enables an app. 17552 callingPackage = null; 17553 } 17554 pkgSetting.setEnabled(newState, userId, callingPackage); 17555 // pkgSetting.pkg.mSetEnabled = newState; 17556 } else { 17557 // We're dealing with a component level state change 17558 // First, verify that this is a valid class name. 17559 PackageParser.Package pkg = pkgSetting.pkg; 17560 if (pkg == null || !pkg.hasComponentClassName(className)) { 17561 if (pkg != null && 17562 pkg.applicationInfo.targetSdkVersion >= 17563 Build.VERSION_CODES.JELLY_BEAN) { 17564 throw new IllegalArgumentException("Component class " + className 17565 + " does not exist in " + packageName); 17566 } else { 17567 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17568 + className + " does not exist in " + packageName); 17569 } 17570 } 17571 switch (newState) { 17572 case COMPONENT_ENABLED_STATE_ENABLED: 17573 if (!pkgSetting.enableComponentLPw(className, userId)) { 17574 return; 17575 } 17576 break; 17577 case COMPONENT_ENABLED_STATE_DISABLED: 17578 if (!pkgSetting.disableComponentLPw(className, userId)) { 17579 return; 17580 } 17581 break; 17582 case COMPONENT_ENABLED_STATE_DEFAULT: 17583 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17584 return; 17585 } 17586 break; 17587 default: 17588 Slog.e(TAG, "Invalid new component state: " + newState); 17589 return; 17590 } 17591 } 17592 scheduleWritePackageRestrictionsLocked(userId); 17593 components = mPendingBroadcasts.get(userId, packageName); 17594 final boolean newPackage = components == null; 17595 if (newPackage) { 17596 components = new ArrayList<String>(); 17597 } 17598 if (!components.contains(componentName)) { 17599 components.add(componentName); 17600 } 17601 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17602 sendNow = true; 17603 // Purge entry from pending broadcast list if another one exists already 17604 // since we are sending one right away. 17605 mPendingBroadcasts.remove(userId, packageName); 17606 } else { 17607 if (newPackage) { 17608 mPendingBroadcasts.put(userId, packageName, components); 17609 } 17610 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17611 // Schedule a message 17612 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17613 } 17614 } 17615 } 17616 17617 long callingId = Binder.clearCallingIdentity(); 17618 try { 17619 if (sendNow) { 17620 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17621 sendPackageChangedBroadcast(packageName, 17622 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17623 } 17624 } finally { 17625 Binder.restoreCallingIdentity(callingId); 17626 } 17627 } 17628 17629 @Override 17630 public void flushPackageRestrictionsAsUser(int userId) { 17631 if (!sUserManager.exists(userId)) { 17632 return; 17633 } 17634 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17635 false /* checkShell */, "flushPackageRestrictions"); 17636 synchronized (mPackages) { 17637 mSettings.writePackageRestrictionsLPr(userId); 17638 mDirtyUsers.remove(userId); 17639 if (mDirtyUsers.isEmpty()) { 17640 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17641 } 17642 } 17643 } 17644 17645 private void sendPackageChangedBroadcast(String packageName, 17646 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17647 if (DEBUG_INSTALL) 17648 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17649 + componentNames); 17650 Bundle extras = new Bundle(4); 17651 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17652 String nameList[] = new String[componentNames.size()]; 17653 componentNames.toArray(nameList); 17654 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17655 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17656 extras.putInt(Intent.EXTRA_UID, packageUid); 17657 // If this is not reporting a change of the overall package, then only send it 17658 // to registered receivers. We don't want to launch a swath of apps for every 17659 // little component state change. 17660 final int flags = !componentNames.contains(packageName) 17661 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17662 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17663 new int[] {UserHandle.getUserId(packageUid)}); 17664 } 17665 17666 @Override 17667 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17668 if (!sUserManager.exists(userId)) return; 17669 final int uid = Binder.getCallingUid(); 17670 final int permission = mContext.checkCallingOrSelfPermission( 17671 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17672 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17673 enforceCrossUserPermission(uid, userId, 17674 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17675 // writer 17676 synchronized (mPackages) { 17677 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17678 allowedByPermission, uid, userId)) { 17679 scheduleWritePackageRestrictionsLocked(userId); 17680 } 17681 } 17682 } 17683 17684 @Override 17685 public String getInstallerPackageName(String packageName) { 17686 // reader 17687 synchronized (mPackages) { 17688 return mSettings.getInstallerPackageNameLPr(packageName); 17689 } 17690 } 17691 17692 public boolean isOrphaned(String packageName) { 17693 // reader 17694 synchronized (mPackages) { 17695 return mSettings.isOrphaned(packageName); 17696 } 17697 } 17698 17699 @Override 17700 public int getApplicationEnabledSetting(String packageName, int userId) { 17701 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17702 int uid = Binder.getCallingUid(); 17703 enforceCrossUserPermission(uid, userId, 17704 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17705 // reader 17706 synchronized (mPackages) { 17707 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17708 } 17709 } 17710 17711 @Override 17712 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17713 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17714 int uid = Binder.getCallingUid(); 17715 enforceCrossUserPermission(uid, userId, 17716 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17717 // reader 17718 synchronized (mPackages) { 17719 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17720 } 17721 } 17722 17723 @Override 17724 public void enterSafeMode() { 17725 enforceSystemOrRoot("Only the system can request entering safe mode"); 17726 17727 if (!mSystemReady) { 17728 mSafeMode = true; 17729 } 17730 } 17731 17732 @Override 17733 public void systemReady() { 17734 mSystemReady = true; 17735 17736 // Read the compatibilty setting when the system is ready. 17737 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17738 mContext.getContentResolver(), 17739 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17740 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17741 if (DEBUG_SETTINGS) { 17742 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17743 } 17744 17745 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17746 17747 synchronized (mPackages) { 17748 // Verify that all of the preferred activity components actually 17749 // exist. It is possible for applications to be updated and at 17750 // that point remove a previously declared activity component that 17751 // had been set as a preferred activity. We try to clean this up 17752 // the next time we encounter that preferred activity, but it is 17753 // possible for the user flow to never be able to return to that 17754 // situation so here we do a sanity check to make sure we haven't 17755 // left any junk around. 17756 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17757 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17758 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17759 removed.clear(); 17760 for (PreferredActivity pa : pir.filterSet()) { 17761 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17762 removed.add(pa); 17763 } 17764 } 17765 if (removed.size() > 0) { 17766 for (int r=0; r<removed.size(); r++) { 17767 PreferredActivity pa = removed.get(r); 17768 Slog.w(TAG, "Removing dangling preferred activity: " 17769 + pa.mPref.mComponent); 17770 pir.removeFilter(pa); 17771 } 17772 mSettings.writePackageRestrictionsLPr( 17773 mSettings.mPreferredActivities.keyAt(i)); 17774 } 17775 } 17776 17777 for (int userId : UserManagerService.getInstance().getUserIds()) { 17778 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17779 grantPermissionsUserIds = ArrayUtils.appendInt( 17780 grantPermissionsUserIds, userId); 17781 } 17782 } 17783 } 17784 sUserManager.systemReady(); 17785 17786 // If we upgraded grant all default permissions before kicking off. 17787 for (int userId : grantPermissionsUserIds) { 17788 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17789 } 17790 17791 // Kick off any messages waiting for system ready 17792 if (mPostSystemReadyMessages != null) { 17793 for (Message msg : mPostSystemReadyMessages) { 17794 msg.sendToTarget(); 17795 } 17796 mPostSystemReadyMessages = null; 17797 } 17798 17799 // Watch for external volumes that come and go over time 17800 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17801 storage.registerListener(mStorageListener); 17802 17803 mInstallerService.systemReady(); 17804 mPackageDexOptimizer.systemReady(); 17805 17806 MountServiceInternal mountServiceInternal = LocalServices.getService( 17807 MountServiceInternal.class); 17808 mountServiceInternal.addExternalStoragePolicy( 17809 new MountServiceInternal.ExternalStorageMountPolicy() { 17810 @Override 17811 public int getMountMode(int uid, String packageName) { 17812 if (Process.isIsolated(uid)) { 17813 return Zygote.MOUNT_EXTERNAL_NONE; 17814 } 17815 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17816 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17817 } 17818 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17819 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17820 } 17821 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17822 return Zygote.MOUNT_EXTERNAL_READ; 17823 } 17824 return Zygote.MOUNT_EXTERNAL_WRITE; 17825 } 17826 17827 @Override 17828 public boolean hasExternalStorage(int uid, String packageName) { 17829 return true; 17830 } 17831 }); 17832 17833 // Now that we're mostly running, clean up stale users and apps 17834 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17835 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17836 } 17837 17838 @Override 17839 public boolean isSafeMode() { 17840 return mSafeMode; 17841 } 17842 17843 @Override 17844 public boolean hasSystemUidErrors() { 17845 return mHasSystemUidErrors; 17846 } 17847 17848 static String arrayToString(int[] array) { 17849 StringBuffer buf = new StringBuffer(128); 17850 buf.append('['); 17851 if (array != null) { 17852 for (int i=0; i<array.length; i++) { 17853 if (i > 0) buf.append(", "); 17854 buf.append(array[i]); 17855 } 17856 } 17857 buf.append(']'); 17858 return buf.toString(); 17859 } 17860 17861 static class DumpState { 17862 public static final int DUMP_LIBS = 1 << 0; 17863 public static final int DUMP_FEATURES = 1 << 1; 17864 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17865 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17866 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17867 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17868 public static final int DUMP_PERMISSIONS = 1 << 6; 17869 public static final int DUMP_PACKAGES = 1 << 7; 17870 public static final int DUMP_SHARED_USERS = 1 << 8; 17871 public static final int DUMP_MESSAGES = 1 << 9; 17872 public static final int DUMP_PROVIDERS = 1 << 10; 17873 public static final int DUMP_VERIFIERS = 1 << 11; 17874 public static final int DUMP_PREFERRED = 1 << 12; 17875 public static final int DUMP_PREFERRED_XML = 1 << 13; 17876 public static final int DUMP_KEYSETS = 1 << 14; 17877 public static final int DUMP_VERSION = 1 << 15; 17878 public static final int DUMP_INSTALLS = 1 << 16; 17879 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17880 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17881 public static final int DUMP_FROZEN = 1 << 19; 17882 public static final int DUMP_DEXOPT = 1 << 20; 17883 17884 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17885 17886 private int mTypes; 17887 17888 private int mOptions; 17889 17890 private boolean mTitlePrinted; 17891 17892 private SharedUserSetting mSharedUser; 17893 17894 public boolean isDumping(int type) { 17895 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17896 return true; 17897 } 17898 17899 return (mTypes & type) != 0; 17900 } 17901 17902 public void setDump(int type) { 17903 mTypes |= type; 17904 } 17905 17906 public boolean isOptionEnabled(int option) { 17907 return (mOptions & option) != 0; 17908 } 17909 17910 public void setOptionEnabled(int option) { 17911 mOptions |= option; 17912 } 17913 17914 public boolean onTitlePrinted() { 17915 final boolean printed = mTitlePrinted; 17916 mTitlePrinted = true; 17917 return printed; 17918 } 17919 17920 public boolean getTitlePrinted() { 17921 return mTitlePrinted; 17922 } 17923 17924 public void setTitlePrinted(boolean enabled) { 17925 mTitlePrinted = enabled; 17926 } 17927 17928 public SharedUserSetting getSharedUser() { 17929 return mSharedUser; 17930 } 17931 17932 public void setSharedUser(SharedUserSetting user) { 17933 mSharedUser = user; 17934 } 17935 } 17936 17937 @Override 17938 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17939 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17940 (new PackageManagerShellCommand(this)).exec( 17941 this, in, out, err, args, resultReceiver); 17942 } 17943 17944 @Override 17945 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17946 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17947 != PackageManager.PERMISSION_GRANTED) { 17948 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17949 + Binder.getCallingPid() 17950 + ", uid=" + Binder.getCallingUid() 17951 + " without permission " 17952 + android.Manifest.permission.DUMP); 17953 return; 17954 } 17955 17956 DumpState dumpState = new DumpState(); 17957 boolean fullPreferred = false; 17958 boolean checkin = false; 17959 17960 String packageName = null; 17961 ArraySet<String> permissionNames = null; 17962 17963 int opti = 0; 17964 while (opti < args.length) { 17965 String opt = args[opti]; 17966 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17967 break; 17968 } 17969 opti++; 17970 17971 if ("-a".equals(opt)) { 17972 // Right now we only know how to print all. 17973 } else if ("-h".equals(opt)) { 17974 pw.println("Package manager dump options:"); 17975 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17976 pw.println(" --checkin: dump for a checkin"); 17977 pw.println(" -f: print details of intent filters"); 17978 pw.println(" -h: print this help"); 17979 pw.println(" cmd may be one of:"); 17980 pw.println(" l[ibraries]: list known shared libraries"); 17981 pw.println(" f[eatures]: list device features"); 17982 pw.println(" k[eysets]: print known keysets"); 17983 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17984 pw.println(" perm[issions]: dump permissions"); 17985 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17986 pw.println(" pref[erred]: print preferred package settings"); 17987 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17988 pw.println(" prov[iders]: dump content providers"); 17989 pw.println(" p[ackages]: dump installed packages"); 17990 pw.println(" s[hared-users]: dump shared user IDs"); 17991 pw.println(" m[essages]: print collected runtime messages"); 17992 pw.println(" v[erifiers]: print package verifier info"); 17993 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17994 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17995 pw.println(" version: print database version info"); 17996 pw.println(" write: write current settings now"); 17997 pw.println(" installs: details about install sessions"); 17998 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17999 pw.println(" dexopt: dump dexopt state"); 18000 pw.println(" <package.name>: info about given package"); 18001 return; 18002 } else if ("--checkin".equals(opt)) { 18003 checkin = true; 18004 } else if ("-f".equals(opt)) { 18005 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18006 } else { 18007 pw.println("Unknown argument: " + opt + "; use -h for help"); 18008 } 18009 } 18010 18011 // Is the caller requesting to dump a particular piece of data? 18012 if (opti < args.length) { 18013 String cmd = args[opti]; 18014 opti++; 18015 // Is this a package name? 18016 if ("android".equals(cmd) || cmd.contains(".")) { 18017 packageName = cmd; 18018 // When dumping a single package, we always dump all of its 18019 // filter information since the amount of data will be reasonable. 18020 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18021 } else if ("check-permission".equals(cmd)) { 18022 if (opti >= args.length) { 18023 pw.println("Error: check-permission missing permission argument"); 18024 return; 18025 } 18026 String perm = args[opti]; 18027 opti++; 18028 if (opti >= args.length) { 18029 pw.println("Error: check-permission missing package argument"); 18030 return; 18031 } 18032 String pkg = args[opti]; 18033 opti++; 18034 int user = UserHandle.getUserId(Binder.getCallingUid()); 18035 if (opti < args.length) { 18036 try { 18037 user = Integer.parseInt(args[opti]); 18038 } catch (NumberFormatException e) { 18039 pw.println("Error: check-permission user argument is not a number: " 18040 + args[opti]); 18041 return; 18042 } 18043 } 18044 pw.println(checkPermission(perm, pkg, user)); 18045 return; 18046 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18047 dumpState.setDump(DumpState.DUMP_LIBS); 18048 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18049 dumpState.setDump(DumpState.DUMP_FEATURES); 18050 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18051 if (opti >= args.length) { 18052 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18053 | DumpState.DUMP_SERVICE_RESOLVERS 18054 | DumpState.DUMP_RECEIVER_RESOLVERS 18055 | DumpState.DUMP_CONTENT_RESOLVERS); 18056 } else { 18057 while (opti < args.length) { 18058 String name = args[opti]; 18059 if ("a".equals(name) || "activity".equals(name)) { 18060 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18061 } else if ("s".equals(name) || "service".equals(name)) { 18062 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18063 } else if ("r".equals(name) || "receiver".equals(name)) { 18064 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18065 } else if ("c".equals(name) || "content".equals(name)) { 18066 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18067 } else { 18068 pw.println("Error: unknown resolver table type: " + name); 18069 return; 18070 } 18071 opti++; 18072 } 18073 } 18074 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18075 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18076 } else if ("permission".equals(cmd)) { 18077 if (opti >= args.length) { 18078 pw.println("Error: permission requires permission name"); 18079 return; 18080 } 18081 permissionNames = new ArraySet<>(); 18082 while (opti < args.length) { 18083 permissionNames.add(args[opti]); 18084 opti++; 18085 } 18086 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18087 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18088 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18089 dumpState.setDump(DumpState.DUMP_PREFERRED); 18090 } else if ("preferred-xml".equals(cmd)) { 18091 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18092 if (opti < args.length && "--full".equals(args[opti])) { 18093 fullPreferred = true; 18094 opti++; 18095 } 18096 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18097 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18098 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18099 dumpState.setDump(DumpState.DUMP_PACKAGES); 18100 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18101 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18102 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18103 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18104 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18105 dumpState.setDump(DumpState.DUMP_MESSAGES); 18106 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18107 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18108 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18109 || "intent-filter-verifiers".equals(cmd)) { 18110 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18111 } else if ("version".equals(cmd)) { 18112 dumpState.setDump(DumpState.DUMP_VERSION); 18113 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18114 dumpState.setDump(DumpState.DUMP_KEYSETS); 18115 } else if ("installs".equals(cmd)) { 18116 dumpState.setDump(DumpState.DUMP_INSTALLS); 18117 } else if ("frozen".equals(cmd)) { 18118 dumpState.setDump(DumpState.DUMP_FROZEN); 18119 } else if ("dexopt".equals(cmd)) { 18120 dumpState.setDump(DumpState.DUMP_DEXOPT); 18121 } else if ("write".equals(cmd)) { 18122 synchronized (mPackages) { 18123 mSettings.writeLPr(); 18124 pw.println("Settings written."); 18125 return; 18126 } 18127 } 18128 } 18129 18130 if (checkin) { 18131 pw.println("vers,1"); 18132 } 18133 18134 // reader 18135 synchronized (mPackages) { 18136 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18137 if (!checkin) { 18138 if (dumpState.onTitlePrinted()) 18139 pw.println(); 18140 pw.println("Database versions:"); 18141 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18142 } 18143 } 18144 18145 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18146 if (!checkin) { 18147 if (dumpState.onTitlePrinted()) 18148 pw.println(); 18149 pw.println("Verifiers:"); 18150 pw.print(" Required: "); 18151 pw.print(mRequiredVerifierPackage); 18152 pw.print(" (uid="); 18153 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18154 UserHandle.USER_SYSTEM)); 18155 pw.println(")"); 18156 } else if (mRequiredVerifierPackage != null) { 18157 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18158 pw.print(","); 18159 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18160 UserHandle.USER_SYSTEM)); 18161 } 18162 } 18163 18164 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18165 packageName == null) { 18166 if (mIntentFilterVerifierComponent != null) { 18167 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18168 if (!checkin) { 18169 if (dumpState.onTitlePrinted()) 18170 pw.println(); 18171 pw.println("Intent Filter Verifier:"); 18172 pw.print(" Using: "); 18173 pw.print(verifierPackageName); 18174 pw.print(" (uid="); 18175 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18176 UserHandle.USER_SYSTEM)); 18177 pw.println(")"); 18178 } else if (verifierPackageName != null) { 18179 pw.print("ifv,"); pw.print(verifierPackageName); 18180 pw.print(","); 18181 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18182 UserHandle.USER_SYSTEM)); 18183 } 18184 } else { 18185 pw.println(); 18186 pw.println("No Intent Filter Verifier available!"); 18187 } 18188 } 18189 18190 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18191 boolean printedHeader = false; 18192 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18193 while (it.hasNext()) { 18194 String name = it.next(); 18195 SharedLibraryEntry ent = mSharedLibraries.get(name); 18196 if (!checkin) { 18197 if (!printedHeader) { 18198 if (dumpState.onTitlePrinted()) 18199 pw.println(); 18200 pw.println("Libraries:"); 18201 printedHeader = true; 18202 } 18203 pw.print(" "); 18204 } else { 18205 pw.print("lib,"); 18206 } 18207 pw.print(name); 18208 if (!checkin) { 18209 pw.print(" -> "); 18210 } 18211 if (ent.path != null) { 18212 if (!checkin) { 18213 pw.print("(jar) "); 18214 pw.print(ent.path); 18215 } else { 18216 pw.print(",jar,"); 18217 pw.print(ent.path); 18218 } 18219 } else { 18220 if (!checkin) { 18221 pw.print("(apk) "); 18222 pw.print(ent.apk); 18223 } else { 18224 pw.print(",apk,"); 18225 pw.print(ent.apk); 18226 } 18227 } 18228 pw.println(); 18229 } 18230 } 18231 18232 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18233 if (dumpState.onTitlePrinted()) 18234 pw.println(); 18235 if (!checkin) { 18236 pw.println("Features:"); 18237 } 18238 18239 for (FeatureInfo feat : mAvailableFeatures.values()) { 18240 if (checkin) { 18241 pw.print("feat,"); 18242 pw.print(feat.name); 18243 pw.print(","); 18244 pw.println(feat.version); 18245 } else { 18246 pw.print(" "); 18247 pw.print(feat.name); 18248 if (feat.version > 0) { 18249 pw.print(" version="); 18250 pw.print(feat.version); 18251 } 18252 pw.println(); 18253 } 18254 } 18255 } 18256 18257 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18258 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18259 : "Activity Resolver Table:", " ", packageName, 18260 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18261 dumpState.setTitlePrinted(true); 18262 } 18263 } 18264 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18265 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18266 : "Receiver Resolver Table:", " ", packageName, 18267 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18268 dumpState.setTitlePrinted(true); 18269 } 18270 } 18271 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18272 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18273 : "Service Resolver Table:", " ", packageName, 18274 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18275 dumpState.setTitlePrinted(true); 18276 } 18277 } 18278 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18279 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18280 : "Provider Resolver Table:", " ", packageName, 18281 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18282 dumpState.setTitlePrinted(true); 18283 } 18284 } 18285 18286 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18287 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18288 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18289 int user = mSettings.mPreferredActivities.keyAt(i); 18290 if (pir.dump(pw, 18291 dumpState.getTitlePrinted() 18292 ? "\nPreferred Activities User " + user + ":" 18293 : "Preferred Activities User " + user + ":", " ", 18294 packageName, true, false)) { 18295 dumpState.setTitlePrinted(true); 18296 } 18297 } 18298 } 18299 18300 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18301 pw.flush(); 18302 FileOutputStream fout = new FileOutputStream(fd); 18303 BufferedOutputStream str = new BufferedOutputStream(fout); 18304 XmlSerializer serializer = new FastXmlSerializer(); 18305 try { 18306 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18307 serializer.startDocument(null, true); 18308 serializer.setFeature( 18309 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18310 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18311 serializer.endDocument(); 18312 serializer.flush(); 18313 } catch (IllegalArgumentException e) { 18314 pw.println("Failed writing: " + e); 18315 } catch (IllegalStateException e) { 18316 pw.println("Failed writing: " + e); 18317 } catch (IOException e) { 18318 pw.println("Failed writing: " + e); 18319 } 18320 } 18321 18322 if (!checkin 18323 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18324 && packageName == null) { 18325 pw.println(); 18326 int count = mSettings.mPackages.size(); 18327 if (count == 0) { 18328 pw.println("No applications!"); 18329 pw.println(); 18330 } else { 18331 final String prefix = " "; 18332 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18333 if (allPackageSettings.size() == 0) { 18334 pw.println("No domain preferred apps!"); 18335 pw.println(); 18336 } else { 18337 pw.println("App verification status:"); 18338 pw.println(); 18339 count = 0; 18340 for (PackageSetting ps : allPackageSettings) { 18341 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18342 if (ivi == null || ivi.getPackageName() == null) continue; 18343 pw.println(prefix + "Package: " + ivi.getPackageName()); 18344 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18345 pw.println(prefix + "Status: " + ivi.getStatusString()); 18346 pw.println(); 18347 count++; 18348 } 18349 if (count == 0) { 18350 pw.println(prefix + "No app verification established."); 18351 pw.println(); 18352 } 18353 for (int userId : sUserManager.getUserIds()) { 18354 pw.println("App linkages for user " + userId + ":"); 18355 pw.println(); 18356 count = 0; 18357 for (PackageSetting ps : allPackageSettings) { 18358 final long status = ps.getDomainVerificationStatusForUser(userId); 18359 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18360 continue; 18361 } 18362 pw.println(prefix + "Package: " + ps.name); 18363 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18364 String statusStr = IntentFilterVerificationInfo. 18365 getStatusStringFromValue(status); 18366 pw.println(prefix + "Status: " + statusStr); 18367 pw.println(); 18368 count++; 18369 } 18370 if (count == 0) { 18371 pw.println(prefix + "No configured app linkages."); 18372 pw.println(); 18373 } 18374 } 18375 } 18376 } 18377 } 18378 18379 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18380 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18381 if (packageName == null && permissionNames == null) { 18382 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18383 if (iperm == 0) { 18384 if (dumpState.onTitlePrinted()) 18385 pw.println(); 18386 pw.println("AppOp Permissions:"); 18387 } 18388 pw.print(" AppOp Permission "); 18389 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18390 pw.println(":"); 18391 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18392 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18393 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18394 } 18395 } 18396 } 18397 } 18398 18399 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18400 boolean printedSomething = false; 18401 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18402 if (packageName != null && !packageName.equals(p.info.packageName)) { 18403 continue; 18404 } 18405 if (!printedSomething) { 18406 if (dumpState.onTitlePrinted()) 18407 pw.println(); 18408 pw.println("Registered ContentProviders:"); 18409 printedSomething = true; 18410 } 18411 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18412 pw.print(" "); pw.println(p.toString()); 18413 } 18414 printedSomething = false; 18415 for (Map.Entry<String, PackageParser.Provider> entry : 18416 mProvidersByAuthority.entrySet()) { 18417 PackageParser.Provider p = entry.getValue(); 18418 if (packageName != null && !packageName.equals(p.info.packageName)) { 18419 continue; 18420 } 18421 if (!printedSomething) { 18422 if (dumpState.onTitlePrinted()) 18423 pw.println(); 18424 pw.println("ContentProvider Authorities:"); 18425 printedSomething = true; 18426 } 18427 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18428 pw.print(" "); pw.println(p.toString()); 18429 if (p.info != null && p.info.applicationInfo != null) { 18430 final String appInfo = p.info.applicationInfo.toString(); 18431 pw.print(" applicationInfo="); pw.println(appInfo); 18432 } 18433 } 18434 } 18435 18436 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18437 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18438 } 18439 18440 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18441 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18442 } 18443 18444 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18445 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18446 } 18447 18448 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18449 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18450 } 18451 18452 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18453 // XXX should handle packageName != null by dumping only install data that 18454 // the given package is involved with. 18455 if (dumpState.onTitlePrinted()) pw.println(); 18456 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18457 } 18458 18459 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18460 // XXX should handle packageName != null by dumping only install data that 18461 // the given package is involved with. 18462 if (dumpState.onTitlePrinted()) pw.println(); 18463 18464 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18465 ipw.println(); 18466 ipw.println("Frozen packages:"); 18467 ipw.increaseIndent(); 18468 if (mFrozenPackages.size() == 0) { 18469 ipw.println("(none)"); 18470 } else { 18471 for (int i = 0; i < mFrozenPackages.size(); i++) { 18472 ipw.println(mFrozenPackages.valueAt(i)); 18473 } 18474 } 18475 ipw.decreaseIndent(); 18476 } 18477 18478 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18479 if (dumpState.onTitlePrinted()) pw.println(); 18480 dumpDexoptStateLPr(pw, packageName); 18481 } 18482 18483 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18484 if (dumpState.onTitlePrinted()) pw.println(); 18485 mSettings.dumpReadMessagesLPr(pw, dumpState); 18486 18487 pw.println(); 18488 pw.println("Package warning messages:"); 18489 BufferedReader in = null; 18490 String line = null; 18491 try { 18492 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18493 while ((line = in.readLine()) != null) { 18494 if (line.contains("ignored: updated version")) continue; 18495 pw.println(line); 18496 } 18497 } catch (IOException ignored) { 18498 } finally { 18499 IoUtils.closeQuietly(in); 18500 } 18501 } 18502 18503 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18504 BufferedReader in = null; 18505 String line = null; 18506 try { 18507 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18508 while ((line = in.readLine()) != null) { 18509 if (line.contains("ignored: updated version")) continue; 18510 pw.print("msg,"); 18511 pw.println(line); 18512 } 18513 } catch (IOException ignored) { 18514 } finally { 18515 IoUtils.closeQuietly(in); 18516 } 18517 } 18518 } 18519 } 18520 18521 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18522 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18523 ipw.println(); 18524 ipw.println("Dexopt state:"); 18525 ipw.increaseIndent(); 18526 Collection<PackageParser.Package> packages = null; 18527 if (packageName != null) { 18528 PackageParser.Package targetPackage = mPackages.get(packageName); 18529 if (targetPackage != null) { 18530 packages = Collections.singletonList(targetPackage); 18531 } else { 18532 ipw.println("Unable to find package: " + packageName); 18533 return; 18534 } 18535 } else { 18536 packages = mPackages.values(); 18537 } 18538 18539 for (PackageParser.Package pkg : packages) { 18540 ipw.println("[" + pkg.packageName + "]"); 18541 ipw.increaseIndent(); 18542 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18543 ipw.decreaseIndent(); 18544 } 18545 } 18546 18547 private String dumpDomainString(String packageName) { 18548 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18549 .getList(); 18550 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18551 18552 ArraySet<String> result = new ArraySet<>(); 18553 if (iviList.size() > 0) { 18554 for (IntentFilterVerificationInfo ivi : iviList) { 18555 for (String host : ivi.getDomains()) { 18556 result.add(host); 18557 } 18558 } 18559 } 18560 if (filters != null && filters.size() > 0) { 18561 for (IntentFilter filter : filters) { 18562 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18563 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18564 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18565 result.addAll(filter.getHostsList()); 18566 } 18567 } 18568 } 18569 18570 StringBuilder sb = new StringBuilder(result.size() * 16); 18571 for (String domain : result) { 18572 if (sb.length() > 0) sb.append(" "); 18573 sb.append(domain); 18574 } 18575 return sb.toString(); 18576 } 18577 18578 // ------- apps on sdcard specific code ------- 18579 static final boolean DEBUG_SD_INSTALL = false; 18580 18581 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18582 18583 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18584 18585 private boolean mMediaMounted = false; 18586 18587 static String getEncryptKey() { 18588 try { 18589 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18590 SD_ENCRYPTION_KEYSTORE_NAME); 18591 if (sdEncKey == null) { 18592 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18593 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18594 if (sdEncKey == null) { 18595 Slog.e(TAG, "Failed to create encryption keys"); 18596 return null; 18597 } 18598 } 18599 return sdEncKey; 18600 } catch (NoSuchAlgorithmException nsae) { 18601 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18602 return null; 18603 } catch (IOException ioe) { 18604 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18605 return null; 18606 } 18607 } 18608 18609 /* 18610 * Update media status on PackageManager. 18611 */ 18612 @Override 18613 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18614 int callingUid = Binder.getCallingUid(); 18615 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18616 throw new SecurityException("Media status can only be updated by the system"); 18617 } 18618 // reader; this apparently protects mMediaMounted, but should probably 18619 // be a different lock in that case. 18620 synchronized (mPackages) { 18621 Log.i(TAG, "Updating external media status from " 18622 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18623 + (mediaStatus ? "mounted" : "unmounted")); 18624 if (DEBUG_SD_INSTALL) 18625 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18626 + ", mMediaMounted=" + mMediaMounted); 18627 if (mediaStatus == mMediaMounted) { 18628 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18629 : 0, -1); 18630 mHandler.sendMessage(msg); 18631 return; 18632 } 18633 mMediaMounted = mediaStatus; 18634 } 18635 // Queue up an async operation since the package installation may take a 18636 // little while. 18637 mHandler.post(new Runnable() { 18638 public void run() { 18639 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18640 } 18641 }); 18642 } 18643 18644 /** 18645 * Called by MountService when the initial ASECs to scan are available. 18646 * Should block until all the ASEC containers are finished being scanned. 18647 */ 18648 public void scanAvailableAsecs() { 18649 updateExternalMediaStatusInner(true, false, false); 18650 } 18651 18652 /* 18653 * Collect information of applications on external media, map them against 18654 * existing containers and update information based on current mount status. 18655 * Please note that we always have to report status if reportStatus has been 18656 * set to true especially when unloading packages. 18657 */ 18658 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18659 boolean externalStorage) { 18660 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18661 int[] uidArr = EmptyArray.INT; 18662 18663 final String[] list = PackageHelper.getSecureContainerList(); 18664 if (ArrayUtils.isEmpty(list)) { 18665 Log.i(TAG, "No secure containers found"); 18666 } else { 18667 // Process list of secure containers and categorize them 18668 // as active or stale based on their package internal state. 18669 18670 // reader 18671 synchronized (mPackages) { 18672 for (String cid : list) { 18673 // Leave stages untouched for now; installer service owns them 18674 if (PackageInstallerService.isStageName(cid)) continue; 18675 18676 if (DEBUG_SD_INSTALL) 18677 Log.i(TAG, "Processing container " + cid); 18678 String pkgName = getAsecPackageName(cid); 18679 if (pkgName == null) { 18680 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18681 continue; 18682 } 18683 if (DEBUG_SD_INSTALL) 18684 Log.i(TAG, "Looking for pkg : " + pkgName); 18685 18686 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18687 if (ps == null) { 18688 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18689 continue; 18690 } 18691 18692 /* 18693 * Skip packages that are not external if we're unmounting 18694 * external storage. 18695 */ 18696 if (externalStorage && !isMounted && !isExternal(ps)) { 18697 continue; 18698 } 18699 18700 final AsecInstallArgs args = new AsecInstallArgs(cid, 18701 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18702 // The package status is changed only if the code path 18703 // matches between settings and the container id. 18704 if (ps.codePathString != null 18705 && ps.codePathString.startsWith(args.getCodePath())) { 18706 if (DEBUG_SD_INSTALL) { 18707 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18708 + " at code path: " + ps.codePathString); 18709 } 18710 18711 // We do have a valid package installed on sdcard 18712 processCids.put(args, ps.codePathString); 18713 final int uid = ps.appId; 18714 if (uid != -1) { 18715 uidArr = ArrayUtils.appendInt(uidArr, uid); 18716 } 18717 } else { 18718 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18719 + ps.codePathString); 18720 } 18721 } 18722 } 18723 18724 Arrays.sort(uidArr); 18725 } 18726 18727 // Process packages with valid entries. 18728 if (isMounted) { 18729 if (DEBUG_SD_INSTALL) 18730 Log.i(TAG, "Loading packages"); 18731 loadMediaPackages(processCids, uidArr, externalStorage); 18732 startCleaningPackages(); 18733 mInstallerService.onSecureContainersAvailable(); 18734 } else { 18735 if (DEBUG_SD_INSTALL) 18736 Log.i(TAG, "Unloading packages"); 18737 unloadMediaPackages(processCids, uidArr, reportStatus); 18738 } 18739 } 18740 18741 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18742 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18743 final int size = infos.size(); 18744 final String[] packageNames = new String[size]; 18745 final int[] packageUids = new int[size]; 18746 for (int i = 0; i < size; i++) { 18747 final ApplicationInfo info = infos.get(i); 18748 packageNames[i] = info.packageName; 18749 packageUids[i] = info.uid; 18750 } 18751 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18752 finishedReceiver); 18753 } 18754 18755 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18756 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18757 sendResourcesChangedBroadcast(mediaStatus, replacing, 18758 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18759 } 18760 18761 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18762 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18763 int size = pkgList.length; 18764 if (size > 0) { 18765 // Send broadcasts here 18766 Bundle extras = new Bundle(); 18767 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18768 if (uidArr != null) { 18769 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18770 } 18771 if (replacing) { 18772 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18773 } 18774 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18775 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18776 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18777 } 18778 } 18779 18780 /* 18781 * Look at potentially valid container ids from processCids If package 18782 * information doesn't match the one on record or package scanning fails, 18783 * the cid is added to list of removeCids. We currently don't delete stale 18784 * containers. 18785 */ 18786 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18787 boolean externalStorage) { 18788 ArrayList<String> pkgList = new ArrayList<String>(); 18789 Set<AsecInstallArgs> keys = processCids.keySet(); 18790 18791 for (AsecInstallArgs args : keys) { 18792 String codePath = processCids.get(args); 18793 if (DEBUG_SD_INSTALL) 18794 Log.i(TAG, "Loading container : " + args.cid); 18795 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18796 try { 18797 // Make sure there are no container errors first. 18798 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18799 Slog.e(TAG, "Failed to mount cid : " + args.cid 18800 + " when installing from sdcard"); 18801 continue; 18802 } 18803 // Check code path here. 18804 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18805 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18806 + " does not match one in settings " + codePath); 18807 continue; 18808 } 18809 // Parse package 18810 int parseFlags = mDefParseFlags; 18811 if (args.isExternalAsec()) { 18812 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18813 } 18814 if (args.isFwdLocked()) { 18815 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18816 } 18817 18818 synchronized (mInstallLock) { 18819 PackageParser.Package pkg = null; 18820 try { 18821 // Sadly we don't know the package name yet to freeze it 18822 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18823 SCAN_IGNORE_FROZEN, 0, null); 18824 } catch (PackageManagerException e) { 18825 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18826 } 18827 // Scan the package 18828 if (pkg != null) { 18829 /* 18830 * TODO why is the lock being held? doPostInstall is 18831 * called in other places without the lock. This needs 18832 * to be straightened out. 18833 */ 18834 // writer 18835 synchronized (mPackages) { 18836 retCode = PackageManager.INSTALL_SUCCEEDED; 18837 pkgList.add(pkg.packageName); 18838 // Post process args 18839 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18840 pkg.applicationInfo.uid); 18841 } 18842 } else { 18843 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18844 } 18845 } 18846 18847 } finally { 18848 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18849 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18850 } 18851 } 18852 } 18853 // writer 18854 synchronized (mPackages) { 18855 // If the platform SDK has changed since the last time we booted, 18856 // we need to re-grant app permission to catch any new ones that 18857 // appear. This is really a hack, and means that apps can in some 18858 // cases get permissions that the user didn't initially explicitly 18859 // allow... it would be nice to have some better way to handle 18860 // this situation. 18861 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18862 : mSettings.getInternalVersion(); 18863 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18864 : StorageManager.UUID_PRIVATE_INTERNAL; 18865 18866 int updateFlags = UPDATE_PERMISSIONS_ALL; 18867 if (ver.sdkVersion != mSdkVersion) { 18868 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18869 + mSdkVersion + "; regranting permissions for external"); 18870 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18871 } 18872 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18873 18874 // Yay, everything is now upgraded 18875 ver.forceCurrent(); 18876 18877 // can downgrade to reader 18878 // Persist settings 18879 mSettings.writeLPr(); 18880 } 18881 // Send a broadcast to let everyone know we are done processing 18882 if (pkgList.size() > 0) { 18883 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18884 } 18885 } 18886 18887 /* 18888 * Utility method to unload a list of specified containers 18889 */ 18890 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18891 // Just unmount all valid containers. 18892 for (AsecInstallArgs arg : cidArgs) { 18893 synchronized (mInstallLock) { 18894 arg.doPostDeleteLI(false); 18895 } 18896 } 18897 } 18898 18899 /* 18900 * Unload packages mounted on external media. This involves deleting package 18901 * data from internal structures, sending broadcasts about disabled packages, 18902 * gc'ing to free up references, unmounting all secure containers 18903 * corresponding to packages on external media, and posting a 18904 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18905 * that we always have to post this message if status has been requested no 18906 * matter what. 18907 */ 18908 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18909 final boolean reportStatus) { 18910 if (DEBUG_SD_INSTALL) 18911 Log.i(TAG, "unloading media packages"); 18912 ArrayList<String> pkgList = new ArrayList<String>(); 18913 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18914 final Set<AsecInstallArgs> keys = processCids.keySet(); 18915 for (AsecInstallArgs args : keys) { 18916 String pkgName = args.getPackageName(); 18917 if (DEBUG_SD_INSTALL) 18918 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18919 // Delete package internally 18920 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18921 synchronized (mInstallLock) { 18922 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18923 final boolean res; 18924 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18925 "unloadMediaPackages")) { 18926 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18927 null); 18928 } 18929 if (res) { 18930 pkgList.add(pkgName); 18931 } else { 18932 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18933 failedList.add(args); 18934 } 18935 } 18936 } 18937 18938 // reader 18939 synchronized (mPackages) { 18940 // We didn't update the settings after removing each package; 18941 // write them now for all packages. 18942 mSettings.writeLPr(); 18943 } 18944 18945 // We have to absolutely send UPDATED_MEDIA_STATUS only 18946 // after confirming that all the receivers processed the ordered 18947 // broadcast when packages get disabled, force a gc to clean things up. 18948 // and unload all the containers. 18949 if (pkgList.size() > 0) { 18950 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18951 new IIntentReceiver.Stub() { 18952 public void performReceive(Intent intent, int resultCode, String data, 18953 Bundle extras, boolean ordered, boolean sticky, 18954 int sendingUser) throws RemoteException { 18955 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18956 reportStatus ? 1 : 0, 1, keys); 18957 mHandler.sendMessage(msg); 18958 } 18959 }); 18960 } else { 18961 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18962 keys); 18963 mHandler.sendMessage(msg); 18964 } 18965 } 18966 18967 private void loadPrivatePackages(final VolumeInfo vol) { 18968 mHandler.post(new Runnable() { 18969 @Override 18970 public void run() { 18971 loadPrivatePackagesInner(vol); 18972 } 18973 }); 18974 } 18975 18976 private void loadPrivatePackagesInner(VolumeInfo vol) { 18977 final String volumeUuid = vol.fsUuid; 18978 if (TextUtils.isEmpty(volumeUuid)) { 18979 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18980 return; 18981 } 18982 18983 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18984 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18985 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18986 18987 final VersionInfo ver; 18988 final List<PackageSetting> packages; 18989 synchronized (mPackages) { 18990 ver = mSettings.findOrCreateVersion(volumeUuid); 18991 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18992 } 18993 18994 for (PackageSetting ps : packages) { 18995 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18996 synchronized (mInstallLock) { 18997 final PackageParser.Package pkg; 18998 try { 18999 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19000 loaded.add(pkg.applicationInfo); 19001 19002 } catch (PackageManagerException e) { 19003 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19004 } 19005 19006 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19007 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19008 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19009 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19010 } 19011 } 19012 } 19013 19014 // Reconcile app data for all started/unlocked users 19015 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19016 final UserManager um = mContext.getSystemService(UserManager.class); 19017 for (UserInfo user : um.getUsers()) { 19018 final int flags; 19019 if (um.isUserUnlockingOrUnlocked(user.id)) { 19020 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19021 } else if (um.isUserRunning(user.id)) { 19022 flags = StorageManager.FLAG_STORAGE_DE; 19023 } else { 19024 continue; 19025 } 19026 19027 try { 19028 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19029 synchronized (mInstallLock) { 19030 reconcileAppsDataLI(volumeUuid, user.id, flags); 19031 } 19032 } catch (IllegalStateException e) { 19033 // Device was probably ejected, and we'll process that event momentarily 19034 Slog.w(TAG, "Failed to prepare storage: " + e); 19035 } 19036 } 19037 19038 synchronized (mPackages) { 19039 int updateFlags = UPDATE_PERMISSIONS_ALL; 19040 if (ver.sdkVersion != mSdkVersion) { 19041 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19042 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19043 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19044 } 19045 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19046 19047 // Yay, everything is now upgraded 19048 ver.forceCurrent(); 19049 19050 mSettings.writeLPr(); 19051 } 19052 19053 for (PackageFreezer freezer : freezers) { 19054 freezer.close(); 19055 } 19056 19057 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19058 sendResourcesChangedBroadcast(true, false, loaded, null); 19059 } 19060 19061 private void unloadPrivatePackages(final VolumeInfo vol) { 19062 mHandler.post(new Runnable() { 19063 @Override 19064 public void run() { 19065 unloadPrivatePackagesInner(vol); 19066 } 19067 }); 19068 } 19069 19070 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19071 final String volumeUuid = vol.fsUuid; 19072 if (TextUtils.isEmpty(volumeUuid)) { 19073 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19074 return; 19075 } 19076 19077 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19078 synchronized (mInstallLock) { 19079 synchronized (mPackages) { 19080 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19081 for (PackageSetting ps : packages) { 19082 if (ps.pkg == null) continue; 19083 19084 final ApplicationInfo info = ps.pkg.applicationInfo; 19085 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19086 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19087 19088 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19089 "unloadPrivatePackagesInner")) { 19090 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19091 false, null)) { 19092 unloaded.add(info); 19093 } else { 19094 Slog.w(TAG, "Failed to unload " + ps.codePath); 19095 } 19096 } 19097 } 19098 19099 mSettings.writeLPr(); 19100 } 19101 } 19102 19103 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19104 sendResourcesChangedBroadcast(false, false, unloaded, null); 19105 } 19106 19107 /** 19108 * Prepare storage areas for given user on all mounted devices. 19109 */ 19110 void prepareUserData(int userId, int userSerial, int flags) { 19111 synchronized (mInstallLock) { 19112 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19113 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19114 final String volumeUuid = vol.getFsUuid(); 19115 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19116 } 19117 } 19118 } 19119 19120 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19121 boolean allowRecover) { 19122 // Prepare storage and verify that serial numbers are consistent; if 19123 // there's a mismatch we need to destroy to avoid leaking data 19124 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19125 try { 19126 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19127 19128 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19129 UserManagerService.enforceSerialNumber( 19130 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19131 } 19132 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19133 UserManagerService.enforceSerialNumber( 19134 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19135 } 19136 19137 synchronized (mInstallLock) { 19138 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19139 } 19140 } catch (Exception e) { 19141 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19142 + " because we failed to prepare: " + e); 19143 destroyUserDataLI(volumeUuid, userId, 19144 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19145 19146 if (allowRecover) { 19147 // Try one last time; if we fail again we're really in trouble 19148 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19149 } 19150 } 19151 } 19152 19153 /** 19154 * Destroy storage areas for given user on all mounted devices. 19155 */ 19156 void destroyUserData(int userId, int flags) { 19157 synchronized (mInstallLock) { 19158 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19159 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19160 final String volumeUuid = vol.getFsUuid(); 19161 destroyUserDataLI(volumeUuid, userId, flags); 19162 } 19163 } 19164 } 19165 19166 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19167 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19168 try { 19169 // Clean up app data, profile data, and media data 19170 mInstaller.destroyUserData(volumeUuid, userId, flags); 19171 19172 // Clean up system data 19173 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19174 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19175 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19176 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19177 } 19178 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19179 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19180 } 19181 } 19182 19183 // Data with special labels is now gone, so finish the job 19184 storage.destroyUserStorage(volumeUuid, userId, flags); 19185 19186 } catch (Exception e) { 19187 logCriticalInfo(Log.WARN, 19188 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19189 } 19190 } 19191 19192 /** 19193 * Examine all users present on given mounted volume, and destroy data 19194 * belonging to users that are no longer valid, or whose user ID has been 19195 * recycled. 19196 */ 19197 private void reconcileUsers(String volumeUuid) { 19198 final List<File> files = new ArrayList<>(); 19199 Collections.addAll(files, FileUtils 19200 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19201 Collections.addAll(files, FileUtils 19202 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19203 for (File file : files) { 19204 if (!file.isDirectory()) continue; 19205 19206 final int userId; 19207 final UserInfo info; 19208 try { 19209 userId = Integer.parseInt(file.getName()); 19210 info = sUserManager.getUserInfo(userId); 19211 } catch (NumberFormatException e) { 19212 Slog.w(TAG, "Invalid user directory " + file); 19213 continue; 19214 } 19215 19216 boolean destroyUser = false; 19217 if (info == null) { 19218 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19219 + " because no matching user was found"); 19220 destroyUser = true; 19221 } else if (!mOnlyCore) { 19222 try { 19223 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19224 } catch (IOException e) { 19225 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19226 + " because we failed to enforce serial number: " + e); 19227 destroyUser = true; 19228 } 19229 } 19230 19231 if (destroyUser) { 19232 synchronized (mInstallLock) { 19233 destroyUserDataLI(volumeUuid, userId, 19234 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19235 } 19236 } 19237 } 19238 } 19239 19240 private void assertPackageKnown(String volumeUuid, String packageName) 19241 throws PackageManagerException { 19242 synchronized (mPackages) { 19243 final PackageSetting ps = mSettings.mPackages.get(packageName); 19244 if (ps == null) { 19245 throw new PackageManagerException("Package " + packageName + " is unknown"); 19246 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19247 throw new PackageManagerException( 19248 "Package " + packageName + " found on unknown volume " + volumeUuid 19249 + "; expected volume " + ps.volumeUuid); 19250 } 19251 } 19252 } 19253 19254 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19255 throws PackageManagerException { 19256 synchronized (mPackages) { 19257 final PackageSetting ps = mSettings.mPackages.get(packageName); 19258 if (ps == null) { 19259 throw new PackageManagerException("Package " + packageName + " is unknown"); 19260 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19261 throw new PackageManagerException( 19262 "Package " + packageName + " found on unknown volume " + volumeUuid 19263 + "; expected volume " + ps.volumeUuid); 19264 } else if (!ps.getInstalled(userId)) { 19265 throw new PackageManagerException( 19266 "Package " + packageName + " not installed for user " + userId); 19267 } 19268 } 19269 } 19270 19271 /** 19272 * Examine all apps present on given mounted volume, and destroy apps that 19273 * aren't expected, either due to uninstallation or reinstallation on 19274 * another volume. 19275 */ 19276 private void reconcileApps(String volumeUuid) { 19277 final File[] files = FileUtils 19278 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19279 for (File file : files) { 19280 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19281 && !PackageInstallerService.isStageName(file.getName()); 19282 if (!isPackage) { 19283 // Ignore entries which are not packages 19284 continue; 19285 } 19286 19287 try { 19288 final PackageLite pkg = PackageParser.parsePackageLite(file, 19289 PackageParser.PARSE_MUST_BE_APK); 19290 assertPackageKnown(volumeUuid, pkg.packageName); 19291 19292 } catch (PackageParserException | PackageManagerException e) { 19293 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19294 synchronized (mInstallLock) { 19295 removeCodePathLI(file); 19296 } 19297 } 19298 } 19299 } 19300 19301 /** 19302 * Reconcile all app data for the given user. 19303 * <p> 19304 * Verifies that directories exist and that ownership and labeling is 19305 * correct for all installed apps on all mounted volumes. 19306 */ 19307 void reconcileAppsData(int userId, int flags) { 19308 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19309 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19310 final String volumeUuid = vol.getFsUuid(); 19311 synchronized (mInstallLock) { 19312 reconcileAppsDataLI(volumeUuid, userId, flags); 19313 } 19314 } 19315 } 19316 19317 /** 19318 * Reconcile all app data on given mounted volume. 19319 * <p> 19320 * Destroys app data that isn't expected, either due to uninstallation or 19321 * reinstallation on another volume. 19322 * <p> 19323 * Verifies that directories exist and that ownership and labeling is 19324 * correct for all installed apps. 19325 */ 19326 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19327 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19328 + Integer.toHexString(flags)); 19329 19330 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19331 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19332 19333 boolean restoreconNeeded = false; 19334 19335 // First look for stale data that doesn't belong, and check if things 19336 // have changed since we did our last restorecon 19337 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19338 if (StorageManager.isFileEncryptedNativeOrEmulated() 19339 && !StorageManager.isUserKeyUnlocked(userId)) { 19340 throw new RuntimeException( 19341 "Yikes, someone asked us to reconcile CE storage while " + userId 19342 + " was still locked; this would have caused massive data loss!"); 19343 } 19344 19345 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19346 19347 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19348 for (File file : files) { 19349 final String packageName = file.getName(); 19350 try { 19351 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19352 } catch (PackageManagerException e) { 19353 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19354 try { 19355 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19356 StorageManager.FLAG_STORAGE_CE, 0); 19357 } catch (InstallerException e2) { 19358 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19359 } 19360 } 19361 } 19362 } 19363 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19364 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19365 19366 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19367 for (File file : files) { 19368 final String packageName = file.getName(); 19369 try { 19370 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19371 } catch (PackageManagerException e) { 19372 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19373 try { 19374 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19375 StorageManager.FLAG_STORAGE_DE, 0); 19376 } catch (InstallerException e2) { 19377 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19378 } 19379 } 19380 } 19381 } 19382 19383 // Ensure that data directories are ready to roll for all packages 19384 // installed for this volume and user 19385 final List<PackageSetting> packages; 19386 synchronized (mPackages) { 19387 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19388 } 19389 int preparedCount = 0; 19390 for (PackageSetting ps : packages) { 19391 final String packageName = ps.name; 19392 if (ps.pkg == null) { 19393 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19394 // TODO: might be due to legacy ASEC apps; we should circle back 19395 // and reconcile again once they're scanned 19396 continue; 19397 } 19398 19399 if (ps.getInstalled(userId)) { 19400 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19401 19402 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19403 // We may have just shuffled around app data directories, so 19404 // prepare them one more time 19405 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19406 } 19407 19408 preparedCount++; 19409 } 19410 } 19411 19412 if (restoreconNeeded) { 19413 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19414 SELinuxMMAC.setRestoreconDone(ceDir); 19415 } 19416 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19417 SELinuxMMAC.setRestoreconDone(deDir); 19418 } 19419 } 19420 19421 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19422 + " packages; restoreconNeeded was " + restoreconNeeded); 19423 } 19424 19425 /** 19426 * Prepare app data for the given app just after it was installed or 19427 * upgraded. This method carefully only touches users that it's installed 19428 * for, and it forces a restorecon to handle any seinfo changes. 19429 * <p> 19430 * Verifies that directories exist and that ownership and labeling is 19431 * correct for all installed apps. If there is an ownership mismatch, it 19432 * will try recovering system apps by wiping data; third-party app data is 19433 * left intact. 19434 * <p> 19435 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19436 */ 19437 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19438 final PackageSetting ps; 19439 synchronized (mPackages) { 19440 ps = mSettings.mPackages.get(pkg.packageName); 19441 mSettings.writeKernelMappingLPr(ps); 19442 } 19443 19444 final UserManager um = mContext.getSystemService(UserManager.class); 19445 for (UserInfo user : um.getUsers()) { 19446 final int flags; 19447 if (um.isUserUnlockingOrUnlocked(user.id)) { 19448 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19449 } else if (um.isUserRunning(user.id)) { 19450 flags = StorageManager.FLAG_STORAGE_DE; 19451 } else { 19452 continue; 19453 } 19454 19455 if (ps.getInstalled(user.id)) { 19456 // Whenever an app changes, force a restorecon of its data 19457 // TODO: when user data is locked, mark that we're still dirty 19458 prepareAppDataLIF(pkg, user.id, flags, true); 19459 } 19460 } 19461 } 19462 19463 /** 19464 * Prepare app data for the given app. 19465 * <p> 19466 * Verifies that directories exist and that ownership and labeling is 19467 * correct for all installed apps. If there is an ownership mismatch, this 19468 * will try recovering system apps by wiping data; third-party app data is 19469 * left intact. 19470 */ 19471 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19472 boolean restoreconNeeded) { 19473 if (pkg == null) { 19474 Slog.wtf(TAG, "Package was null!", new Throwable()); 19475 return; 19476 } 19477 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19478 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19479 for (int i = 0; i < childCount; i++) { 19480 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19481 } 19482 } 19483 19484 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19485 boolean restoreconNeeded) { 19486 if (DEBUG_APP_DATA) { 19487 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19488 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19489 } 19490 19491 final String volumeUuid = pkg.volumeUuid; 19492 final String packageName = pkg.packageName; 19493 final ApplicationInfo app = pkg.applicationInfo; 19494 final int appId = UserHandle.getAppId(app.uid); 19495 19496 Preconditions.checkNotNull(app.seinfo); 19497 19498 try { 19499 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19500 appId, app.seinfo, app.targetSdkVersion); 19501 } catch (InstallerException e) { 19502 if (app.isSystemApp()) { 19503 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19504 + ", but trying to recover: " + e); 19505 destroyAppDataLeafLIF(pkg, userId, flags); 19506 try { 19507 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19508 appId, app.seinfo, app.targetSdkVersion); 19509 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19510 } catch (InstallerException e2) { 19511 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19512 } 19513 } else { 19514 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19515 } 19516 } 19517 19518 if (restoreconNeeded) { 19519 try { 19520 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19521 app.seinfo); 19522 } catch (InstallerException e) { 19523 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19524 } 19525 } 19526 19527 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19528 try { 19529 // CE storage is unlocked right now, so read out the inode and 19530 // remember for use later when it's locked 19531 // TODO: mark this structure as dirty so we persist it! 19532 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19533 StorageManager.FLAG_STORAGE_CE); 19534 synchronized (mPackages) { 19535 final PackageSetting ps = mSettings.mPackages.get(packageName); 19536 if (ps != null) { 19537 ps.setCeDataInode(ceDataInode, userId); 19538 } 19539 } 19540 } catch (InstallerException e) { 19541 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19542 } 19543 } 19544 19545 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19546 } 19547 19548 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19549 if (pkg == null) { 19550 Slog.wtf(TAG, "Package was null!", new Throwable()); 19551 return; 19552 } 19553 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19554 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19555 for (int i = 0; i < childCount; i++) { 19556 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19557 } 19558 } 19559 19560 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19561 final String volumeUuid = pkg.volumeUuid; 19562 final String packageName = pkg.packageName; 19563 final ApplicationInfo app = pkg.applicationInfo; 19564 19565 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19566 // Create a native library symlink only if we have native libraries 19567 // and if the native libraries are 32 bit libraries. We do not provide 19568 // this symlink for 64 bit libraries. 19569 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19570 final String nativeLibPath = app.nativeLibraryDir; 19571 try { 19572 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19573 nativeLibPath, userId); 19574 } catch (InstallerException e) { 19575 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19576 } 19577 } 19578 } 19579 } 19580 19581 /** 19582 * For system apps on non-FBE devices, this method migrates any existing 19583 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19584 * requested by the app. 19585 */ 19586 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19587 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19588 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19589 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19590 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19591 try { 19592 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19593 storageTarget); 19594 } catch (InstallerException e) { 19595 logCriticalInfo(Log.WARN, 19596 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19597 } 19598 return true; 19599 } else { 19600 return false; 19601 } 19602 } 19603 19604 public PackageFreezer freezePackage(String packageName, String killReason) { 19605 return new PackageFreezer(packageName, killReason); 19606 } 19607 19608 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19609 String killReason) { 19610 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19611 return new PackageFreezer(); 19612 } else { 19613 return freezePackage(packageName, killReason); 19614 } 19615 } 19616 19617 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19618 String killReason) { 19619 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19620 return new PackageFreezer(); 19621 } else { 19622 return freezePackage(packageName, killReason); 19623 } 19624 } 19625 19626 /** 19627 * Class that freezes and kills the given package upon creation, and 19628 * unfreezes it upon closing. This is typically used when doing surgery on 19629 * app code/data to prevent the app from running while you're working. 19630 */ 19631 private class PackageFreezer implements AutoCloseable { 19632 private final String mPackageName; 19633 private final PackageFreezer[] mChildren; 19634 19635 private final boolean mWeFroze; 19636 19637 private final AtomicBoolean mClosed = new AtomicBoolean(); 19638 private final CloseGuard mCloseGuard = CloseGuard.get(); 19639 19640 /** 19641 * Create and return a stub freezer that doesn't actually do anything, 19642 * typically used when someone requested 19643 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19644 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19645 */ 19646 public PackageFreezer() { 19647 mPackageName = null; 19648 mChildren = null; 19649 mWeFroze = false; 19650 mCloseGuard.open("close"); 19651 } 19652 19653 public PackageFreezer(String packageName, String killReason) { 19654 synchronized (mPackages) { 19655 mPackageName = packageName; 19656 mWeFroze = mFrozenPackages.add(mPackageName); 19657 19658 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19659 if (ps != null) { 19660 killApplication(ps.name, ps.appId, killReason); 19661 } 19662 19663 final PackageParser.Package p = mPackages.get(packageName); 19664 if (p != null && p.childPackages != null) { 19665 final int N = p.childPackages.size(); 19666 mChildren = new PackageFreezer[N]; 19667 for (int i = 0; i < N; i++) { 19668 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19669 killReason); 19670 } 19671 } else { 19672 mChildren = null; 19673 } 19674 } 19675 mCloseGuard.open("close"); 19676 } 19677 19678 @Override 19679 protected void finalize() throws Throwable { 19680 try { 19681 mCloseGuard.warnIfOpen(); 19682 close(); 19683 } finally { 19684 super.finalize(); 19685 } 19686 } 19687 19688 @Override 19689 public void close() { 19690 mCloseGuard.close(); 19691 if (mClosed.compareAndSet(false, true)) { 19692 synchronized (mPackages) { 19693 if (mWeFroze) { 19694 mFrozenPackages.remove(mPackageName); 19695 } 19696 19697 if (mChildren != null) { 19698 for (PackageFreezer freezer : mChildren) { 19699 freezer.close(); 19700 } 19701 } 19702 } 19703 } 19704 } 19705 } 19706 19707 /** 19708 * Verify that given package is currently frozen. 19709 */ 19710 private void checkPackageFrozen(String packageName) { 19711 synchronized (mPackages) { 19712 if (!mFrozenPackages.contains(packageName)) { 19713 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19714 } 19715 } 19716 } 19717 19718 @Override 19719 public int movePackage(final String packageName, final String volumeUuid) { 19720 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19721 19722 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19723 final int moveId = mNextMoveId.getAndIncrement(); 19724 mHandler.post(new Runnable() { 19725 @Override 19726 public void run() { 19727 try { 19728 movePackageInternal(packageName, volumeUuid, moveId, user); 19729 } catch (PackageManagerException e) { 19730 Slog.w(TAG, "Failed to move " + packageName, e); 19731 mMoveCallbacks.notifyStatusChanged(moveId, 19732 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19733 } 19734 } 19735 }); 19736 return moveId; 19737 } 19738 19739 private void movePackageInternal(final String packageName, final String volumeUuid, 19740 final int moveId, UserHandle user) throws PackageManagerException { 19741 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19742 final PackageManager pm = mContext.getPackageManager(); 19743 19744 final boolean currentAsec; 19745 final String currentVolumeUuid; 19746 final File codeFile; 19747 final String installerPackageName; 19748 final String packageAbiOverride; 19749 final int appId; 19750 final String seinfo; 19751 final String label; 19752 final int targetSdkVersion; 19753 final PackageFreezer freezer; 19754 final int[] installedUserIds; 19755 19756 // reader 19757 synchronized (mPackages) { 19758 final PackageParser.Package pkg = mPackages.get(packageName); 19759 final PackageSetting ps = mSettings.mPackages.get(packageName); 19760 if (pkg == null || ps == null) { 19761 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19762 } 19763 19764 if (pkg.applicationInfo.isSystemApp()) { 19765 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19766 "Cannot move system application"); 19767 } 19768 19769 if (pkg.applicationInfo.isExternalAsec()) { 19770 currentAsec = true; 19771 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19772 } else if (pkg.applicationInfo.isForwardLocked()) { 19773 currentAsec = true; 19774 currentVolumeUuid = "forward_locked"; 19775 } else { 19776 currentAsec = false; 19777 currentVolumeUuid = ps.volumeUuid; 19778 19779 final File probe = new File(pkg.codePath); 19780 final File probeOat = new File(probe, "oat"); 19781 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19782 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19783 "Move only supported for modern cluster style installs"); 19784 } 19785 } 19786 19787 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19788 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19789 "Package already moved to " + volumeUuid); 19790 } 19791 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19792 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19793 "Device admin cannot be moved"); 19794 } 19795 19796 if (mFrozenPackages.contains(packageName)) { 19797 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19798 "Failed to move already frozen package"); 19799 } 19800 19801 codeFile = new File(pkg.codePath); 19802 installerPackageName = ps.installerPackageName; 19803 packageAbiOverride = ps.cpuAbiOverrideString; 19804 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19805 seinfo = pkg.applicationInfo.seinfo; 19806 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19807 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19808 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19809 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19810 } 19811 19812 final Bundle extras = new Bundle(); 19813 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19814 extras.putString(Intent.EXTRA_TITLE, label); 19815 mMoveCallbacks.notifyCreated(moveId, extras); 19816 19817 int installFlags; 19818 final boolean moveCompleteApp; 19819 final File measurePath; 19820 19821 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19822 installFlags = INSTALL_INTERNAL; 19823 moveCompleteApp = !currentAsec; 19824 measurePath = Environment.getDataAppDirectory(volumeUuid); 19825 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19826 installFlags = INSTALL_EXTERNAL; 19827 moveCompleteApp = false; 19828 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19829 } else { 19830 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19831 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19832 || !volume.isMountedWritable()) { 19833 freezer.close(); 19834 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19835 "Move location not mounted private volume"); 19836 } 19837 19838 Preconditions.checkState(!currentAsec); 19839 19840 installFlags = INSTALL_INTERNAL; 19841 moveCompleteApp = true; 19842 measurePath = Environment.getDataAppDirectory(volumeUuid); 19843 } 19844 19845 final PackageStats stats = new PackageStats(null, -1); 19846 synchronized (mInstaller) { 19847 for (int userId : installedUserIds) { 19848 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19849 freezer.close(); 19850 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19851 "Failed to measure package size"); 19852 } 19853 } 19854 } 19855 19856 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19857 + stats.dataSize); 19858 19859 final long startFreeBytes = measurePath.getFreeSpace(); 19860 final long sizeBytes; 19861 if (moveCompleteApp) { 19862 sizeBytes = stats.codeSize + stats.dataSize; 19863 } else { 19864 sizeBytes = stats.codeSize; 19865 } 19866 19867 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19868 freezer.close(); 19869 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19870 "Not enough free space to move"); 19871 } 19872 19873 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19874 19875 final CountDownLatch installedLatch = new CountDownLatch(1); 19876 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19877 @Override 19878 public void onUserActionRequired(Intent intent) throws RemoteException { 19879 throw new IllegalStateException(); 19880 } 19881 19882 @Override 19883 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19884 Bundle extras) throws RemoteException { 19885 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19886 + PackageManager.installStatusToString(returnCode, msg)); 19887 19888 installedLatch.countDown(); 19889 freezer.close(); 19890 19891 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19892 switch (status) { 19893 case PackageInstaller.STATUS_SUCCESS: 19894 mMoveCallbacks.notifyStatusChanged(moveId, 19895 PackageManager.MOVE_SUCCEEDED); 19896 break; 19897 case PackageInstaller.STATUS_FAILURE_STORAGE: 19898 mMoveCallbacks.notifyStatusChanged(moveId, 19899 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19900 break; 19901 default: 19902 mMoveCallbacks.notifyStatusChanged(moveId, 19903 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19904 break; 19905 } 19906 } 19907 }; 19908 19909 final MoveInfo move; 19910 if (moveCompleteApp) { 19911 // Kick off a thread to report progress estimates 19912 new Thread() { 19913 @Override 19914 public void run() { 19915 while (true) { 19916 try { 19917 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19918 break; 19919 } 19920 } catch (InterruptedException ignored) { 19921 } 19922 19923 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19924 final int progress = 10 + (int) MathUtils.constrain( 19925 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19926 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19927 } 19928 } 19929 }.start(); 19930 19931 final String dataAppName = codeFile.getName(); 19932 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19933 dataAppName, appId, seinfo, targetSdkVersion); 19934 } else { 19935 move = null; 19936 } 19937 19938 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19939 19940 final Message msg = mHandler.obtainMessage(INIT_COPY); 19941 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19942 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19943 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19944 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19945 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19946 msg.obj = params; 19947 19948 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19949 System.identityHashCode(msg.obj)); 19950 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19951 System.identityHashCode(msg.obj)); 19952 19953 mHandler.sendMessage(msg); 19954 } 19955 19956 @Override 19957 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19958 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19959 19960 final int realMoveId = mNextMoveId.getAndIncrement(); 19961 final Bundle extras = new Bundle(); 19962 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19963 mMoveCallbacks.notifyCreated(realMoveId, extras); 19964 19965 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19966 @Override 19967 public void onCreated(int moveId, Bundle extras) { 19968 // Ignored 19969 } 19970 19971 @Override 19972 public void onStatusChanged(int moveId, int status, long estMillis) { 19973 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19974 } 19975 }; 19976 19977 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19978 storage.setPrimaryStorageUuid(volumeUuid, callback); 19979 return realMoveId; 19980 } 19981 19982 @Override 19983 public int getMoveStatus(int moveId) { 19984 mContext.enforceCallingOrSelfPermission( 19985 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19986 return mMoveCallbacks.mLastStatus.get(moveId); 19987 } 19988 19989 @Override 19990 public void registerMoveCallback(IPackageMoveObserver callback) { 19991 mContext.enforceCallingOrSelfPermission( 19992 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19993 mMoveCallbacks.register(callback); 19994 } 19995 19996 @Override 19997 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19998 mContext.enforceCallingOrSelfPermission( 19999 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20000 mMoveCallbacks.unregister(callback); 20001 } 20002 20003 @Override 20004 public boolean setInstallLocation(int loc) { 20005 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20006 null); 20007 if (getInstallLocation() == loc) { 20008 return true; 20009 } 20010 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20011 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20012 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20013 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20014 return true; 20015 } 20016 return false; 20017 } 20018 20019 @Override 20020 public int getInstallLocation() { 20021 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20022 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20023 PackageHelper.APP_INSTALL_AUTO); 20024 } 20025 20026 /** Called by UserManagerService */ 20027 void cleanUpUser(UserManagerService userManager, int userHandle) { 20028 synchronized (mPackages) { 20029 mDirtyUsers.remove(userHandle); 20030 mUserNeedsBadging.delete(userHandle); 20031 mSettings.removeUserLPw(userHandle); 20032 mPendingBroadcasts.remove(userHandle); 20033 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20034 removeUnusedPackagesLPw(userManager, userHandle); 20035 } 20036 } 20037 20038 /** 20039 * We're removing userHandle and would like to remove any downloaded packages 20040 * that are no longer in use by any other user. 20041 * @param userHandle the user being removed 20042 */ 20043 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20044 final boolean DEBUG_CLEAN_APKS = false; 20045 int [] users = userManager.getUserIds(); 20046 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20047 while (psit.hasNext()) { 20048 PackageSetting ps = psit.next(); 20049 if (ps.pkg == null) { 20050 continue; 20051 } 20052 final String packageName = ps.pkg.packageName; 20053 // Skip over if system app 20054 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20055 continue; 20056 } 20057 if (DEBUG_CLEAN_APKS) { 20058 Slog.i(TAG, "Checking package " + packageName); 20059 } 20060 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20061 if (keep) { 20062 if (DEBUG_CLEAN_APKS) { 20063 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20064 } 20065 } else { 20066 for (int i = 0; i < users.length; i++) { 20067 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20068 keep = true; 20069 if (DEBUG_CLEAN_APKS) { 20070 Slog.i(TAG, " Keeping package " + packageName + " for user " 20071 + users[i]); 20072 } 20073 break; 20074 } 20075 } 20076 } 20077 if (!keep) { 20078 if (DEBUG_CLEAN_APKS) { 20079 Slog.i(TAG, " Removing package " + packageName); 20080 } 20081 mHandler.post(new Runnable() { 20082 public void run() { 20083 deletePackageX(packageName, userHandle, 0); 20084 } //end run 20085 }); 20086 } 20087 } 20088 } 20089 20090 /** Called by UserManagerService */ 20091 void createNewUser(int userHandle) { 20092 synchronized (mInstallLock) { 20093 mSettings.createNewUserLI(this, mInstaller, userHandle); 20094 } 20095 synchronized (mPackages) { 20096 applyFactoryDefaultBrowserLPw(userHandle); 20097 primeDomainVerificationsLPw(userHandle); 20098 } 20099 } 20100 20101 void newUserCreated(final int userHandle) { 20102 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 20103 // If permission review for legacy apps is required, we represent 20104 // dagerous permissions for such apps as always granted runtime 20105 // permissions to keep per user flag state whether review is needed. 20106 // Hence, if a new user is added we have to propagate dangerous 20107 // permission grants for these legacy apps. 20108 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20109 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20110 | UPDATE_PERMISSIONS_REPLACE_ALL); 20111 } 20112 } 20113 20114 @Override 20115 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20116 mContext.enforceCallingOrSelfPermission( 20117 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20118 "Only package verification agents can read the verifier device identity"); 20119 20120 synchronized (mPackages) { 20121 return mSettings.getVerifierDeviceIdentityLPw(); 20122 } 20123 } 20124 20125 @Override 20126 public void setPermissionEnforced(String permission, boolean enforced) { 20127 // TODO: Now that we no longer change GID for storage, this should to away. 20128 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20129 "setPermissionEnforced"); 20130 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20131 synchronized (mPackages) { 20132 if (mSettings.mReadExternalStorageEnforced == null 20133 || mSettings.mReadExternalStorageEnforced != enforced) { 20134 mSettings.mReadExternalStorageEnforced = enforced; 20135 mSettings.writeLPr(); 20136 } 20137 } 20138 // kill any non-foreground processes so we restart them and 20139 // grant/revoke the GID. 20140 final IActivityManager am = ActivityManagerNative.getDefault(); 20141 if (am != null) { 20142 final long token = Binder.clearCallingIdentity(); 20143 try { 20144 am.killProcessesBelowForeground("setPermissionEnforcement"); 20145 } catch (RemoteException e) { 20146 } finally { 20147 Binder.restoreCallingIdentity(token); 20148 } 20149 } 20150 } else { 20151 throw new IllegalArgumentException("No selective enforcement for " + permission); 20152 } 20153 } 20154 20155 @Override 20156 @Deprecated 20157 public boolean isPermissionEnforced(String permission) { 20158 return true; 20159 } 20160 20161 @Override 20162 public boolean isStorageLow() { 20163 final long token = Binder.clearCallingIdentity(); 20164 try { 20165 final DeviceStorageMonitorInternal 20166 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20167 if (dsm != null) { 20168 return dsm.isMemoryLow(); 20169 } else { 20170 return false; 20171 } 20172 } finally { 20173 Binder.restoreCallingIdentity(token); 20174 } 20175 } 20176 20177 @Override 20178 public IPackageInstaller getPackageInstaller() { 20179 return mInstallerService; 20180 } 20181 20182 private boolean userNeedsBadging(int userId) { 20183 int index = mUserNeedsBadging.indexOfKey(userId); 20184 if (index < 0) { 20185 final UserInfo userInfo; 20186 final long token = Binder.clearCallingIdentity(); 20187 try { 20188 userInfo = sUserManager.getUserInfo(userId); 20189 } finally { 20190 Binder.restoreCallingIdentity(token); 20191 } 20192 final boolean b; 20193 if (userInfo != null && userInfo.isManagedProfile()) { 20194 b = true; 20195 } else { 20196 b = false; 20197 } 20198 mUserNeedsBadging.put(userId, b); 20199 return b; 20200 } 20201 return mUserNeedsBadging.valueAt(index); 20202 } 20203 20204 @Override 20205 public KeySet getKeySetByAlias(String packageName, String alias) { 20206 if (packageName == null || alias == null) { 20207 return null; 20208 } 20209 synchronized(mPackages) { 20210 final PackageParser.Package pkg = mPackages.get(packageName); 20211 if (pkg == null) { 20212 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20213 throw new IllegalArgumentException("Unknown package: " + packageName); 20214 } 20215 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20216 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20217 } 20218 } 20219 20220 @Override 20221 public KeySet getSigningKeySet(String packageName) { 20222 if (packageName == null) { 20223 return null; 20224 } 20225 synchronized(mPackages) { 20226 final PackageParser.Package pkg = mPackages.get(packageName); 20227 if (pkg == null) { 20228 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20229 throw new IllegalArgumentException("Unknown package: " + packageName); 20230 } 20231 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20232 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20233 throw new SecurityException("May not access signing KeySet of other apps."); 20234 } 20235 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20236 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20237 } 20238 } 20239 20240 @Override 20241 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20242 if (packageName == null || ks == null) { 20243 return false; 20244 } 20245 synchronized(mPackages) { 20246 final PackageParser.Package pkg = mPackages.get(packageName); 20247 if (pkg == null) { 20248 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20249 throw new IllegalArgumentException("Unknown package: " + packageName); 20250 } 20251 IBinder ksh = ks.getToken(); 20252 if (ksh instanceof KeySetHandle) { 20253 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20254 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20255 } 20256 return false; 20257 } 20258 } 20259 20260 @Override 20261 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20262 if (packageName == null || ks == null) { 20263 return false; 20264 } 20265 synchronized(mPackages) { 20266 final PackageParser.Package pkg = mPackages.get(packageName); 20267 if (pkg == null) { 20268 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20269 throw new IllegalArgumentException("Unknown package: " + packageName); 20270 } 20271 IBinder ksh = ks.getToken(); 20272 if (ksh instanceof KeySetHandle) { 20273 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20274 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20275 } 20276 return false; 20277 } 20278 } 20279 20280 private void deletePackageIfUnusedLPr(final String packageName) { 20281 PackageSetting ps = mSettings.mPackages.get(packageName); 20282 if (ps == null) { 20283 return; 20284 } 20285 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20286 // TODO Implement atomic delete if package is unused 20287 // It is currently possible that the package will be deleted even if it is installed 20288 // after this method returns. 20289 mHandler.post(new Runnable() { 20290 public void run() { 20291 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20292 } 20293 }); 20294 } 20295 } 20296 20297 /** 20298 * Check and throw if the given before/after packages would be considered a 20299 * downgrade. 20300 */ 20301 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20302 throws PackageManagerException { 20303 if (after.versionCode < before.mVersionCode) { 20304 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20305 "Update version code " + after.versionCode + " is older than current " 20306 + before.mVersionCode); 20307 } else if (after.versionCode == before.mVersionCode) { 20308 if (after.baseRevisionCode < before.baseRevisionCode) { 20309 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20310 "Update base revision code " + after.baseRevisionCode 20311 + " is older than current " + before.baseRevisionCode); 20312 } 20313 20314 if (!ArrayUtils.isEmpty(after.splitNames)) { 20315 for (int i = 0; i < after.splitNames.length; i++) { 20316 final String splitName = after.splitNames[i]; 20317 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20318 if (j != -1) { 20319 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20320 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20321 "Update split " + splitName + " revision code " 20322 + after.splitRevisionCodes[i] + " is older than current " 20323 + before.splitRevisionCodes[j]); 20324 } 20325 } 20326 } 20327 } 20328 } 20329 } 20330 20331 private static class MoveCallbacks extends Handler { 20332 private static final int MSG_CREATED = 1; 20333 private static final int MSG_STATUS_CHANGED = 2; 20334 20335 private final RemoteCallbackList<IPackageMoveObserver> 20336 mCallbacks = new RemoteCallbackList<>(); 20337 20338 private final SparseIntArray mLastStatus = new SparseIntArray(); 20339 20340 public MoveCallbacks(Looper looper) { 20341 super(looper); 20342 } 20343 20344 public void register(IPackageMoveObserver callback) { 20345 mCallbacks.register(callback); 20346 } 20347 20348 public void unregister(IPackageMoveObserver callback) { 20349 mCallbacks.unregister(callback); 20350 } 20351 20352 @Override 20353 public void handleMessage(Message msg) { 20354 final SomeArgs args = (SomeArgs) msg.obj; 20355 final int n = mCallbacks.beginBroadcast(); 20356 for (int i = 0; i < n; i++) { 20357 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20358 try { 20359 invokeCallback(callback, msg.what, args); 20360 } catch (RemoteException ignored) { 20361 } 20362 } 20363 mCallbacks.finishBroadcast(); 20364 args.recycle(); 20365 } 20366 20367 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20368 throws RemoteException { 20369 switch (what) { 20370 case MSG_CREATED: { 20371 callback.onCreated(args.argi1, (Bundle) args.arg2); 20372 break; 20373 } 20374 case MSG_STATUS_CHANGED: { 20375 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20376 break; 20377 } 20378 } 20379 } 20380 20381 private void notifyCreated(int moveId, Bundle extras) { 20382 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20383 20384 final SomeArgs args = SomeArgs.obtain(); 20385 args.argi1 = moveId; 20386 args.arg2 = extras; 20387 obtainMessage(MSG_CREATED, args).sendToTarget(); 20388 } 20389 20390 private void notifyStatusChanged(int moveId, int status) { 20391 notifyStatusChanged(moveId, status, -1); 20392 } 20393 20394 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20395 Slog.v(TAG, "Move " + moveId + " status " + status); 20396 20397 final SomeArgs args = SomeArgs.obtain(); 20398 args.argi1 = moveId; 20399 args.argi2 = status; 20400 args.arg3 = estMillis; 20401 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20402 20403 synchronized (mLastStatus) { 20404 mLastStatus.put(moveId, status); 20405 } 20406 } 20407 } 20408 20409 private final static class OnPermissionChangeListeners extends Handler { 20410 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20411 20412 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20413 new RemoteCallbackList<>(); 20414 20415 public OnPermissionChangeListeners(Looper looper) { 20416 super(looper); 20417 } 20418 20419 @Override 20420 public void handleMessage(Message msg) { 20421 switch (msg.what) { 20422 case MSG_ON_PERMISSIONS_CHANGED: { 20423 final int uid = msg.arg1; 20424 handleOnPermissionsChanged(uid); 20425 } break; 20426 } 20427 } 20428 20429 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20430 mPermissionListeners.register(listener); 20431 20432 } 20433 20434 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20435 mPermissionListeners.unregister(listener); 20436 } 20437 20438 public void onPermissionsChanged(int uid) { 20439 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20440 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20441 } 20442 } 20443 20444 private void handleOnPermissionsChanged(int uid) { 20445 final int count = mPermissionListeners.beginBroadcast(); 20446 try { 20447 for (int i = 0; i < count; i++) { 20448 IOnPermissionsChangeListener callback = mPermissionListeners 20449 .getBroadcastItem(i); 20450 try { 20451 callback.onPermissionsChanged(uid); 20452 } catch (RemoteException e) { 20453 Log.e(TAG, "Permission listener is dead", e); 20454 } 20455 } 20456 } finally { 20457 mPermissionListeners.finishBroadcast(); 20458 } 20459 } 20460 } 20461 20462 private class PackageManagerInternalImpl extends PackageManagerInternal { 20463 @Override 20464 public void setLocationPackagesProvider(PackagesProvider provider) { 20465 synchronized (mPackages) { 20466 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20467 } 20468 } 20469 20470 @Override 20471 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20472 synchronized (mPackages) { 20473 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20474 } 20475 } 20476 20477 @Override 20478 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20479 synchronized (mPackages) { 20480 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20481 } 20482 } 20483 20484 @Override 20485 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20486 synchronized (mPackages) { 20487 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20488 } 20489 } 20490 20491 @Override 20492 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20493 synchronized (mPackages) { 20494 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20495 } 20496 } 20497 20498 @Override 20499 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20500 synchronized (mPackages) { 20501 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20502 } 20503 } 20504 20505 @Override 20506 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20507 synchronized (mPackages) { 20508 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20509 packageName, userId); 20510 } 20511 } 20512 20513 @Override 20514 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20515 synchronized (mPackages) { 20516 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20517 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20518 packageName, userId); 20519 } 20520 } 20521 20522 @Override 20523 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20524 synchronized (mPackages) { 20525 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20526 packageName, userId); 20527 } 20528 } 20529 20530 @Override 20531 public void setKeepUninstalledPackages(final List<String> packageList) { 20532 Preconditions.checkNotNull(packageList); 20533 List<String> removedFromList = null; 20534 synchronized (mPackages) { 20535 if (mKeepUninstalledPackages != null) { 20536 final int packagesCount = mKeepUninstalledPackages.size(); 20537 for (int i = 0; i < packagesCount; i++) { 20538 String oldPackage = mKeepUninstalledPackages.get(i); 20539 if (packageList != null && packageList.contains(oldPackage)) { 20540 continue; 20541 } 20542 if (removedFromList == null) { 20543 removedFromList = new ArrayList<>(); 20544 } 20545 removedFromList.add(oldPackage); 20546 } 20547 } 20548 mKeepUninstalledPackages = new ArrayList<>(packageList); 20549 if (removedFromList != null) { 20550 final int removedCount = removedFromList.size(); 20551 for (int i = 0; i < removedCount; i++) { 20552 deletePackageIfUnusedLPr(removedFromList.get(i)); 20553 } 20554 } 20555 } 20556 } 20557 20558 @Override 20559 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20560 synchronized (mPackages) { 20561 // If we do not support permission review, done. 20562 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20563 return false; 20564 } 20565 20566 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20567 if (packageSetting == null) { 20568 return false; 20569 } 20570 20571 // Permission review applies only to apps not supporting the new permission model. 20572 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20573 return false; 20574 } 20575 20576 // Legacy apps have the permission and get user consent on launch. 20577 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20578 return permissionsState.isPermissionReviewRequired(userId); 20579 } 20580 } 20581 20582 @Override 20583 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20584 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20585 } 20586 20587 @Override 20588 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20589 int userId) { 20590 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20591 } 20592 } 20593 20594 @Override 20595 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20596 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20597 synchronized (mPackages) { 20598 final long identity = Binder.clearCallingIdentity(); 20599 try { 20600 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20601 packageNames, userId); 20602 } finally { 20603 Binder.restoreCallingIdentity(identity); 20604 } 20605 } 20606 } 20607 20608 private static void enforceSystemOrPhoneCaller(String tag) { 20609 int callingUid = Binder.getCallingUid(); 20610 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20611 throw new SecurityException( 20612 "Cannot call " + tag + " from UID " + callingUid); 20613 } 20614 } 20615 20616 boolean isHistoricalPackageUsageAvailable() { 20617 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20618 } 20619 20620 /** 20621 * Return a <b>copy</b> of the collection of packages known to the package manager. 20622 * @return A copy of the values of mPackages. 20623 */ 20624 Collection<PackageParser.Package> getPackages() { 20625 synchronized (mPackages) { 20626 return new ArrayList<>(mPackages.values()); 20627 } 20628 } 20629 20630 /** 20631 * Logs process start information (including base APK hash) to the security log. 20632 * @hide 20633 */ 20634 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20635 String apkFile, int pid) { 20636 if (!SecurityLog.isLoggingEnabled()) { 20637 return; 20638 } 20639 Bundle data = new Bundle(); 20640 data.putLong("startTimestamp", System.currentTimeMillis()); 20641 data.putString("processName", processName); 20642 data.putInt("uid", uid); 20643 data.putString("seinfo", seinfo); 20644 data.putString("apkFile", apkFile); 20645 data.putInt("pid", pid); 20646 Message msg = mProcessLoggingHandler.obtainMessage( 20647 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20648 msg.setData(data); 20649 mProcessLoggingHandler.sendMessage(msg); 20650 } 20651} 20652