PackageManagerService.java revision 7366e8c16afb76ca1394385ab28be43e9ebb1898
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.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 102 103import android.Manifest; 104import android.annotation.NonNull; 105import android.annotation.Nullable; 106import android.annotation.UserIdInt; 107import android.app.ActivityManager; 108import android.app.ActivityManagerNative; 109import android.app.IActivityManager; 110import android.app.ResourcesManager; 111import android.app.admin.IDevicePolicyManager; 112import android.app.admin.SecurityLog; 113import android.app.backup.IBackupManager; 114import android.content.BroadcastReceiver; 115import android.content.ComponentName; 116import android.content.Context; 117import android.content.IIntentReceiver; 118import android.content.Intent; 119import android.content.IntentFilter; 120import android.content.IntentSender; 121import android.content.IntentSender.SendIntentException; 122import android.content.ServiceConnection; 123import android.content.pm.ActivityInfo; 124import android.content.pm.ApplicationInfo; 125import android.content.pm.AppsQueryHelper; 126import android.content.pm.ComponentInfo; 127import android.content.pm.EphemeralApplicationInfo; 128import android.content.pm.EphemeralResolveInfo; 129import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 130import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 131import android.content.pm.FeatureInfo; 132import android.content.pm.IOnPermissionsChangeListener; 133import android.content.pm.IPackageDataObserver; 134import android.content.pm.IPackageDeleteObserver; 135import android.content.pm.IPackageDeleteObserver2; 136import android.content.pm.IPackageInstallObserver2; 137import android.content.pm.IPackageInstaller; 138import android.content.pm.IPackageManager; 139import android.content.pm.IPackageMoveObserver; 140import android.content.pm.IPackageStatsObserver; 141import android.content.pm.InstrumentationInfo; 142import android.content.pm.IntentFilterVerificationInfo; 143import android.content.pm.KeySet; 144import android.content.pm.PackageCleanItem; 145import android.content.pm.PackageInfo; 146import android.content.pm.PackageInfoLite; 147import android.content.pm.PackageInstaller; 148import android.content.pm.PackageManager; 149import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 150import android.content.pm.PackageManagerInternal; 151import android.content.pm.PackageParser; 152import android.content.pm.PackageParser.ActivityIntentInfo; 153import android.content.pm.PackageParser.PackageLite; 154import android.content.pm.PackageParser.PackageParserException; 155import android.content.pm.PackageStats; 156import android.content.pm.PackageUserState; 157import android.content.pm.ParceledListSlice; 158import android.content.pm.PermissionGroupInfo; 159import android.content.pm.PermissionInfo; 160import android.content.pm.ProviderInfo; 161import android.content.pm.ResolveInfo; 162import android.content.pm.ServiceInfo; 163import android.content.pm.Signature; 164import android.content.pm.UserInfo; 165import android.content.pm.VerifierDeviceIdentity; 166import android.content.pm.VerifierInfo; 167import android.content.res.Resources; 168import android.graphics.Bitmap; 169import android.hardware.display.DisplayManager; 170import android.net.Uri; 171import android.os.Binder; 172import android.os.Build; 173import android.os.Bundle; 174import android.os.Debug; 175import android.os.Environment; 176import android.os.Environment.UserEnvironment; 177import android.os.FileUtils; 178import android.os.Handler; 179import android.os.IBinder; 180import android.os.Looper; 181import android.os.Message; 182import android.os.Parcel; 183import android.os.ParcelFileDescriptor; 184import android.os.Process; 185import android.os.RemoteCallbackList; 186import android.os.RemoteException; 187import android.os.ResultReceiver; 188import android.os.SELinux; 189import android.os.ServiceManager; 190import android.os.SystemClock; 191import android.os.SystemProperties; 192import android.os.Trace; 193import android.os.UserHandle; 194import android.os.UserManager; 195import android.os.UserManagerInternal; 196import android.os.storage.IMountService; 197import android.os.storage.MountServiceInternal; 198import android.os.storage.StorageEventListener; 199import android.os.storage.StorageManager; 200import android.os.storage.VolumeInfo; 201import android.os.storage.VolumeRecord; 202import android.provider.Settings.Global; 203import android.security.KeyStore; 204import android.security.SystemKeyStore; 205import android.system.ErrnoException; 206import android.system.Os; 207import android.text.TextUtils; 208import android.text.format.DateUtils; 209import android.util.ArrayMap; 210import android.util.ArraySet; 211import android.util.AtomicFile; 212import android.util.DisplayMetrics; 213import android.util.EventLog; 214import android.util.ExceptionUtils; 215import android.util.Log; 216import android.util.LogPrinter; 217import android.util.MathUtils; 218import android.util.PrintStreamPrinter; 219import android.util.Slog; 220import android.util.SparseArray; 221import android.util.SparseBooleanArray; 222import android.util.SparseIntArray; 223import android.util.Xml; 224import android.util.jar.StrictJarFile; 225import android.view.Display; 226 227import com.android.internal.R; 228import com.android.internal.annotations.GuardedBy; 229import com.android.internal.app.IMediaContainerService; 230import com.android.internal.app.ResolverActivity; 231import com.android.internal.content.NativeLibraryHelper; 232import com.android.internal.content.PackageHelper; 233import com.android.internal.logging.MetricsLogger; 234import com.android.internal.os.IParcelFileDescriptorFactory; 235import com.android.internal.os.InstallerConnection.InstallerException; 236import com.android.internal.os.SomeArgs; 237import com.android.internal.os.Zygote; 238import com.android.internal.telephony.CarrierAppUtils; 239import com.android.internal.util.ArrayUtils; 240import com.android.internal.util.FastPrintWriter; 241import com.android.internal.util.FastXmlSerializer; 242import com.android.internal.util.IndentingPrintWriter; 243import com.android.internal.util.Preconditions; 244import com.android.internal.util.XmlUtils; 245import com.android.server.AttributeCache; 246import com.android.server.EventLogTags; 247import com.android.server.FgThread; 248import com.android.server.IntentResolver; 249import com.android.server.LocalServices; 250import com.android.server.ServiceThread; 251import com.android.server.SystemConfig; 252import com.android.server.Watchdog; 253import com.android.server.net.NetworkPolicyManagerInternal; 254import com.android.server.pm.PermissionsState.PermissionState; 255import com.android.server.pm.Settings.DatabaseVersion; 256import com.android.server.pm.Settings.VersionInfo; 257import com.android.server.storage.DeviceStorageMonitorInternal; 258 259import dalvik.system.CloseGuard; 260import dalvik.system.DexFile; 261import dalvik.system.VMRuntime; 262 263import libcore.io.IoUtils; 264import libcore.util.EmptyArray; 265 266import org.xmlpull.v1.XmlPullParser; 267import org.xmlpull.v1.XmlPullParserException; 268import org.xmlpull.v1.XmlSerializer; 269 270import java.io.BufferedInputStream; 271import java.io.BufferedOutputStream; 272import java.io.BufferedReader; 273import java.io.ByteArrayInputStream; 274import java.io.ByteArrayOutputStream; 275import java.io.File; 276import java.io.FileDescriptor; 277import java.io.FileInputStream; 278import java.io.FileNotFoundException; 279import java.io.FileOutputStream; 280import java.io.FileReader; 281import java.io.FilenameFilter; 282import java.io.IOException; 283import java.io.InputStream; 284import java.io.PrintWriter; 285import java.nio.charset.StandardCharsets; 286import java.security.DigestInputStream; 287import java.security.MessageDigest; 288import java.security.NoSuchAlgorithmException; 289import java.security.PublicKey; 290import java.security.cert.Certificate; 291import java.security.cert.CertificateEncodingException; 292import java.security.cert.CertificateException; 293import java.text.SimpleDateFormat; 294import java.util.ArrayList; 295import java.util.Arrays; 296import java.util.Collection; 297import java.util.Collections; 298import java.util.Comparator; 299import java.util.Date; 300import java.util.HashSet; 301import java.util.Iterator; 302import java.util.List; 303import java.util.Map; 304import java.util.Objects; 305import java.util.Set; 306import java.util.concurrent.CountDownLatch; 307import java.util.concurrent.TimeUnit; 308import java.util.concurrent.atomic.AtomicBoolean; 309import java.util.concurrent.atomic.AtomicInteger; 310import java.util.concurrent.atomic.AtomicLong; 311 312/** 313 * Keep track of all those APKs everywhere. 314 * <p> 315 * Internally there are two important locks: 316 * <ul> 317 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 318 * and other related state. It is a fine-grained lock that should only be held 319 * momentarily, as it's one of the most contended locks in the system. 320 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 321 * operations typically involve heavy lifting of application data on disk. Since 322 * {@code installd} is single-threaded, and it's operations can often be slow, 323 * this lock should never be acquired while already holding {@link #mPackages}. 324 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 325 * holding {@link #mInstallLock}. 326 * </ul> 327 * Many internal methods rely on the caller to hold the appropriate locks, and 328 * this contract is expressed through method name suffixes: 329 * <ul> 330 * <li>fooLI(): the caller must hold {@link #mInstallLock} 331 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 332 * being modified must be frozen 333 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 334 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 335 * </ul> 336 * <p> 337 * Because this class is very central to the platform's security; please run all 338 * CTS and unit tests whenever making modifications: 339 * 340 * <pre> 341 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 342 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 343 * </pre> 344 */ 345public class PackageManagerService extends IPackageManager.Stub { 346 static final String TAG = "PackageManager"; 347 static final boolean DEBUG_SETTINGS = false; 348 static final boolean DEBUG_PREFERRED = false; 349 static final boolean DEBUG_UPGRADE = false; 350 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 351 private static final boolean DEBUG_BACKUP = false; 352 private static final boolean DEBUG_INSTALL = false; 353 private static final boolean DEBUG_REMOVE = false; 354 private static final boolean DEBUG_BROADCASTS = false; 355 private static final boolean DEBUG_SHOW_INFO = false; 356 private static final boolean DEBUG_PACKAGE_INFO = false; 357 private static final boolean DEBUG_INTENT_MATCHING = false; 358 private static final boolean DEBUG_PACKAGE_SCANNING = false; 359 private static final boolean DEBUG_VERIFY = false; 360 private static final boolean DEBUG_FILTERS = false; 361 362 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 363 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 364 // user, but by default initialize to this. 365 static final boolean DEBUG_DEXOPT = false; 366 367 private static final boolean DEBUG_ABI_SELECTION = false; 368 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 369 private static final boolean DEBUG_TRIAGED_MISSING = false; 370 private static final boolean DEBUG_APP_DATA = false; 371 372 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 373 374 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 375 376 private static final int RADIO_UID = Process.PHONE_UID; 377 private static final int LOG_UID = Process.LOG_UID; 378 private static final int NFC_UID = Process.NFC_UID; 379 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 380 private static final int SHELL_UID = Process.SHELL_UID; 381 382 // Cap the size of permission trees that 3rd party apps can define 383 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 384 385 // Suffix used during package installation when copying/moving 386 // package apks to install directory. 387 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 388 389 static final int SCAN_NO_DEX = 1<<1; 390 static final int SCAN_FORCE_DEX = 1<<2; 391 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 392 static final int SCAN_NEW_INSTALL = 1<<4; 393 static final int SCAN_NO_PATHS = 1<<5; 394 static final int SCAN_UPDATE_TIME = 1<<6; 395 static final int SCAN_DEFER_DEX = 1<<7; 396 static final int SCAN_BOOTING = 1<<8; 397 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 398 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 399 static final int SCAN_REPLACING = 1<<11; 400 static final int SCAN_REQUIRE_KNOWN = 1<<12; 401 static final int SCAN_MOVE = 1<<13; 402 static final int SCAN_INITIAL = 1<<14; 403 static final int SCAN_CHECK_ONLY = 1<<15; 404 static final int SCAN_DONT_KILL_APP = 1<<17; 405 static final int SCAN_IGNORE_FROZEN = 1<<18; 406 407 static final int REMOVE_CHATTY = 1<<16; 408 409 private static final int[] EMPTY_INT_ARRAY = new int[0]; 410 411 /** 412 * Timeout (in milliseconds) after which the watchdog should declare that 413 * our handler thread is wedged. The usual default for such things is one 414 * minute but we sometimes do very lengthy I/O operations on this thread, 415 * such as installing multi-gigabyte applications, so ours needs to be longer. 416 */ 417 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 418 419 /** 420 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 421 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 422 * settings entry if available, otherwise we use the hardcoded default. If it's been 423 * more than this long since the last fstrim, we force one during the boot sequence. 424 * 425 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 426 * one gets run at the next available charging+idle time. This final mandatory 427 * no-fstrim check kicks in only of the other scheduling criteria is never met. 428 */ 429 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 430 431 /** 432 * Whether verification is enabled by default. 433 */ 434 private static final boolean DEFAULT_VERIFY_ENABLE = true; 435 436 /** 437 * The default maximum time to wait for the verification agent to return in 438 * milliseconds. 439 */ 440 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 441 442 /** 443 * The default response for package verification timeout. 444 * 445 * This can be either PackageManager.VERIFICATION_ALLOW or 446 * PackageManager.VERIFICATION_REJECT. 447 */ 448 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 449 450 static final String PLATFORM_PACKAGE_NAME = "android"; 451 452 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 453 454 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 455 DEFAULT_CONTAINER_PACKAGE, 456 "com.android.defcontainer.DefaultContainerService"); 457 458 private static final String KILL_APP_REASON_GIDS_CHANGED = 459 "permission grant or revoke changed gids"; 460 461 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 462 "permissions revoked"; 463 464 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 465 466 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 467 468 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 469 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 470 471 /** Permission grant: not grant the permission. */ 472 private static final int GRANT_DENIED = 1; 473 474 /** Permission grant: grant the permission as an install permission. */ 475 private static final int GRANT_INSTALL = 2; 476 477 /** Permission grant: grant the permission as a runtime one. */ 478 private static final int GRANT_RUNTIME = 3; 479 480 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 481 private static final int GRANT_UPGRADE = 4; 482 483 /** Canonical intent used to identify what counts as a "web browser" app */ 484 private static final Intent sBrowserIntent; 485 static { 486 sBrowserIntent = new Intent(); 487 sBrowserIntent.setAction(Intent.ACTION_VIEW); 488 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 489 sBrowserIntent.setData(Uri.parse("http:")); 490 } 491 492 /** 493 * The set of all protected actions [i.e. those actions for which a high priority 494 * intent filter is disallowed]. 495 */ 496 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 497 static { 498 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 499 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 500 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 501 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 502 } 503 504 // Compilation reasons. 505 public static final int REASON_FIRST_BOOT = 0; 506 public static final int REASON_BOOT = 1; 507 public static final int REASON_INSTALL = 2; 508 public static final int REASON_BACKGROUND_DEXOPT = 3; 509 public static final int REASON_AB_OTA = 4; 510 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 511 public static final int REASON_SHARED_APK = 6; 512 public static final int REASON_FORCED_DEXOPT = 7; 513 public static final int REASON_CORE_APP = 8; 514 515 public static final int REASON_LAST = REASON_CORE_APP; 516 517 /** Special library name that skips shared libraries check during compilation. */ 518 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 519 520 final ServiceThread mHandlerThread; 521 522 final PackageHandler mHandler; 523 524 private final ProcessLoggingHandler mProcessLoggingHandler; 525 526 /** 527 * Messages for {@link #mHandler} that need to wait for system ready before 528 * being dispatched. 529 */ 530 private ArrayList<Message> mPostSystemReadyMessages; 531 532 final int mSdkVersion = Build.VERSION.SDK_INT; 533 534 final Context mContext; 535 final boolean mFactoryTest; 536 final boolean mOnlyCore; 537 final DisplayMetrics mMetrics; 538 final int mDefParseFlags; 539 final String[] mSeparateProcesses; 540 final boolean mIsUpgrade; 541 final boolean mIsPreNUpgrade; 542 543 /** The location for ASEC container files on internal storage. */ 544 final String mAsecInternalPath; 545 546 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 547 // LOCK HELD. Can be called with mInstallLock held. 548 @GuardedBy("mInstallLock") 549 final Installer mInstaller; 550 551 /** Directory where installed third-party apps stored */ 552 final File mAppInstallDir; 553 final File mEphemeralInstallDir; 554 555 /** 556 * Directory to which applications installed internally have their 557 * 32 bit native libraries copied. 558 */ 559 private File mAppLib32InstallDir; 560 561 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 562 // apps. 563 final File mDrmAppPrivateInstallDir; 564 565 // ---------------------------------------------------------------- 566 567 // Lock for state used when installing and doing other long running 568 // operations. Methods that must be called with this lock held have 569 // the suffix "LI". 570 final Object mInstallLock = new Object(); 571 572 // ---------------------------------------------------------------- 573 574 // Keys are String (package name), values are Package. This also serves 575 // as the lock for the global state. Methods that must be called with 576 // this lock held have the prefix "LP". 577 @GuardedBy("mPackages") 578 final ArrayMap<String, PackageParser.Package> mPackages = 579 new ArrayMap<String, PackageParser.Package>(); 580 581 final ArrayMap<String, Set<String>> mKnownCodebase = 582 new ArrayMap<String, Set<String>>(); 583 584 // Tracks available target package names -> overlay package paths. 585 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 586 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 587 588 /** 589 * Tracks new system packages [received in an OTA] that we expect to 590 * find updated user-installed versions. Keys are package name, values 591 * are package location. 592 */ 593 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 594 /** 595 * Tracks high priority intent filters for protected actions. During boot, certain 596 * filter actions are protected and should never be allowed to have a high priority 597 * intent filter for them. However, there is one, and only one exception -- the 598 * setup wizard. It must be able to define a high priority intent filter for these 599 * actions to ensure there are no escapes from the wizard. We need to delay processing 600 * of these during boot as we need to look at all of the system packages in order 601 * to know which component is the setup wizard. 602 */ 603 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 604 /** 605 * Whether or not processing protected filters should be deferred. 606 */ 607 private boolean mDeferProtectedFilters = true; 608 609 /** 610 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 611 */ 612 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 613 /** 614 * Whether or not system app permissions should be promoted from install to runtime. 615 */ 616 boolean mPromoteSystemApps; 617 618 @GuardedBy("mPackages") 619 final Settings mSettings; 620 621 /** 622 * Set of package names that are currently "frozen", which means active 623 * surgery is being done on the code/data for that package. The platform 624 * will refuse to launch frozen packages to avoid race conditions. 625 * 626 * @see PackageFreezer 627 */ 628 @GuardedBy("mPackages") 629 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 630 631 final ProtectedPackages mProtectedPackages; 632 633 boolean mFirstBoot; 634 635 // System configuration read by SystemConfig. 636 final int[] mGlobalGids; 637 final SparseArray<ArraySet<String>> mSystemPermissions; 638 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 639 640 // If mac_permissions.xml was found for seinfo labeling. 641 boolean mFoundPolicyFile; 642 643 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 644 645 public static final class SharedLibraryEntry { 646 public final String path; 647 public final String apk; 648 649 SharedLibraryEntry(String _path, String _apk) { 650 path = _path; 651 apk = _apk; 652 } 653 } 654 655 // Currently known shared libraries. 656 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 657 new ArrayMap<String, SharedLibraryEntry>(); 658 659 // All available activities, for your resolving pleasure. 660 final ActivityIntentResolver mActivities = 661 new ActivityIntentResolver(); 662 663 // All available receivers, for your resolving pleasure. 664 final ActivityIntentResolver mReceivers = 665 new ActivityIntentResolver(); 666 667 // All available services, for your resolving pleasure. 668 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 669 670 // All available providers, for your resolving pleasure. 671 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 672 673 // Mapping from provider base names (first directory in content URI codePath) 674 // to the provider information. 675 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 676 new ArrayMap<String, PackageParser.Provider>(); 677 678 // Mapping from instrumentation class names to info about them. 679 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 680 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 681 682 // Mapping from permission names to info about them. 683 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 684 new ArrayMap<String, PackageParser.PermissionGroup>(); 685 686 // Packages whose data we have transfered into another package, thus 687 // should no longer exist. 688 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 689 690 // Broadcast actions that are only available to the system. 691 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 692 693 /** List of packages waiting for verification. */ 694 final SparseArray<PackageVerificationState> mPendingVerification 695 = new SparseArray<PackageVerificationState>(); 696 697 /** Set of packages associated with each app op permission. */ 698 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 699 700 final PackageInstallerService mInstallerService; 701 702 private final PackageDexOptimizer mPackageDexOptimizer; 703 704 private AtomicInteger mNextMoveId = new AtomicInteger(); 705 private final MoveCallbacks mMoveCallbacks; 706 707 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 708 709 // Cache of users who need badging. 710 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 711 712 /** Token for keys in mPendingVerification. */ 713 private int mPendingVerificationToken = 0; 714 715 volatile boolean mSystemReady; 716 volatile boolean mSafeMode; 717 volatile boolean mHasSystemUidErrors; 718 719 ApplicationInfo mAndroidApplication; 720 final ActivityInfo mResolveActivity = new ActivityInfo(); 721 final ResolveInfo mResolveInfo = new ResolveInfo(); 722 ComponentName mResolveComponentName; 723 PackageParser.Package mPlatformPackage; 724 ComponentName mCustomResolverComponentName; 725 726 boolean mResolverReplaced = false; 727 728 private final @Nullable ComponentName mIntentFilterVerifierComponent; 729 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 730 731 private int mIntentFilterVerificationToken = 0; 732 733 /** Component that knows whether or not an ephemeral application exists */ 734 final ComponentName mEphemeralResolverComponent; 735 /** The service connection to the ephemeral resolver */ 736 final EphemeralResolverConnection mEphemeralResolverConnection; 737 738 /** Component used to install ephemeral applications */ 739 final ComponentName mEphemeralInstallerComponent; 740 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 741 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 742 743 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 744 = new SparseArray<IntentFilterVerificationState>(); 745 746 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 747 new DefaultPermissionGrantPolicy(this); 748 749 // List of packages names to keep cached, even if they are uninstalled for all users 750 private List<String> mKeepUninstalledPackages; 751 752 private UserManagerInternal mUserManagerInternal; 753 754 private static class IFVerificationParams { 755 PackageParser.Package pkg; 756 boolean replacing; 757 int userId; 758 int verifierUid; 759 760 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 761 int _userId, int _verifierUid) { 762 pkg = _pkg; 763 replacing = _replacing; 764 userId = _userId; 765 replacing = _replacing; 766 verifierUid = _verifierUid; 767 } 768 } 769 770 private interface IntentFilterVerifier<T extends IntentFilter> { 771 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 772 T filter, String packageName); 773 void startVerifications(int userId); 774 void receiveVerificationResponse(int verificationId); 775 } 776 777 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 778 private Context mContext; 779 private ComponentName mIntentFilterVerifierComponent; 780 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 781 782 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 783 mContext = context; 784 mIntentFilterVerifierComponent = verifierComponent; 785 } 786 787 private String getDefaultScheme() { 788 return IntentFilter.SCHEME_HTTPS; 789 } 790 791 @Override 792 public void startVerifications(int userId) { 793 // Launch verifications requests 794 int count = mCurrentIntentFilterVerifications.size(); 795 for (int n=0; n<count; n++) { 796 int verificationId = mCurrentIntentFilterVerifications.get(n); 797 final IntentFilterVerificationState ivs = 798 mIntentFilterVerificationStates.get(verificationId); 799 800 String packageName = ivs.getPackageName(); 801 802 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 803 final int filterCount = filters.size(); 804 ArraySet<String> domainsSet = new ArraySet<>(); 805 for (int m=0; m<filterCount; m++) { 806 PackageParser.ActivityIntentInfo filter = filters.get(m); 807 domainsSet.addAll(filter.getHostsList()); 808 } 809 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 810 synchronized (mPackages) { 811 if (mSettings.createIntentFilterVerificationIfNeededLPw( 812 packageName, domainsList) != null) { 813 scheduleWriteSettingsLocked(); 814 } 815 } 816 sendVerificationRequest(userId, verificationId, ivs); 817 } 818 mCurrentIntentFilterVerifications.clear(); 819 } 820 821 private void sendVerificationRequest(int userId, int verificationId, 822 IntentFilterVerificationState ivs) { 823 824 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 827 verificationId); 828 verificationIntent.putExtra( 829 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 830 getDefaultScheme()); 831 verificationIntent.putExtra( 832 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 833 ivs.getHostsString()); 834 verificationIntent.putExtra( 835 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 836 ivs.getPackageName()); 837 verificationIntent.setComponent(mIntentFilterVerifierComponent); 838 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 839 840 UserHandle user = new UserHandle(userId); 841 mContext.sendBroadcastAsUser(verificationIntent, user); 842 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 843 "Sending IntentFilter verification broadcast"); 844 } 845 846 public void receiveVerificationResponse(int verificationId) { 847 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 848 849 final boolean verified = ivs.isVerified(); 850 851 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 852 final int count = filters.size(); 853 if (DEBUG_DOMAIN_VERIFICATION) { 854 Slog.i(TAG, "Received verification response " + verificationId 855 + " for " + count + " filters, verified=" + verified); 856 } 857 for (int n=0; n<count; n++) { 858 PackageParser.ActivityIntentInfo filter = filters.get(n); 859 filter.setVerified(verified); 860 861 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 862 + " verified with result:" + verified + " and hosts:" 863 + ivs.getHostsString()); 864 } 865 866 mIntentFilterVerificationStates.remove(verificationId); 867 868 final String packageName = ivs.getPackageName(); 869 IntentFilterVerificationInfo ivi = null; 870 871 synchronized (mPackages) { 872 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 873 } 874 if (ivi == null) { 875 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 876 + verificationId + " packageName:" + packageName); 877 return; 878 } 879 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 880 "Updating IntentFilterVerificationInfo for package " + packageName 881 +" verificationId:" + verificationId); 882 883 synchronized (mPackages) { 884 if (verified) { 885 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 886 } else { 887 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 888 } 889 scheduleWriteSettingsLocked(); 890 891 final int userId = ivs.getUserId(); 892 if (userId != UserHandle.USER_ALL) { 893 final int userStatus = 894 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 895 896 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 897 boolean needUpdate = false; 898 899 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 900 // already been set by the User thru the Disambiguation dialog 901 switch (userStatus) { 902 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 903 if (verified) { 904 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 905 } else { 906 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 907 } 908 needUpdate = true; 909 break; 910 911 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 912 if (verified) { 913 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 914 needUpdate = true; 915 } 916 break; 917 918 default: 919 // Nothing to do 920 } 921 922 if (needUpdate) { 923 mSettings.updateIntentFilterVerificationStatusLPw( 924 packageName, updatedStatus, userId); 925 scheduleWritePackageRestrictionsLocked(userId); 926 } 927 } 928 } 929 } 930 931 @Override 932 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 933 ActivityIntentInfo filter, String packageName) { 934 if (!hasValidDomains(filter)) { 935 return false; 936 } 937 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 938 if (ivs == null) { 939 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 940 packageName); 941 } 942 if (DEBUG_DOMAIN_VERIFICATION) { 943 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 944 } 945 ivs.addFilter(filter); 946 return true; 947 } 948 949 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 950 int userId, int verificationId, String packageName) { 951 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 952 verifierUid, userId, packageName); 953 ivs.setPendingState(); 954 synchronized (mPackages) { 955 mIntentFilterVerificationStates.append(verificationId, ivs); 956 mCurrentIntentFilterVerifications.add(verificationId); 957 } 958 return ivs; 959 } 960 } 961 962 private static boolean hasValidDomains(ActivityIntentInfo filter) { 963 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 964 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 965 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 966 } 967 968 // Set of pending broadcasts for aggregating enable/disable of components. 969 static class PendingPackageBroadcasts { 970 // for each user id, a map of <package name -> components within that package> 971 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 972 973 public PendingPackageBroadcasts() { 974 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 975 } 976 977 public ArrayList<String> get(int userId, String packageName) { 978 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 979 return packages.get(packageName); 980 } 981 982 public void put(int userId, String packageName, ArrayList<String> components) { 983 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 984 packages.put(packageName, components); 985 } 986 987 public void remove(int userId, String packageName) { 988 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 989 if (packages != null) { 990 packages.remove(packageName); 991 } 992 } 993 994 public void remove(int userId) { 995 mUidMap.remove(userId); 996 } 997 998 public int userIdCount() { 999 return mUidMap.size(); 1000 } 1001 1002 public int userIdAt(int n) { 1003 return mUidMap.keyAt(n); 1004 } 1005 1006 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1007 return mUidMap.get(userId); 1008 } 1009 1010 public int size() { 1011 // total number of pending broadcast entries across all userIds 1012 int num = 0; 1013 for (int i = 0; i< mUidMap.size(); i++) { 1014 num += mUidMap.valueAt(i).size(); 1015 } 1016 return num; 1017 } 1018 1019 public void clear() { 1020 mUidMap.clear(); 1021 } 1022 1023 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1024 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1025 if (map == null) { 1026 map = new ArrayMap<String, ArrayList<String>>(); 1027 mUidMap.put(userId, map); 1028 } 1029 return map; 1030 } 1031 } 1032 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1033 1034 // Service Connection to remote media container service to copy 1035 // package uri's from external media onto secure containers 1036 // or internal storage. 1037 private IMediaContainerService mContainerService = null; 1038 1039 static final int SEND_PENDING_BROADCAST = 1; 1040 static final int MCS_BOUND = 3; 1041 static final int END_COPY = 4; 1042 static final int INIT_COPY = 5; 1043 static final int MCS_UNBIND = 6; 1044 static final int START_CLEANING_PACKAGE = 7; 1045 static final int FIND_INSTALL_LOC = 8; 1046 static final int POST_INSTALL = 9; 1047 static final int MCS_RECONNECT = 10; 1048 static final int MCS_GIVE_UP = 11; 1049 static final int UPDATED_MEDIA_STATUS = 12; 1050 static final int WRITE_SETTINGS = 13; 1051 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1052 static final int PACKAGE_VERIFIED = 15; 1053 static final int CHECK_PENDING_VERIFICATION = 16; 1054 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1055 static final int INTENT_FILTER_VERIFIED = 18; 1056 static final int WRITE_PACKAGE_LIST = 19; 1057 1058 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1059 1060 // Delay time in millisecs 1061 static final int BROADCAST_DELAY = 10 * 1000; 1062 1063 static UserManagerService sUserManager; 1064 1065 // Stores a list of users whose package restrictions file needs to be updated 1066 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1067 1068 final private DefaultContainerConnection mDefContainerConn = 1069 new DefaultContainerConnection(); 1070 class DefaultContainerConnection implements ServiceConnection { 1071 public void onServiceConnected(ComponentName name, IBinder service) { 1072 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1073 IMediaContainerService imcs = 1074 IMediaContainerService.Stub.asInterface(service); 1075 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1076 } 1077 1078 public void onServiceDisconnected(ComponentName name) { 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1080 } 1081 } 1082 1083 // Recordkeeping of restore-after-install operations that are currently in flight 1084 // between the Package Manager and the Backup Manager 1085 static class PostInstallData { 1086 public InstallArgs args; 1087 public PackageInstalledInfo res; 1088 1089 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1090 args = _a; 1091 res = _r; 1092 } 1093 } 1094 1095 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1096 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1097 1098 // XML tags for backup/restore of various bits of state 1099 private static final String TAG_PREFERRED_BACKUP = "pa"; 1100 private static final String TAG_DEFAULT_APPS = "da"; 1101 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1102 1103 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1104 private static final String TAG_ALL_GRANTS = "rt-grants"; 1105 private static final String TAG_GRANT = "grant"; 1106 private static final String ATTR_PACKAGE_NAME = "pkg"; 1107 1108 private static final String TAG_PERMISSION = "perm"; 1109 private static final String ATTR_PERMISSION_NAME = "name"; 1110 private static final String ATTR_IS_GRANTED = "g"; 1111 private static final String ATTR_USER_SET = "set"; 1112 private static final String ATTR_USER_FIXED = "fixed"; 1113 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1114 1115 // System/policy permission grants are not backed up 1116 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1117 FLAG_PERMISSION_POLICY_FIXED 1118 | FLAG_PERMISSION_SYSTEM_FIXED 1119 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1120 1121 // And we back up these user-adjusted states 1122 private static final int USER_RUNTIME_GRANT_MASK = 1123 FLAG_PERMISSION_USER_SET 1124 | FLAG_PERMISSION_USER_FIXED 1125 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1126 1127 final @Nullable String mRequiredVerifierPackage; 1128 final @NonNull String mRequiredInstallerPackage; 1129 final @Nullable String mSetupWizardPackage; 1130 final @NonNull String mServicesSystemSharedLibraryPackageName; 1131 final @NonNull String mSharedSystemSharedLibraryPackageName; 1132 1133 private final PackageUsage mPackageUsage = new PackageUsage(); 1134 1135 private class PackageUsage { 1136 private static final int WRITE_INTERVAL 1137 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1138 1139 private final Object mFileLock = new Object(); 1140 private final AtomicLong mLastWritten = new AtomicLong(0); 1141 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1142 1143 private boolean mIsHistoricalPackageUsageAvailable = true; 1144 1145 boolean isHistoricalPackageUsageAvailable() { 1146 return mIsHistoricalPackageUsageAvailable; 1147 } 1148 1149 void write(boolean force) { 1150 if (force) { 1151 writeInternal(); 1152 return; 1153 } 1154 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1155 && !DEBUG_DEXOPT) { 1156 return; 1157 } 1158 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1159 new Thread("PackageUsage_DiskWriter") { 1160 @Override 1161 public void run() { 1162 try { 1163 writeInternal(); 1164 } finally { 1165 mBackgroundWriteRunning.set(false); 1166 } 1167 } 1168 }.start(); 1169 } 1170 } 1171 1172 private void writeInternal() { 1173 synchronized (mPackages) { 1174 synchronized (mFileLock) { 1175 AtomicFile file = getFile(); 1176 FileOutputStream f = null; 1177 try { 1178 f = file.startWrite(); 1179 BufferedOutputStream out = new BufferedOutputStream(f); 1180 FileUtils.setPermissions(file.getBaseFile().getPath(), 1181 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1182 StringBuilder sb = new StringBuilder(); 1183 1184 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1185 sb.append('\n'); 1186 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1187 1188 for (PackageParser.Package pkg : mPackages.values()) { 1189 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1190 continue; 1191 } 1192 sb.setLength(0); 1193 sb.append(pkg.packageName); 1194 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1195 sb.append(' '); 1196 sb.append(usageTimeInMillis); 1197 } 1198 sb.append('\n'); 1199 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1200 } 1201 out.flush(); 1202 file.finishWrite(f); 1203 } catch (IOException e) { 1204 if (f != null) { 1205 file.failWrite(f); 1206 } 1207 Log.e(TAG, "Failed to write package usage times", e); 1208 } 1209 } 1210 } 1211 mLastWritten.set(SystemClock.elapsedRealtime()); 1212 } 1213 1214 void readLP() { 1215 synchronized (mFileLock) { 1216 AtomicFile file = getFile(); 1217 BufferedInputStream in = null; 1218 try { 1219 in = new BufferedInputStream(file.openRead()); 1220 StringBuffer sb = new StringBuffer(); 1221 1222 String firstLine = readLine(in, sb); 1223 if (firstLine == null) { 1224 // Empty file. Do nothing. 1225 } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) { 1226 readVersion1LP(in, sb); 1227 } else { 1228 readVersion0LP(in, sb, firstLine); 1229 } 1230 } catch (FileNotFoundException expected) { 1231 mIsHistoricalPackageUsageAvailable = false; 1232 } catch (IOException e) { 1233 Log.w(TAG, "Failed to read package usage times", e); 1234 } finally { 1235 IoUtils.closeQuietly(in); 1236 } 1237 } 1238 mLastWritten.set(SystemClock.elapsedRealtime()); 1239 } 1240 1241 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1242 throws IOException { 1243 // Initial version of the file had no version number and stored one 1244 // package-timestamp pair per line. 1245 // Note that the first line has already been read from the InputStream. 1246 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1247 String[] tokens = line.split(" "); 1248 if (tokens.length != 2) { 1249 throw new IOException("Failed to parse " + line + 1250 " as package-timestamp pair."); 1251 } 1252 1253 String packageName = tokens[0]; 1254 PackageParser.Package pkg = mPackages.get(packageName); 1255 if (pkg == null) { 1256 continue; 1257 } 1258 1259 long timestamp = parseAsLong(tokens[1]); 1260 for (int reason = 0; 1261 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1262 reason++) { 1263 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1264 } 1265 } 1266 } 1267 1268 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1269 // Version 1 of the file started with the corresponding version 1270 // number and then stored a package name and eight timestamps per line. 1271 String line; 1272 while ((line = readLine(in, sb)) != null) { 1273 String[] tokens = line.split(" "); 1274 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1275 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1276 } 1277 1278 String packageName = tokens[0]; 1279 PackageParser.Package pkg = mPackages.get(packageName); 1280 if (pkg == null) { 1281 continue; 1282 } 1283 1284 for (int reason = 0; 1285 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1286 reason++) { 1287 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1288 } 1289 } 1290 } 1291 1292 private long parseAsLong(String token) throws IOException { 1293 try { 1294 return Long.parseLong(token); 1295 } catch (NumberFormatException e) { 1296 throw new IOException("Failed to parse " + token + " as a long.", e); 1297 } 1298 } 1299 1300 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1301 return readToken(in, sb, '\n'); 1302 } 1303 1304 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1305 throws IOException { 1306 sb.setLength(0); 1307 while (true) { 1308 int ch = in.read(); 1309 if (ch == -1) { 1310 if (sb.length() == 0) { 1311 return null; 1312 } 1313 throw new IOException("Unexpected EOF"); 1314 } 1315 if (ch == endOfToken) { 1316 return sb.toString(); 1317 } 1318 sb.append((char)ch); 1319 } 1320 } 1321 1322 private AtomicFile getFile() { 1323 File dataDir = Environment.getDataDirectory(); 1324 File systemDir = new File(dataDir, "system"); 1325 File fname = new File(systemDir, "package-usage.list"); 1326 return new AtomicFile(fname); 1327 } 1328 1329 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1330 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1331 } 1332 1333 class PackageHandler extends Handler { 1334 private boolean mBound = false; 1335 final ArrayList<HandlerParams> mPendingInstalls = 1336 new ArrayList<HandlerParams>(); 1337 1338 private boolean connectToService() { 1339 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1340 " DefaultContainerService"); 1341 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1342 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1343 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1344 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 mBound = true; 1347 return true; 1348 } 1349 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1350 return false; 1351 } 1352 1353 private void disconnectService() { 1354 mContainerService = null; 1355 mBound = false; 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1357 mContext.unbindService(mDefContainerConn); 1358 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1359 } 1360 1361 PackageHandler(Looper looper) { 1362 super(looper); 1363 } 1364 1365 public void handleMessage(Message msg) { 1366 try { 1367 doHandleMessage(msg); 1368 } finally { 1369 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1370 } 1371 } 1372 1373 void doHandleMessage(Message msg) { 1374 switch (msg.what) { 1375 case INIT_COPY: { 1376 HandlerParams params = (HandlerParams) msg.obj; 1377 int idx = mPendingInstalls.size(); 1378 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1379 // If a bind was already initiated we dont really 1380 // need to do anything. The pending install 1381 // will be processed later on. 1382 if (!mBound) { 1383 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1384 System.identityHashCode(mHandler)); 1385 // If this is the only one pending we might 1386 // have to bind to the service again. 1387 if (!connectToService()) { 1388 Slog.e(TAG, "Failed to bind to media container service"); 1389 params.serviceError(); 1390 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1391 System.identityHashCode(mHandler)); 1392 if (params.traceMethod != null) { 1393 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1394 params.traceCookie); 1395 } 1396 return; 1397 } else { 1398 // Once we bind to the service, the first 1399 // pending request will be processed. 1400 mPendingInstalls.add(idx, params); 1401 } 1402 } else { 1403 mPendingInstalls.add(idx, params); 1404 // Already bound to the service. Just make 1405 // sure we trigger off processing the first request. 1406 if (idx == 0) { 1407 mHandler.sendEmptyMessage(MCS_BOUND); 1408 } 1409 } 1410 break; 1411 } 1412 case MCS_BOUND: { 1413 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1414 if (msg.obj != null) { 1415 mContainerService = (IMediaContainerService) msg.obj; 1416 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1417 System.identityHashCode(mHandler)); 1418 } 1419 if (mContainerService == null) { 1420 if (!mBound) { 1421 // Something seriously wrong since we are not bound and we are not 1422 // waiting for connection. Bail out. 1423 Slog.e(TAG, "Cannot bind to media container service"); 1424 for (HandlerParams params : mPendingInstalls) { 1425 // Indicate service bind error 1426 params.serviceError(); 1427 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1428 System.identityHashCode(params)); 1429 if (params.traceMethod != null) { 1430 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1431 params.traceMethod, params.traceCookie); 1432 } 1433 return; 1434 } 1435 mPendingInstalls.clear(); 1436 } else { 1437 Slog.w(TAG, "Waiting to connect to media container service"); 1438 } 1439 } else if (mPendingInstalls.size() > 0) { 1440 HandlerParams params = mPendingInstalls.get(0); 1441 if (params != null) { 1442 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1443 System.identityHashCode(params)); 1444 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1445 if (params.startCopy()) { 1446 // We are done... look for more work or to 1447 // go idle. 1448 if (DEBUG_SD_INSTALL) Log.i(TAG, 1449 "Checking for more work or unbind..."); 1450 // Delete pending install 1451 if (mPendingInstalls.size() > 0) { 1452 mPendingInstalls.remove(0); 1453 } 1454 if (mPendingInstalls.size() == 0) { 1455 if (mBound) { 1456 if (DEBUG_SD_INSTALL) Log.i(TAG, 1457 "Posting delayed MCS_UNBIND"); 1458 removeMessages(MCS_UNBIND); 1459 Message ubmsg = obtainMessage(MCS_UNBIND); 1460 // Unbind after a little delay, to avoid 1461 // continual thrashing. 1462 sendMessageDelayed(ubmsg, 10000); 1463 } 1464 } else { 1465 // There are more pending requests in queue. 1466 // Just post MCS_BOUND message to trigger processing 1467 // of next pending install. 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, 1469 "Posting MCS_BOUND for next work"); 1470 mHandler.sendEmptyMessage(MCS_BOUND); 1471 } 1472 } 1473 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1474 } 1475 } else { 1476 // Should never happen ideally. 1477 Slog.w(TAG, "Empty queue"); 1478 } 1479 break; 1480 } 1481 case MCS_RECONNECT: { 1482 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1483 if (mPendingInstalls.size() > 0) { 1484 if (mBound) { 1485 disconnectService(); 1486 } 1487 if (!connectToService()) { 1488 Slog.e(TAG, "Failed to bind to media container service"); 1489 for (HandlerParams params : mPendingInstalls) { 1490 // Indicate service bind error 1491 params.serviceError(); 1492 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1493 System.identityHashCode(params)); 1494 } 1495 mPendingInstalls.clear(); 1496 } 1497 } 1498 break; 1499 } 1500 case MCS_UNBIND: { 1501 // If there is no actual work left, then time to unbind. 1502 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1503 1504 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1505 if (mBound) { 1506 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1507 1508 disconnectService(); 1509 } 1510 } else if (mPendingInstalls.size() > 0) { 1511 // There are more pending requests in queue. 1512 // Just post MCS_BOUND message to trigger processing 1513 // of next pending install. 1514 mHandler.sendEmptyMessage(MCS_BOUND); 1515 } 1516 1517 break; 1518 } 1519 case MCS_GIVE_UP: { 1520 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1521 HandlerParams params = mPendingInstalls.remove(0); 1522 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1523 System.identityHashCode(params)); 1524 break; 1525 } 1526 case SEND_PENDING_BROADCAST: { 1527 String packages[]; 1528 ArrayList<String> components[]; 1529 int size = 0; 1530 int uids[]; 1531 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1532 synchronized (mPackages) { 1533 if (mPendingBroadcasts == null) { 1534 return; 1535 } 1536 size = mPendingBroadcasts.size(); 1537 if (size <= 0) { 1538 // Nothing to be done. Just return 1539 return; 1540 } 1541 packages = new String[size]; 1542 components = new ArrayList[size]; 1543 uids = new int[size]; 1544 int i = 0; // filling out the above arrays 1545 1546 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1547 int packageUserId = mPendingBroadcasts.userIdAt(n); 1548 Iterator<Map.Entry<String, ArrayList<String>>> it 1549 = mPendingBroadcasts.packagesForUserId(packageUserId) 1550 .entrySet().iterator(); 1551 while (it.hasNext() && i < size) { 1552 Map.Entry<String, ArrayList<String>> ent = it.next(); 1553 packages[i] = ent.getKey(); 1554 components[i] = ent.getValue(); 1555 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1556 uids[i] = (ps != null) 1557 ? UserHandle.getUid(packageUserId, ps.appId) 1558 : -1; 1559 i++; 1560 } 1561 } 1562 size = i; 1563 mPendingBroadcasts.clear(); 1564 } 1565 // Send broadcasts 1566 for (int i = 0; i < size; i++) { 1567 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1568 } 1569 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1570 break; 1571 } 1572 case START_CLEANING_PACKAGE: { 1573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1574 final String packageName = (String)msg.obj; 1575 final int userId = msg.arg1; 1576 final boolean andCode = msg.arg2 != 0; 1577 synchronized (mPackages) { 1578 if (userId == UserHandle.USER_ALL) { 1579 int[] users = sUserManager.getUserIds(); 1580 for (int user : users) { 1581 mSettings.addPackageToCleanLPw( 1582 new PackageCleanItem(user, packageName, andCode)); 1583 } 1584 } else { 1585 mSettings.addPackageToCleanLPw( 1586 new PackageCleanItem(userId, packageName, andCode)); 1587 } 1588 } 1589 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1590 startCleaningPackages(); 1591 } break; 1592 case POST_INSTALL: { 1593 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1594 1595 PostInstallData data = mRunningInstalls.get(msg.arg1); 1596 final boolean didRestore = (msg.arg2 != 0); 1597 mRunningInstalls.delete(msg.arg1); 1598 1599 if (data != null) { 1600 InstallArgs args = data.args; 1601 PackageInstalledInfo parentRes = data.res; 1602 1603 final boolean grantPermissions = (args.installFlags 1604 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1605 final boolean killApp = (args.installFlags 1606 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1607 final String[] grantedPermissions = args.installGrantPermissions; 1608 1609 // Handle the parent package 1610 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1611 grantedPermissions, didRestore, args.installerPackageName, 1612 args.observer); 1613 1614 // Handle the child packages 1615 final int childCount = (parentRes.addedChildPackages != null) 1616 ? parentRes.addedChildPackages.size() : 0; 1617 for (int i = 0; i < childCount; i++) { 1618 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1619 handlePackagePostInstall(childRes, grantPermissions, killApp, 1620 grantedPermissions, false, args.installerPackageName, 1621 args.observer); 1622 } 1623 1624 // Log tracing if needed 1625 if (args.traceMethod != null) { 1626 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1627 args.traceCookie); 1628 } 1629 } else { 1630 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1631 } 1632 1633 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1634 } break; 1635 case UPDATED_MEDIA_STATUS: { 1636 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1637 boolean reportStatus = msg.arg1 == 1; 1638 boolean doGc = msg.arg2 == 1; 1639 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1640 if (doGc) { 1641 // Force a gc to clear up stale containers. 1642 Runtime.getRuntime().gc(); 1643 } 1644 if (msg.obj != null) { 1645 @SuppressWarnings("unchecked") 1646 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1647 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1648 // Unload containers 1649 unloadAllContainers(args); 1650 } 1651 if (reportStatus) { 1652 try { 1653 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1654 PackageHelper.getMountService().finishMediaUpdate(); 1655 } catch (RemoteException e) { 1656 Log.e(TAG, "MountService not running?"); 1657 } 1658 } 1659 } break; 1660 case WRITE_SETTINGS: { 1661 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1662 synchronized (mPackages) { 1663 removeMessages(WRITE_SETTINGS); 1664 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1665 mSettings.writeLPr(); 1666 mDirtyUsers.clear(); 1667 } 1668 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1669 } break; 1670 case WRITE_PACKAGE_RESTRICTIONS: { 1671 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1672 synchronized (mPackages) { 1673 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1674 for (int userId : mDirtyUsers) { 1675 mSettings.writePackageRestrictionsLPr(userId); 1676 } 1677 mDirtyUsers.clear(); 1678 } 1679 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1680 } break; 1681 case WRITE_PACKAGE_LIST: { 1682 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1683 synchronized (mPackages) { 1684 removeMessages(WRITE_PACKAGE_LIST); 1685 mSettings.writePackageListLPr(msg.arg1); 1686 } 1687 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1688 } break; 1689 case CHECK_PENDING_VERIFICATION: { 1690 final int verificationId = msg.arg1; 1691 final PackageVerificationState state = mPendingVerification.get(verificationId); 1692 1693 if ((state != null) && !state.timeoutExtended()) { 1694 final InstallArgs args = state.getInstallArgs(); 1695 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1696 1697 Slog.i(TAG, "Verification timed out for " + originUri); 1698 mPendingVerification.remove(verificationId); 1699 1700 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1701 1702 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1703 Slog.i(TAG, "Continuing with installation of " + originUri); 1704 state.setVerifierResponse(Binder.getCallingUid(), 1705 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1706 broadcastPackageVerified(verificationId, originUri, 1707 PackageManager.VERIFICATION_ALLOW, 1708 state.getInstallArgs().getUser()); 1709 try { 1710 ret = args.copyApk(mContainerService, true); 1711 } catch (RemoteException e) { 1712 Slog.e(TAG, "Could not contact the ContainerService"); 1713 } 1714 } else { 1715 broadcastPackageVerified(verificationId, originUri, 1716 PackageManager.VERIFICATION_REJECT, 1717 state.getInstallArgs().getUser()); 1718 } 1719 1720 Trace.asyncTraceEnd( 1721 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1722 1723 processPendingInstall(args, ret); 1724 mHandler.sendEmptyMessage(MCS_UNBIND); 1725 } 1726 break; 1727 } 1728 case PACKAGE_VERIFIED: { 1729 final int verificationId = msg.arg1; 1730 1731 final PackageVerificationState state = mPendingVerification.get(verificationId); 1732 if (state == null) { 1733 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1734 break; 1735 } 1736 1737 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1738 1739 state.setVerifierResponse(response.callerUid, response.code); 1740 1741 if (state.isVerificationComplete()) { 1742 mPendingVerification.remove(verificationId); 1743 1744 final InstallArgs args = state.getInstallArgs(); 1745 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1746 1747 int ret; 1748 if (state.isInstallAllowed()) { 1749 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1750 broadcastPackageVerified(verificationId, originUri, 1751 response.code, state.getInstallArgs().getUser()); 1752 try { 1753 ret = args.copyApk(mContainerService, true); 1754 } catch (RemoteException e) { 1755 Slog.e(TAG, "Could not contact the ContainerService"); 1756 } 1757 } else { 1758 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1759 } 1760 1761 Trace.asyncTraceEnd( 1762 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1763 1764 processPendingInstall(args, ret); 1765 mHandler.sendEmptyMessage(MCS_UNBIND); 1766 } 1767 1768 break; 1769 } 1770 case START_INTENT_FILTER_VERIFICATIONS: { 1771 IFVerificationParams params = (IFVerificationParams) msg.obj; 1772 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1773 params.replacing, params.pkg); 1774 break; 1775 } 1776 case INTENT_FILTER_VERIFIED: { 1777 final int verificationId = msg.arg1; 1778 1779 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1780 verificationId); 1781 if (state == null) { 1782 Slog.w(TAG, "Invalid IntentFilter verification token " 1783 + verificationId + " received"); 1784 break; 1785 } 1786 1787 final int userId = state.getUserId(); 1788 1789 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1790 "Processing IntentFilter verification with token:" 1791 + verificationId + " and userId:" + userId); 1792 1793 final IntentFilterVerificationResponse response = 1794 (IntentFilterVerificationResponse) msg.obj; 1795 1796 state.setVerifierResponse(response.callerUid, response.code); 1797 1798 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1799 "IntentFilter verification with token:" + verificationId 1800 + " and userId:" + userId 1801 + " is settings verifier response with response code:" 1802 + response.code); 1803 1804 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1805 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1806 + response.getFailedDomainsString()); 1807 } 1808 1809 if (state.isVerificationComplete()) { 1810 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1811 } else { 1812 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1813 "IntentFilter verification with token:" + verificationId 1814 + " was not said to be complete"); 1815 } 1816 1817 break; 1818 } 1819 } 1820 } 1821 } 1822 1823 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1824 boolean killApp, String[] grantedPermissions, 1825 boolean launchedForRestore, String installerPackage, 1826 IPackageInstallObserver2 installObserver) { 1827 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1828 // Send the removed broadcasts 1829 if (res.removedInfo != null) { 1830 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1831 } 1832 1833 // Now that we successfully installed the package, grant runtime 1834 // permissions if requested before broadcasting the install. 1835 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1836 >= Build.VERSION_CODES.M) { 1837 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1838 } 1839 1840 final boolean update = res.removedInfo != null 1841 && res.removedInfo.removedPackage != null; 1842 1843 // If this is the first time we have child packages for a disabled privileged 1844 // app that had no children, we grant requested runtime permissions to the new 1845 // children if the parent on the system image had them already granted. 1846 if (res.pkg.parentPackage != null) { 1847 synchronized (mPackages) { 1848 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1849 } 1850 } 1851 1852 synchronized (mPackages) { 1853 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1854 } 1855 1856 final String packageName = res.pkg.applicationInfo.packageName; 1857 Bundle extras = new Bundle(1); 1858 extras.putInt(Intent.EXTRA_UID, res.uid); 1859 1860 // Determine the set of users who are adding this package for 1861 // the first time vs. those who are seeing an update. 1862 int[] firstUsers = EMPTY_INT_ARRAY; 1863 int[] updateUsers = EMPTY_INT_ARRAY; 1864 if (res.origUsers == null || res.origUsers.length == 0) { 1865 firstUsers = res.newUsers; 1866 } else { 1867 for (int newUser : res.newUsers) { 1868 boolean isNew = true; 1869 for (int origUser : res.origUsers) { 1870 if (origUser == newUser) { 1871 isNew = false; 1872 break; 1873 } 1874 } 1875 if (isNew) { 1876 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1877 } else { 1878 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1879 } 1880 } 1881 } 1882 1883 // Send installed broadcasts if the install/update is not ephemeral 1884 if (!isEphemeral(res.pkg)) { 1885 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1886 1887 // Send added for users that see the package for the first time 1888 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1889 extras, 0 /*flags*/, null /*targetPackage*/, 1890 null /*finishedReceiver*/, firstUsers); 1891 1892 // Send added for users that don't see the package for the first time 1893 if (update) { 1894 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1895 } 1896 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1897 extras, 0 /*flags*/, null /*targetPackage*/, 1898 null /*finishedReceiver*/, updateUsers); 1899 1900 // Send replaced for users that don't see the package for the first time 1901 if (update) { 1902 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1903 packageName, extras, 0 /*flags*/, 1904 null /*targetPackage*/, null /*finishedReceiver*/, 1905 updateUsers); 1906 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1907 null /*package*/, null /*extras*/, 0 /*flags*/, 1908 packageName /*targetPackage*/, 1909 null /*finishedReceiver*/, updateUsers); 1910 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1911 // First-install and we did a restore, so we're responsible for the 1912 // first-launch broadcast. 1913 if (DEBUG_BACKUP) { 1914 Slog.i(TAG, "Post-restore of " + packageName 1915 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1916 } 1917 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1918 } 1919 1920 // Send broadcast package appeared if forward locked/external for all users 1921 // treat asec-hosted packages like removable media on upgrade 1922 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1923 if (DEBUG_INSTALL) { 1924 Slog.i(TAG, "upgrading pkg " + res.pkg 1925 + " is ASEC-hosted -> AVAILABLE"); 1926 } 1927 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1928 ArrayList<String> pkgList = new ArrayList<>(1); 1929 pkgList.add(packageName); 1930 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1931 } 1932 } 1933 1934 // Work that needs to happen on first install within each user 1935 if (firstUsers != null && firstUsers.length > 0) { 1936 synchronized (mPackages) { 1937 for (int userId : firstUsers) { 1938 // If this app is a browser and it's newly-installed for some 1939 // users, clear any default-browser state in those users. The 1940 // app's nature doesn't depend on the user, so we can just check 1941 // its browser nature in any user and generalize. 1942 if (packageIsBrowser(packageName, userId)) { 1943 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1944 } 1945 1946 // We may also need to apply pending (restored) runtime 1947 // permission grants within these users. 1948 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1949 } 1950 } 1951 } 1952 1953 // Log current value of "unknown sources" setting 1954 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1955 getUnknownSourcesSettings()); 1956 1957 // Force a gc to clear up things 1958 Runtime.getRuntime().gc(); 1959 1960 // Remove the replaced package's older resources safely now 1961 // We delete after a gc for applications on sdcard. 1962 if (res.removedInfo != null && res.removedInfo.args != null) { 1963 synchronized (mInstallLock) { 1964 res.removedInfo.args.doPostDeleteLI(true); 1965 } 1966 } 1967 } 1968 1969 // If someone is watching installs - notify them 1970 if (installObserver != null) { 1971 try { 1972 Bundle extras = extrasForInstallResult(res); 1973 installObserver.onPackageInstalled(res.name, res.returnCode, 1974 res.returnMsg, extras); 1975 } catch (RemoteException e) { 1976 Slog.i(TAG, "Observer no longer exists."); 1977 } 1978 } 1979 } 1980 1981 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1982 PackageParser.Package pkg) { 1983 if (pkg.parentPackage == null) { 1984 return; 1985 } 1986 if (pkg.requestedPermissions == null) { 1987 return; 1988 } 1989 final PackageSetting disabledSysParentPs = mSettings 1990 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1991 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1992 || !disabledSysParentPs.isPrivileged() 1993 || (disabledSysParentPs.childPackageNames != null 1994 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1995 return; 1996 } 1997 final int[] allUserIds = sUserManager.getUserIds(); 1998 final int permCount = pkg.requestedPermissions.size(); 1999 for (int i = 0; i < permCount; i++) { 2000 String permission = pkg.requestedPermissions.get(i); 2001 BasePermission bp = mSettings.mPermissions.get(permission); 2002 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2003 continue; 2004 } 2005 for (int userId : allUserIds) { 2006 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2007 permission, userId)) { 2008 grantRuntimePermission(pkg.packageName, permission, userId); 2009 } 2010 } 2011 } 2012 } 2013 2014 private StorageEventListener mStorageListener = new StorageEventListener() { 2015 @Override 2016 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2017 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2018 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2019 final String volumeUuid = vol.getFsUuid(); 2020 2021 // Clean up any users or apps that were removed or recreated 2022 // while this volume was missing 2023 reconcileUsers(volumeUuid); 2024 reconcileApps(volumeUuid); 2025 2026 // Clean up any install sessions that expired or were 2027 // cancelled while this volume was missing 2028 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2029 2030 loadPrivatePackages(vol); 2031 2032 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2033 unloadPrivatePackages(vol); 2034 } 2035 } 2036 2037 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2038 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2039 updateExternalMediaStatus(true, false); 2040 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2041 updateExternalMediaStatus(false, false); 2042 } 2043 } 2044 } 2045 2046 @Override 2047 public void onVolumeForgotten(String fsUuid) { 2048 if (TextUtils.isEmpty(fsUuid)) { 2049 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2050 return; 2051 } 2052 2053 // Remove any apps installed on the forgotten volume 2054 synchronized (mPackages) { 2055 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2056 for (PackageSetting ps : packages) { 2057 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2058 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2059 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2060 } 2061 2062 mSettings.onVolumeForgotten(fsUuid); 2063 mSettings.writeLPr(); 2064 } 2065 } 2066 }; 2067 2068 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2069 String[] grantedPermissions) { 2070 for (int userId : userIds) { 2071 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2072 } 2073 2074 // We could have touched GID membership, so flush out packages.list 2075 synchronized (mPackages) { 2076 mSettings.writePackageListLPr(); 2077 } 2078 } 2079 2080 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2081 String[] grantedPermissions) { 2082 SettingBase sb = (SettingBase) pkg.mExtras; 2083 if (sb == null) { 2084 return; 2085 } 2086 2087 PermissionsState permissionsState = sb.getPermissionsState(); 2088 2089 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2090 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2091 2092 for (String permission : pkg.requestedPermissions) { 2093 final BasePermission bp; 2094 synchronized (mPackages) { 2095 bp = mSettings.mPermissions.get(permission); 2096 } 2097 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2098 && (grantedPermissions == null 2099 || ArrayUtils.contains(grantedPermissions, permission))) { 2100 final int flags = permissionsState.getPermissionFlags(permission, userId); 2101 // Installer cannot change immutable permissions. 2102 if ((flags & immutableFlags) == 0) { 2103 grantRuntimePermission(pkg.packageName, permission, userId); 2104 } 2105 } 2106 } 2107 } 2108 2109 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2110 Bundle extras = null; 2111 switch (res.returnCode) { 2112 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2113 extras = new Bundle(); 2114 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2115 res.origPermission); 2116 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2117 res.origPackage); 2118 break; 2119 } 2120 case PackageManager.INSTALL_SUCCEEDED: { 2121 extras = new Bundle(); 2122 extras.putBoolean(Intent.EXTRA_REPLACING, 2123 res.removedInfo != null && res.removedInfo.removedPackage != null); 2124 break; 2125 } 2126 } 2127 return extras; 2128 } 2129 2130 void scheduleWriteSettingsLocked() { 2131 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2132 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2133 } 2134 } 2135 2136 void scheduleWritePackageListLocked(int userId) { 2137 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2138 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2139 msg.arg1 = userId; 2140 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2141 } 2142 } 2143 2144 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2145 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2146 scheduleWritePackageRestrictionsLocked(userId); 2147 } 2148 2149 void scheduleWritePackageRestrictionsLocked(int userId) { 2150 final int[] userIds = (userId == UserHandle.USER_ALL) 2151 ? sUserManager.getUserIds() : new int[]{userId}; 2152 for (int nextUserId : userIds) { 2153 if (!sUserManager.exists(nextUserId)) return; 2154 mDirtyUsers.add(nextUserId); 2155 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2156 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2157 } 2158 } 2159 } 2160 2161 public static PackageManagerService main(Context context, Installer installer, 2162 boolean factoryTest, boolean onlyCore) { 2163 // Self-check for initial settings. 2164 PackageManagerServiceCompilerMapping.checkProperties(); 2165 2166 PackageManagerService m = new PackageManagerService(context, installer, 2167 factoryTest, onlyCore); 2168 m.enableSystemUserPackages(); 2169 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2170 // disabled after already being started. 2171 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2172 UserHandle.USER_SYSTEM); 2173 ServiceManager.addService("package", m); 2174 return m; 2175 } 2176 2177 private void enableSystemUserPackages() { 2178 if (!UserManager.isSplitSystemUser()) { 2179 return; 2180 } 2181 // For system user, enable apps based on the following conditions: 2182 // - app is whitelisted or belong to one of these groups: 2183 // -- system app which has no launcher icons 2184 // -- system app which has INTERACT_ACROSS_USERS permission 2185 // -- system IME app 2186 // - app is not in the blacklist 2187 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2188 Set<String> enableApps = new ArraySet<>(); 2189 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2190 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2191 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2192 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2193 enableApps.addAll(wlApps); 2194 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2195 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2196 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2197 enableApps.removeAll(blApps); 2198 Log.i(TAG, "Applications installed for system user: " + enableApps); 2199 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2200 UserHandle.SYSTEM); 2201 final int allAppsSize = allAps.size(); 2202 synchronized (mPackages) { 2203 for (int i = 0; i < allAppsSize; i++) { 2204 String pName = allAps.get(i); 2205 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2206 // Should not happen, but we shouldn't be failing if it does 2207 if (pkgSetting == null) { 2208 continue; 2209 } 2210 boolean install = enableApps.contains(pName); 2211 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2212 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2213 + " for system user"); 2214 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2215 } 2216 } 2217 } 2218 } 2219 2220 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2221 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2222 Context.DISPLAY_SERVICE); 2223 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2224 } 2225 2226 /** 2227 * Requests that files preopted on a secondary system partition be copied to the data partition 2228 * if possible. Note that the actual copying of the files is accomplished by init for security 2229 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2230 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2231 */ 2232 private static void requestCopyPreoptedFiles() { 2233 final int WAIT_TIME_MS = 100; 2234 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2235 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2236 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2237 // We will wait for up to 100 seconds. 2238 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2239 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2240 try { 2241 Thread.sleep(WAIT_TIME_MS); 2242 } catch (InterruptedException e) { 2243 // Do nothing 2244 } 2245 if (SystemClock.uptimeMillis() > timeEnd) { 2246 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2247 Slog.wtf(TAG, "cppreopt did not finish!"); 2248 break; 2249 } 2250 } 2251 } 2252 } 2253 2254 public PackageManagerService(Context context, Installer installer, 2255 boolean factoryTest, boolean onlyCore) { 2256 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2257 SystemClock.uptimeMillis()); 2258 2259 if (mSdkVersion <= 0) { 2260 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2261 } 2262 2263 mContext = context; 2264 mFactoryTest = factoryTest; 2265 mOnlyCore = onlyCore; 2266 mMetrics = new DisplayMetrics(); 2267 mSettings = new Settings(mPackages); 2268 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2269 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2270 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2271 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2272 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2273 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2274 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2275 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2276 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2277 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2278 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2279 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2280 2281 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2282 if (separateProcesses != null && separateProcesses.length() > 0) { 2283 if ("*".equals(separateProcesses)) { 2284 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2285 mSeparateProcesses = null; 2286 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2287 } else { 2288 mDefParseFlags = 0; 2289 mSeparateProcesses = separateProcesses.split(","); 2290 Slog.w(TAG, "Running with debug.separate_processes: " 2291 + separateProcesses); 2292 } 2293 } else { 2294 mDefParseFlags = 0; 2295 mSeparateProcesses = null; 2296 } 2297 2298 mInstaller = installer; 2299 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2300 "*dexopt*"); 2301 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2302 2303 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2304 FgThread.get().getLooper()); 2305 2306 getDefaultDisplayMetrics(context, mMetrics); 2307 2308 SystemConfig systemConfig = SystemConfig.getInstance(); 2309 mGlobalGids = systemConfig.getGlobalGids(); 2310 mSystemPermissions = systemConfig.getSystemPermissions(); 2311 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2312 2313 mProtectedPackages = new ProtectedPackages(mContext); 2314 2315 synchronized (mInstallLock) { 2316 // writer 2317 synchronized (mPackages) { 2318 mHandlerThread = new ServiceThread(TAG, 2319 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2320 mHandlerThread.start(); 2321 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2322 mProcessLoggingHandler = new ProcessLoggingHandler(); 2323 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2324 2325 File dataDir = Environment.getDataDirectory(); 2326 mAppInstallDir = new File(dataDir, "app"); 2327 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2328 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2329 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2330 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2331 2332 sUserManager = new UserManagerService(context, this, mPackages); 2333 2334 // Propagate permission configuration in to package manager. 2335 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2336 = systemConfig.getPermissions(); 2337 for (int i=0; i<permConfig.size(); i++) { 2338 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2339 BasePermission bp = mSettings.mPermissions.get(perm.name); 2340 if (bp == null) { 2341 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2342 mSettings.mPermissions.put(perm.name, bp); 2343 } 2344 if (perm.gids != null) { 2345 bp.setGids(perm.gids, perm.perUser); 2346 } 2347 } 2348 2349 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2350 for (int i=0; i<libConfig.size(); i++) { 2351 mSharedLibraries.put(libConfig.keyAt(i), 2352 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2353 } 2354 2355 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2356 2357 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2358 2359 if (mFirstBoot) { 2360 requestCopyPreoptedFiles(); 2361 } 2362 2363 String customResolverActivity = Resources.getSystem().getString( 2364 R.string.config_customResolverActivity); 2365 if (TextUtils.isEmpty(customResolverActivity)) { 2366 customResolverActivity = null; 2367 } else { 2368 mCustomResolverComponentName = ComponentName.unflattenFromString( 2369 customResolverActivity); 2370 } 2371 2372 long startTime = SystemClock.uptimeMillis(); 2373 2374 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2375 startTime); 2376 2377 // Set flag to monitor and not change apk file paths when 2378 // scanning install directories. 2379 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2380 2381 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2382 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2383 2384 if (bootClassPath == null) { 2385 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2386 } 2387 2388 if (systemServerClassPath == null) { 2389 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2390 } 2391 2392 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2393 final String[] dexCodeInstructionSets = 2394 getDexCodeInstructionSets( 2395 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2396 2397 /** 2398 * Ensure all external libraries have had dexopt run on them. 2399 */ 2400 if (mSharedLibraries.size() > 0) { 2401 // NOTE: For now, we're compiling these system "shared libraries" 2402 // (and framework jars) into all available architectures. It's possible 2403 // to compile them only when we come across an app that uses them (there's 2404 // already logic for that in scanPackageLI) but that adds some complexity. 2405 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2406 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2407 final String lib = libEntry.path; 2408 if (lib == null) { 2409 continue; 2410 } 2411 2412 try { 2413 // Shared libraries do not have profiles so we perform a full 2414 // AOT compilation (if needed). 2415 int dexoptNeeded = DexFile.getDexOptNeeded( 2416 lib, dexCodeInstructionSet, 2417 getCompilerFilterForReason(REASON_SHARED_APK), 2418 false /* newProfile */); 2419 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2420 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2421 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2422 getCompilerFilterForReason(REASON_SHARED_APK), 2423 StorageManager.UUID_PRIVATE_INTERNAL, 2424 SKIP_SHARED_LIBRARY_CHECK); 2425 } 2426 } catch (FileNotFoundException e) { 2427 Slog.w(TAG, "Library not found: " + lib); 2428 } catch (IOException | InstallerException e) { 2429 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2430 + e.getMessage()); 2431 } 2432 } 2433 } 2434 } 2435 2436 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2437 2438 final VersionInfo ver = mSettings.getInternalVersion(); 2439 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2440 2441 // when upgrading from pre-M, promote system app permissions from install to runtime 2442 mPromoteSystemApps = 2443 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2444 2445 // When upgrading from pre-N, we need to handle package extraction like first boot, 2446 // as there is no profiling data available. 2447 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2448 2449 // save off the names of pre-existing system packages prior to scanning; we don't 2450 // want to automatically grant runtime permissions for new system apps 2451 if (mPromoteSystemApps) { 2452 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2453 while (pkgSettingIter.hasNext()) { 2454 PackageSetting ps = pkgSettingIter.next(); 2455 if (isSystemApp(ps)) { 2456 mExistingSystemPackages.add(ps.name); 2457 } 2458 } 2459 } 2460 2461 // Collect vendor overlay packages. 2462 // (Do this before scanning any apps.) 2463 // For security and version matching reason, only consider 2464 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2465 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2466 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2467 | PackageParser.PARSE_IS_SYSTEM 2468 | PackageParser.PARSE_IS_SYSTEM_DIR 2469 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2470 2471 // Find base frameworks (resource packages without code). 2472 scanDirTracedLI(frameworkDir, mDefParseFlags 2473 | PackageParser.PARSE_IS_SYSTEM 2474 | PackageParser.PARSE_IS_SYSTEM_DIR 2475 | PackageParser.PARSE_IS_PRIVILEGED, 2476 scanFlags | SCAN_NO_DEX, 0); 2477 2478 // Collected privileged system packages. 2479 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2480 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2481 | PackageParser.PARSE_IS_SYSTEM 2482 | PackageParser.PARSE_IS_SYSTEM_DIR 2483 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2484 2485 // Collect ordinary system packages. 2486 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2487 scanDirTracedLI(systemAppDir, mDefParseFlags 2488 | PackageParser.PARSE_IS_SYSTEM 2489 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2490 2491 // Collect all vendor packages. 2492 File vendorAppDir = new File("/vendor/app"); 2493 try { 2494 vendorAppDir = vendorAppDir.getCanonicalFile(); 2495 } catch (IOException e) { 2496 // failed to look up canonical path, continue with original one 2497 } 2498 scanDirTracedLI(vendorAppDir, mDefParseFlags 2499 | PackageParser.PARSE_IS_SYSTEM 2500 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2501 2502 // Collect all OEM packages. 2503 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2504 scanDirTracedLI(oemAppDir, mDefParseFlags 2505 | PackageParser.PARSE_IS_SYSTEM 2506 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2507 2508 // Prune any system packages that no longer exist. 2509 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2510 if (!mOnlyCore) { 2511 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2512 while (psit.hasNext()) { 2513 PackageSetting ps = psit.next(); 2514 2515 /* 2516 * If this is not a system app, it can't be a 2517 * disable system app. 2518 */ 2519 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2520 continue; 2521 } 2522 2523 /* 2524 * If the package is scanned, it's not erased. 2525 */ 2526 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2527 if (scannedPkg != null) { 2528 /* 2529 * If the system app is both scanned and in the 2530 * disabled packages list, then it must have been 2531 * added via OTA. Remove it from the currently 2532 * scanned package so the previously user-installed 2533 * application can be scanned. 2534 */ 2535 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2536 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2537 + ps.name + "; removing system app. Last known codePath=" 2538 + ps.codePathString + ", installStatus=" + ps.installStatus 2539 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2540 + scannedPkg.mVersionCode); 2541 removePackageLI(scannedPkg, true); 2542 mExpectingBetter.put(ps.name, ps.codePath); 2543 } 2544 2545 continue; 2546 } 2547 2548 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2549 psit.remove(); 2550 logCriticalInfo(Log.WARN, "System package " + ps.name 2551 + " no longer exists; it's data will be wiped"); 2552 // Actual deletion of code and data will be handled by later 2553 // reconciliation step 2554 } else { 2555 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2556 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2557 possiblyDeletedUpdatedSystemApps.add(ps.name); 2558 } 2559 } 2560 } 2561 } 2562 2563 //look for any incomplete package installations 2564 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2565 for (int i = 0; i < deletePkgsList.size(); i++) { 2566 // Actual deletion of code and data will be handled by later 2567 // reconciliation step 2568 final String packageName = deletePkgsList.get(i).name; 2569 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2570 synchronized (mPackages) { 2571 mSettings.removePackageLPw(packageName); 2572 } 2573 } 2574 2575 //delete tmp files 2576 deleteTempPackageFiles(); 2577 2578 // Remove any shared userIDs that have no associated packages 2579 mSettings.pruneSharedUsersLPw(); 2580 2581 if (!mOnlyCore) { 2582 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2583 SystemClock.uptimeMillis()); 2584 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2585 2586 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2587 | PackageParser.PARSE_FORWARD_LOCK, 2588 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2589 2590 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2591 | PackageParser.PARSE_IS_EPHEMERAL, 2592 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2593 2594 /** 2595 * Remove disable package settings for any updated system 2596 * apps that were removed via an OTA. If they're not a 2597 * previously-updated app, remove them completely. 2598 * Otherwise, just revoke their system-level permissions. 2599 */ 2600 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2601 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2602 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2603 2604 String msg; 2605 if (deletedPkg == null) { 2606 msg = "Updated system package " + deletedAppName 2607 + " no longer exists; it's data will be wiped"; 2608 // Actual deletion of code and data will be handled by later 2609 // reconciliation step 2610 } else { 2611 msg = "Updated system app + " + deletedAppName 2612 + " no longer present; removing system privileges for " 2613 + deletedAppName; 2614 2615 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2616 2617 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2618 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2619 } 2620 logCriticalInfo(Log.WARN, msg); 2621 } 2622 2623 /** 2624 * Make sure all system apps that we expected to appear on 2625 * the userdata partition actually showed up. If they never 2626 * appeared, crawl back and revive the system version. 2627 */ 2628 for (int i = 0; i < mExpectingBetter.size(); i++) { 2629 final String packageName = mExpectingBetter.keyAt(i); 2630 if (!mPackages.containsKey(packageName)) { 2631 final File scanFile = mExpectingBetter.valueAt(i); 2632 2633 logCriticalInfo(Log.WARN, "Expected better " + packageName 2634 + " but never showed up; reverting to system"); 2635 2636 int reparseFlags = mDefParseFlags; 2637 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2638 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2639 | PackageParser.PARSE_IS_SYSTEM_DIR 2640 | PackageParser.PARSE_IS_PRIVILEGED; 2641 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2642 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2643 | PackageParser.PARSE_IS_SYSTEM_DIR; 2644 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2645 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2646 | PackageParser.PARSE_IS_SYSTEM_DIR; 2647 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2648 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2649 | PackageParser.PARSE_IS_SYSTEM_DIR; 2650 } else { 2651 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2652 continue; 2653 } 2654 2655 mSettings.enableSystemPackageLPw(packageName); 2656 2657 try { 2658 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2659 } catch (PackageManagerException e) { 2660 Slog.e(TAG, "Failed to parse original system package: " 2661 + e.getMessage()); 2662 } 2663 } 2664 } 2665 } 2666 mExpectingBetter.clear(); 2667 2668 // Resolve protected action filters. Only the setup wizard is allowed to 2669 // have a high priority filter for these actions. 2670 mSetupWizardPackage = getSetupWizardPackageName(); 2671 if (mProtectedFilters.size() > 0) { 2672 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2673 Slog.i(TAG, "No setup wizard;" 2674 + " All protected intents capped to priority 0"); 2675 } 2676 for (ActivityIntentInfo filter : mProtectedFilters) { 2677 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2678 if (DEBUG_FILTERS) { 2679 Slog.i(TAG, "Found setup wizard;" 2680 + " allow priority " + filter.getPriority() + ";" 2681 + " package: " + filter.activity.info.packageName 2682 + " activity: " + filter.activity.className 2683 + " priority: " + filter.getPriority()); 2684 } 2685 // skip setup wizard; allow it to keep the high priority filter 2686 continue; 2687 } 2688 Slog.w(TAG, "Protected action; cap priority to 0;" 2689 + " package: " + filter.activity.info.packageName 2690 + " activity: " + filter.activity.className 2691 + " origPrio: " + filter.getPriority()); 2692 filter.setPriority(0); 2693 } 2694 } 2695 mDeferProtectedFilters = false; 2696 mProtectedFilters.clear(); 2697 2698 // Now that we know all of the shared libraries, update all clients to have 2699 // the correct library paths. 2700 updateAllSharedLibrariesLPw(); 2701 2702 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2703 // NOTE: We ignore potential failures here during a system scan (like 2704 // the rest of the commands above) because there's precious little we 2705 // can do about it. A settings error is reported, though. 2706 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2707 false /* boot complete */); 2708 } 2709 2710 // Now that we know all the packages we are keeping, 2711 // read and update their last usage times. 2712 mPackageUsage.readLP(); 2713 2714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2715 SystemClock.uptimeMillis()); 2716 Slog.i(TAG, "Time to scan packages: " 2717 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2718 + " seconds"); 2719 2720 // If the platform SDK has changed since the last time we booted, 2721 // we need to re-grant app permission to catch any new ones that 2722 // appear. This is really a hack, and means that apps can in some 2723 // cases get permissions that the user didn't initially explicitly 2724 // allow... it would be nice to have some better way to handle 2725 // this situation. 2726 int updateFlags = UPDATE_PERMISSIONS_ALL; 2727 if (ver.sdkVersion != mSdkVersion) { 2728 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2729 + mSdkVersion + "; regranting permissions for internal storage"); 2730 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2731 } 2732 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2733 ver.sdkVersion = mSdkVersion; 2734 2735 // If this is the first boot or an update from pre-M, and it is a normal 2736 // boot, then we need to initialize the default preferred apps across 2737 // all defined users. 2738 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2739 for (UserInfo user : sUserManager.getUsers(true)) { 2740 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2741 applyFactoryDefaultBrowserLPw(user.id); 2742 primeDomainVerificationsLPw(user.id); 2743 } 2744 } 2745 2746 // Prepare storage for system user really early during boot, 2747 // since core system apps like SettingsProvider and SystemUI 2748 // can't wait for user to start 2749 final int storageFlags; 2750 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2751 storageFlags = StorageManager.FLAG_STORAGE_DE; 2752 } else { 2753 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2754 } 2755 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2756 storageFlags); 2757 2758 // If this is first boot after an OTA, and a normal boot, then 2759 // we need to clear code cache directories. 2760 // Note that we do *not* clear the application profiles. These remain valid 2761 // across OTAs and are used to drive profile verification (post OTA) and 2762 // profile compilation (without waiting to collect a fresh set of profiles). 2763 if (mIsUpgrade && !onlyCore) { 2764 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2765 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2766 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2767 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2768 // No apps are running this early, so no need to freeze 2769 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2770 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2771 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2772 } 2773 } 2774 ver.fingerprint = Build.FINGERPRINT; 2775 } 2776 2777 checkDefaultBrowser(); 2778 2779 // clear only after permissions and other defaults have been updated 2780 mExistingSystemPackages.clear(); 2781 mPromoteSystemApps = false; 2782 2783 // All the changes are done during package scanning. 2784 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2785 2786 // can downgrade to reader 2787 mSettings.writeLPr(); 2788 2789 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2790 // early on (before the package manager declares itself as early) because other 2791 // components in the system server might ask for package contexts for these apps. 2792 // 2793 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2794 // (i.e, that the data partition is unavailable). 2795 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2796 long start = System.nanoTime(); 2797 List<PackageParser.Package> coreApps = new ArrayList<>(); 2798 for (PackageParser.Package pkg : mPackages.values()) { 2799 if (pkg.coreApp) { 2800 coreApps.add(pkg); 2801 } 2802 } 2803 2804 int[] stats = performDexOptUpgrade(coreApps, false, 2805 getCompilerFilterForReason(REASON_CORE_APP)); 2806 2807 final int elapsedTimeSeconds = 2808 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2809 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2810 2811 if (DEBUG_DEXOPT) { 2812 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2813 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2814 } 2815 2816 2817 // TODO: Should we log these stats to tron too ? 2818 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2819 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2820 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2821 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2822 } 2823 2824 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2825 SystemClock.uptimeMillis()); 2826 2827 if (!mOnlyCore) { 2828 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2829 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2830 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2831 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2832 mIntentFilterVerifierComponent); 2833 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2834 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2835 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2836 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2837 } else { 2838 mRequiredVerifierPackage = null; 2839 mRequiredInstallerPackage = null; 2840 mIntentFilterVerifierComponent = null; 2841 mIntentFilterVerifier = null; 2842 mServicesSystemSharedLibraryPackageName = null; 2843 mSharedSystemSharedLibraryPackageName = null; 2844 } 2845 2846 mInstallerService = new PackageInstallerService(context, this); 2847 2848 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2849 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2850 // both the installer and resolver must be present to enable ephemeral 2851 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2852 if (DEBUG_EPHEMERAL) { 2853 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2854 + " installer:" + ephemeralInstallerComponent); 2855 } 2856 mEphemeralResolverComponent = ephemeralResolverComponent; 2857 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2858 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2859 mEphemeralResolverConnection = 2860 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2861 } else { 2862 if (DEBUG_EPHEMERAL) { 2863 final String missingComponent = 2864 (ephemeralResolverComponent == null) 2865 ? (ephemeralInstallerComponent == null) 2866 ? "resolver and installer" 2867 : "resolver" 2868 : "installer"; 2869 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2870 } 2871 mEphemeralResolverComponent = null; 2872 mEphemeralInstallerComponent = null; 2873 mEphemeralResolverConnection = null; 2874 } 2875 2876 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2877 } // synchronized (mPackages) 2878 } // synchronized (mInstallLock) 2879 2880 // Now after opening every single application zip, make sure they 2881 // are all flushed. Not really needed, but keeps things nice and 2882 // tidy. 2883 Runtime.getRuntime().gc(); 2884 2885 // The initial scanning above does many calls into installd while 2886 // holding the mPackages lock, but we're mostly interested in yelling 2887 // once we have a booted system. 2888 mInstaller.setWarnIfHeld(mPackages); 2889 2890 // Expose private service for system components to use. 2891 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2892 } 2893 2894 @Override 2895 public boolean isFirstBoot() { 2896 return mFirstBoot; 2897 } 2898 2899 @Override 2900 public boolean isOnlyCoreApps() { 2901 return mOnlyCore; 2902 } 2903 2904 @Override 2905 public boolean isUpgrade() { 2906 return mIsUpgrade; 2907 } 2908 2909 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2910 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2911 2912 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2913 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2914 UserHandle.USER_SYSTEM); 2915 if (matches.size() == 1) { 2916 return matches.get(0).getComponentInfo().packageName; 2917 } else { 2918 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2919 return null; 2920 } 2921 } 2922 2923 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2924 synchronized (mPackages) { 2925 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2926 if (libraryEntry == null) { 2927 throw new IllegalStateException("Missing required shared library:" + libraryName); 2928 } 2929 return libraryEntry.apk; 2930 } 2931 } 2932 2933 private @NonNull String getRequiredInstallerLPr() { 2934 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2935 intent.addCategory(Intent.CATEGORY_DEFAULT); 2936 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2937 2938 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2939 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2940 UserHandle.USER_SYSTEM); 2941 if (matches.size() == 1) { 2942 ResolveInfo resolveInfo = matches.get(0); 2943 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2944 throw new RuntimeException("The installer must be a privileged app"); 2945 } 2946 return matches.get(0).getComponentInfo().packageName; 2947 } else { 2948 throw new RuntimeException("There must be exactly one installer; found " + matches); 2949 } 2950 } 2951 2952 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2953 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2954 2955 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2956 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2957 UserHandle.USER_SYSTEM); 2958 ResolveInfo best = null; 2959 final int N = matches.size(); 2960 for (int i = 0; i < N; i++) { 2961 final ResolveInfo cur = matches.get(i); 2962 final String packageName = cur.getComponentInfo().packageName; 2963 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2964 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2965 continue; 2966 } 2967 2968 if (best == null || cur.priority > best.priority) { 2969 best = cur; 2970 } 2971 } 2972 2973 if (best != null) { 2974 return best.getComponentInfo().getComponentName(); 2975 } else { 2976 throw new RuntimeException("There must be at least one intent filter verifier"); 2977 } 2978 } 2979 2980 private @Nullable ComponentName getEphemeralResolverLPr() { 2981 final String[] packageArray = 2982 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2983 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2984 if (DEBUG_EPHEMERAL) { 2985 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2986 } 2987 return null; 2988 } 2989 2990 final int resolveFlags = 2991 MATCH_DIRECT_BOOT_AWARE 2992 | MATCH_DIRECT_BOOT_UNAWARE 2993 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2994 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2995 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2996 resolveFlags, UserHandle.USER_SYSTEM); 2997 2998 final int N = resolvers.size(); 2999 if (N == 0) { 3000 if (DEBUG_EPHEMERAL) { 3001 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3002 } 3003 return null; 3004 } 3005 3006 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3007 for (int i = 0; i < N; i++) { 3008 final ResolveInfo info = resolvers.get(i); 3009 3010 if (info.serviceInfo == null) { 3011 continue; 3012 } 3013 3014 final String packageName = info.serviceInfo.packageName; 3015 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3016 if (DEBUG_EPHEMERAL) { 3017 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3018 + " pkg: " + packageName + ", info:" + info); 3019 } 3020 continue; 3021 } 3022 3023 if (DEBUG_EPHEMERAL) { 3024 Slog.v(TAG, "Ephemeral resolver found;" 3025 + " pkg: " + packageName + ", info:" + info); 3026 } 3027 return new ComponentName(packageName, info.serviceInfo.name); 3028 } 3029 if (DEBUG_EPHEMERAL) { 3030 Slog.v(TAG, "Ephemeral resolver NOT found"); 3031 } 3032 return null; 3033 } 3034 3035 private @Nullable ComponentName getEphemeralInstallerLPr() { 3036 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3037 intent.addCategory(Intent.CATEGORY_DEFAULT); 3038 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3039 3040 final int resolveFlags = 3041 MATCH_DIRECT_BOOT_AWARE 3042 | MATCH_DIRECT_BOOT_UNAWARE 3043 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3044 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3045 resolveFlags, UserHandle.USER_SYSTEM); 3046 if (matches.size() == 0) { 3047 return null; 3048 } else if (matches.size() == 1) { 3049 return matches.get(0).getComponentInfo().getComponentName(); 3050 } else { 3051 throw new RuntimeException( 3052 "There must be at most one ephemeral installer; found " + matches); 3053 } 3054 } 3055 3056 private void primeDomainVerificationsLPw(int userId) { 3057 if (DEBUG_DOMAIN_VERIFICATION) { 3058 Slog.d(TAG, "Priming domain verifications in user " + userId); 3059 } 3060 3061 SystemConfig systemConfig = SystemConfig.getInstance(); 3062 ArraySet<String> packages = systemConfig.getLinkedApps(); 3063 ArraySet<String> domains = new ArraySet<String>(); 3064 3065 for (String packageName : packages) { 3066 PackageParser.Package pkg = mPackages.get(packageName); 3067 if (pkg != null) { 3068 if (!pkg.isSystemApp()) { 3069 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3070 continue; 3071 } 3072 3073 domains.clear(); 3074 for (PackageParser.Activity a : pkg.activities) { 3075 for (ActivityIntentInfo filter : a.intents) { 3076 if (hasValidDomains(filter)) { 3077 domains.addAll(filter.getHostsList()); 3078 } 3079 } 3080 } 3081 3082 if (domains.size() > 0) { 3083 if (DEBUG_DOMAIN_VERIFICATION) { 3084 Slog.v(TAG, " + " + packageName); 3085 } 3086 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3087 // state w.r.t. the formal app-linkage "no verification attempted" state; 3088 // and then 'always' in the per-user state actually used for intent resolution. 3089 final IntentFilterVerificationInfo ivi; 3090 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3091 new ArrayList<String>(domains)); 3092 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3093 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3094 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3095 } else { 3096 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3097 + "' does not handle web links"); 3098 } 3099 } else { 3100 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3101 } 3102 } 3103 3104 scheduleWritePackageRestrictionsLocked(userId); 3105 scheduleWriteSettingsLocked(); 3106 } 3107 3108 private void applyFactoryDefaultBrowserLPw(int userId) { 3109 // The default browser app's package name is stored in a string resource, 3110 // with a product-specific overlay used for vendor customization. 3111 String browserPkg = mContext.getResources().getString( 3112 com.android.internal.R.string.default_browser); 3113 if (!TextUtils.isEmpty(browserPkg)) { 3114 // non-empty string => required to be a known package 3115 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3116 if (ps == null) { 3117 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3118 browserPkg = null; 3119 } else { 3120 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3121 } 3122 } 3123 3124 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3125 // default. If there's more than one, just leave everything alone. 3126 if (browserPkg == null) { 3127 calculateDefaultBrowserLPw(userId); 3128 } 3129 } 3130 3131 private void calculateDefaultBrowserLPw(int userId) { 3132 List<String> allBrowsers = resolveAllBrowserApps(userId); 3133 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3134 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3135 } 3136 3137 private List<String> resolveAllBrowserApps(int userId) { 3138 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3139 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3140 PackageManager.MATCH_ALL, userId); 3141 3142 final int count = list.size(); 3143 List<String> result = new ArrayList<String>(count); 3144 for (int i=0; i<count; i++) { 3145 ResolveInfo info = list.get(i); 3146 if (info.activityInfo == null 3147 || !info.handleAllWebDataURI 3148 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3149 || result.contains(info.activityInfo.packageName)) { 3150 continue; 3151 } 3152 result.add(info.activityInfo.packageName); 3153 } 3154 3155 return result; 3156 } 3157 3158 private boolean packageIsBrowser(String packageName, int userId) { 3159 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3160 PackageManager.MATCH_ALL, userId); 3161 final int N = list.size(); 3162 for (int i = 0; i < N; i++) { 3163 ResolveInfo info = list.get(i); 3164 if (packageName.equals(info.activityInfo.packageName)) { 3165 return true; 3166 } 3167 } 3168 return false; 3169 } 3170 3171 private void checkDefaultBrowser() { 3172 final int myUserId = UserHandle.myUserId(); 3173 final String packageName = getDefaultBrowserPackageName(myUserId); 3174 if (packageName != null) { 3175 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3176 if (info == null) { 3177 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3178 synchronized (mPackages) { 3179 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3180 } 3181 } 3182 } 3183 } 3184 3185 @Override 3186 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3187 throws RemoteException { 3188 try { 3189 return super.onTransact(code, data, reply, flags); 3190 } catch (RuntimeException e) { 3191 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3192 Slog.wtf(TAG, "Package Manager Crash", e); 3193 } 3194 throw e; 3195 } 3196 } 3197 3198 static int[] appendInts(int[] cur, int[] add) { 3199 if (add == null) return cur; 3200 if (cur == null) return add; 3201 final int N = add.length; 3202 for (int i=0; i<N; i++) { 3203 cur = appendInt(cur, add[i]); 3204 } 3205 return cur; 3206 } 3207 3208 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3209 if (!sUserManager.exists(userId)) return null; 3210 if (ps == null) { 3211 return null; 3212 } 3213 final PackageParser.Package p = ps.pkg; 3214 if (p == null) { 3215 return null; 3216 } 3217 3218 final PermissionsState permissionsState = ps.getPermissionsState(); 3219 3220 // Compute GIDs only if requested 3221 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3222 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3223 // Compute granted permissions only if package has requested permissions 3224 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3225 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3226 final PackageUserState state = ps.readUserState(userId); 3227 3228 return PackageParser.generatePackageInfo(p, gids, flags, 3229 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3230 } 3231 3232 @Override 3233 public void checkPackageStartable(String packageName, int userId) { 3234 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3235 3236 synchronized (mPackages) { 3237 final PackageSetting ps = mSettings.mPackages.get(packageName); 3238 if (ps == null) { 3239 throw new SecurityException("Package " + packageName + " was not found!"); 3240 } 3241 3242 if (!ps.getInstalled(userId)) { 3243 throw new SecurityException( 3244 "Package " + packageName + " was not installed for user " + userId + "!"); 3245 } 3246 3247 if (mSafeMode && !ps.isSystem()) { 3248 throw new SecurityException("Package " + packageName + " not a system app!"); 3249 } 3250 3251 if (mFrozenPackages.contains(packageName)) { 3252 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3253 } 3254 3255 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3256 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3257 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3258 } 3259 } 3260 } 3261 3262 @Override 3263 public boolean isPackageAvailable(String packageName, int userId) { 3264 if (!sUserManager.exists(userId)) return false; 3265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3266 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3267 synchronized (mPackages) { 3268 PackageParser.Package p = mPackages.get(packageName); 3269 if (p != null) { 3270 final PackageSetting ps = (PackageSetting) p.mExtras; 3271 if (ps != null) { 3272 final PackageUserState state = ps.readUserState(userId); 3273 if (state != null) { 3274 return PackageParser.isAvailable(state); 3275 } 3276 } 3277 } 3278 } 3279 return false; 3280 } 3281 3282 @Override 3283 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3284 if (!sUserManager.exists(userId)) return null; 3285 flags = updateFlagsForPackage(flags, userId, packageName); 3286 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3287 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3288 // reader 3289 synchronized (mPackages) { 3290 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3291 PackageParser.Package p = null; 3292 if (matchFactoryOnly) { 3293 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3294 if (ps != null) { 3295 return generatePackageInfo(ps, flags, userId); 3296 } 3297 } 3298 if (p == null) { 3299 p = mPackages.get(packageName); 3300 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3301 return null; 3302 } 3303 } 3304 if (DEBUG_PACKAGE_INFO) 3305 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3306 if (p != null) { 3307 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3308 } 3309 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3310 final PackageSetting ps = mSettings.mPackages.get(packageName); 3311 return generatePackageInfo(ps, flags, userId); 3312 } 3313 } 3314 return null; 3315 } 3316 3317 @Override 3318 public String[] currentToCanonicalPackageNames(String[] names) { 3319 String[] out = new String[names.length]; 3320 // reader 3321 synchronized (mPackages) { 3322 for (int i=names.length-1; i>=0; i--) { 3323 PackageSetting ps = mSettings.mPackages.get(names[i]); 3324 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3325 } 3326 } 3327 return out; 3328 } 3329 3330 @Override 3331 public String[] canonicalToCurrentPackageNames(String[] names) { 3332 String[] out = new String[names.length]; 3333 // reader 3334 synchronized (mPackages) { 3335 for (int i=names.length-1; i>=0; i--) { 3336 String cur = mSettings.mRenamedPackages.get(names[i]); 3337 out[i] = cur != null ? cur : names[i]; 3338 } 3339 } 3340 return out; 3341 } 3342 3343 @Override 3344 public int getPackageUid(String packageName, int flags, int userId) { 3345 if (!sUserManager.exists(userId)) return -1; 3346 flags = updateFlagsForPackage(flags, userId, packageName); 3347 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3348 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3349 3350 // reader 3351 synchronized (mPackages) { 3352 final PackageParser.Package p = mPackages.get(packageName); 3353 if (p != null && p.isMatch(flags)) { 3354 return UserHandle.getUid(userId, p.applicationInfo.uid); 3355 } 3356 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3357 final PackageSetting ps = mSettings.mPackages.get(packageName); 3358 if (ps != null && ps.isMatch(flags)) { 3359 return UserHandle.getUid(userId, ps.appId); 3360 } 3361 } 3362 } 3363 3364 return -1; 3365 } 3366 3367 @Override 3368 public int[] getPackageGids(String packageName, int flags, int userId) { 3369 if (!sUserManager.exists(userId)) return null; 3370 flags = updateFlagsForPackage(flags, userId, packageName); 3371 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3372 false /* requireFullPermission */, false /* checkShell */, 3373 "getPackageGids"); 3374 3375 // reader 3376 synchronized (mPackages) { 3377 final PackageParser.Package p = mPackages.get(packageName); 3378 if (p != null && p.isMatch(flags)) { 3379 PackageSetting ps = (PackageSetting) p.mExtras; 3380 return ps.getPermissionsState().computeGids(userId); 3381 } 3382 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3383 final PackageSetting ps = mSettings.mPackages.get(packageName); 3384 if (ps != null && ps.isMatch(flags)) { 3385 return ps.getPermissionsState().computeGids(userId); 3386 } 3387 } 3388 } 3389 3390 return null; 3391 } 3392 3393 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3394 if (bp.perm != null) { 3395 return PackageParser.generatePermissionInfo(bp.perm, flags); 3396 } 3397 PermissionInfo pi = new PermissionInfo(); 3398 pi.name = bp.name; 3399 pi.packageName = bp.sourcePackage; 3400 pi.nonLocalizedLabel = bp.name; 3401 pi.protectionLevel = bp.protectionLevel; 3402 return pi; 3403 } 3404 3405 @Override 3406 public PermissionInfo getPermissionInfo(String name, int flags) { 3407 // reader 3408 synchronized (mPackages) { 3409 final BasePermission p = mSettings.mPermissions.get(name); 3410 if (p != null) { 3411 return generatePermissionInfo(p, flags); 3412 } 3413 return null; 3414 } 3415 } 3416 3417 @Override 3418 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3419 int flags) { 3420 // reader 3421 synchronized (mPackages) { 3422 if (group != null && !mPermissionGroups.containsKey(group)) { 3423 // This is thrown as NameNotFoundException 3424 return null; 3425 } 3426 3427 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3428 for (BasePermission p : mSettings.mPermissions.values()) { 3429 if (group == null) { 3430 if (p.perm == null || p.perm.info.group == null) { 3431 out.add(generatePermissionInfo(p, flags)); 3432 } 3433 } else { 3434 if (p.perm != null && group.equals(p.perm.info.group)) { 3435 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3436 } 3437 } 3438 } 3439 return new ParceledListSlice<>(out); 3440 } 3441 } 3442 3443 @Override 3444 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3445 // reader 3446 synchronized (mPackages) { 3447 return PackageParser.generatePermissionGroupInfo( 3448 mPermissionGroups.get(name), flags); 3449 } 3450 } 3451 3452 @Override 3453 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3454 // reader 3455 synchronized (mPackages) { 3456 final int N = mPermissionGroups.size(); 3457 ArrayList<PermissionGroupInfo> out 3458 = new ArrayList<PermissionGroupInfo>(N); 3459 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3460 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3461 } 3462 return new ParceledListSlice<>(out); 3463 } 3464 } 3465 3466 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3467 int userId) { 3468 if (!sUserManager.exists(userId)) return null; 3469 PackageSetting ps = mSettings.mPackages.get(packageName); 3470 if (ps != null) { 3471 if (ps.pkg == null) { 3472 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3473 if (pInfo != null) { 3474 return pInfo.applicationInfo; 3475 } 3476 return null; 3477 } 3478 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3479 ps.readUserState(userId), userId); 3480 } 3481 return null; 3482 } 3483 3484 @Override 3485 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3486 if (!sUserManager.exists(userId)) return null; 3487 flags = updateFlagsForApplication(flags, userId, packageName); 3488 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3489 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3490 // writer 3491 synchronized (mPackages) { 3492 PackageParser.Package p = mPackages.get(packageName); 3493 if (DEBUG_PACKAGE_INFO) Log.v( 3494 TAG, "getApplicationInfo " + packageName 3495 + ": " + p); 3496 if (p != null) { 3497 PackageSetting ps = mSettings.mPackages.get(packageName); 3498 if (ps == null) return null; 3499 // Note: isEnabledLP() does not apply here - always return info 3500 return PackageParser.generateApplicationInfo( 3501 p, flags, ps.readUserState(userId), userId); 3502 } 3503 if ("android".equals(packageName)||"system".equals(packageName)) { 3504 return mAndroidApplication; 3505 } 3506 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3507 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3508 } 3509 } 3510 return null; 3511 } 3512 3513 @Override 3514 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3515 final IPackageDataObserver observer) { 3516 mContext.enforceCallingOrSelfPermission( 3517 android.Manifest.permission.CLEAR_APP_CACHE, null); 3518 // Queue up an async operation since clearing cache may take a little while. 3519 mHandler.post(new Runnable() { 3520 public void run() { 3521 mHandler.removeCallbacks(this); 3522 boolean success = true; 3523 synchronized (mInstallLock) { 3524 try { 3525 mInstaller.freeCache(volumeUuid, freeStorageSize); 3526 } catch (InstallerException e) { 3527 Slog.w(TAG, "Couldn't clear application caches: " + e); 3528 success = false; 3529 } 3530 } 3531 if (observer != null) { 3532 try { 3533 observer.onRemoveCompleted(null, success); 3534 } catch (RemoteException e) { 3535 Slog.w(TAG, "RemoveException when invoking call back"); 3536 } 3537 } 3538 } 3539 }); 3540 } 3541 3542 @Override 3543 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3544 final IntentSender pi) { 3545 mContext.enforceCallingOrSelfPermission( 3546 android.Manifest.permission.CLEAR_APP_CACHE, null); 3547 // Queue up an async operation since clearing cache may take a little while. 3548 mHandler.post(new Runnable() { 3549 public void run() { 3550 mHandler.removeCallbacks(this); 3551 boolean success = true; 3552 synchronized (mInstallLock) { 3553 try { 3554 mInstaller.freeCache(volumeUuid, freeStorageSize); 3555 } catch (InstallerException e) { 3556 Slog.w(TAG, "Couldn't clear application caches: " + e); 3557 success = false; 3558 } 3559 } 3560 if(pi != null) { 3561 try { 3562 // Callback via pending intent 3563 int code = success ? 1 : 0; 3564 pi.sendIntent(null, code, null, 3565 null, null); 3566 } catch (SendIntentException e1) { 3567 Slog.i(TAG, "Failed to send pending intent"); 3568 } 3569 } 3570 } 3571 }); 3572 } 3573 3574 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3575 synchronized (mInstallLock) { 3576 try { 3577 mInstaller.freeCache(volumeUuid, freeStorageSize); 3578 } catch (InstallerException e) { 3579 throw new IOException("Failed to free enough space", e); 3580 } 3581 } 3582 } 3583 3584 /** 3585 * Update given flags based on encryption status of current user. 3586 */ 3587 private int updateFlags(int flags, int userId) { 3588 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3589 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3590 // Caller expressed an explicit opinion about what encryption 3591 // aware/unaware components they want to see, so fall through and 3592 // give them what they want 3593 } else { 3594 // Caller expressed no opinion, so match based on user state 3595 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3596 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3597 } else { 3598 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3599 } 3600 } 3601 return flags; 3602 } 3603 3604 private UserManagerInternal getUserManagerInternal() { 3605 if (mUserManagerInternal == null) { 3606 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3607 } 3608 return mUserManagerInternal; 3609 } 3610 3611 /** 3612 * Update given flags when being used to request {@link PackageInfo}. 3613 */ 3614 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3615 boolean triaged = true; 3616 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3617 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3618 // Caller is asking for component details, so they'd better be 3619 // asking for specific encryption matching behavior, or be triaged 3620 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3621 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3622 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3623 triaged = false; 3624 } 3625 } 3626 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3627 | PackageManager.MATCH_SYSTEM_ONLY 3628 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3629 triaged = false; 3630 } 3631 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3632 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3633 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3634 } 3635 return updateFlags(flags, userId); 3636 } 3637 3638 /** 3639 * Update given flags when being used to request {@link ApplicationInfo}. 3640 */ 3641 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3642 return updateFlagsForPackage(flags, userId, cookie); 3643 } 3644 3645 /** 3646 * Update given flags when being used to request {@link ComponentInfo}. 3647 */ 3648 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3649 if (cookie instanceof Intent) { 3650 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3651 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3652 } 3653 } 3654 3655 boolean triaged = true; 3656 // Caller is asking for component details, so they'd better be 3657 // asking for specific encryption matching behavior, or be triaged 3658 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3659 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3660 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3661 triaged = false; 3662 } 3663 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3664 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3665 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3666 } 3667 3668 return updateFlags(flags, userId); 3669 } 3670 3671 /** 3672 * Update given flags when being used to request {@link ResolveInfo}. 3673 */ 3674 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3675 // Safe mode means we shouldn't match any third-party components 3676 if (mSafeMode) { 3677 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3678 } 3679 3680 return updateFlagsForComponent(flags, userId, cookie); 3681 } 3682 3683 @Override 3684 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3685 if (!sUserManager.exists(userId)) return null; 3686 flags = updateFlagsForComponent(flags, userId, component); 3687 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3688 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3689 synchronized (mPackages) { 3690 PackageParser.Activity a = mActivities.mActivities.get(component); 3691 3692 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3693 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3694 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3695 if (ps == null) return null; 3696 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3697 userId); 3698 } 3699 if (mResolveComponentName.equals(component)) { 3700 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3701 new PackageUserState(), userId); 3702 } 3703 } 3704 return null; 3705 } 3706 3707 @Override 3708 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3709 String resolvedType) { 3710 synchronized (mPackages) { 3711 if (component.equals(mResolveComponentName)) { 3712 // The resolver supports EVERYTHING! 3713 return true; 3714 } 3715 PackageParser.Activity a = mActivities.mActivities.get(component); 3716 if (a == null) { 3717 return false; 3718 } 3719 for (int i=0; i<a.intents.size(); i++) { 3720 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3721 intent.getData(), intent.getCategories(), TAG) >= 0) { 3722 return true; 3723 } 3724 } 3725 return false; 3726 } 3727 } 3728 3729 @Override 3730 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3731 if (!sUserManager.exists(userId)) return null; 3732 flags = updateFlagsForComponent(flags, userId, component); 3733 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3734 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3735 synchronized (mPackages) { 3736 PackageParser.Activity a = mReceivers.mActivities.get(component); 3737 if (DEBUG_PACKAGE_INFO) Log.v( 3738 TAG, "getReceiverInfo " + component + ": " + a); 3739 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3740 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3741 if (ps == null) return null; 3742 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3743 userId); 3744 } 3745 } 3746 return null; 3747 } 3748 3749 @Override 3750 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3751 if (!sUserManager.exists(userId)) return null; 3752 flags = updateFlagsForComponent(flags, userId, component); 3753 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3754 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3755 synchronized (mPackages) { 3756 PackageParser.Service s = mServices.mServices.get(component); 3757 if (DEBUG_PACKAGE_INFO) Log.v( 3758 TAG, "getServiceInfo " + component + ": " + s); 3759 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3760 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3761 if (ps == null) return null; 3762 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3763 userId); 3764 } 3765 } 3766 return null; 3767 } 3768 3769 @Override 3770 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3771 if (!sUserManager.exists(userId)) return null; 3772 flags = updateFlagsForComponent(flags, userId, component); 3773 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3774 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3775 synchronized (mPackages) { 3776 PackageParser.Provider p = mProviders.mProviders.get(component); 3777 if (DEBUG_PACKAGE_INFO) Log.v( 3778 TAG, "getProviderInfo " + component + ": " + p); 3779 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3780 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3781 if (ps == null) return null; 3782 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3783 userId); 3784 } 3785 } 3786 return null; 3787 } 3788 3789 @Override 3790 public String[] getSystemSharedLibraryNames() { 3791 Set<String> libSet; 3792 synchronized (mPackages) { 3793 libSet = mSharedLibraries.keySet(); 3794 int size = libSet.size(); 3795 if (size > 0) { 3796 String[] libs = new String[size]; 3797 libSet.toArray(libs); 3798 return libs; 3799 } 3800 } 3801 return null; 3802 } 3803 3804 @Override 3805 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3806 synchronized (mPackages) { 3807 return mServicesSystemSharedLibraryPackageName; 3808 } 3809 } 3810 3811 @Override 3812 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3813 synchronized (mPackages) { 3814 return mSharedSystemSharedLibraryPackageName; 3815 } 3816 } 3817 3818 @Override 3819 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3820 synchronized (mPackages) { 3821 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3822 3823 final FeatureInfo fi = new FeatureInfo(); 3824 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3825 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3826 res.add(fi); 3827 3828 return new ParceledListSlice<>(res); 3829 } 3830 } 3831 3832 @Override 3833 public boolean hasSystemFeature(String name, int version) { 3834 synchronized (mPackages) { 3835 final FeatureInfo feat = mAvailableFeatures.get(name); 3836 if (feat == null) { 3837 return false; 3838 } else { 3839 return feat.version >= version; 3840 } 3841 } 3842 } 3843 3844 @Override 3845 public int checkPermission(String permName, String pkgName, int userId) { 3846 if (!sUserManager.exists(userId)) { 3847 return PackageManager.PERMISSION_DENIED; 3848 } 3849 3850 synchronized (mPackages) { 3851 final PackageParser.Package p = mPackages.get(pkgName); 3852 if (p != null && p.mExtras != null) { 3853 final PackageSetting ps = (PackageSetting) p.mExtras; 3854 final PermissionsState permissionsState = ps.getPermissionsState(); 3855 if (permissionsState.hasPermission(permName, userId)) { 3856 return PackageManager.PERMISSION_GRANTED; 3857 } 3858 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3859 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3860 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3861 return PackageManager.PERMISSION_GRANTED; 3862 } 3863 } 3864 } 3865 3866 return PackageManager.PERMISSION_DENIED; 3867 } 3868 3869 @Override 3870 public int checkUidPermission(String permName, int uid) { 3871 final int userId = UserHandle.getUserId(uid); 3872 3873 if (!sUserManager.exists(userId)) { 3874 return PackageManager.PERMISSION_DENIED; 3875 } 3876 3877 synchronized (mPackages) { 3878 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3879 if (obj != null) { 3880 final SettingBase ps = (SettingBase) obj; 3881 final PermissionsState permissionsState = ps.getPermissionsState(); 3882 if (permissionsState.hasPermission(permName, userId)) { 3883 return PackageManager.PERMISSION_GRANTED; 3884 } 3885 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3886 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3887 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3888 return PackageManager.PERMISSION_GRANTED; 3889 } 3890 } else { 3891 ArraySet<String> perms = mSystemPermissions.get(uid); 3892 if (perms != null) { 3893 if (perms.contains(permName)) { 3894 return PackageManager.PERMISSION_GRANTED; 3895 } 3896 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3897 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3898 return PackageManager.PERMISSION_GRANTED; 3899 } 3900 } 3901 } 3902 } 3903 3904 return PackageManager.PERMISSION_DENIED; 3905 } 3906 3907 @Override 3908 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3909 if (UserHandle.getCallingUserId() != userId) { 3910 mContext.enforceCallingPermission( 3911 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3912 "isPermissionRevokedByPolicy for user " + userId); 3913 } 3914 3915 if (checkPermission(permission, packageName, userId) 3916 == PackageManager.PERMISSION_GRANTED) { 3917 return false; 3918 } 3919 3920 final long identity = Binder.clearCallingIdentity(); 3921 try { 3922 final int flags = getPermissionFlags(permission, packageName, userId); 3923 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3924 } finally { 3925 Binder.restoreCallingIdentity(identity); 3926 } 3927 } 3928 3929 @Override 3930 public String getPermissionControllerPackageName() { 3931 synchronized (mPackages) { 3932 return mRequiredInstallerPackage; 3933 } 3934 } 3935 3936 /** 3937 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3938 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3939 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3940 * @param message the message to log on security exception 3941 */ 3942 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3943 boolean checkShell, String message) { 3944 if (userId < 0) { 3945 throw new IllegalArgumentException("Invalid userId " + userId); 3946 } 3947 if (checkShell) { 3948 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3949 } 3950 if (userId == UserHandle.getUserId(callingUid)) return; 3951 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3952 if (requireFullPermission) { 3953 mContext.enforceCallingOrSelfPermission( 3954 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3955 } else { 3956 try { 3957 mContext.enforceCallingOrSelfPermission( 3958 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3959 } catch (SecurityException se) { 3960 mContext.enforceCallingOrSelfPermission( 3961 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3962 } 3963 } 3964 } 3965 } 3966 3967 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3968 if (callingUid == Process.SHELL_UID) { 3969 if (userHandle >= 0 3970 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3971 throw new SecurityException("Shell does not have permission to access user " 3972 + userHandle); 3973 } else if (userHandle < 0) { 3974 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3975 + Debug.getCallers(3)); 3976 } 3977 } 3978 } 3979 3980 private BasePermission findPermissionTreeLP(String permName) { 3981 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3982 if (permName.startsWith(bp.name) && 3983 permName.length() > bp.name.length() && 3984 permName.charAt(bp.name.length()) == '.') { 3985 return bp; 3986 } 3987 } 3988 return null; 3989 } 3990 3991 private BasePermission checkPermissionTreeLP(String permName) { 3992 if (permName != null) { 3993 BasePermission bp = findPermissionTreeLP(permName); 3994 if (bp != null) { 3995 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3996 return bp; 3997 } 3998 throw new SecurityException("Calling uid " 3999 + Binder.getCallingUid() 4000 + " is not allowed to add to permission tree " 4001 + bp.name + " owned by uid " + bp.uid); 4002 } 4003 } 4004 throw new SecurityException("No permission tree found for " + permName); 4005 } 4006 4007 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4008 if (s1 == null) { 4009 return s2 == null; 4010 } 4011 if (s2 == null) { 4012 return false; 4013 } 4014 if (s1.getClass() != s2.getClass()) { 4015 return false; 4016 } 4017 return s1.equals(s2); 4018 } 4019 4020 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4021 if (pi1.icon != pi2.icon) return false; 4022 if (pi1.logo != pi2.logo) return false; 4023 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4024 if (!compareStrings(pi1.name, pi2.name)) return false; 4025 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4026 // We'll take care of setting this one. 4027 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4028 // These are not currently stored in settings. 4029 //if (!compareStrings(pi1.group, pi2.group)) return false; 4030 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4031 //if (pi1.labelRes != pi2.labelRes) return false; 4032 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4033 return true; 4034 } 4035 4036 int permissionInfoFootprint(PermissionInfo info) { 4037 int size = info.name.length(); 4038 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4039 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4040 return size; 4041 } 4042 4043 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4044 int size = 0; 4045 for (BasePermission perm : mSettings.mPermissions.values()) { 4046 if (perm.uid == tree.uid) { 4047 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4048 } 4049 } 4050 return size; 4051 } 4052 4053 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4054 // We calculate the max size of permissions defined by this uid and throw 4055 // if that plus the size of 'info' would exceed our stated maximum. 4056 if (tree.uid != Process.SYSTEM_UID) { 4057 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4058 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4059 throw new SecurityException("Permission tree size cap exceeded"); 4060 } 4061 } 4062 } 4063 4064 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4065 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4066 throw new SecurityException("Label must be specified in permission"); 4067 } 4068 BasePermission tree = checkPermissionTreeLP(info.name); 4069 BasePermission bp = mSettings.mPermissions.get(info.name); 4070 boolean added = bp == null; 4071 boolean changed = true; 4072 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4073 if (added) { 4074 enforcePermissionCapLocked(info, tree); 4075 bp = new BasePermission(info.name, tree.sourcePackage, 4076 BasePermission.TYPE_DYNAMIC); 4077 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4078 throw new SecurityException( 4079 "Not allowed to modify non-dynamic permission " 4080 + info.name); 4081 } else { 4082 if (bp.protectionLevel == fixedLevel 4083 && bp.perm.owner.equals(tree.perm.owner) 4084 && bp.uid == tree.uid 4085 && comparePermissionInfos(bp.perm.info, info)) { 4086 changed = false; 4087 } 4088 } 4089 bp.protectionLevel = fixedLevel; 4090 info = new PermissionInfo(info); 4091 info.protectionLevel = fixedLevel; 4092 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4093 bp.perm.info.packageName = tree.perm.info.packageName; 4094 bp.uid = tree.uid; 4095 if (added) { 4096 mSettings.mPermissions.put(info.name, bp); 4097 } 4098 if (changed) { 4099 if (!async) { 4100 mSettings.writeLPr(); 4101 } else { 4102 scheduleWriteSettingsLocked(); 4103 } 4104 } 4105 return added; 4106 } 4107 4108 @Override 4109 public boolean addPermission(PermissionInfo info) { 4110 synchronized (mPackages) { 4111 return addPermissionLocked(info, false); 4112 } 4113 } 4114 4115 @Override 4116 public boolean addPermissionAsync(PermissionInfo info) { 4117 synchronized (mPackages) { 4118 return addPermissionLocked(info, true); 4119 } 4120 } 4121 4122 @Override 4123 public void removePermission(String name) { 4124 synchronized (mPackages) { 4125 checkPermissionTreeLP(name); 4126 BasePermission bp = mSettings.mPermissions.get(name); 4127 if (bp != null) { 4128 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4129 throw new SecurityException( 4130 "Not allowed to modify non-dynamic permission " 4131 + name); 4132 } 4133 mSettings.mPermissions.remove(name); 4134 mSettings.writeLPr(); 4135 } 4136 } 4137 } 4138 4139 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4140 BasePermission bp) { 4141 int index = pkg.requestedPermissions.indexOf(bp.name); 4142 if (index == -1) { 4143 throw new SecurityException("Package " + pkg.packageName 4144 + " has not requested permission " + bp.name); 4145 } 4146 if (!bp.isRuntime() && !bp.isDevelopment()) { 4147 throw new SecurityException("Permission " + bp.name 4148 + " is not a changeable permission type"); 4149 } 4150 } 4151 4152 @Override 4153 public void grantRuntimePermission(String packageName, String name, final int userId) { 4154 if (!sUserManager.exists(userId)) { 4155 Log.e(TAG, "No such user:" + userId); 4156 return; 4157 } 4158 4159 mContext.enforceCallingOrSelfPermission( 4160 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4161 "grantRuntimePermission"); 4162 4163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4164 true /* requireFullPermission */, true /* checkShell */, 4165 "grantRuntimePermission"); 4166 4167 final int uid; 4168 final SettingBase sb; 4169 4170 synchronized (mPackages) { 4171 final PackageParser.Package pkg = mPackages.get(packageName); 4172 if (pkg == null) { 4173 throw new IllegalArgumentException("Unknown package: " + packageName); 4174 } 4175 4176 final BasePermission bp = mSettings.mPermissions.get(name); 4177 if (bp == null) { 4178 throw new IllegalArgumentException("Unknown permission: " + name); 4179 } 4180 4181 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4182 4183 // If a permission review is required for legacy apps we represent 4184 // their permissions as always granted runtime ones since we need 4185 // to keep the review required permission flag per user while an 4186 // install permission's state is shared across all users. 4187 if (Build.PERMISSIONS_REVIEW_REQUIRED 4188 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4189 && bp.isRuntime()) { 4190 return; 4191 } 4192 4193 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4194 sb = (SettingBase) pkg.mExtras; 4195 if (sb == null) { 4196 throw new IllegalArgumentException("Unknown package: " + packageName); 4197 } 4198 4199 final PermissionsState permissionsState = sb.getPermissionsState(); 4200 4201 final int flags = permissionsState.getPermissionFlags(name, userId); 4202 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4203 throw new SecurityException("Cannot grant system fixed permission " 4204 + name + " for package " + packageName); 4205 } 4206 4207 if (bp.isDevelopment()) { 4208 // Development permissions must be handled specially, since they are not 4209 // normal runtime permissions. For now they apply to all users. 4210 if (permissionsState.grantInstallPermission(bp) != 4211 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4212 scheduleWriteSettingsLocked(); 4213 } 4214 return; 4215 } 4216 4217 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4218 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4219 return; 4220 } 4221 4222 final int result = permissionsState.grantRuntimePermission(bp, userId); 4223 switch (result) { 4224 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4225 return; 4226 } 4227 4228 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4229 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4230 mHandler.post(new Runnable() { 4231 @Override 4232 public void run() { 4233 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4234 } 4235 }); 4236 } 4237 break; 4238 } 4239 4240 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4241 4242 // Not critical if that is lost - app has to request again. 4243 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4244 } 4245 4246 // Only need to do this if user is initialized. Otherwise it's a new user 4247 // and there are no processes running as the user yet and there's no need 4248 // to make an expensive call to remount processes for the changed permissions. 4249 if (READ_EXTERNAL_STORAGE.equals(name) 4250 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4251 final long token = Binder.clearCallingIdentity(); 4252 try { 4253 if (sUserManager.isInitialized(userId)) { 4254 MountServiceInternal mountServiceInternal = LocalServices.getService( 4255 MountServiceInternal.class); 4256 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4257 } 4258 } finally { 4259 Binder.restoreCallingIdentity(token); 4260 } 4261 } 4262 } 4263 4264 @Override 4265 public void revokeRuntimePermission(String packageName, String name, int userId) { 4266 if (!sUserManager.exists(userId)) { 4267 Log.e(TAG, "No such user:" + userId); 4268 return; 4269 } 4270 4271 mContext.enforceCallingOrSelfPermission( 4272 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4273 "revokeRuntimePermission"); 4274 4275 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4276 true /* requireFullPermission */, true /* checkShell */, 4277 "revokeRuntimePermission"); 4278 4279 final int appId; 4280 4281 synchronized (mPackages) { 4282 final PackageParser.Package pkg = mPackages.get(packageName); 4283 if (pkg == null) { 4284 throw new IllegalArgumentException("Unknown package: " + packageName); 4285 } 4286 4287 final BasePermission bp = mSettings.mPermissions.get(name); 4288 if (bp == null) { 4289 throw new IllegalArgumentException("Unknown permission: " + name); 4290 } 4291 4292 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4293 4294 // If a permission review is required for legacy apps we represent 4295 // their permissions as always granted runtime ones since we need 4296 // to keep the review required permission flag per user while an 4297 // install permission's state is shared across all users. 4298 if (Build.PERMISSIONS_REVIEW_REQUIRED 4299 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4300 && bp.isRuntime()) { 4301 return; 4302 } 4303 4304 SettingBase sb = (SettingBase) pkg.mExtras; 4305 if (sb == null) { 4306 throw new IllegalArgumentException("Unknown package: " + packageName); 4307 } 4308 4309 final PermissionsState permissionsState = sb.getPermissionsState(); 4310 4311 final int flags = permissionsState.getPermissionFlags(name, userId); 4312 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4313 throw new SecurityException("Cannot revoke system fixed permission " 4314 + name + " for package " + packageName); 4315 } 4316 4317 if (bp.isDevelopment()) { 4318 // Development permissions must be handled specially, since they are not 4319 // normal runtime permissions. For now they apply to all users. 4320 if (permissionsState.revokeInstallPermission(bp) != 4321 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4322 scheduleWriteSettingsLocked(); 4323 } 4324 return; 4325 } 4326 4327 if (permissionsState.revokeRuntimePermission(bp, userId) == 4328 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4329 return; 4330 } 4331 4332 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4333 4334 // Critical, after this call app should never have the permission. 4335 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4336 4337 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4338 } 4339 4340 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4341 } 4342 4343 @Override 4344 public void resetRuntimePermissions() { 4345 mContext.enforceCallingOrSelfPermission( 4346 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4347 "revokeRuntimePermission"); 4348 4349 int callingUid = Binder.getCallingUid(); 4350 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4351 mContext.enforceCallingOrSelfPermission( 4352 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4353 "resetRuntimePermissions"); 4354 } 4355 4356 synchronized (mPackages) { 4357 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4358 for (int userId : UserManagerService.getInstance().getUserIds()) { 4359 final int packageCount = mPackages.size(); 4360 for (int i = 0; i < packageCount; i++) { 4361 PackageParser.Package pkg = mPackages.valueAt(i); 4362 if (!(pkg.mExtras instanceof PackageSetting)) { 4363 continue; 4364 } 4365 PackageSetting ps = (PackageSetting) pkg.mExtras; 4366 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4367 } 4368 } 4369 } 4370 } 4371 4372 @Override 4373 public int getPermissionFlags(String name, String packageName, int userId) { 4374 if (!sUserManager.exists(userId)) { 4375 return 0; 4376 } 4377 4378 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4379 4380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4381 true /* requireFullPermission */, false /* checkShell */, 4382 "getPermissionFlags"); 4383 4384 synchronized (mPackages) { 4385 final PackageParser.Package pkg = mPackages.get(packageName); 4386 if (pkg == null) { 4387 return 0; 4388 } 4389 4390 final BasePermission bp = mSettings.mPermissions.get(name); 4391 if (bp == null) { 4392 return 0; 4393 } 4394 4395 SettingBase sb = (SettingBase) pkg.mExtras; 4396 if (sb == null) { 4397 return 0; 4398 } 4399 4400 PermissionsState permissionsState = sb.getPermissionsState(); 4401 return permissionsState.getPermissionFlags(name, userId); 4402 } 4403 } 4404 4405 @Override 4406 public void updatePermissionFlags(String name, String packageName, int flagMask, 4407 int flagValues, int userId) { 4408 if (!sUserManager.exists(userId)) { 4409 return; 4410 } 4411 4412 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4413 4414 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4415 true /* requireFullPermission */, true /* checkShell */, 4416 "updatePermissionFlags"); 4417 4418 // Only the system can change these flags and nothing else. 4419 if (getCallingUid() != Process.SYSTEM_UID) { 4420 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4421 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4422 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4423 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4424 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4425 } 4426 4427 synchronized (mPackages) { 4428 final PackageParser.Package pkg = mPackages.get(packageName); 4429 if (pkg == null) { 4430 throw new IllegalArgumentException("Unknown package: " + packageName); 4431 } 4432 4433 final BasePermission bp = mSettings.mPermissions.get(name); 4434 if (bp == null) { 4435 throw new IllegalArgumentException("Unknown permission: " + name); 4436 } 4437 4438 SettingBase sb = (SettingBase) pkg.mExtras; 4439 if (sb == null) { 4440 throw new IllegalArgumentException("Unknown package: " + packageName); 4441 } 4442 4443 PermissionsState permissionsState = sb.getPermissionsState(); 4444 4445 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4446 4447 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4448 // Install and runtime permissions are stored in different places, 4449 // so figure out what permission changed and persist the change. 4450 if (permissionsState.getInstallPermissionState(name) != null) { 4451 scheduleWriteSettingsLocked(); 4452 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4453 || hadState) { 4454 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4455 } 4456 } 4457 } 4458 } 4459 4460 /** 4461 * Update the permission flags for all packages and runtime permissions of a user in order 4462 * to allow device or profile owner to remove POLICY_FIXED. 4463 */ 4464 @Override 4465 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4466 if (!sUserManager.exists(userId)) { 4467 return; 4468 } 4469 4470 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4471 4472 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4473 true /* requireFullPermission */, true /* checkShell */, 4474 "updatePermissionFlagsForAllApps"); 4475 4476 // Only the system can change system fixed flags. 4477 if (getCallingUid() != Process.SYSTEM_UID) { 4478 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4479 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4480 } 4481 4482 synchronized (mPackages) { 4483 boolean changed = false; 4484 final int packageCount = mPackages.size(); 4485 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4486 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4487 SettingBase sb = (SettingBase) pkg.mExtras; 4488 if (sb == null) { 4489 continue; 4490 } 4491 PermissionsState permissionsState = sb.getPermissionsState(); 4492 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4493 userId, flagMask, flagValues); 4494 } 4495 if (changed) { 4496 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4497 } 4498 } 4499 } 4500 4501 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4502 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4503 != PackageManager.PERMISSION_GRANTED 4504 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4505 != PackageManager.PERMISSION_GRANTED) { 4506 throw new SecurityException(message + " requires " 4507 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4508 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4509 } 4510 } 4511 4512 @Override 4513 public boolean shouldShowRequestPermissionRationale(String permissionName, 4514 String packageName, int userId) { 4515 if (UserHandle.getCallingUserId() != userId) { 4516 mContext.enforceCallingPermission( 4517 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4518 "canShowRequestPermissionRationale for user " + userId); 4519 } 4520 4521 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4522 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4523 return false; 4524 } 4525 4526 if (checkPermission(permissionName, packageName, userId) 4527 == PackageManager.PERMISSION_GRANTED) { 4528 return false; 4529 } 4530 4531 final int flags; 4532 4533 final long identity = Binder.clearCallingIdentity(); 4534 try { 4535 flags = getPermissionFlags(permissionName, 4536 packageName, userId); 4537 } finally { 4538 Binder.restoreCallingIdentity(identity); 4539 } 4540 4541 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4542 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4543 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4544 4545 if ((flags & fixedFlags) != 0) { 4546 return false; 4547 } 4548 4549 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4550 } 4551 4552 @Override 4553 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4554 mContext.enforceCallingOrSelfPermission( 4555 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4556 "addOnPermissionsChangeListener"); 4557 4558 synchronized (mPackages) { 4559 mOnPermissionChangeListeners.addListenerLocked(listener); 4560 } 4561 } 4562 4563 @Override 4564 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4565 synchronized (mPackages) { 4566 mOnPermissionChangeListeners.removeListenerLocked(listener); 4567 } 4568 } 4569 4570 @Override 4571 public boolean isProtectedBroadcast(String actionName) { 4572 synchronized (mPackages) { 4573 if (mProtectedBroadcasts.contains(actionName)) { 4574 return true; 4575 } else if (actionName != null) { 4576 // TODO: remove these terrible hacks 4577 if (actionName.startsWith("android.net.netmon.lingerExpired") 4578 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4579 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4580 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4581 return true; 4582 } 4583 } 4584 } 4585 return false; 4586 } 4587 4588 @Override 4589 public int checkSignatures(String pkg1, String pkg2) { 4590 synchronized (mPackages) { 4591 final PackageParser.Package p1 = mPackages.get(pkg1); 4592 final PackageParser.Package p2 = mPackages.get(pkg2); 4593 if (p1 == null || p1.mExtras == null 4594 || p2 == null || p2.mExtras == null) { 4595 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4596 } 4597 return compareSignatures(p1.mSignatures, p2.mSignatures); 4598 } 4599 } 4600 4601 @Override 4602 public int checkUidSignatures(int uid1, int uid2) { 4603 // Map to base uids. 4604 uid1 = UserHandle.getAppId(uid1); 4605 uid2 = UserHandle.getAppId(uid2); 4606 // reader 4607 synchronized (mPackages) { 4608 Signature[] s1; 4609 Signature[] s2; 4610 Object obj = mSettings.getUserIdLPr(uid1); 4611 if (obj != null) { 4612 if (obj instanceof SharedUserSetting) { 4613 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4614 } else if (obj instanceof PackageSetting) { 4615 s1 = ((PackageSetting)obj).signatures.mSignatures; 4616 } else { 4617 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4618 } 4619 } else { 4620 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4621 } 4622 obj = mSettings.getUserIdLPr(uid2); 4623 if (obj != null) { 4624 if (obj instanceof SharedUserSetting) { 4625 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4626 } else if (obj instanceof PackageSetting) { 4627 s2 = ((PackageSetting)obj).signatures.mSignatures; 4628 } else { 4629 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4630 } 4631 } else { 4632 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4633 } 4634 return compareSignatures(s1, s2); 4635 } 4636 } 4637 4638 /** 4639 * This method should typically only be used when granting or revoking 4640 * permissions, since the app may immediately restart after this call. 4641 * <p> 4642 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4643 * guard your work against the app being relaunched. 4644 */ 4645 private void killUid(int appId, int userId, String reason) { 4646 final long identity = Binder.clearCallingIdentity(); 4647 try { 4648 IActivityManager am = ActivityManagerNative.getDefault(); 4649 if (am != null) { 4650 try { 4651 am.killUid(appId, userId, reason); 4652 } catch (RemoteException e) { 4653 /* ignore - same process */ 4654 } 4655 } 4656 } finally { 4657 Binder.restoreCallingIdentity(identity); 4658 } 4659 } 4660 4661 /** 4662 * Compares two sets of signatures. Returns: 4663 * <br /> 4664 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4665 * <br /> 4666 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4667 * <br /> 4668 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4669 * <br /> 4670 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4671 * <br /> 4672 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4673 */ 4674 static int compareSignatures(Signature[] s1, Signature[] s2) { 4675 if (s1 == null) { 4676 return s2 == null 4677 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4678 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4679 } 4680 4681 if (s2 == null) { 4682 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4683 } 4684 4685 if (s1.length != s2.length) { 4686 return PackageManager.SIGNATURE_NO_MATCH; 4687 } 4688 4689 // Since both signature sets are of size 1, we can compare without HashSets. 4690 if (s1.length == 1) { 4691 return s1[0].equals(s2[0]) ? 4692 PackageManager.SIGNATURE_MATCH : 4693 PackageManager.SIGNATURE_NO_MATCH; 4694 } 4695 4696 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4697 for (Signature sig : s1) { 4698 set1.add(sig); 4699 } 4700 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4701 for (Signature sig : s2) { 4702 set2.add(sig); 4703 } 4704 // Make sure s2 contains all signatures in s1. 4705 if (set1.equals(set2)) { 4706 return PackageManager.SIGNATURE_MATCH; 4707 } 4708 return PackageManager.SIGNATURE_NO_MATCH; 4709 } 4710 4711 /** 4712 * If the database version for this type of package (internal storage or 4713 * external storage) is less than the version where package signatures 4714 * were updated, return true. 4715 */ 4716 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4717 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4718 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4719 } 4720 4721 /** 4722 * Used for backward compatibility to make sure any packages with 4723 * certificate chains get upgraded to the new style. {@code existingSigs} 4724 * will be in the old format (since they were stored on disk from before the 4725 * system upgrade) and {@code scannedSigs} will be in the newer format. 4726 */ 4727 private int compareSignaturesCompat(PackageSignatures existingSigs, 4728 PackageParser.Package scannedPkg) { 4729 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4730 return PackageManager.SIGNATURE_NO_MATCH; 4731 } 4732 4733 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4734 for (Signature sig : existingSigs.mSignatures) { 4735 existingSet.add(sig); 4736 } 4737 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4738 for (Signature sig : scannedPkg.mSignatures) { 4739 try { 4740 Signature[] chainSignatures = sig.getChainSignatures(); 4741 for (Signature chainSig : chainSignatures) { 4742 scannedCompatSet.add(chainSig); 4743 } 4744 } catch (CertificateEncodingException e) { 4745 scannedCompatSet.add(sig); 4746 } 4747 } 4748 /* 4749 * Make sure the expanded scanned set contains all signatures in the 4750 * existing one. 4751 */ 4752 if (scannedCompatSet.equals(existingSet)) { 4753 // Migrate the old signatures to the new scheme. 4754 existingSigs.assignSignatures(scannedPkg.mSignatures); 4755 // The new KeySets will be re-added later in the scanning process. 4756 synchronized (mPackages) { 4757 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4758 } 4759 return PackageManager.SIGNATURE_MATCH; 4760 } 4761 return PackageManager.SIGNATURE_NO_MATCH; 4762 } 4763 4764 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4765 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4766 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4767 } 4768 4769 private int compareSignaturesRecover(PackageSignatures existingSigs, 4770 PackageParser.Package scannedPkg) { 4771 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4772 return PackageManager.SIGNATURE_NO_MATCH; 4773 } 4774 4775 String msg = null; 4776 try { 4777 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4778 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4779 + scannedPkg.packageName); 4780 return PackageManager.SIGNATURE_MATCH; 4781 } 4782 } catch (CertificateException e) { 4783 msg = e.getMessage(); 4784 } 4785 4786 logCriticalInfo(Log.INFO, 4787 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4788 return PackageManager.SIGNATURE_NO_MATCH; 4789 } 4790 4791 @Override 4792 public List<String> getAllPackages() { 4793 synchronized (mPackages) { 4794 return new ArrayList<String>(mPackages.keySet()); 4795 } 4796 } 4797 4798 @Override 4799 public String[] getPackagesForUid(int uid) { 4800 uid = UserHandle.getAppId(uid); 4801 // reader 4802 synchronized (mPackages) { 4803 Object obj = mSettings.getUserIdLPr(uid); 4804 if (obj instanceof SharedUserSetting) { 4805 final SharedUserSetting sus = (SharedUserSetting) obj; 4806 final int N = sus.packages.size(); 4807 final String[] res = new String[N]; 4808 for (int i = 0; i < N; i++) { 4809 res[i] = sus.packages.valueAt(i).name; 4810 } 4811 return res; 4812 } else if (obj instanceof PackageSetting) { 4813 final PackageSetting ps = (PackageSetting) obj; 4814 return new String[] { ps.name }; 4815 } 4816 } 4817 return null; 4818 } 4819 4820 @Override 4821 public String getNameForUid(int uid) { 4822 // reader 4823 synchronized (mPackages) { 4824 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4825 if (obj instanceof SharedUserSetting) { 4826 final SharedUserSetting sus = (SharedUserSetting) obj; 4827 return sus.name + ":" + sus.userId; 4828 } else if (obj instanceof PackageSetting) { 4829 final PackageSetting ps = (PackageSetting) obj; 4830 return ps.name; 4831 } 4832 } 4833 return null; 4834 } 4835 4836 @Override 4837 public int getUidForSharedUser(String sharedUserName) { 4838 if(sharedUserName == null) { 4839 return -1; 4840 } 4841 // reader 4842 synchronized (mPackages) { 4843 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4844 if (suid == null) { 4845 return -1; 4846 } 4847 return suid.userId; 4848 } 4849 } 4850 4851 @Override 4852 public int getFlagsForUid(int uid) { 4853 synchronized (mPackages) { 4854 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4855 if (obj instanceof SharedUserSetting) { 4856 final SharedUserSetting sus = (SharedUserSetting) obj; 4857 return sus.pkgFlags; 4858 } else if (obj instanceof PackageSetting) { 4859 final PackageSetting ps = (PackageSetting) obj; 4860 return ps.pkgFlags; 4861 } 4862 } 4863 return 0; 4864 } 4865 4866 @Override 4867 public int getPrivateFlagsForUid(int uid) { 4868 synchronized (mPackages) { 4869 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4870 if (obj instanceof SharedUserSetting) { 4871 final SharedUserSetting sus = (SharedUserSetting) obj; 4872 return sus.pkgPrivateFlags; 4873 } else if (obj instanceof PackageSetting) { 4874 final PackageSetting ps = (PackageSetting) obj; 4875 return ps.pkgPrivateFlags; 4876 } 4877 } 4878 return 0; 4879 } 4880 4881 @Override 4882 public boolean isUidPrivileged(int uid) { 4883 uid = UserHandle.getAppId(uid); 4884 // reader 4885 synchronized (mPackages) { 4886 Object obj = mSettings.getUserIdLPr(uid); 4887 if (obj instanceof SharedUserSetting) { 4888 final SharedUserSetting sus = (SharedUserSetting) obj; 4889 final Iterator<PackageSetting> it = sus.packages.iterator(); 4890 while (it.hasNext()) { 4891 if (it.next().isPrivileged()) { 4892 return true; 4893 } 4894 } 4895 } else if (obj instanceof PackageSetting) { 4896 final PackageSetting ps = (PackageSetting) obj; 4897 return ps.isPrivileged(); 4898 } 4899 } 4900 return false; 4901 } 4902 4903 @Override 4904 public String[] getAppOpPermissionPackages(String permissionName) { 4905 synchronized (mPackages) { 4906 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4907 if (pkgs == null) { 4908 return null; 4909 } 4910 return pkgs.toArray(new String[pkgs.size()]); 4911 } 4912 } 4913 4914 @Override 4915 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4916 int flags, int userId) { 4917 try { 4918 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4919 4920 if (!sUserManager.exists(userId)) return null; 4921 flags = updateFlagsForResolve(flags, userId, intent); 4922 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4923 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4924 4925 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4926 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4927 flags, userId); 4928 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4929 4930 final ResolveInfo bestChoice = 4931 chooseBestActivity(intent, resolvedType, flags, query, userId); 4932 4933 if (isEphemeralAllowed(intent, query, userId)) { 4934 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4935 final EphemeralResolveInfo ai = 4936 getEphemeralResolveInfo(intent, resolvedType, userId); 4937 if (ai != null) { 4938 if (DEBUG_EPHEMERAL) { 4939 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4940 } 4941 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4942 bestChoice.ephemeralResolveInfo = ai; 4943 } 4944 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4945 } 4946 return bestChoice; 4947 } finally { 4948 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4949 } 4950 } 4951 4952 @Override 4953 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4954 IntentFilter filter, int match, ComponentName activity) { 4955 final int userId = UserHandle.getCallingUserId(); 4956 if (DEBUG_PREFERRED) { 4957 Log.v(TAG, "setLastChosenActivity intent=" + intent 4958 + " resolvedType=" + resolvedType 4959 + " flags=" + flags 4960 + " filter=" + filter 4961 + " match=" + match 4962 + " activity=" + activity); 4963 filter.dump(new PrintStreamPrinter(System.out), " "); 4964 } 4965 intent.setComponent(null); 4966 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4967 userId); 4968 // Find any earlier preferred or last chosen entries and nuke them 4969 findPreferredActivity(intent, resolvedType, 4970 flags, query, 0, false, true, false, userId); 4971 // Add the new activity as the last chosen for this filter 4972 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4973 "Setting last chosen"); 4974 } 4975 4976 @Override 4977 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4978 final int userId = UserHandle.getCallingUserId(); 4979 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4980 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4981 userId); 4982 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4983 false, false, false, userId); 4984 } 4985 4986 4987 private boolean isEphemeralAllowed( 4988 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4989 // Short circuit and return early if possible. 4990 if (DISABLE_EPHEMERAL_APPS) { 4991 return false; 4992 } 4993 final int callingUser = UserHandle.getCallingUserId(); 4994 if (callingUser != UserHandle.USER_SYSTEM) { 4995 return false; 4996 } 4997 if (mEphemeralResolverConnection == null) { 4998 return false; 4999 } 5000 if (intent.getComponent() != null) { 5001 return false; 5002 } 5003 if (intent.getPackage() != null) { 5004 return false; 5005 } 5006 final boolean isWebUri = hasWebURI(intent); 5007 if (!isWebUri) { 5008 return false; 5009 } 5010 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5011 synchronized (mPackages) { 5012 final int count = resolvedActivites.size(); 5013 for (int n = 0; n < count; n++) { 5014 ResolveInfo info = resolvedActivites.get(n); 5015 String packageName = info.activityInfo.packageName; 5016 PackageSetting ps = mSettings.mPackages.get(packageName); 5017 if (ps != null) { 5018 // Try to get the status from User settings first 5019 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5020 int status = (int) (packedStatus >> 32); 5021 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5022 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5023 if (DEBUG_EPHEMERAL) { 5024 Slog.v(TAG, "DENY ephemeral apps;" 5025 + " pkg: " + packageName + ", status: " + status); 5026 } 5027 return false; 5028 } 5029 } 5030 } 5031 } 5032 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5033 return true; 5034 } 5035 5036 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 5037 int userId) { 5038 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 5039 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 5040 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 5041 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 5042 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 5043 ephemeralPrefixCount); 5044 final int[] shaPrefix = digest.getDigestPrefix(); 5045 final byte[][] digestBytes = digest.getDigestBytes(); 5046 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5047 mEphemeralResolverConnection.getEphemeralResolveInfoList( 5048 shaPrefix, ephemeralPrefixMask); 5049 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5050 // No hash prefix match; there are no ephemeral apps for this domain. 5051 return null; 5052 } 5053 5054 // Go in reverse order so we match the narrowest scope first. 5055 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 5056 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 5057 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 5058 continue; 5059 } 5060 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5061 // No filters; this should never happen. 5062 if (filters.isEmpty()) { 5063 continue; 5064 } 5065 // We have a domain match; resolve the filters to see if anything matches. 5066 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5067 for (int j = filters.size() - 1; j >= 0; --j) { 5068 final EphemeralResolveIntentInfo intentInfo = 5069 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5070 ephemeralResolver.addFilter(intentInfo); 5071 } 5072 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5073 intent, resolvedType, false /*defaultOnly*/, userId); 5074 if (!matchedResolveInfoList.isEmpty()) { 5075 return matchedResolveInfoList.get(0); 5076 } 5077 } 5078 } 5079 // Hash or filter mis-match; no ephemeral apps for this domain. 5080 return null; 5081 } 5082 5083 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5084 int flags, List<ResolveInfo> query, int userId) { 5085 if (query != null) { 5086 final int N = query.size(); 5087 if (N == 1) { 5088 return query.get(0); 5089 } else if (N > 1) { 5090 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5091 // If there is more than one activity with the same priority, 5092 // then let the user decide between them. 5093 ResolveInfo r0 = query.get(0); 5094 ResolveInfo r1 = query.get(1); 5095 if (DEBUG_INTENT_MATCHING || debug) { 5096 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5097 + r1.activityInfo.name + "=" + r1.priority); 5098 } 5099 // If the first activity has a higher priority, or a different 5100 // default, then it is always desirable to pick it. 5101 if (r0.priority != r1.priority 5102 || r0.preferredOrder != r1.preferredOrder 5103 || r0.isDefault != r1.isDefault) { 5104 return query.get(0); 5105 } 5106 // If we have saved a preference for a preferred activity for 5107 // this Intent, use that. 5108 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5109 flags, query, r0.priority, true, false, debug, userId); 5110 if (ri != null) { 5111 return ri; 5112 } 5113 ri = new ResolveInfo(mResolveInfo); 5114 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5115 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5116 // If all of the options come from the same package, show the application's 5117 // label and icon instead of the generic resolver's. 5118 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5119 // and then throw away the ResolveInfo itself, meaning that the caller loses 5120 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5121 // a fallback for this case; we only set the target package's resources on 5122 // the ResolveInfo, not the ActivityInfo. 5123 final String intentPackage = intent.getPackage(); 5124 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5125 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5126 ri.resolvePackageName = intentPackage; 5127 if (userNeedsBadging(userId)) { 5128 ri.noResourceId = true; 5129 } else { 5130 ri.icon = appi.icon; 5131 } 5132 ri.iconResourceId = appi.icon; 5133 ri.labelRes = appi.labelRes; 5134 } 5135 ri.activityInfo.applicationInfo = new ApplicationInfo( 5136 ri.activityInfo.applicationInfo); 5137 if (userId != 0) { 5138 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5139 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5140 } 5141 // Make sure that the resolver is displayable in car mode 5142 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5143 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5144 return ri; 5145 } 5146 } 5147 return null; 5148 } 5149 5150 /** 5151 * Return true if the given list is not empty and all of its contents have 5152 * an activityInfo with the given package name. 5153 */ 5154 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5155 if (ArrayUtils.isEmpty(list)) { 5156 return false; 5157 } 5158 for (int i = 0, N = list.size(); i < N; i++) { 5159 final ResolveInfo ri = list.get(i); 5160 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5161 if (ai == null || !packageName.equals(ai.packageName)) { 5162 return false; 5163 } 5164 } 5165 return true; 5166 } 5167 5168 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5169 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5170 final int N = query.size(); 5171 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5172 .get(userId); 5173 // Get the list of persistent preferred activities that handle the intent 5174 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5175 List<PersistentPreferredActivity> pprefs = ppir != null 5176 ? ppir.queryIntent(intent, resolvedType, 5177 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5178 : null; 5179 if (pprefs != null && pprefs.size() > 0) { 5180 final int M = pprefs.size(); 5181 for (int i=0; i<M; i++) { 5182 final PersistentPreferredActivity ppa = pprefs.get(i); 5183 if (DEBUG_PREFERRED || debug) { 5184 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5185 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5186 + "\n component=" + ppa.mComponent); 5187 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5188 } 5189 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5190 flags | MATCH_DISABLED_COMPONENTS, userId); 5191 if (DEBUG_PREFERRED || debug) { 5192 Slog.v(TAG, "Found persistent preferred activity:"); 5193 if (ai != null) { 5194 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5195 } else { 5196 Slog.v(TAG, " null"); 5197 } 5198 } 5199 if (ai == null) { 5200 // This previously registered persistent preferred activity 5201 // component is no longer known. Ignore it and do NOT remove it. 5202 continue; 5203 } 5204 for (int j=0; j<N; j++) { 5205 final ResolveInfo ri = query.get(j); 5206 if (!ri.activityInfo.applicationInfo.packageName 5207 .equals(ai.applicationInfo.packageName)) { 5208 continue; 5209 } 5210 if (!ri.activityInfo.name.equals(ai.name)) { 5211 continue; 5212 } 5213 // Found a persistent preference that can handle the intent. 5214 if (DEBUG_PREFERRED || debug) { 5215 Slog.v(TAG, "Returning persistent preferred activity: " + 5216 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5217 } 5218 return ri; 5219 } 5220 } 5221 } 5222 return null; 5223 } 5224 5225 // TODO: handle preferred activities missing while user has amnesia 5226 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5227 List<ResolveInfo> query, int priority, boolean always, 5228 boolean removeMatches, boolean debug, int userId) { 5229 if (!sUserManager.exists(userId)) return null; 5230 flags = updateFlagsForResolve(flags, userId, intent); 5231 // writer 5232 synchronized (mPackages) { 5233 if (intent.getSelector() != null) { 5234 intent = intent.getSelector(); 5235 } 5236 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5237 5238 // Try to find a matching persistent preferred activity. 5239 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5240 debug, userId); 5241 5242 // If a persistent preferred activity matched, use it. 5243 if (pri != null) { 5244 return pri; 5245 } 5246 5247 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5248 // Get the list of preferred activities that handle the intent 5249 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5250 List<PreferredActivity> prefs = pir != null 5251 ? pir.queryIntent(intent, resolvedType, 5252 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5253 : null; 5254 if (prefs != null && prefs.size() > 0) { 5255 boolean changed = false; 5256 try { 5257 // First figure out how good the original match set is. 5258 // We will only allow preferred activities that came 5259 // from the same match quality. 5260 int match = 0; 5261 5262 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5263 5264 final int N = query.size(); 5265 for (int j=0; j<N; j++) { 5266 final ResolveInfo ri = query.get(j); 5267 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5268 + ": 0x" + Integer.toHexString(match)); 5269 if (ri.match > match) { 5270 match = ri.match; 5271 } 5272 } 5273 5274 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5275 + Integer.toHexString(match)); 5276 5277 match &= IntentFilter.MATCH_CATEGORY_MASK; 5278 final int M = prefs.size(); 5279 for (int i=0; i<M; i++) { 5280 final PreferredActivity pa = prefs.get(i); 5281 if (DEBUG_PREFERRED || debug) { 5282 Slog.v(TAG, "Checking PreferredActivity ds=" 5283 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5284 + "\n component=" + pa.mPref.mComponent); 5285 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5286 } 5287 if (pa.mPref.mMatch != match) { 5288 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5289 + Integer.toHexString(pa.mPref.mMatch)); 5290 continue; 5291 } 5292 // If it's not an "always" type preferred activity and that's what we're 5293 // looking for, skip it. 5294 if (always && !pa.mPref.mAlways) { 5295 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5296 continue; 5297 } 5298 final ActivityInfo ai = getActivityInfo( 5299 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5300 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5301 userId); 5302 if (DEBUG_PREFERRED || debug) { 5303 Slog.v(TAG, "Found preferred activity:"); 5304 if (ai != null) { 5305 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5306 } else { 5307 Slog.v(TAG, " null"); 5308 } 5309 } 5310 if (ai == null) { 5311 // This previously registered preferred activity 5312 // component is no longer known. Most likely an update 5313 // to the app was installed and in the new version this 5314 // component no longer exists. Clean it up by removing 5315 // it from the preferred activities list, and skip it. 5316 Slog.w(TAG, "Removing dangling preferred activity: " 5317 + pa.mPref.mComponent); 5318 pir.removeFilter(pa); 5319 changed = true; 5320 continue; 5321 } 5322 for (int j=0; j<N; j++) { 5323 final ResolveInfo ri = query.get(j); 5324 if (!ri.activityInfo.applicationInfo.packageName 5325 .equals(ai.applicationInfo.packageName)) { 5326 continue; 5327 } 5328 if (!ri.activityInfo.name.equals(ai.name)) { 5329 continue; 5330 } 5331 5332 if (removeMatches) { 5333 pir.removeFilter(pa); 5334 changed = true; 5335 if (DEBUG_PREFERRED) { 5336 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5337 } 5338 break; 5339 } 5340 5341 // Okay we found a previously set preferred or last chosen app. 5342 // If the result set is different from when this 5343 // was created, we need to clear it and re-ask the 5344 // user their preference, if we're looking for an "always" type entry. 5345 if (always && !pa.mPref.sameSet(query)) { 5346 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5347 + intent + " type " + resolvedType); 5348 if (DEBUG_PREFERRED) { 5349 Slog.v(TAG, "Removing preferred activity since set changed " 5350 + pa.mPref.mComponent); 5351 } 5352 pir.removeFilter(pa); 5353 // Re-add the filter as a "last chosen" entry (!always) 5354 PreferredActivity lastChosen = new PreferredActivity( 5355 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5356 pir.addFilter(lastChosen); 5357 changed = true; 5358 return null; 5359 } 5360 5361 // Yay! Either the set matched or we're looking for the last chosen 5362 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5363 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5364 return ri; 5365 } 5366 } 5367 } finally { 5368 if (changed) { 5369 if (DEBUG_PREFERRED) { 5370 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5371 } 5372 scheduleWritePackageRestrictionsLocked(userId); 5373 } 5374 } 5375 } 5376 } 5377 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5378 return null; 5379 } 5380 5381 /* 5382 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5383 */ 5384 @Override 5385 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5386 int targetUserId) { 5387 mContext.enforceCallingOrSelfPermission( 5388 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5389 List<CrossProfileIntentFilter> matches = 5390 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5391 if (matches != null) { 5392 int size = matches.size(); 5393 for (int i = 0; i < size; i++) { 5394 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5395 } 5396 } 5397 if (hasWebURI(intent)) { 5398 // cross-profile app linking works only towards the parent. 5399 final UserInfo parent = getProfileParent(sourceUserId); 5400 synchronized(mPackages) { 5401 int flags = updateFlagsForResolve(0, parent.id, intent); 5402 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5403 intent, resolvedType, flags, sourceUserId, parent.id); 5404 return xpDomainInfo != null; 5405 } 5406 } 5407 return false; 5408 } 5409 5410 private UserInfo getProfileParent(int userId) { 5411 final long identity = Binder.clearCallingIdentity(); 5412 try { 5413 return sUserManager.getProfileParent(userId); 5414 } finally { 5415 Binder.restoreCallingIdentity(identity); 5416 } 5417 } 5418 5419 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5420 String resolvedType, int userId) { 5421 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5422 if (resolver != null) { 5423 return resolver.queryIntent(intent, resolvedType, false, userId); 5424 } 5425 return null; 5426 } 5427 5428 @Override 5429 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5430 String resolvedType, int flags, int userId) { 5431 try { 5432 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5433 5434 return new ParceledListSlice<>( 5435 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5436 } finally { 5437 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5438 } 5439 } 5440 5441 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5442 String resolvedType, int flags, int userId) { 5443 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5444 flags = updateFlagsForResolve(flags, userId, intent); 5445 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5446 false /* requireFullPermission */, false /* checkShell */, 5447 "query intent activities"); 5448 ComponentName comp = intent.getComponent(); 5449 if (comp == null) { 5450 if (intent.getSelector() != null) { 5451 intent = intent.getSelector(); 5452 comp = intent.getComponent(); 5453 } 5454 } 5455 5456 if (comp != null) { 5457 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5458 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5459 if (ai != null) { 5460 final ResolveInfo ri = new ResolveInfo(); 5461 ri.activityInfo = ai; 5462 list.add(ri); 5463 } 5464 return list; 5465 } 5466 5467 // reader 5468 synchronized (mPackages) { 5469 final String pkgName = intent.getPackage(); 5470 if (pkgName == null) { 5471 List<CrossProfileIntentFilter> matchingFilters = 5472 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5473 // Check for results that need to skip the current profile. 5474 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5475 resolvedType, flags, userId); 5476 if (xpResolveInfo != null) { 5477 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5478 result.add(xpResolveInfo); 5479 return filterIfNotSystemUser(result, userId); 5480 } 5481 5482 // Check for results in the current profile. 5483 List<ResolveInfo> result = mActivities.queryIntent( 5484 intent, resolvedType, flags, userId); 5485 result = filterIfNotSystemUser(result, userId); 5486 5487 // Check for cross profile results. 5488 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5489 xpResolveInfo = queryCrossProfileIntents( 5490 matchingFilters, intent, resolvedType, flags, userId, 5491 hasNonNegativePriorityResult); 5492 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5493 boolean isVisibleToUser = filterIfNotSystemUser( 5494 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5495 if (isVisibleToUser) { 5496 result.add(xpResolveInfo); 5497 Collections.sort(result, mResolvePrioritySorter); 5498 } 5499 } 5500 if (hasWebURI(intent)) { 5501 CrossProfileDomainInfo xpDomainInfo = null; 5502 final UserInfo parent = getProfileParent(userId); 5503 if (parent != null) { 5504 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5505 flags, userId, parent.id); 5506 } 5507 if (xpDomainInfo != null) { 5508 if (xpResolveInfo != null) { 5509 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5510 // in the result. 5511 result.remove(xpResolveInfo); 5512 } 5513 if (result.size() == 0) { 5514 result.add(xpDomainInfo.resolveInfo); 5515 return result; 5516 } 5517 } else if (result.size() <= 1) { 5518 return result; 5519 } 5520 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5521 xpDomainInfo, userId); 5522 Collections.sort(result, mResolvePrioritySorter); 5523 } 5524 return result; 5525 } 5526 final PackageParser.Package pkg = mPackages.get(pkgName); 5527 if (pkg != null) { 5528 return filterIfNotSystemUser( 5529 mActivities.queryIntentForPackage( 5530 intent, resolvedType, flags, pkg.activities, userId), 5531 userId); 5532 } 5533 return new ArrayList<ResolveInfo>(); 5534 } 5535 } 5536 5537 private static class CrossProfileDomainInfo { 5538 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5539 ResolveInfo resolveInfo; 5540 /* Best domain verification status of the activities found in the other profile */ 5541 int bestDomainVerificationStatus; 5542 } 5543 5544 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5545 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5546 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5547 sourceUserId)) { 5548 return null; 5549 } 5550 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5551 resolvedType, flags, parentUserId); 5552 5553 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5554 return null; 5555 } 5556 CrossProfileDomainInfo result = null; 5557 int size = resultTargetUser.size(); 5558 for (int i = 0; i < size; i++) { 5559 ResolveInfo riTargetUser = resultTargetUser.get(i); 5560 // Intent filter verification is only for filters that specify a host. So don't return 5561 // those that handle all web uris. 5562 if (riTargetUser.handleAllWebDataURI) { 5563 continue; 5564 } 5565 String packageName = riTargetUser.activityInfo.packageName; 5566 PackageSetting ps = mSettings.mPackages.get(packageName); 5567 if (ps == null) { 5568 continue; 5569 } 5570 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5571 int status = (int)(verificationState >> 32); 5572 if (result == null) { 5573 result = new CrossProfileDomainInfo(); 5574 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5575 sourceUserId, parentUserId); 5576 result.bestDomainVerificationStatus = status; 5577 } else { 5578 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5579 result.bestDomainVerificationStatus); 5580 } 5581 } 5582 // Don't consider matches with status NEVER across profiles. 5583 if (result != null && result.bestDomainVerificationStatus 5584 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5585 return null; 5586 } 5587 return result; 5588 } 5589 5590 /** 5591 * Verification statuses are ordered from the worse to the best, except for 5592 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5593 */ 5594 private int bestDomainVerificationStatus(int status1, int status2) { 5595 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5596 return status2; 5597 } 5598 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5599 return status1; 5600 } 5601 return (int) MathUtils.max(status1, status2); 5602 } 5603 5604 private boolean isUserEnabled(int userId) { 5605 long callingId = Binder.clearCallingIdentity(); 5606 try { 5607 UserInfo userInfo = sUserManager.getUserInfo(userId); 5608 return userInfo != null && userInfo.isEnabled(); 5609 } finally { 5610 Binder.restoreCallingIdentity(callingId); 5611 } 5612 } 5613 5614 /** 5615 * Filter out activities with systemUserOnly flag set, when current user is not System. 5616 * 5617 * @return filtered list 5618 */ 5619 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5620 if (userId == UserHandle.USER_SYSTEM) { 5621 return resolveInfos; 5622 } 5623 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5624 ResolveInfo info = resolveInfos.get(i); 5625 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5626 resolveInfos.remove(i); 5627 } 5628 } 5629 return resolveInfos; 5630 } 5631 5632 /** 5633 * @param resolveInfos list of resolve infos in descending priority order 5634 * @return if the list contains a resolve info with non-negative priority 5635 */ 5636 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5637 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5638 } 5639 5640 private static boolean hasWebURI(Intent intent) { 5641 if (intent.getData() == null) { 5642 return false; 5643 } 5644 final String scheme = intent.getScheme(); 5645 if (TextUtils.isEmpty(scheme)) { 5646 return false; 5647 } 5648 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5649 } 5650 5651 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5652 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5653 int userId) { 5654 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5655 5656 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5657 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5658 candidates.size()); 5659 } 5660 5661 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5662 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5663 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5664 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5665 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5666 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5667 5668 synchronized (mPackages) { 5669 final int count = candidates.size(); 5670 // First, try to use linked apps. Partition the candidates into four lists: 5671 // one for the final results, one for the "do not use ever", one for "undefined status" 5672 // and finally one for "browser app type". 5673 for (int n=0; n<count; n++) { 5674 ResolveInfo info = candidates.get(n); 5675 String packageName = info.activityInfo.packageName; 5676 PackageSetting ps = mSettings.mPackages.get(packageName); 5677 if (ps != null) { 5678 // Add to the special match all list (Browser use case) 5679 if (info.handleAllWebDataURI) { 5680 matchAllList.add(info); 5681 continue; 5682 } 5683 // Try to get the status from User settings first 5684 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5685 int status = (int)(packedStatus >> 32); 5686 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5687 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5688 if (DEBUG_DOMAIN_VERIFICATION) { 5689 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5690 + " : linkgen=" + linkGeneration); 5691 } 5692 // Use link-enabled generation as preferredOrder, i.e. 5693 // prefer newly-enabled over earlier-enabled. 5694 info.preferredOrder = linkGeneration; 5695 alwaysList.add(info); 5696 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5697 if (DEBUG_DOMAIN_VERIFICATION) { 5698 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5699 } 5700 neverList.add(info); 5701 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5702 if (DEBUG_DOMAIN_VERIFICATION) { 5703 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5704 } 5705 alwaysAskList.add(info); 5706 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5707 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5708 if (DEBUG_DOMAIN_VERIFICATION) { 5709 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5710 } 5711 undefinedList.add(info); 5712 } 5713 } 5714 } 5715 5716 // We'll want to include browser possibilities in a few cases 5717 boolean includeBrowser = false; 5718 5719 // First try to add the "always" resolution(s) for the current user, if any 5720 if (alwaysList.size() > 0) { 5721 result.addAll(alwaysList); 5722 } else { 5723 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5724 result.addAll(undefinedList); 5725 // Maybe add one for the other profile. 5726 if (xpDomainInfo != null && ( 5727 xpDomainInfo.bestDomainVerificationStatus 5728 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5729 result.add(xpDomainInfo.resolveInfo); 5730 } 5731 includeBrowser = true; 5732 } 5733 5734 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5735 // If there were 'always' entries their preferred order has been set, so we also 5736 // back that off to make the alternatives equivalent 5737 if (alwaysAskList.size() > 0) { 5738 for (ResolveInfo i : result) { 5739 i.preferredOrder = 0; 5740 } 5741 result.addAll(alwaysAskList); 5742 includeBrowser = true; 5743 } 5744 5745 if (includeBrowser) { 5746 // Also add browsers (all of them or only the default one) 5747 if (DEBUG_DOMAIN_VERIFICATION) { 5748 Slog.v(TAG, " ...including browsers in candidate set"); 5749 } 5750 if ((matchFlags & MATCH_ALL) != 0) { 5751 result.addAll(matchAllList); 5752 } else { 5753 // Browser/generic handling case. If there's a default browser, go straight 5754 // to that (but only if there is no other higher-priority match). 5755 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5756 int maxMatchPrio = 0; 5757 ResolveInfo defaultBrowserMatch = null; 5758 final int numCandidates = matchAllList.size(); 5759 for (int n = 0; n < numCandidates; n++) { 5760 ResolveInfo info = matchAllList.get(n); 5761 // track the highest overall match priority... 5762 if (info.priority > maxMatchPrio) { 5763 maxMatchPrio = info.priority; 5764 } 5765 // ...and the highest-priority default browser match 5766 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5767 if (defaultBrowserMatch == null 5768 || (defaultBrowserMatch.priority < info.priority)) { 5769 if (debug) { 5770 Slog.v(TAG, "Considering default browser match " + info); 5771 } 5772 defaultBrowserMatch = info; 5773 } 5774 } 5775 } 5776 if (defaultBrowserMatch != null 5777 && defaultBrowserMatch.priority >= maxMatchPrio 5778 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5779 { 5780 if (debug) { 5781 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5782 } 5783 result.add(defaultBrowserMatch); 5784 } else { 5785 result.addAll(matchAllList); 5786 } 5787 } 5788 5789 // If there is nothing selected, add all candidates and remove the ones that the user 5790 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5791 if (result.size() == 0) { 5792 result.addAll(candidates); 5793 result.removeAll(neverList); 5794 } 5795 } 5796 } 5797 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5798 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5799 result.size()); 5800 for (ResolveInfo info : result) { 5801 Slog.v(TAG, " + " + info.activityInfo); 5802 } 5803 } 5804 return result; 5805 } 5806 5807 // Returns a packed value as a long: 5808 // 5809 // high 'int'-sized word: link status: undefined/ask/never/always. 5810 // low 'int'-sized word: relative priority among 'always' results. 5811 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5812 long result = ps.getDomainVerificationStatusForUser(userId); 5813 // if none available, get the master status 5814 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5815 if (ps.getIntentFilterVerificationInfo() != null) { 5816 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5817 } 5818 } 5819 return result; 5820 } 5821 5822 private ResolveInfo querySkipCurrentProfileIntents( 5823 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5824 int flags, int sourceUserId) { 5825 if (matchingFilters != null) { 5826 int size = matchingFilters.size(); 5827 for (int i = 0; i < size; i ++) { 5828 CrossProfileIntentFilter filter = matchingFilters.get(i); 5829 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5830 // Checking if there are activities in the target user that can handle the 5831 // intent. 5832 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5833 resolvedType, flags, sourceUserId); 5834 if (resolveInfo != null) { 5835 return resolveInfo; 5836 } 5837 } 5838 } 5839 } 5840 return null; 5841 } 5842 5843 // Return matching ResolveInfo in target user if any. 5844 private ResolveInfo queryCrossProfileIntents( 5845 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5846 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5847 if (matchingFilters != null) { 5848 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5849 // match the same intent. For performance reasons, it is better not to 5850 // run queryIntent twice for the same userId 5851 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5852 int size = matchingFilters.size(); 5853 for (int i = 0; i < size; i++) { 5854 CrossProfileIntentFilter filter = matchingFilters.get(i); 5855 int targetUserId = filter.getTargetUserId(); 5856 boolean skipCurrentProfile = 5857 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5858 boolean skipCurrentProfileIfNoMatchFound = 5859 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5860 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5861 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5862 // Checking if there are activities in the target user that can handle the 5863 // intent. 5864 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5865 resolvedType, flags, sourceUserId); 5866 if (resolveInfo != null) return resolveInfo; 5867 alreadyTriedUserIds.put(targetUserId, true); 5868 } 5869 } 5870 } 5871 return null; 5872 } 5873 5874 /** 5875 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5876 * will forward the intent to the filter's target user. 5877 * Otherwise, returns null. 5878 */ 5879 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5880 String resolvedType, int flags, int sourceUserId) { 5881 int targetUserId = filter.getTargetUserId(); 5882 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5883 resolvedType, flags, targetUserId); 5884 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5885 // If all the matches in the target profile are suspended, return null. 5886 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5887 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5888 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5889 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5890 targetUserId); 5891 } 5892 } 5893 } 5894 return null; 5895 } 5896 5897 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5898 int sourceUserId, int targetUserId) { 5899 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5900 long ident = Binder.clearCallingIdentity(); 5901 boolean targetIsProfile; 5902 try { 5903 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5904 } finally { 5905 Binder.restoreCallingIdentity(ident); 5906 } 5907 String className; 5908 if (targetIsProfile) { 5909 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5910 } else { 5911 className = FORWARD_INTENT_TO_PARENT; 5912 } 5913 ComponentName forwardingActivityComponentName = new ComponentName( 5914 mAndroidApplication.packageName, className); 5915 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5916 sourceUserId); 5917 if (!targetIsProfile) { 5918 forwardingActivityInfo.showUserIcon = targetUserId; 5919 forwardingResolveInfo.noResourceId = true; 5920 } 5921 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5922 forwardingResolveInfo.priority = 0; 5923 forwardingResolveInfo.preferredOrder = 0; 5924 forwardingResolveInfo.match = 0; 5925 forwardingResolveInfo.isDefault = true; 5926 forwardingResolveInfo.filter = filter; 5927 forwardingResolveInfo.targetUserId = targetUserId; 5928 return forwardingResolveInfo; 5929 } 5930 5931 @Override 5932 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5933 Intent[] specifics, String[] specificTypes, Intent intent, 5934 String resolvedType, int flags, int userId) { 5935 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5936 specificTypes, intent, resolvedType, flags, userId)); 5937 } 5938 5939 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5940 Intent[] specifics, String[] specificTypes, Intent intent, 5941 String resolvedType, int flags, int userId) { 5942 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5943 flags = updateFlagsForResolve(flags, userId, intent); 5944 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5945 false /* requireFullPermission */, false /* checkShell */, 5946 "query intent activity options"); 5947 final String resultsAction = intent.getAction(); 5948 5949 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5950 | PackageManager.GET_RESOLVED_FILTER, userId); 5951 5952 if (DEBUG_INTENT_MATCHING) { 5953 Log.v(TAG, "Query " + intent + ": " + results); 5954 } 5955 5956 int specificsPos = 0; 5957 int N; 5958 5959 // todo: note that the algorithm used here is O(N^2). This 5960 // isn't a problem in our current environment, but if we start running 5961 // into situations where we have more than 5 or 10 matches then this 5962 // should probably be changed to something smarter... 5963 5964 // First we go through and resolve each of the specific items 5965 // that were supplied, taking care of removing any corresponding 5966 // duplicate items in the generic resolve list. 5967 if (specifics != null) { 5968 for (int i=0; i<specifics.length; i++) { 5969 final Intent sintent = specifics[i]; 5970 if (sintent == null) { 5971 continue; 5972 } 5973 5974 if (DEBUG_INTENT_MATCHING) { 5975 Log.v(TAG, "Specific #" + i + ": " + sintent); 5976 } 5977 5978 String action = sintent.getAction(); 5979 if (resultsAction != null && resultsAction.equals(action)) { 5980 // If this action was explicitly requested, then don't 5981 // remove things that have it. 5982 action = null; 5983 } 5984 5985 ResolveInfo ri = null; 5986 ActivityInfo ai = null; 5987 5988 ComponentName comp = sintent.getComponent(); 5989 if (comp == null) { 5990 ri = resolveIntent( 5991 sintent, 5992 specificTypes != null ? specificTypes[i] : null, 5993 flags, userId); 5994 if (ri == null) { 5995 continue; 5996 } 5997 if (ri == mResolveInfo) { 5998 // ACK! Must do something better with this. 5999 } 6000 ai = ri.activityInfo; 6001 comp = new ComponentName(ai.applicationInfo.packageName, 6002 ai.name); 6003 } else { 6004 ai = getActivityInfo(comp, flags, userId); 6005 if (ai == null) { 6006 continue; 6007 } 6008 } 6009 6010 // Look for any generic query activities that are duplicates 6011 // of this specific one, and remove them from the results. 6012 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6013 N = results.size(); 6014 int j; 6015 for (j=specificsPos; j<N; j++) { 6016 ResolveInfo sri = results.get(j); 6017 if ((sri.activityInfo.name.equals(comp.getClassName()) 6018 && sri.activityInfo.applicationInfo.packageName.equals( 6019 comp.getPackageName())) 6020 || (action != null && sri.filter.matchAction(action))) { 6021 results.remove(j); 6022 if (DEBUG_INTENT_MATCHING) Log.v( 6023 TAG, "Removing duplicate item from " + j 6024 + " due to specific " + specificsPos); 6025 if (ri == null) { 6026 ri = sri; 6027 } 6028 j--; 6029 N--; 6030 } 6031 } 6032 6033 // Add this specific item to its proper place. 6034 if (ri == null) { 6035 ri = new ResolveInfo(); 6036 ri.activityInfo = ai; 6037 } 6038 results.add(specificsPos, ri); 6039 ri.specificIndex = i; 6040 specificsPos++; 6041 } 6042 } 6043 6044 // Now we go through the remaining generic results and remove any 6045 // duplicate actions that are found here. 6046 N = results.size(); 6047 for (int i=specificsPos; i<N-1; i++) { 6048 final ResolveInfo rii = results.get(i); 6049 if (rii.filter == null) { 6050 continue; 6051 } 6052 6053 // Iterate over all of the actions of this result's intent 6054 // filter... typically this should be just one. 6055 final Iterator<String> it = rii.filter.actionsIterator(); 6056 if (it == null) { 6057 continue; 6058 } 6059 while (it.hasNext()) { 6060 final String action = it.next(); 6061 if (resultsAction != null && resultsAction.equals(action)) { 6062 // If this action was explicitly requested, then don't 6063 // remove things that have it. 6064 continue; 6065 } 6066 for (int j=i+1; j<N; j++) { 6067 final ResolveInfo rij = results.get(j); 6068 if (rij.filter != null && rij.filter.hasAction(action)) { 6069 results.remove(j); 6070 if (DEBUG_INTENT_MATCHING) Log.v( 6071 TAG, "Removing duplicate item from " + j 6072 + " due to action " + action + " at " + i); 6073 j--; 6074 N--; 6075 } 6076 } 6077 } 6078 6079 // If the caller didn't request filter information, drop it now 6080 // so we don't have to marshall/unmarshall it. 6081 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6082 rii.filter = null; 6083 } 6084 } 6085 6086 // Filter out the caller activity if so requested. 6087 if (caller != null) { 6088 N = results.size(); 6089 for (int i=0; i<N; i++) { 6090 ActivityInfo ainfo = results.get(i).activityInfo; 6091 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6092 && caller.getClassName().equals(ainfo.name)) { 6093 results.remove(i); 6094 break; 6095 } 6096 } 6097 } 6098 6099 // If the caller didn't request filter information, 6100 // drop them now so we don't have to 6101 // marshall/unmarshall it. 6102 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6103 N = results.size(); 6104 for (int i=0; i<N; i++) { 6105 results.get(i).filter = null; 6106 } 6107 } 6108 6109 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6110 return results; 6111 } 6112 6113 @Override 6114 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6115 String resolvedType, int flags, int userId) { 6116 return new ParceledListSlice<>( 6117 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6118 } 6119 6120 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6121 String resolvedType, int flags, int userId) { 6122 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6123 flags = updateFlagsForResolve(flags, userId, intent); 6124 ComponentName comp = intent.getComponent(); 6125 if (comp == null) { 6126 if (intent.getSelector() != null) { 6127 intent = intent.getSelector(); 6128 comp = intent.getComponent(); 6129 } 6130 } 6131 if (comp != null) { 6132 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6133 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6134 if (ai != null) { 6135 ResolveInfo ri = new ResolveInfo(); 6136 ri.activityInfo = ai; 6137 list.add(ri); 6138 } 6139 return list; 6140 } 6141 6142 // reader 6143 synchronized (mPackages) { 6144 String pkgName = intent.getPackage(); 6145 if (pkgName == null) { 6146 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6147 } 6148 final PackageParser.Package pkg = mPackages.get(pkgName); 6149 if (pkg != null) { 6150 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6151 userId); 6152 } 6153 return Collections.emptyList(); 6154 } 6155 } 6156 6157 @Override 6158 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6159 if (!sUserManager.exists(userId)) return null; 6160 flags = updateFlagsForResolve(flags, userId, intent); 6161 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6162 if (query != null) { 6163 if (query.size() >= 1) { 6164 // If there is more than one service with the same priority, 6165 // just arbitrarily pick the first one. 6166 return query.get(0); 6167 } 6168 } 6169 return null; 6170 } 6171 6172 @Override 6173 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6174 String resolvedType, int flags, int userId) { 6175 return new ParceledListSlice<>( 6176 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6177 } 6178 6179 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6180 String resolvedType, int flags, int userId) { 6181 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6182 flags = updateFlagsForResolve(flags, userId, intent); 6183 ComponentName comp = intent.getComponent(); 6184 if (comp == null) { 6185 if (intent.getSelector() != null) { 6186 intent = intent.getSelector(); 6187 comp = intent.getComponent(); 6188 } 6189 } 6190 if (comp != null) { 6191 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6192 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6193 if (si != null) { 6194 final ResolveInfo ri = new ResolveInfo(); 6195 ri.serviceInfo = si; 6196 list.add(ri); 6197 } 6198 return list; 6199 } 6200 6201 // reader 6202 synchronized (mPackages) { 6203 String pkgName = intent.getPackage(); 6204 if (pkgName == null) { 6205 return mServices.queryIntent(intent, resolvedType, flags, userId); 6206 } 6207 final PackageParser.Package pkg = mPackages.get(pkgName); 6208 if (pkg != null) { 6209 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6210 userId); 6211 } 6212 return Collections.emptyList(); 6213 } 6214 } 6215 6216 @Override 6217 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6218 String resolvedType, int flags, int userId) { 6219 return new ParceledListSlice<>( 6220 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6221 } 6222 6223 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6224 Intent intent, String resolvedType, int flags, int userId) { 6225 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6226 flags = updateFlagsForResolve(flags, userId, intent); 6227 ComponentName comp = intent.getComponent(); 6228 if (comp == null) { 6229 if (intent.getSelector() != null) { 6230 intent = intent.getSelector(); 6231 comp = intent.getComponent(); 6232 } 6233 } 6234 if (comp != null) { 6235 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6236 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6237 if (pi != null) { 6238 final ResolveInfo ri = new ResolveInfo(); 6239 ri.providerInfo = pi; 6240 list.add(ri); 6241 } 6242 return list; 6243 } 6244 6245 // reader 6246 synchronized (mPackages) { 6247 String pkgName = intent.getPackage(); 6248 if (pkgName == null) { 6249 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6250 } 6251 final PackageParser.Package pkg = mPackages.get(pkgName); 6252 if (pkg != null) { 6253 return mProviders.queryIntentForPackage( 6254 intent, resolvedType, flags, pkg.providers, userId); 6255 } 6256 return Collections.emptyList(); 6257 } 6258 } 6259 6260 @Override 6261 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6262 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6263 flags = updateFlagsForPackage(flags, userId, null); 6264 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6265 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6266 true /* requireFullPermission */, false /* checkShell */, 6267 "get installed packages"); 6268 6269 // writer 6270 synchronized (mPackages) { 6271 ArrayList<PackageInfo> list; 6272 if (listUninstalled) { 6273 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6274 for (PackageSetting ps : mSettings.mPackages.values()) { 6275 final PackageInfo pi; 6276 if (ps.pkg != null) { 6277 pi = generatePackageInfo(ps, flags, userId); 6278 } else { 6279 pi = generatePackageInfo(ps, flags, userId); 6280 } 6281 if (pi != null) { 6282 list.add(pi); 6283 } 6284 } 6285 } else { 6286 list = new ArrayList<PackageInfo>(mPackages.size()); 6287 for (PackageParser.Package p : mPackages.values()) { 6288 final PackageInfo pi = 6289 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6290 if (pi != null) { 6291 list.add(pi); 6292 } 6293 } 6294 } 6295 6296 return new ParceledListSlice<PackageInfo>(list); 6297 } 6298 } 6299 6300 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6301 String[] permissions, boolean[] tmp, int flags, int userId) { 6302 int numMatch = 0; 6303 final PermissionsState permissionsState = ps.getPermissionsState(); 6304 for (int i=0; i<permissions.length; i++) { 6305 final String permission = permissions[i]; 6306 if (permissionsState.hasPermission(permission, userId)) { 6307 tmp[i] = true; 6308 numMatch++; 6309 } else { 6310 tmp[i] = false; 6311 } 6312 } 6313 if (numMatch == 0) { 6314 return; 6315 } 6316 final PackageInfo pi; 6317 if (ps.pkg != null) { 6318 pi = generatePackageInfo(ps, flags, userId); 6319 } else { 6320 pi = generatePackageInfo(ps, flags, userId); 6321 } 6322 // The above might return null in cases of uninstalled apps or install-state 6323 // skew across users/profiles. 6324 if (pi != null) { 6325 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6326 if (numMatch == permissions.length) { 6327 pi.requestedPermissions = permissions; 6328 } else { 6329 pi.requestedPermissions = new String[numMatch]; 6330 numMatch = 0; 6331 for (int i=0; i<permissions.length; i++) { 6332 if (tmp[i]) { 6333 pi.requestedPermissions[numMatch] = permissions[i]; 6334 numMatch++; 6335 } 6336 } 6337 } 6338 } 6339 list.add(pi); 6340 } 6341 } 6342 6343 @Override 6344 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6345 String[] permissions, int flags, int userId) { 6346 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6347 flags = updateFlagsForPackage(flags, userId, permissions); 6348 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6349 6350 // writer 6351 synchronized (mPackages) { 6352 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6353 boolean[] tmpBools = new boolean[permissions.length]; 6354 if (listUninstalled) { 6355 for (PackageSetting ps : mSettings.mPackages.values()) { 6356 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6357 } 6358 } else { 6359 for (PackageParser.Package pkg : mPackages.values()) { 6360 PackageSetting ps = (PackageSetting)pkg.mExtras; 6361 if (ps != null) { 6362 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6363 userId); 6364 } 6365 } 6366 } 6367 6368 return new ParceledListSlice<PackageInfo>(list); 6369 } 6370 } 6371 6372 @Override 6373 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6374 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6375 flags = updateFlagsForApplication(flags, userId, null); 6376 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6377 6378 // writer 6379 synchronized (mPackages) { 6380 ArrayList<ApplicationInfo> list; 6381 if (listUninstalled) { 6382 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6383 for (PackageSetting ps : mSettings.mPackages.values()) { 6384 ApplicationInfo ai; 6385 if (ps.pkg != null) { 6386 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6387 ps.readUserState(userId), userId); 6388 } else { 6389 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6390 } 6391 if (ai != null) { 6392 list.add(ai); 6393 } 6394 } 6395 } else { 6396 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6397 for (PackageParser.Package p : mPackages.values()) { 6398 if (p.mExtras != null) { 6399 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6400 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6401 if (ai != null) { 6402 list.add(ai); 6403 } 6404 } 6405 } 6406 } 6407 6408 return new ParceledListSlice<ApplicationInfo>(list); 6409 } 6410 } 6411 6412 @Override 6413 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6414 if (DISABLE_EPHEMERAL_APPS) { 6415 return null; 6416 } 6417 6418 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6419 "getEphemeralApplications"); 6420 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6421 true /* requireFullPermission */, false /* checkShell */, 6422 "getEphemeralApplications"); 6423 synchronized (mPackages) { 6424 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6425 .getEphemeralApplicationsLPw(userId); 6426 if (ephemeralApps != null) { 6427 return new ParceledListSlice<>(ephemeralApps); 6428 } 6429 } 6430 return null; 6431 } 6432 6433 @Override 6434 public boolean isEphemeralApplication(String packageName, int userId) { 6435 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6436 true /* requireFullPermission */, false /* checkShell */, 6437 "isEphemeral"); 6438 if (DISABLE_EPHEMERAL_APPS) { 6439 return false; 6440 } 6441 6442 if (!isCallerSameApp(packageName)) { 6443 return false; 6444 } 6445 synchronized (mPackages) { 6446 PackageParser.Package pkg = mPackages.get(packageName); 6447 if (pkg != null) { 6448 return pkg.applicationInfo.isEphemeralApp(); 6449 } 6450 } 6451 return false; 6452 } 6453 6454 @Override 6455 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6456 if (DISABLE_EPHEMERAL_APPS) { 6457 return null; 6458 } 6459 6460 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6461 true /* requireFullPermission */, false /* checkShell */, 6462 "getCookie"); 6463 if (!isCallerSameApp(packageName)) { 6464 return null; 6465 } 6466 synchronized (mPackages) { 6467 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6468 packageName, userId); 6469 } 6470 } 6471 6472 @Override 6473 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6474 if (DISABLE_EPHEMERAL_APPS) { 6475 return true; 6476 } 6477 6478 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6479 true /* requireFullPermission */, true /* checkShell */, 6480 "setCookie"); 6481 if (!isCallerSameApp(packageName)) { 6482 return false; 6483 } 6484 synchronized (mPackages) { 6485 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6486 packageName, cookie, userId); 6487 } 6488 } 6489 6490 @Override 6491 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6492 if (DISABLE_EPHEMERAL_APPS) { 6493 return null; 6494 } 6495 6496 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6497 "getEphemeralApplicationIcon"); 6498 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6499 true /* requireFullPermission */, false /* checkShell */, 6500 "getEphemeralApplicationIcon"); 6501 synchronized (mPackages) { 6502 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6503 packageName, userId); 6504 } 6505 } 6506 6507 private boolean isCallerSameApp(String packageName) { 6508 PackageParser.Package pkg = mPackages.get(packageName); 6509 return pkg != null 6510 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6511 } 6512 6513 @Override 6514 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6515 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6516 } 6517 6518 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6519 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6520 6521 // reader 6522 synchronized (mPackages) { 6523 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6524 final int userId = UserHandle.getCallingUserId(); 6525 while (i.hasNext()) { 6526 final PackageParser.Package p = i.next(); 6527 if (p.applicationInfo == null) continue; 6528 6529 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6530 && !p.applicationInfo.isDirectBootAware(); 6531 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6532 && p.applicationInfo.isDirectBootAware(); 6533 6534 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6535 && (!mSafeMode || isSystemApp(p)) 6536 && (matchesUnaware || matchesAware)) { 6537 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6538 if (ps != null) { 6539 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6540 ps.readUserState(userId), userId); 6541 if (ai != null) { 6542 finalList.add(ai); 6543 } 6544 } 6545 } 6546 } 6547 } 6548 6549 return finalList; 6550 } 6551 6552 @Override 6553 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6554 if (!sUserManager.exists(userId)) return null; 6555 flags = updateFlagsForComponent(flags, userId, name); 6556 // reader 6557 synchronized (mPackages) { 6558 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6559 PackageSetting ps = provider != null 6560 ? mSettings.mPackages.get(provider.owner.packageName) 6561 : null; 6562 return ps != null 6563 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6564 ? PackageParser.generateProviderInfo(provider, flags, 6565 ps.readUserState(userId), userId) 6566 : null; 6567 } 6568 } 6569 6570 /** 6571 * @deprecated 6572 */ 6573 @Deprecated 6574 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6575 // reader 6576 synchronized (mPackages) { 6577 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6578 .entrySet().iterator(); 6579 final int userId = UserHandle.getCallingUserId(); 6580 while (i.hasNext()) { 6581 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6582 PackageParser.Provider p = entry.getValue(); 6583 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6584 6585 if (ps != null && p.syncable 6586 && (!mSafeMode || (p.info.applicationInfo.flags 6587 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6588 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6589 ps.readUserState(userId), userId); 6590 if (info != null) { 6591 outNames.add(entry.getKey()); 6592 outInfo.add(info); 6593 } 6594 } 6595 } 6596 } 6597 } 6598 6599 @Override 6600 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6601 int uid, int flags) { 6602 final int userId = processName != null ? UserHandle.getUserId(uid) 6603 : UserHandle.getCallingUserId(); 6604 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6605 flags = updateFlagsForComponent(flags, userId, processName); 6606 6607 ArrayList<ProviderInfo> finalList = null; 6608 // reader 6609 synchronized (mPackages) { 6610 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6611 while (i.hasNext()) { 6612 final PackageParser.Provider p = i.next(); 6613 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6614 if (ps != null && p.info.authority != null 6615 && (processName == null 6616 || (p.info.processName.equals(processName) 6617 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6618 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6619 if (finalList == null) { 6620 finalList = new ArrayList<ProviderInfo>(3); 6621 } 6622 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6623 ps.readUserState(userId), userId); 6624 if (info != null) { 6625 finalList.add(info); 6626 } 6627 } 6628 } 6629 } 6630 6631 if (finalList != null) { 6632 Collections.sort(finalList, mProviderInitOrderSorter); 6633 return new ParceledListSlice<ProviderInfo>(finalList); 6634 } 6635 6636 return ParceledListSlice.emptyList(); 6637 } 6638 6639 @Override 6640 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6641 // reader 6642 synchronized (mPackages) { 6643 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6644 return PackageParser.generateInstrumentationInfo(i, flags); 6645 } 6646 } 6647 6648 @Override 6649 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6650 String targetPackage, int flags) { 6651 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6652 } 6653 6654 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6655 int flags) { 6656 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6657 6658 // reader 6659 synchronized (mPackages) { 6660 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6661 while (i.hasNext()) { 6662 final PackageParser.Instrumentation p = i.next(); 6663 if (targetPackage == null 6664 || targetPackage.equals(p.info.targetPackage)) { 6665 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6666 flags); 6667 if (ii != null) { 6668 finalList.add(ii); 6669 } 6670 } 6671 } 6672 } 6673 6674 return finalList; 6675 } 6676 6677 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6678 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6679 if (overlays == null) { 6680 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6681 return; 6682 } 6683 for (PackageParser.Package opkg : overlays.values()) { 6684 // Not much to do if idmap fails: we already logged the error 6685 // and we certainly don't want to abort installation of pkg simply 6686 // because an overlay didn't fit properly. For these reasons, 6687 // ignore the return value of createIdmapForPackagePairLI. 6688 createIdmapForPackagePairLI(pkg, opkg); 6689 } 6690 } 6691 6692 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6693 PackageParser.Package opkg) { 6694 if (!opkg.mTrustedOverlay) { 6695 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6696 opkg.baseCodePath + ": overlay not trusted"); 6697 return false; 6698 } 6699 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6700 if (overlaySet == null) { 6701 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6702 opkg.baseCodePath + " but target package has no known overlays"); 6703 return false; 6704 } 6705 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6706 // TODO: generate idmap for split APKs 6707 try { 6708 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6709 } catch (InstallerException e) { 6710 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6711 + opkg.baseCodePath); 6712 return false; 6713 } 6714 PackageParser.Package[] overlayArray = 6715 overlaySet.values().toArray(new PackageParser.Package[0]); 6716 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6717 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6718 return p1.mOverlayPriority - p2.mOverlayPriority; 6719 } 6720 }; 6721 Arrays.sort(overlayArray, cmp); 6722 6723 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6724 int i = 0; 6725 for (PackageParser.Package p : overlayArray) { 6726 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6727 } 6728 return true; 6729 } 6730 6731 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6733 try { 6734 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6735 } finally { 6736 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6737 } 6738 } 6739 6740 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6741 final File[] files = dir.listFiles(); 6742 if (ArrayUtils.isEmpty(files)) { 6743 Log.d(TAG, "No files in app dir " + dir); 6744 return; 6745 } 6746 6747 if (DEBUG_PACKAGE_SCANNING) { 6748 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6749 + " flags=0x" + Integer.toHexString(parseFlags)); 6750 } 6751 6752 for (File file : files) { 6753 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6754 && !PackageInstallerService.isStageName(file.getName()); 6755 if (!isPackage) { 6756 // Ignore entries which are not packages 6757 continue; 6758 } 6759 try { 6760 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6761 scanFlags, currentTime, null); 6762 } catch (PackageManagerException e) { 6763 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6764 6765 // Delete invalid userdata apps 6766 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6767 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6768 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6769 removeCodePathLI(file); 6770 } 6771 } 6772 } 6773 } 6774 6775 private static File getSettingsProblemFile() { 6776 File dataDir = Environment.getDataDirectory(); 6777 File systemDir = new File(dataDir, "system"); 6778 File fname = new File(systemDir, "uiderrors.txt"); 6779 return fname; 6780 } 6781 6782 static void reportSettingsProblem(int priority, String msg) { 6783 logCriticalInfo(priority, msg); 6784 } 6785 6786 static void logCriticalInfo(int priority, String msg) { 6787 Slog.println(priority, TAG, msg); 6788 EventLogTags.writePmCriticalInfo(msg); 6789 try { 6790 File fname = getSettingsProblemFile(); 6791 FileOutputStream out = new FileOutputStream(fname, true); 6792 PrintWriter pw = new FastPrintWriter(out); 6793 SimpleDateFormat formatter = new SimpleDateFormat(); 6794 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6795 pw.println(dateString + ": " + msg); 6796 pw.close(); 6797 FileUtils.setPermissions( 6798 fname.toString(), 6799 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6800 -1, -1); 6801 } catch (java.io.IOException e) { 6802 } 6803 } 6804 6805 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6806 if (srcFile.isDirectory()) { 6807 final File baseFile = new File(pkg.baseCodePath); 6808 long maxModifiedTime = baseFile.lastModified(); 6809 if (pkg.splitCodePaths != null) { 6810 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6811 final File splitFile = new File(pkg.splitCodePaths[i]); 6812 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6813 } 6814 } 6815 return maxModifiedTime; 6816 } 6817 return srcFile.lastModified(); 6818 } 6819 6820 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6821 final int policyFlags) throws PackageManagerException { 6822 if (ps != null 6823 && ps.codePath.equals(srcFile) 6824 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6825 && !isCompatSignatureUpdateNeeded(pkg) 6826 && !isRecoverSignatureUpdateNeeded(pkg)) { 6827 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6828 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6829 ArraySet<PublicKey> signingKs; 6830 synchronized (mPackages) { 6831 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6832 } 6833 if (ps.signatures.mSignatures != null 6834 && ps.signatures.mSignatures.length != 0 6835 && signingKs != null) { 6836 // Optimization: reuse the existing cached certificates 6837 // if the package appears to be unchanged. 6838 pkg.mSignatures = ps.signatures.mSignatures; 6839 pkg.mSigningKeys = signingKs; 6840 return; 6841 } 6842 6843 Slog.w(TAG, "PackageSetting for " + ps.name 6844 + " is missing signatures. Collecting certs again to recover them."); 6845 } else { 6846 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6847 } 6848 6849 try { 6850 PackageParser.collectCertificates(pkg, policyFlags); 6851 } catch (PackageParserException e) { 6852 throw PackageManagerException.from(e); 6853 } 6854 } 6855 6856 /** 6857 * Traces a package scan. 6858 * @see #scanPackageLI(File, int, int, long, UserHandle) 6859 */ 6860 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6861 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6862 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6863 try { 6864 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6865 } finally { 6866 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6867 } 6868 } 6869 6870 /** 6871 * Scans a package and returns the newly parsed package. 6872 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6873 */ 6874 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6875 long currentTime, UserHandle user) throws PackageManagerException { 6876 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6877 PackageParser pp = new PackageParser(); 6878 pp.setSeparateProcesses(mSeparateProcesses); 6879 pp.setOnlyCoreApps(mOnlyCore); 6880 pp.setDisplayMetrics(mMetrics); 6881 6882 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6883 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6884 } 6885 6886 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6887 final PackageParser.Package pkg; 6888 try { 6889 pkg = pp.parsePackage(scanFile, parseFlags); 6890 } catch (PackageParserException e) { 6891 throw PackageManagerException.from(e); 6892 } finally { 6893 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6894 } 6895 6896 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6897 } 6898 6899 /** 6900 * Scans a package and returns the newly parsed package. 6901 * @throws PackageManagerException on a parse error. 6902 */ 6903 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6904 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6905 throws PackageManagerException { 6906 // If the package has children and this is the first dive in the function 6907 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6908 // packages (parent and children) would be successfully scanned before the 6909 // actual scan since scanning mutates internal state and we want to atomically 6910 // install the package and its children. 6911 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6912 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6913 scanFlags |= SCAN_CHECK_ONLY; 6914 } 6915 } else { 6916 scanFlags &= ~SCAN_CHECK_ONLY; 6917 } 6918 6919 // Scan the parent 6920 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6921 scanFlags, currentTime, user); 6922 6923 // Scan the children 6924 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6925 for (int i = 0; i < childCount; i++) { 6926 PackageParser.Package childPackage = pkg.childPackages.get(i); 6927 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6928 currentTime, user); 6929 } 6930 6931 6932 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6933 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6934 } 6935 6936 return scannedPkg; 6937 } 6938 6939 /** 6940 * Scans a package and returns the newly parsed package. 6941 * @throws PackageManagerException on a parse error. 6942 */ 6943 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6944 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6945 throws PackageManagerException { 6946 PackageSetting ps = null; 6947 PackageSetting updatedPkg; 6948 // reader 6949 synchronized (mPackages) { 6950 // Look to see if we already know about this package. 6951 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6952 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6953 // This package has been renamed to its original name. Let's 6954 // use that. 6955 ps = mSettings.peekPackageLPr(oldName); 6956 } 6957 // If there was no original package, see one for the real package name. 6958 if (ps == null) { 6959 ps = mSettings.peekPackageLPr(pkg.packageName); 6960 } 6961 // Check to see if this package could be hiding/updating a system 6962 // package. Must look for it either under the original or real 6963 // package name depending on our state. 6964 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6965 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6966 6967 // If this is a package we don't know about on the system partition, we 6968 // may need to remove disabled child packages on the system partition 6969 // or may need to not add child packages if the parent apk is updated 6970 // on the data partition and no longer defines this child package. 6971 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6972 // If this is a parent package for an updated system app and this system 6973 // app got an OTA update which no longer defines some of the child packages 6974 // we have to prune them from the disabled system packages. 6975 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6976 if (disabledPs != null) { 6977 final int scannedChildCount = (pkg.childPackages != null) 6978 ? pkg.childPackages.size() : 0; 6979 final int disabledChildCount = disabledPs.childPackageNames != null 6980 ? disabledPs.childPackageNames.size() : 0; 6981 for (int i = 0; i < disabledChildCount; i++) { 6982 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6983 boolean disabledPackageAvailable = false; 6984 for (int j = 0; j < scannedChildCount; j++) { 6985 PackageParser.Package childPkg = pkg.childPackages.get(j); 6986 if (childPkg.packageName.equals(disabledChildPackageName)) { 6987 disabledPackageAvailable = true; 6988 break; 6989 } 6990 } 6991 if (!disabledPackageAvailable) { 6992 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6993 } 6994 } 6995 } 6996 } 6997 } 6998 6999 boolean updatedPkgBetter = false; 7000 // First check if this is a system package that may involve an update 7001 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7002 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7003 // it needs to drop FLAG_PRIVILEGED. 7004 if (locationIsPrivileged(scanFile)) { 7005 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7006 } else { 7007 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7008 } 7009 7010 if (ps != null && !ps.codePath.equals(scanFile)) { 7011 // The path has changed from what was last scanned... check the 7012 // version of the new path against what we have stored to determine 7013 // what to do. 7014 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7015 if (pkg.mVersionCode <= ps.versionCode) { 7016 // The system package has been updated and the code path does not match 7017 // Ignore entry. Skip it. 7018 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7019 + " ignored: updated version " + ps.versionCode 7020 + " better than this " + pkg.mVersionCode); 7021 if (!updatedPkg.codePath.equals(scanFile)) { 7022 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7023 + ps.name + " changing from " + updatedPkg.codePathString 7024 + " to " + scanFile); 7025 updatedPkg.codePath = scanFile; 7026 updatedPkg.codePathString = scanFile.toString(); 7027 updatedPkg.resourcePath = scanFile; 7028 updatedPkg.resourcePathString = scanFile.toString(); 7029 } 7030 updatedPkg.pkg = pkg; 7031 updatedPkg.versionCode = pkg.mVersionCode; 7032 7033 // Update the disabled system child packages to point to the package too. 7034 final int childCount = updatedPkg.childPackageNames != null 7035 ? updatedPkg.childPackageNames.size() : 0; 7036 for (int i = 0; i < childCount; i++) { 7037 String childPackageName = updatedPkg.childPackageNames.get(i); 7038 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7039 childPackageName); 7040 if (updatedChildPkg != null) { 7041 updatedChildPkg.pkg = pkg; 7042 updatedChildPkg.versionCode = pkg.mVersionCode; 7043 } 7044 } 7045 7046 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7047 + scanFile + " ignored: updated version " + ps.versionCode 7048 + " better than this " + pkg.mVersionCode); 7049 } else { 7050 // The current app on the system partition is better than 7051 // what we have updated to on the data partition; switch 7052 // back to the system partition version. 7053 // At this point, its safely assumed that package installation for 7054 // apps in system partition will go through. If not there won't be a working 7055 // version of the app 7056 // writer 7057 synchronized (mPackages) { 7058 // Just remove the loaded entries from package lists. 7059 mPackages.remove(ps.name); 7060 } 7061 7062 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7063 + " reverting from " + ps.codePathString 7064 + ": new version " + pkg.mVersionCode 7065 + " better than installed " + ps.versionCode); 7066 7067 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7068 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7069 synchronized (mInstallLock) { 7070 args.cleanUpResourcesLI(); 7071 } 7072 synchronized (mPackages) { 7073 mSettings.enableSystemPackageLPw(ps.name); 7074 } 7075 updatedPkgBetter = true; 7076 } 7077 } 7078 } 7079 7080 if (updatedPkg != null) { 7081 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7082 // initially 7083 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7084 7085 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7086 // flag set initially 7087 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7088 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7089 } 7090 } 7091 7092 // Verify certificates against what was last scanned 7093 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7094 7095 /* 7096 * A new system app appeared, but we already had a non-system one of the 7097 * same name installed earlier. 7098 */ 7099 boolean shouldHideSystemApp = false; 7100 if (updatedPkg == null && ps != null 7101 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7102 /* 7103 * Check to make sure the signatures match first. If they don't, 7104 * wipe the installed application and its data. 7105 */ 7106 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7107 != PackageManager.SIGNATURE_MATCH) { 7108 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7109 + " signatures don't match existing userdata copy; removing"); 7110 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7111 "scanPackageInternalLI")) { 7112 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7113 } 7114 ps = null; 7115 } else { 7116 /* 7117 * If the newly-added system app is an older version than the 7118 * already installed version, hide it. It will be scanned later 7119 * and re-added like an update. 7120 */ 7121 if (pkg.mVersionCode <= ps.versionCode) { 7122 shouldHideSystemApp = true; 7123 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7124 + " but new version " + pkg.mVersionCode + " better than installed " 7125 + ps.versionCode + "; hiding system"); 7126 } else { 7127 /* 7128 * The newly found system app is a newer version that the 7129 * one previously installed. Simply remove the 7130 * already-installed application and replace it with our own 7131 * while keeping the application data. 7132 */ 7133 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7134 + " reverting from " + ps.codePathString + ": new version " 7135 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7136 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7137 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7138 synchronized (mInstallLock) { 7139 args.cleanUpResourcesLI(); 7140 } 7141 } 7142 } 7143 } 7144 7145 // The apk is forward locked (not public) if its code and resources 7146 // are kept in different files. (except for app in either system or 7147 // vendor path). 7148 // TODO grab this value from PackageSettings 7149 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7150 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7151 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7152 } 7153 } 7154 7155 // TODO: extend to support forward-locked splits 7156 String resourcePath = null; 7157 String baseResourcePath = null; 7158 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7159 if (ps != null && ps.resourcePathString != null) { 7160 resourcePath = ps.resourcePathString; 7161 baseResourcePath = ps.resourcePathString; 7162 } else { 7163 // Should not happen at all. Just log an error. 7164 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7165 } 7166 } else { 7167 resourcePath = pkg.codePath; 7168 baseResourcePath = pkg.baseCodePath; 7169 } 7170 7171 // Set application objects path explicitly. 7172 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7173 pkg.setApplicationInfoCodePath(pkg.codePath); 7174 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7175 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7176 pkg.setApplicationInfoResourcePath(resourcePath); 7177 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7178 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7179 7180 // Note that we invoke the following method only if we are about to unpack an application 7181 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7182 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7183 7184 /* 7185 * If the system app should be overridden by a previously installed 7186 * data, hide the system app now and let the /data/app scan pick it up 7187 * again. 7188 */ 7189 if (shouldHideSystemApp) { 7190 synchronized (mPackages) { 7191 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7192 } 7193 } 7194 7195 return scannedPkg; 7196 } 7197 7198 private static String fixProcessName(String defProcessName, 7199 String processName, int uid) { 7200 if (processName == null) { 7201 return defProcessName; 7202 } 7203 return processName; 7204 } 7205 7206 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7207 throws PackageManagerException { 7208 if (pkgSetting.signatures.mSignatures != null) { 7209 // Already existing package. Make sure signatures match 7210 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7211 == PackageManager.SIGNATURE_MATCH; 7212 if (!match) { 7213 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7214 == PackageManager.SIGNATURE_MATCH; 7215 } 7216 if (!match) { 7217 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7218 == PackageManager.SIGNATURE_MATCH; 7219 } 7220 if (!match) { 7221 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7222 + pkg.packageName + " signatures do not match the " 7223 + "previously installed version; ignoring!"); 7224 } 7225 } 7226 7227 // Check for shared user signatures 7228 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7229 // Already existing package. Make sure signatures match 7230 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7231 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7232 if (!match) { 7233 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7234 == PackageManager.SIGNATURE_MATCH; 7235 } 7236 if (!match) { 7237 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7238 == PackageManager.SIGNATURE_MATCH; 7239 } 7240 if (!match) { 7241 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7242 "Package " + pkg.packageName 7243 + " has no signatures that match those in shared user " 7244 + pkgSetting.sharedUser.name + "; ignoring!"); 7245 } 7246 } 7247 } 7248 7249 /** 7250 * Enforces that only the system UID or root's UID can call a method exposed 7251 * via Binder. 7252 * 7253 * @param message used as message if SecurityException is thrown 7254 * @throws SecurityException if the caller is not system or root 7255 */ 7256 private static final void enforceSystemOrRoot(String message) { 7257 final int uid = Binder.getCallingUid(); 7258 if (uid != Process.SYSTEM_UID && uid != 0) { 7259 throw new SecurityException(message); 7260 } 7261 } 7262 7263 @Override 7264 public void performFstrimIfNeeded() { 7265 enforceSystemOrRoot("Only the system can request fstrim"); 7266 7267 // Before everything else, see whether we need to fstrim. 7268 try { 7269 IMountService ms = PackageHelper.getMountService(); 7270 if (ms != null) { 7271 boolean doTrim = false; 7272 final long interval = android.provider.Settings.Global.getLong( 7273 mContext.getContentResolver(), 7274 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7275 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7276 if (interval > 0) { 7277 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7278 if (timeSinceLast > interval) { 7279 doTrim = true; 7280 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7281 + "; running immediately"); 7282 } 7283 } 7284 if (doTrim) { 7285 if (!isFirstBoot()) { 7286 try { 7287 ActivityManagerNative.getDefault().showBootMessage( 7288 mContext.getResources().getString( 7289 R.string.android_upgrading_fstrim), true); 7290 } catch (RemoteException e) { 7291 } 7292 } 7293 ms.runMaintenance(); 7294 } 7295 } else { 7296 Slog.e(TAG, "Mount service unavailable!"); 7297 } 7298 } catch (RemoteException e) { 7299 // Can't happen; MountService is local 7300 } 7301 } 7302 7303 @Override 7304 public void updatePackagesIfNeeded() { 7305 enforceSystemOrRoot("Only the system can request package update"); 7306 7307 // We need to re-extract after an OTA. 7308 boolean causeUpgrade = isUpgrade(); 7309 7310 // First boot or factory reset. 7311 // Note: we also handle devices that are upgrading to N right now as if it is their 7312 // first boot, as they do not have profile data. 7313 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7314 7315 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7316 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7317 7318 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7319 return; 7320 } 7321 7322 List<PackageParser.Package> pkgs; 7323 synchronized (mPackages) { 7324 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7325 } 7326 7327 final long startTime = System.nanoTime(); 7328 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7329 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7330 7331 final int elapsedTimeSeconds = 7332 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7333 7334 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7335 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7336 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7337 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7338 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7339 } 7340 7341 /** 7342 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7343 * containing statistics about the invocation. The array consists of three elements, 7344 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7345 * and {@code numberOfPackagesFailed}. 7346 */ 7347 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7348 String compilerFilter) { 7349 7350 int numberOfPackagesVisited = 0; 7351 int numberOfPackagesOptimized = 0; 7352 int numberOfPackagesSkipped = 0; 7353 int numberOfPackagesFailed = 0; 7354 final int numberOfPackagesToDexopt = pkgs.size(); 7355 7356 for (PackageParser.Package pkg : pkgs) { 7357 numberOfPackagesVisited++; 7358 7359 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7360 if (DEBUG_DEXOPT) { 7361 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7362 } 7363 numberOfPackagesSkipped++; 7364 continue; 7365 } 7366 7367 if (DEBUG_DEXOPT) { 7368 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7369 numberOfPackagesToDexopt + ": " + pkg.packageName); 7370 } 7371 7372 if (showDialog) { 7373 try { 7374 ActivityManagerNative.getDefault().showBootMessage( 7375 mContext.getResources().getString(R.string.android_upgrading_apk, 7376 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7377 } catch (RemoteException e) { 7378 } 7379 } 7380 7381 // If the OTA updates a system app which was previously preopted to a non-preopted state 7382 // the app might end up being verified at runtime. That's because by default the apps 7383 // are verify-profile but for preopted apps there's no profile. 7384 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7385 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7386 // filter (by default interpret-only). 7387 // Note that at this stage unused apps are already filtered. 7388 if (isSystemApp(pkg) && 7389 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7390 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7391 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7392 } 7393 7394 // checkProfiles is false to avoid merging profiles during boot which 7395 // might interfere with background compilation (b/28612421). 7396 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7397 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7398 // trade-off worth doing to save boot time work. 7399 int dexOptStatus = performDexOptTraced(pkg.packageName, 7400 false /* checkProfiles */, 7401 compilerFilter, 7402 false /* force */); 7403 switch (dexOptStatus) { 7404 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7405 numberOfPackagesOptimized++; 7406 break; 7407 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7408 numberOfPackagesSkipped++; 7409 break; 7410 case PackageDexOptimizer.DEX_OPT_FAILED: 7411 numberOfPackagesFailed++; 7412 break; 7413 default: 7414 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7415 break; 7416 } 7417 } 7418 7419 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7420 numberOfPackagesFailed }; 7421 } 7422 7423 @Override 7424 public void notifyPackageUse(String packageName, int reason) { 7425 synchronized (mPackages) { 7426 PackageParser.Package p = mPackages.get(packageName); 7427 if (p == null) { 7428 return; 7429 } 7430 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7431 } 7432 } 7433 7434 // TODO: this is not used nor needed. Delete it. 7435 @Override 7436 public boolean performDexOptIfNeeded(String packageName) { 7437 int dexOptStatus = performDexOptTraced(packageName, 7438 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7439 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7440 } 7441 7442 @Override 7443 public boolean performDexOpt(String packageName, 7444 boolean checkProfiles, int compileReason, boolean force) { 7445 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7446 getCompilerFilterForReason(compileReason), force); 7447 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7448 } 7449 7450 @Override 7451 public boolean performDexOptMode(String packageName, 7452 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7453 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7454 targetCompilerFilter, force); 7455 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7456 } 7457 7458 private int performDexOptTraced(String packageName, 7459 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7460 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7461 try { 7462 return performDexOptInternal(packageName, checkProfiles, 7463 targetCompilerFilter, force); 7464 } finally { 7465 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7466 } 7467 } 7468 7469 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7470 // if the package can now be considered up to date for the given filter. 7471 private int performDexOptInternal(String packageName, 7472 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7473 PackageParser.Package p; 7474 synchronized (mPackages) { 7475 p = mPackages.get(packageName); 7476 if (p == null) { 7477 // Package could not be found. Report failure. 7478 return PackageDexOptimizer.DEX_OPT_FAILED; 7479 } 7480 mPackageUsage.write(false); 7481 } 7482 long callingId = Binder.clearCallingIdentity(); 7483 try { 7484 synchronized (mInstallLock) { 7485 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7486 targetCompilerFilter, force); 7487 } 7488 } finally { 7489 Binder.restoreCallingIdentity(callingId); 7490 } 7491 } 7492 7493 public ArraySet<String> getOptimizablePackages() { 7494 ArraySet<String> pkgs = new ArraySet<String>(); 7495 synchronized (mPackages) { 7496 for (PackageParser.Package p : mPackages.values()) { 7497 if (PackageDexOptimizer.canOptimizePackage(p)) { 7498 pkgs.add(p.packageName); 7499 } 7500 } 7501 } 7502 return pkgs; 7503 } 7504 7505 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7506 boolean checkProfiles, String targetCompilerFilter, 7507 boolean force) { 7508 // Select the dex optimizer based on the force parameter. 7509 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7510 // allocate an object here. 7511 PackageDexOptimizer pdo = force 7512 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7513 : mPackageDexOptimizer; 7514 7515 // Optimize all dependencies first. Note: we ignore the return value and march on 7516 // on errors. 7517 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7518 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7519 if (!deps.isEmpty()) { 7520 for (PackageParser.Package depPackage : deps) { 7521 // TODO: Analyze and investigate if we (should) profile libraries. 7522 // Currently this will do a full compilation of the library by default. 7523 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7524 false /* checkProfiles */, 7525 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7526 } 7527 } 7528 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7529 targetCompilerFilter); 7530 } 7531 7532 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7533 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7534 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7535 Set<String> collectedNames = new HashSet<>(); 7536 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7537 7538 retValue.remove(p); 7539 7540 return retValue; 7541 } else { 7542 return Collections.emptyList(); 7543 } 7544 } 7545 7546 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7547 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7548 if (!collectedNames.contains(p.packageName)) { 7549 collectedNames.add(p.packageName); 7550 collected.add(p); 7551 7552 if (p.usesLibraries != null) { 7553 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7554 } 7555 if (p.usesOptionalLibraries != null) { 7556 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7557 collectedNames); 7558 } 7559 } 7560 } 7561 7562 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7563 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7564 for (String libName : libs) { 7565 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7566 if (libPkg != null) { 7567 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7568 } 7569 } 7570 } 7571 7572 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7573 synchronized (mPackages) { 7574 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7575 if (lib != null && lib.apk != null) { 7576 return mPackages.get(lib.apk); 7577 } 7578 } 7579 return null; 7580 } 7581 7582 public void shutdown() { 7583 mPackageUsage.write(true); 7584 } 7585 7586 @Override 7587 public void dumpProfiles(String packageName) { 7588 PackageParser.Package pkg; 7589 synchronized (mPackages) { 7590 pkg = mPackages.get(packageName); 7591 if (pkg == null) { 7592 throw new IllegalArgumentException("Unknown package: " + packageName); 7593 } 7594 } 7595 /* Only the shell, root, or the app user should be able to dump profiles. */ 7596 int callingUid = Binder.getCallingUid(); 7597 if (callingUid != Process.SHELL_UID && 7598 callingUid != Process.ROOT_UID && 7599 callingUid != pkg.applicationInfo.uid) { 7600 throw new SecurityException("dumpProfiles"); 7601 } 7602 7603 synchronized (mInstallLock) { 7604 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7605 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7606 try { 7607 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7608 String gid = Integer.toString(sharedGid); 7609 String codePaths = TextUtils.join(";", allCodePaths); 7610 mInstaller.dumpProfiles(gid, packageName, codePaths); 7611 } catch (InstallerException e) { 7612 Slog.w(TAG, "Failed to dump profiles", e); 7613 } 7614 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7615 } 7616 } 7617 7618 @Override 7619 public void forceDexOpt(String packageName) { 7620 enforceSystemOrRoot("forceDexOpt"); 7621 7622 PackageParser.Package pkg; 7623 synchronized (mPackages) { 7624 pkg = mPackages.get(packageName); 7625 if (pkg == null) { 7626 throw new IllegalArgumentException("Unknown package: " + packageName); 7627 } 7628 } 7629 7630 synchronized (mInstallLock) { 7631 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7632 7633 // Whoever is calling forceDexOpt wants a fully compiled package. 7634 // Don't use profiles since that may cause compilation to be skipped. 7635 final int res = performDexOptInternalWithDependenciesLI(pkg, 7636 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7637 true /* force */); 7638 7639 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7640 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7641 throw new IllegalStateException("Failed to dexopt: " + res); 7642 } 7643 } 7644 } 7645 7646 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7647 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7648 Slog.w(TAG, "Unable to update from " + oldPkg.name 7649 + " to " + newPkg.packageName 7650 + ": old package not in system partition"); 7651 return false; 7652 } else if (mPackages.get(oldPkg.name) != null) { 7653 Slog.w(TAG, "Unable to update from " + oldPkg.name 7654 + " to " + newPkg.packageName 7655 + ": old package still exists"); 7656 return false; 7657 } 7658 return true; 7659 } 7660 7661 void removeCodePathLI(File codePath) { 7662 if (codePath.isDirectory()) { 7663 try { 7664 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7665 } catch (InstallerException e) { 7666 Slog.w(TAG, "Failed to remove code path", e); 7667 } 7668 } else { 7669 codePath.delete(); 7670 } 7671 } 7672 7673 private int[] resolveUserIds(int userId) { 7674 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7675 } 7676 7677 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7678 if (pkg == null) { 7679 Slog.wtf(TAG, "Package was null!", new Throwable()); 7680 return; 7681 } 7682 clearAppDataLeafLIF(pkg, userId, flags); 7683 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7684 for (int i = 0; i < childCount; i++) { 7685 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7686 } 7687 } 7688 7689 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7690 final PackageSetting ps; 7691 synchronized (mPackages) { 7692 ps = mSettings.mPackages.get(pkg.packageName); 7693 } 7694 for (int realUserId : resolveUserIds(userId)) { 7695 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7696 try { 7697 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7698 ceDataInode); 7699 } catch (InstallerException e) { 7700 Slog.w(TAG, String.valueOf(e)); 7701 } 7702 } 7703 } 7704 7705 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7706 if (pkg == null) { 7707 Slog.wtf(TAG, "Package was null!", new Throwable()); 7708 return; 7709 } 7710 destroyAppDataLeafLIF(pkg, userId, flags); 7711 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7712 for (int i = 0; i < childCount; i++) { 7713 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7714 } 7715 } 7716 7717 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7718 final PackageSetting ps; 7719 synchronized (mPackages) { 7720 ps = mSettings.mPackages.get(pkg.packageName); 7721 } 7722 for (int realUserId : resolveUserIds(userId)) { 7723 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7724 try { 7725 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7726 ceDataInode); 7727 } catch (InstallerException e) { 7728 Slog.w(TAG, String.valueOf(e)); 7729 } 7730 } 7731 } 7732 7733 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7734 if (pkg == null) { 7735 Slog.wtf(TAG, "Package was null!", new Throwable()); 7736 return; 7737 } 7738 destroyAppProfilesLeafLIF(pkg); 7739 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7740 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7741 for (int i = 0; i < childCount; i++) { 7742 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7743 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7744 true /* removeBaseMarker */); 7745 } 7746 } 7747 7748 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7749 boolean removeBaseMarker) { 7750 if (pkg.isForwardLocked()) { 7751 return; 7752 } 7753 7754 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7755 try { 7756 path = PackageManagerServiceUtils.realpath(new File(path)); 7757 } catch (IOException e) { 7758 // TODO: Should we return early here ? 7759 Slog.w(TAG, "Failed to get canonical path", e); 7760 continue; 7761 } 7762 7763 final String useMarker = path.replace('/', '@'); 7764 for (int realUserId : resolveUserIds(userId)) { 7765 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7766 if (removeBaseMarker) { 7767 File foreignUseMark = new File(profileDir, useMarker); 7768 if (foreignUseMark.exists()) { 7769 if (!foreignUseMark.delete()) { 7770 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7771 + pkg.packageName); 7772 } 7773 } 7774 } 7775 7776 File[] markers = profileDir.listFiles(); 7777 if (markers != null) { 7778 final String searchString = "@" + pkg.packageName + "@"; 7779 // We also delete all markers that contain the package name we're 7780 // uninstalling. These are associated with secondary dex-files belonging 7781 // to the package. Reconstructing the path of these dex files is messy 7782 // in general. 7783 for (File marker : markers) { 7784 if (marker.getName().indexOf(searchString) > 0) { 7785 if (!marker.delete()) { 7786 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7787 + pkg.packageName); 7788 } 7789 } 7790 } 7791 } 7792 } 7793 } 7794 } 7795 7796 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7797 try { 7798 mInstaller.destroyAppProfiles(pkg.packageName); 7799 } catch (InstallerException e) { 7800 Slog.w(TAG, String.valueOf(e)); 7801 } 7802 } 7803 7804 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7805 if (pkg == null) { 7806 Slog.wtf(TAG, "Package was null!", new Throwable()); 7807 return; 7808 } 7809 clearAppProfilesLeafLIF(pkg); 7810 // We don't remove the base foreign use marker when clearing profiles because 7811 // we will rename it when the app is updated. Unlike the actual profile contents, 7812 // the foreign use marker is good across installs. 7813 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7814 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7815 for (int i = 0; i < childCount; i++) { 7816 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7817 } 7818 } 7819 7820 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7821 try { 7822 mInstaller.clearAppProfiles(pkg.packageName); 7823 } catch (InstallerException e) { 7824 Slog.w(TAG, String.valueOf(e)); 7825 } 7826 } 7827 7828 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7829 long lastUpdateTime) { 7830 // Set parent install/update time 7831 PackageSetting ps = (PackageSetting) pkg.mExtras; 7832 if (ps != null) { 7833 ps.firstInstallTime = firstInstallTime; 7834 ps.lastUpdateTime = lastUpdateTime; 7835 } 7836 // Set children install/update time 7837 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7838 for (int i = 0; i < childCount; i++) { 7839 PackageParser.Package childPkg = pkg.childPackages.get(i); 7840 ps = (PackageSetting) childPkg.mExtras; 7841 if (ps != null) { 7842 ps.firstInstallTime = firstInstallTime; 7843 ps.lastUpdateTime = lastUpdateTime; 7844 } 7845 } 7846 } 7847 7848 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7849 PackageParser.Package changingLib) { 7850 if (file.path != null) { 7851 usesLibraryFiles.add(file.path); 7852 return; 7853 } 7854 PackageParser.Package p = mPackages.get(file.apk); 7855 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7856 // If we are doing this while in the middle of updating a library apk, 7857 // then we need to make sure to use that new apk for determining the 7858 // dependencies here. (We haven't yet finished committing the new apk 7859 // to the package manager state.) 7860 if (p == null || p.packageName.equals(changingLib.packageName)) { 7861 p = changingLib; 7862 } 7863 } 7864 if (p != null) { 7865 usesLibraryFiles.addAll(p.getAllCodePaths()); 7866 } 7867 } 7868 7869 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7870 PackageParser.Package changingLib) throws PackageManagerException { 7871 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7872 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7873 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7874 for (int i=0; i<N; i++) { 7875 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7876 if (file == null) { 7877 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7878 "Package " + pkg.packageName + " requires unavailable shared library " 7879 + pkg.usesLibraries.get(i) + "; failing!"); 7880 } 7881 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7882 } 7883 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7884 for (int i=0; i<N; i++) { 7885 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7886 if (file == null) { 7887 Slog.w(TAG, "Package " + pkg.packageName 7888 + " desires unavailable shared library " 7889 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7890 } else { 7891 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7892 } 7893 } 7894 N = usesLibraryFiles.size(); 7895 if (N > 0) { 7896 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7897 } else { 7898 pkg.usesLibraryFiles = null; 7899 } 7900 } 7901 } 7902 7903 private static boolean hasString(List<String> list, List<String> which) { 7904 if (list == null) { 7905 return false; 7906 } 7907 for (int i=list.size()-1; i>=0; i--) { 7908 for (int j=which.size()-1; j>=0; j--) { 7909 if (which.get(j).equals(list.get(i))) { 7910 return true; 7911 } 7912 } 7913 } 7914 return false; 7915 } 7916 7917 private void updateAllSharedLibrariesLPw() { 7918 for (PackageParser.Package pkg : mPackages.values()) { 7919 try { 7920 updateSharedLibrariesLPw(pkg, null); 7921 } catch (PackageManagerException e) { 7922 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7923 } 7924 } 7925 } 7926 7927 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7928 PackageParser.Package changingPkg) { 7929 ArrayList<PackageParser.Package> res = null; 7930 for (PackageParser.Package pkg : mPackages.values()) { 7931 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7932 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7933 if (res == null) { 7934 res = new ArrayList<PackageParser.Package>(); 7935 } 7936 res.add(pkg); 7937 try { 7938 updateSharedLibrariesLPw(pkg, changingPkg); 7939 } catch (PackageManagerException e) { 7940 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7941 } 7942 } 7943 } 7944 return res; 7945 } 7946 7947 /** 7948 * Derive the value of the {@code cpuAbiOverride} based on the provided 7949 * value and an optional stored value from the package settings. 7950 */ 7951 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7952 String cpuAbiOverride = null; 7953 7954 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7955 cpuAbiOverride = null; 7956 } else if (abiOverride != null) { 7957 cpuAbiOverride = abiOverride; 7958 } else if (settings != null) { 7959 cpuAbiOverride = settings.cpuAbiOverrideString; 7960 } 7961 7962 return cpuAbiOverride; 7963 } 7964 7965 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7966 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7967 throws PackageManagerException { 7968 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7969 // If the package has children and this is the first dive in the function 7970 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7971 // whether all packages (parent and children) would be successfully scanned 7972 // before the actual scan since scanning mutates internal state and we want 7973 // to atomically install the package and its children. 7974 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7975 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7976 scanFlags |= SCAN_CHECK_ONLY; 7977 } 7978 } else { 7979 scanFlags &= ~SCAN_CHECK_ONLY; 7980 } 7981 7982 final PackageParser.Package scannedPkg; 7983 try { 7984 // Scan the parent 7985 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7986 // Scan the children 7987 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7988 for (int i = 0; i < childCount; i++) { 7989 PackageParser.Package childPkg = pkg.childPackages.get(i); 7990 scanPackageLI(childPkg, policyFlags, 7991 scanFlags, currentTime, user); 7992 } 7993 } finally { 7994 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7995 } 7996 7997 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7998 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7999 } 8000 8001 return scannedPkg; 8002 } 8003 8004 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8005 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8006 boolean success = false; 8007 try { 8008 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8009 currentTime, user); 8010 success = true; 8011 return res; 8012 } finally { 8013 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8014 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8015 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8016 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8017 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8018 } 8019 } 8020 } 8021 8022 /** 8023 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8024 */ 8025 private static boolean apkHasCode(String fileName) { 8026 StrictJarFile jarFile = null; 8027 try { 8028 jarFile = new StrictJarFile(fileName, 8029 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8030 return jarFile.findEntry("classes.dex") != null; 8031 } catch (IOException ignore) { 8032 } finally { 8033 try { 8034 if (jarFile != null) { 8035 jarFile.close(); 8036 } 8037 } catch (IOException ignore) {} 8038 } 8039 return false; 8040 } 8041 8042 /** 8043 * Enforces code policy for the package. This ensures that if an APK has 8044 * declared hasCode="true" in its manifest that the APK actually contains 8045 * code. 8046 * 8047 * @throws PackageManagerException If bytecode could not be found when it should exist 8048 */ 8049 private static void enforceCodePolicy(PackageParser.Package pkg) 8050 throws PackageManagerException { 8051 final boolean shouldHaveCode = 8052 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8053 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8054 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8055 "Package " + pkg.baseCodePath + " code is missing"); 8056 } 8057 8058 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8059 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8060 final boolean splitShouldHaveCode = 8061 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8062 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8063 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8064 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8065 } 8066 } 8067 } 8068 } 8069 8070 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8071 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8072 throws PackageManagerException { 8073 final File scanFile = new File(pkg.codePath); 8074 if (pkg.applicationInfo.getCodePath() == null || 8075 pkg.applicationInfo.getResourcePath() == null) { 8076 // Bail out. The resource and code paths haven't been set. 8077 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8078 "Code and resource paths haven't been set correctly"); 8079 } 8080 8081 // Apply policy 8082 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8083 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8084 if (pkg.applicationInfo.isDirectBootAware()) { 8085 // we're direct boot aware; set for all components 8086 for (PackageParser.Service s : pkg.services) { 8087 s.info.encryptionAware = s.info.directBootAware = true; 8088 } 8089 for (PackageParser.Provider p : pkg.providers) { 8090 p.info.encryptionAware = p.info.directBootAware = true; 8091 } 8092 for (PackageParser.Activity a : pkg.activities) { 8093 a.info.encryptionAware = a.info.directBootAware = true; 8094 } 8095 for (PackageParser.Activity r : pkg.receivers) { 8096 r.info.encryptionAware = r.info.directBootAware = true; 8097 } 8098 } 8099 } else { 8100 // Only allow system apps to be flagged as core apps. 8101 pkg.coreApp = false; 8102 // clear flags not applicable to regular apps 8103 pkg.applicationInfo.privateFlags &= 8104 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8105 pkg.applicationInfo.privateFlags &= 8106 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8107 } 8108 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8109 8110 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8111 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8112 } 8113 8114 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8115 enforceCodePolicy(pkg); 8116 } 8117 8118 if (mCustomResolverComponentName != null && 8119 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8120 setUpCustomResolverActivity(pkg); 8121 } 8122 8123 if (pkg.packageName.equals("android")) { 8124 synchronized (mPackages) { 8125 if (mAndroidApplication != null) { 8126 Slog.w(TAG, "*************************************************"); 8127 Slog.w(TAG, "Core android package being redefined. Skipping."); 8128 Slog.w(TAG, " file=" + scanFile); 8129 Slog.w(TAG, "*************************************************"); 8130 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8131 "Core android package being redefined. Skipping."); 8132 } 8133 8134 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8135 // Set up information for our fall-back user intent resolution activity. 8136 mPlatformPackage = pkg; 8137 pkg.mVersionCode = mSdkVersion; 8138 mAndroidApplication = pkg.applicationInfo; 8139 8140 if (!mResolverReplaced) { 8141 mResolveActivity.applicationInfo = mAndroidApplication; 8142 mResolveActivity.name = ResolverActivity.class.getName(); 8143 mResolveActivity.packageName = mAndroidApplication.packageName; 8144 mResolveActivity.processName = "system:ui"; 8145 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8146 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8147 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8148 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8149 mResolveActivity.exported = true; 8150 mResolveActivity.enabled = true; 8151 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8152 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8153 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8154 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8155 | ActivityInfo.CONFIG_ORIENTATION 8156 | ActivityInfo.CONFIG_KEYBOARD 8157 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8158 mResolveInfo.activityInfo = mResolveActivity; 8159 mResolveInfo.priority = 0; 8160 mResolveInfo.preferredOrder = 0; 8161 mResolveInfo.match = 0; 8162 mResolveComponentName = new ComponentName( 8163 mAndroidApplication.packageName, mResolveActivity.name); 8164 } 8165 } 8166 } 8167 } 8168 8169 if (DEBUG_PACKAGE_SCANNING) { 8170 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8171 Log.d(TAG, "Scanning package " + pkg.packageName); 8172 } 8173 8174 synchronized (mPackages) { 8175 if (mPackages.containsKey(pkg.packageName) 8176 || mSharedLibraries.containsKey(pkg.packageName)) { 8177 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8178 "Application package " + pkg.packageName 8179 + " already installed. Skipping duplicate."); 8180 } 8181 8182 // If we're only installing presumed-existing packages, require that the 8183 // scanned APK is both already known and at the path previously established 8184 // for it. Previously unknown packages we pick up normally, but if we have an 8185 // a priori expectation about this package's install presence, enforce it. 8186 // With a singular exception for new system packages. When an OTA contains 8187 // a new system package, we allow the codepath to change from a system location 8188 // to the user-installed location. If we don't allow this change, any newer, 8189 // user-installed version of the application will be ignored. 8190 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8191 if (mExpectingBetter.containsKey(pkg.packageName)) { 8192 logCriticalInfo(Log.WARN, 8193 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8194 } else { 8195 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8196 if (known != null) { 8197 if (DEBUG_PACKAGE_SCANNING) { 8198 Log.d(TAG, "Examining " + pkg.codePath 8199 + " and requiring known paths " + known.codePathString 8200 + " & " + known.resourcePathString); 8201 } 8202 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8203 || !pkg.applicationInfo.getResourcePath().equals( 8204 known.resourcePathString)) { 8205 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8206 "Application package " + pkg.packageName 8207 + " found at " + pkg.applicationInfo.getCodePath() 8208 + " but expected at " + known.codePathString 8209 + "; ignoring."); 8210 } 8211 } 8212 } 8213 } 8214 } 8215 8216 // Initialize package source and resource directories 8217 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8218 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8219 8220 SharedUserSetting suid = null; 8221 PackageSetting pkgSetting = null; 8222 8223 if (!isSystemApp(pkg)) { 8224 // Only system apps can use these features. 8225 pkg.mOriginalPackages = null; 8226 pkg.mRealPackage = null; 8227 pkg.mAdoptPermissions = null; 8228 } 8229 8230 // Getting the package setting may have a side-effect, so if we 8231 // are only checking if scan would succeed, stash a copy of the 8232 // old setting to restore at the end. 8233 PackageSetting nonMutatedPs = null; 8234 8235 // writer 8236 synchronized (mPackages) { 8237 if (pkg.mSharedUserId != null) { 8238 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8239 if (suid == null) { 8240 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8241 "Creating application package " + pkg.packageName 8242 + " for shared user failed"); 8243 } 8244 if (DEBUG_PACKAGE_SCANNING) { 8245 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8246 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8247 + "): packages=" + suid.packages); 8248 } 8249 } 8250 8251 // Check if we are renaming from an original package name. 8252 PackageSetting origPackage = null; 8253 String realName = null; 8254 if (pkg.mOriginalPackages != null) { 8255 // This package may need to be renamed to a previously 8256 // installed name. Let's check on that... 8257 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8258 if (pkg.mOriginalPackages.contains(renamed)) { 8259 // This package had originally been installed as the 8260 // original name, and we have already taken care of 8261 // transitioning to the new one. Just update the new 8262 // one to continue using the old name. 8263 realName = pkg.mRealPackage; 8264 if (!pkg.packageName.equals(renamed)) { 8265 // Callers into this function may have already taken 8266 // care of renaming the package; only do it here if 8267 // it is not already done. 8268 pkg.setPackageName(renamed); 8269 } 8270 8271 } else { 8272 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8273 if ((origPackage = mSettings.peekPackageLPr( 8274 pkg.mOriginalPackages.get(i))) != null) { 8275 // We do have the package already installed under its 8276 // original name... should we use it? 8277 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8278 // New package is not compatible with original. 8279 origPackage = null; 8280 continue; 8281 } else if (origPackage.sharedUser != null) { 8282 // Make sure uid is compatible between packages. 8283 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8284 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8285 + " to " + pkg.packageName + ": old uid " 8286 + origPackage.sharedUser.name 8287 + " differs from " + pkg.mSharedUserId); 8288 origPackage = null; 8289 continue; 8290 } 8291 // TODO: Add case when shared user id is added [b/28144775] 8292 } else { 8293 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8294 + pkg.packageName + " to old name " + origPackage.name); 8295 } 8296 break; 8297 } 8298 } 8299 } 8300 } 8301 8302 if (mTransferedPackages.contains(pkg.packageName)) { 8303 Slog.w(TAG, "Package " + pkg.packageName 8304 + " was transferred to another, but its .apk remains"); 8305 } 8306 8307 // See comments in nonMutatedPs declaration 8308 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8309 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8310 if (foundPs != null) { 8311 nonMutatedPs = new PackageSetting(foundPs); 8312 } 8313 } 8314 8315 // Just create the setting, don't add it yet. For already existing packages 8316 // the PkgSetting exists already and doesn't have to be created. 8317 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8318 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8319 pkg.applicationInfo.primaryCpuAbi, 8320 pkg.applicationInfo.secondaryCpuAbi, 8321 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8322 user, false); 8323 if (pkgSetting == null) { 8324 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8325 "Creating application package " + pkg.packageName + " failed"); 8326 } 8327 8328 if (pkgSetting.origPackage != null) { 8329 // If we are first transitioning from an original package, 8330 // fix up the new package's name now. We need to do this after 8331 // looking up the package under its new name, so getPackageLP 8332 // can take care of fiddling things correctly. 8333 pkg.setPackageName(origPackage.name); 8334 8335 // File a report about this. 8336 String msg = "New package " + pkgSetting.realName 8337 + " renamed to replace old package " + pkgSetting.name; 8338 reportSettingsProblem(Log.WARN, msg); 8339 8340 // Make a note of it. 8341 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8342 mTransferedPackages.add(origPackage.name); 8343 } 8344 8345 // No longer need to retain this. 8346 pkgSetting.origPackage = null; 8347 } 8348 8349 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8350 // Make a note of it. 8351 mTransferedPackages.add(pkg.packageName); 8352 } 8353 8354 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8355 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8356 } 8357 8358 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8359 // Check all shared libraries and map to their actual file path. 8360 // We only do this here for apps not on a system dir, because those 8361 // are the only ones that can fail an install due to this. We 8362 // will take care of the system apps by updating all of their 8363 // library paths after the scan is done. 8364 updateSharedLibrariesLPw(pkg, null); 8365 } 8366 8367 if (mFoundPolicyFile) { 8368 SELinuxMMAC.assignSeinfoValue(pkg); 8369 } 8370 8371 pkg.applicationInfo.uid = pkgSetting.appId; 8372 pkg.mExtras = pkgSetting; 8373 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8374 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8375 // We just determined the app is signed correctly, so bring 8376 // over the latest parsed certs. 8377 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8378 } else { 8379 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8380 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8381 "Package " + pkg.packageName + " upgrade keys do not match the " 8382 + "previously installed version"); 8383 } else { 8384 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8385 String msg = "System package " + pkg.packageName 8386 + " signature changed; retaining data."; 8387 reportSettingsProblem(Log.WARN, msg); 8388 } 8389 } 8390 } else { 8391 try { 8392 verifySignaturesLP(pkgSetting, pkg); 8393 // We just determined the app is signed correctly, so bring 8394 // over the latest parsed certs. 8395 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8396 } catch (PackageManagerException e) { 8397 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8398 throw e; 8399 } 8400 // The signature has changed, but this package is in the system 8401 // image... let's recover! 8402 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8403 // However... if this package is part of a shared user, but it 8404 // doesn't match the signature of the shared user, let's fail. 8405 // What this means is that you can't change the signatures 8406 // associated with an overall shared user, which doesn't seem all 8407 // that unreasonable. 8408 if (pkgSetting.sharedUser != null) { 8409 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8410 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8411 throw new PackageManagerException( 8412 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8413 "Signature mismatch for shared user: " 8414 + pkgSetting.sharedUser); 8415 } 8416 } 8417 // File a report about this. 8418 String msg = "System package " + pkg.packageName 8419 + " signature changed; retaining data."; 8420 reportSettingsProblem(Log.WARN, msg); 8421 } 8422 } 8423 // Verify that this new package doesn't have any content providers 8424 // that conflict with existing packages. Only do this if the 8425 // package isn't already installed, since we don't want to break 8426 // things that are installed. 8427 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8428 final int N = pkg.providers.size(); 8429 int i; 8430 for (i=0; i<N; i++) { 8431 PackageParser.Provider p = pkg.providers.get(i); 8432 if (p.info.authority != null) { 8433 String names[] = p.info.authority.split(";"); 8434 for (int j = 0; j < names.length; j++) { 8435 if (mProvidersByAuthority.containsKey(names[j])) { 8436 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8437 final String otherPackageName = 8438 ((other != null && other.getComponentName() != null) ? 8439 other.getComponentName().getPackageName() : "?"); 8440 throw new PackageManagerException( 8441 INSTALL_FAILED_CONFLICTING_PROVIDER, 8442 "Can't install because provider name " + names[j] 8443 + " (in package " + pkg.applicationInfo.packageName 8444 + ") is already used by " + otherPackageName); 8445 } 8446 } 8447 } 8448 } 8449 } 8450 8451 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8452 // This package wants to adopt ownership of permissions from 8453 // another package. 8454 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8455 final String origName = pkg.mAdoptPermissions.get(i); 8456 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8457 if (orig != null) { 8458 if (verifyPackageUpdateLPr(orig, pkg)) { 8459 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8460 + pkg.packageName); 8461 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8462 } 8463 } 8464 } 8465 } 8466 } 8467 8468 final String pkgName = pkg.packageName; 8469 8470 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8471 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8472 pkg.applicationInfo.processName = fixProcessName( 8473 pkg.applicationInfo.packageName, 8474 pkg.applicationInfo.processName, 8475 pkg.applicationInfo.uid); 8476 8477 if (pkg != mPlatformPackage) { 8478 // Get all of our default paths setup 8479 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8480 } 8481 8482 final String path = scanFile.getPath(); 8483 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8484 8485 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8486 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8487 8488 // Some system apps still use directory structure for native libraries 8489 // in which case we might end up not detecting abi solely based on apk 8490 // structure. Try to detect abi based on directory structure. 8491 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8492 pkg.applicationInfo.primaryCpuAbi == null) { 8493 setBundledAppAbisAndRoots(pkg, pkgSetting); 8494 setNativeLibraryPaths(pkg); 8495 } 8496 8497 } else { 8498 if ((scanFlags & SCAN_MOVE) != 0) { 8499 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8500 // but we already have this packages package info in the PackageSetting. We just 8501 // use that and derive the native library path based on the new codepath. 8502 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8503 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8504 } 8505 8506 // Set native library paths again. For moves, the path will be updated based on the 8507 // ABIs we've determined above. For non-moves, the path will be updated based on the 8508 // ABIs we determined during compilation, but the path will depend on the final 8509 // package path (after the rename away from the stage path). 8510 setNativeLibraryPaths(pkg); 8511 } 8512 8513 // This is a special case for the "system" package, where the ABI is 8514 // dictated by the zygote configuration (and init.rc). We should keep track 8515 // of this ABI so that we can deal with "normal" applications that run under 8516 // the same UID correctly. 8517 if (mPlatformPackage == pkg) { 8518 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8519 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8520 } 8521 8522 // If there's a mismatch between the abi-override in the package setting 8523 // and the abiOverride specified for the install. Warn about this because we 8524 // would've already compiled the app without taking the package setting into 8525 // account. 8526 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8527 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8528 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8529 " for package " + pkg.packageName); 8530 } 8531 } 8532 8533 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8534 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8535 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8536 8537 // Copy the derived override back to the parsed package, so that we can 8538 // update the package settings accordingly. 8539 pkg.cpuAbiOverride = cpuAbiOverride; 8540 8541 if (DEBUG_ABI_SELECTION) { 8542 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8543 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8544 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8545 } 8546 8547 // Push the derived path down into PackageSettings so we know what to 8548 // clean up at uninstall time. 8549 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8550 8551 if (DEBUG_ABI_SELECTION) { 8552 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8553 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8554 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8555 } 8556 8557 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8558 // We don't do this here during boot because we can do it all 8559 // at once after scanning all existing packages. 8560 // 8561 // We also do this *before* we perform dexopt on this package, so that 8562 // we can avoid redundant dexopts, and also to make sure we've got the 8563 // code and package path correct. 8564 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8565 pkg, true /* boot complete */); 8566 } 8567 8568 if (mFactoryTest && pkg.requestedPermissions.contains( 8569 android.Manifest.permission.FACTORY_TEST)) { 8570 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8571 } 8572 8573 ArrayList<PackageParser.Package> clientLibPkgs = null; 8574 8575 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8576 if (nonMutatedPs != null) { 8577 synchronized (mPackages) { 8578 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8579 } 8580 } 8581 return pkg; 8582 } 8583 8584 // Only privileged apps and updated privileged apps can add child packages. 8585 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8586 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8587 throw new PackageManagerException("Only privileged apps and updated " 8588 + "privileged apps can add child packages. Ignoring package " 8589 + pkg.packageName); 8590 } 8591 final int childCount = pkg.childPackages.size(); 8592 for (int i = 0; i < childCount; i++) { 8593 PackageParser.Package childPkg = pkg.childPackages.get(i); 8594 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8595 childPkg.packageName)) { 8596 throw new PackageManagerException("Cannot override a child package of " 8597 + "another disabled system app. Ignoring package " + pkg.packageName); 8598 } 8599 } 8600 } 8601 8602 // writer 8603 synchronized (mPackages) { 8604 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8605 // Only system apps can add new shared libraries. 8606 if (pkg.libraryNames != null) { 8607 for (int i=0; i<pkg.libraryNames.size(); i++) { 8608 String name = pkg.libraryNames.get(i); 8609 boolean allowed = false; 8610 if (pkg.isUpdatedSystemApp()) { 8611 // New library entries can only be added through the 8612 // system image. This is important to get rid of a lot 8613 // of nasty edge cases: for example if we allowed a non- 8614 // system update of the app to add a library, then uninstalling 8615 // the update would make the library go away, and assumptions 8616 // we made such as through app install filtering would now 8617 // have allowed apps on the device which aren't compatible 8618 // with it. Better to just have the restriction here, be 8619 // conservative, and create many fewer cases that can negatively 8620 // impact the user experience. 8621 final PackageSetting sysPs = mSettings 8622 .getDisabledSystemPkgLPr(pkg.packageName); 8623 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8624 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8625 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8626 allowed = true; 8627 break; 8628 } 8629 } 8630 } 8631 } else { 8632 allowed = true; 8633 } 8634 if (allowed) { 8635 if (!mSharedLibraries.containsKey(name)) { 8636 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8637 } else if (!name.equals(pkg.packageName)) { 8638 Slog.w(TAG, "Package " + pkg.packageName + " library " 8639 + name + " already exists; skipping"); 8640 } 8641 } else { 8642 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8643 + name + " that is not declared on system image; skipping"); 8644 } 8645 } 8646 if ((scanFlags & SCAN_BOOTING) == 0) { 8647 // If we are not booting, we need to update any applications 8648 // that are clients of our shared library. If we are booting, 8649 // this will all be done once the scan is complete. 8650 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8651 } 8652 } 8653 } 8654 } 8655 8656 if ((scanFlags & SCAN_BOOTING) != 0) { 8657 // No apps can run during boot scan, so they don't need to be frozen 8658 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8659 // Caller asked to not kill app, so it's probably not frozen 8660 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8661 // Caller asked us to ignore frozen check for some reason; they 8662 // probably didn't know the package name 8663 } else { 8664 // We're doing major surgery on this package, so it better be frozen 8665 // right now to keep it from launching 8666 checkPackageFrozen(pkgName); 8667 } 8668 8669 // Also need to kill any apps that are dependent on the library. 8670 if (clientLibPkgs != null) { 8671 for (int i=0; i<clientLibPkgs.size(); i++) { 8672 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8673 killApplication(clientPkg.applicationInfo.packageName, 8674 clientPkg.applicationInfo.uid, "update lib"); 8675 } 8676 } 8677 8678 // Make sure we're not adding any bogus keyset info 8679 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8680 ksms.assertScannedPackageValid(pkg); 8681 8682 // writer 8683 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8684 8685 boolean createIdmapFailed = false; 8686 synchronized (mPackages) { 8687 // We don't expect installation to fail beyond this point 8688 8689 if (pkgSetting.pkg != null) { 8690 // Note that |user| might be null during the initial boot scan. If a codePath 8691 // for an app has changed during a boot scan, it's due to an app update that's 8692 // part of the system partition and marker changes must be applied to all users. 8693 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8694 (user != null) ? user : UserHandle.ALL); 8695 } 8696 8697 // Add the new setting to mSettings 8698 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8699 // Add the new setting to mPackages 8700 mPackages.put(pkg.applicationInfo.packageName, pkg); 8701 // Make sure we don't accidentally delete its data. 8702 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8703 while (iter.hasNext()) { 8704 PackageCleanItem item = iter.next(); 8705 if (pkgName.equals(item.packageName)) { 8706 iter.remove(); 8707 } 8708 } 8709 8710 // Take care of first install / last update times. 8711 if (currentTime != 0) { 8712 if (pkgSetting.firstInstallTime == 0) { 8713 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8714 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8715 pkgSetting.lastUpdateTime = currentTime; 8716 } 8717 } else if (pkgSetting.firstInstallTime == 0) { 8718 // We need *something*. Take time time stamp of the file. 8719 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8720 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8721 if (scanFileTime != pkgSetting.timeStamp) { 8722 // A package on the system image has changed; consider this 8723 // to be an update. 8724 pkgSetting.lastUpdateTime = scanFileTime; 8725 } 8726 } 8727 8728 // Add the package's KeySets to the global KeySetManagerService 8729 ksms.addScannedPackageLPw(pkg); 8730 8731 int N = pkg.providers.size(); 8732 StringBuilder r = null; 8733 int i; 8734 for (i=0; i<N; i++) { 8735 PackageParser.Provider p = pkg.providers.get(i); 8736 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8737 p.info.processName, pkg.applicationInfo.uid); 8738 mProviders.addProvider(p); 8739 p.syncable = p.info.isSyncable; 8740 if (p.info.authority != null) { 8741 String names[] = p.info.authority.split(";"); 8742 p.info.authority = null; 8743 for (int j = 0; j < names.length; j++) { 8744 if (j == 1 && p.syncable) { 8745 // We only want the first authority for a provider to possibly be 8746 // syncable, so if we already added this provider using a different 8747 // authority clear the syncable flag. We copy the provider before 8748 // changing it because the mProviders object contains a reference 8749 // to a provider that we don't want to change. 8750 // Only do this for the second authority since the resulting provider 8751 // object can be the same for all future authorities for this provider. 8752 p = new PackageParser.Provider(p); 8753 p.syncable = false; 8754 } 8755 if (!mProvidersByAuthority.containsKey(names[j])) { 8756 mProvidersByAuthority.put(names[j], p); 8757 if (p.info.authority == null) { 8758 p.info.authority = names[j]; 8759 } else { 8760 p.info.authority = p.info.authority + ";" + names[j]; 8761 } 8762 if (DEBUG_PACKAGE_SCANNING) { 8763 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8764 Log.d(TAG, "Registered content provider: " + names[j] 8765 + ", className = " + p.info.name + ", isSyncable = " 8766 + p.info.isSyncable); 8767 } 8768 } else { 8769 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8770 Slog.w(TAG, "Skipping provider name " + names[j] + 8771 " (in package " + pkg.applicationInfo.packageName + 8772 "): name already used by " 8773 + ((other != null && other.getComponentName() != null) 8774 ? other.getComponentName().getPackageName() : "?")); 8775 } 8776 } 8777 } 8778 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8779 if (r == null) { 8780 r = new StringBuilder(256); 8781 } else { 8782 r.append(' '); 8783 } 8784 r.append(p.info.name); 8785 } 8786 } 8787 if (r != null) { 8788 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8789 } 8790 8791 N = pkg.services.size(); 8792 r = null; 8793 for (i=0; i<N; i++) { 8794 PackageParser.Service s = pkg.services.get(i); 8795 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8796 s.info.processName, pkg.applicationInfo.uid); 8797 mServices.addService(s); 8798 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8799 if (r == null) { 8800 r = new StringBuilder(256); 8801 } else { 8802 r.append(' '); 8803 } 8804 r.append(s.info.name); 8805 } 8806 } 8807 if (r != null) { 8808 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8809 } 8810 8811 N = pkg.receivers.size(); 8812 r = null; 8813 for (i=0; i<N; i++) { 8814 PackageParser.Activity a = pkg.receivers.get(i); 8815 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8816 a.info.processName, pkg.applicationInfo.uid); 8817 mReceivers.addActivity(a, "receiver"); 8818 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8819 if (r == null) { 8820 r = new StringBuilder(256); 8821 } else { 8822 r.append(' '); 8823 } 8824 r.append(a.info.name); 8825 } 8826 } 8827 if (r != null) { 8828 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8829 } 8830 8831 N = pkg.activities.size(); 8832 r = null; 8833 for (i=0; i<N; i++) { 8834 PackageParser.Activity a = pkg.activities.get(i); 8835 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8836 a.info.processName, pkg.applicationInfo.uid); 8837 mActivities.addActivity(a, "activity"); 8838 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8839 if (r == null) { 8840 r = new StringBuilder(256); 8841 } else { 8842 r.append(' '); 8843 } 8844 r.append(a.info.name); 8845 } 8846 } 8847 if (r != null) { 8848 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8849 } 8850 8851 N = pkg.permissionGroups.size(); 8852 r = null; 8853 for (i=0; i<N; i++) { 8854 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8855 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8856 if (cur == null) { 8857 mPermissionGroups.put(pg.info.name, pg); 8858 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8859 if (r == null) { 8860 r = new StringBuilder(256); 8861 } else { 8862 r.append(' '); 8863 } 8864 r.append(pg.info.name); 8865 } 8866 } else { 8867 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8868 + pg.info.packageName + " ignored: original from " 8869 + cur.info.packageName); 8870 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8871 if (r == null) { 8872 r = new StringBuilder(256); 8873 } else { 8874 r.append(' '); 8875 } 8876 r.append("DUP:"); 8877 r.append(pg.info.name); 8878 } 8879 } 8880 } 8881 if (r != null) { 8882 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8883 } 8884 8885 N = pkg.permissions.size(); 8886 r = null; 8887 for (i=0; i<N; i++) { 8888 PackageParser.Permission p = pkg.permissions.get(i); 8889 8890 // Assume by default that we did not install this permission into the system. 8891 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8892 8893 // Now that permission groups have a special meaning, we ignore permission 8894 // groups for legacy apps to prevent unexpected behavior. In particular, 8895 // permissions for one app being granted to someone just becase they happen 8896 // to be in a group defined by another app (before this had no implications). 8897 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8898 p.group = mPermissionGroups.get(p.info.group); 8899 // Warn for a permission in an unknown group. 8900 if (p.info.group != null && p.group == null) { 8901 Slog.w(TAG, "Permission " + p.info.name + " from package " 8902 + p.info.packageName + " in an unknown group " + p.info.group); 8903 } 8904 } 8905 8906 ArrayMap<String, BasePermission> permissionMap = 8907 p.tree ? mSettings.mPermissionTrees 8908 : mSettings.mPermissions; 8909 BasePermission bp = permissionMap.get(p.info.name); 8910 8911 // Allow system apps to redefine non-system permissions 8912 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8913 final boolean currentOwnerIsSystem = (bp.perm != null 8914 && isSystemApp(bp.perm.owner)); 8915 if (isSystemApp(p.owner)) { 8916 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8917 // It's a built-in permission and no owner, take ownership now 8918 bp.packageSetting = pkgSetting; 8919 bp.perm = p; 8920 bp.uid = pkg.applicationInfo.uid; 8921 bp.sourcePackage = p.info.packageName; 8922 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8923 } else if (!currentOwnerIsSystem) { 8924 String msg = "New decl " + p.owner + " of permission " 8925 + p.info.name + " is system; overriding " + bp.sourcePackage; 8926 reportSettingsProblem(Log.WARN, msg); 8927 bp = null; 8928 } 8929 } 8930 } 8931 8932 if (bp == null) { 8933 bp = new BasePermission(p.info.name, p.info.packageName, 8934 BasePermission.TYPE_NORMAL); 8935 permissionMap.put(p.info.name, bp); 8936 } 8937 8938 if (bp.perm == null) { 8939 if (bp.sourcePackage == null 8940 || bp.sourcePackage.equals(p.info.packageName)) { 8941 BasePermission tree = findPermissionTreeLP(p.info.name); 8942 if (tree == null 8943 || tree.sourcePackage.equals(p.info.packageName)) { 8944 bp.packageSetting = pkgSetting; 8945 bp.perm = p; 8946 bp.uid = pkg.applicationInfo.uid; 8947 bp.sourcePackage = p.info.packageName; 8948 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8949 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8950 if (r == null) { 8951 r = new StringBuilder(256); 8952 } else { 8953 r.append(' '); 8954 } 8955 r.append(p.info.name); 8956 } 8957 } else { 8958 Slog.w(TAG, "Permission " + p.info.name + " from package " 8959 + p.info.packageName + " ignored: base tree " 8960 + tree.name + " is from package " 8961 + tree.sourcePackage); 8962 } 8963 } else { 8964 Slog.w(TAG, "Permission " + p.info.name + " from package " 8965 + p.info.packageName + " ignored: original from " 8966 + bp.sourcePackage); 8967 } 8968 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8969 if (r == null) { 8970 r = new StringBuilder(256); 8971 } else { 8972 r.append(' '); 8973 } 8974 r.append("DUP:"); 8975 r.append(p.info.name); 8976 } 8977 if (bp.perm == p) { 8978 bp.protectionLevel = p.info.protectionLevel; 8979 } 8980 } 8981 8982 if (r != null) { 8983 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8984 } 8985 8986 N = pkg.instrumentation.size(); 8987 r = null; 8988 for (i=0; i<N; i++) { 8989 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8990 a.info.packageName = pkg.applicationInfo.packageName; 8991 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8992 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8993 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8994 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8995 a.info.dataDir = pkg.applicationInfo.dataDir; 8996 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8997 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8998 8999 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9000 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9001 mInstrumentation.put(a.getComponentName(), a); 9002 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 9003 if (r == null) { 9004 r = new StringBuilder(256); 9005 } else { 9006 r.append(' '); 9007 } 9008 r.append(a.info.name); 9009 } 9010 } 9011 if (r != null) { 9012 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9013 } 9014 9015 if (pkg.protectedBroadcasts != null) { 9016 N = pkg.protectedBroadcasts.size(); 9017 for (i=0; i<N; i++) { 9018 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9019 } 9020 } 9021 9022 pkgSetting.setTimeStamp(scanFileTime); 9023 9024 // Create idmap files for pairs of (packages, overlay packages). 9025 // Note: "android", ie framework-res.apk, is handled by native layers. 9026 if (pkg.mOverlayTarget != null) { 9027 // This is an overlay package. 9028 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9029 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9030 mOverlays.put(pkg.mOverlayTarget, 9031 new ArrayMap<String, PackageParser.Package>()); 9032 } 9033 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9034 map.put(pkg.packageName, pkg); 9035 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9036 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9037 createIdmapFailed = true; 9038 } 9039 } 9040 } else if (mOverlays.containsKey(pkg.packageName) && 9041 !pkg.packageName.equals("android")) { 9042 // This is a regular package, with one or more known overlay packages. 9043 createIdmapsForPackageLI(pkg); 9044 } 9045 } 9046 9047 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9048 9049 if (createIdmapFailed) { 9050 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9051 "scanPackageLI failed to createIdmap"); 9052 } 9053 return pkg; 9054 } 9055 9056 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9057 PackageParser.Package update, UserHandle user) { 9058 if (existing.applicationInfo == null || update.applicationInfo == null) { 9059 // This isn't due to an app installation. 9060 return; 9061 } 9062 9063 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9064 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9065 9066 // The codePath hasn't changed, so there's nothing for us to do. 9067 if (Objects.equals(oldCodePath, newCodePath)) { 9068 return; 9069 } 9070 9071 File canonicalNewCodePath; 9072 try { 9073 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9074 } catch (IOException e) { 9075 Slog.w(TAG, "Failed to get canonical path.", e); 9076 return; 9077 } 9078 9079 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9080 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9081 // that the last component of the path (i.e, the name) doesn't need canonicalization 9082 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9083 // but may change in the future. Hopefully this function won't exist at that point. 9084 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9085 oldCodePath.getName()); 9086 9087 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9088 // with "@". 9089 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9090 if (!oldMarkerPrefix.endsWith("@")) { 9091 oldMarkerPrefix += "@"; 9092 } 9093 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9094 if (!newMarkerPrefix.endsWith("@")) { 9095 newMarkerPrefix += "@"; 9096 } 9097 9098 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9099 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9100 for (String updatedPath : updatedPaths) { 9101 String updatedPathName = new File(updatedPath).getName(); 9102 markerSuffixes.add(updatedPathName.replace('/', '@')); 9103 } 9104 9105 for (int userId : resolveUserIds(user.getIdentifier())) { 9106 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9107 9108 for (String markerSuffix : markerSuffixes) { 9109 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9110 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9111 if (oldForeignUseMark.exists()) { 9112 try { 9113 Os.rename(oldForeignUseMark.getAbsolutePath(), 9114 newForeignUseMark.getAbsolutePath()); 9115 } catch (ErrnoException e) { 9116 Slog.w(TAG, "Failed to rename foreign use marker", e); 9117 oldForeignUseMark.delete(); 9118 } 9119 } 9120 } 9121 } 9122 } 9123 9124 /** 9125 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9126 * is derived purely on the basis of the contents of {@code scanFile} and 9127 * {@code cpuAbiOverride}. 9128 * 9129 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9130 */ 9131 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9132 String cpuAbiOverride, boolean extractLibs) 9133 throws PackageManagerException { 9134 // TODO: We can probably be smarter about this stuff. For installed apps, 9135 // we can calculate this information at install time once and for all. For 9136 // system apps, we can probably assume that this information doesn't change 9137 // after the first boot scan. As things stand, we do lots of unnecessary work. 9138 9139 // Give ourselves some initial paths; we'll come back for another 9140 // pass once we've determined ABI below. 9141 setNativeLibraryPaths(pkg); 9142 9143 // We would never need to extract libs for forward-locked and external packages, 9144 // since the container service will do it for us. We shouldn't attempt to 9145 // extract libs from system app when it was not updated. 9146 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9147 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9148 extractLibs = false; 9149 } 9150 9151 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9152 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9153 9154 NativeLibraryHelper.Handle handle = null; 9155 try { 9156 handle = NativeLibraryHelper.Handle.create(pkg); 9157 // TODO(multiArch): This can be null for apps that didn't go through the 9158 // usual installation process. We can calculate it again, like we 9159 // do during install time. 9160 // 9161 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9162 // unnecessary. 9163 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9164 9165 // Null out the abis so that they can be recalculated. 9166 pkg.applicationInfo.primaryCpuAbi = null; 9167 pkg.applicationInfo.secondaryCpuAbi = null; 9168 if (isMultiArch(pkg.applicationInfo)) { 9169 // Warn if we've set an abiOverride for multi-lib packages.. 9170 // By definition, we need to copy both 32 and 64 bit libraries for 9171 // such packages. 9172 if (pkg.cpuAbiOverride != null 9173 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9174 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9175 } 9176 9177 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9178 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9179 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9180 if (extractLibs) { 9181 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9182 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9183 useIsaSpecificSubdirs); 9184 } else { 9185 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9186 } 9187 } 9188 9189 maybeThrowExceptionForMultiArchCopy( 9190 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9191 9192 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9193 if (extractLibs) { 9194 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9195 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9196 useIsaSpecificSubdirs); 9197 } else { 9198 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9199 } 9200 } 9201 9202 maybeThrowExceptionForMultiArchCopy( 9203 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9204 9205 if (abi64 >= 0) { 9206 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9207 } 9208 9209 if (abi32 >= 0) { 9210 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9211 if (abi64 >= 0) { 9212 if (pkg.use32bitAbi) { 9213 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9214 pkg.applicationInfo.primaryCpuAbi = abi; 9215 } else { 9216 pkg.applicationInfo.secondaryCpuAbi = abi; 9217 } 9218 } else { 9219 pkg.applicationInfo.primaryCpuAbi = abi; 9220 } 9221 } 9222 9223 } else { 9224 String[] abiList = (cpuAbiOverride != null) ? 9225 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9226 9227 // Enable gross and lame hacks for apps that are built with old 9228 // SDK tools. We must scan their APKs for renderscript bitcode and 9229 // not launch them if it's present. Don't bother checking on devices 9230 // that don't have 64 bit support. 9231 boolean needsRenderScriptOverride = false; 9232 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9233 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9234 abiList = Build.SUPPORTED_32_BIT_ABIS; 9235 needsRenderScriptOverride = true; 9236 } 9237 9238 final int copyRet; 9239 if (extractLibs) { 9240 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9241 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9242 } else { 9243 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9244 } 9245 9246 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9247 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9248 "Error unpackaging native libs for app, errorCode=" + copyRet); 9249 } 9250 9251 if (copyRet >= 0) { 9252 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9253 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9254 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9255 } else if (needsRenderScriptOverride) { 9256 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9257 } 9258 } 9259 } catch (IOException ioe) { 9260 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9261 } finally { 9262 IoUtils.closeQuietly(handle); 9263 } 9264 9265 // Now that we've calculated the ABIs and determined if it's an internal app, 9266 // we will go ahead and populate the nativeLibraryPath. 9267 setNativeLibraryPaths(pkg); 9268 } 9269 9270 /** 9271 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9272 * i.e, so that all packages can be run inside a single process if required. 9273 * 9274 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9275 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9276 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9277 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9278 * updating a package that belongs to a shared user. 9279 * 9280 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9281 * adds unnecessary complexity. 9282 */ 9283 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9284 PackageParser.Package scannedPackage, boolean bootComplete) { 9285 String requiredInstructionSet = null; 9286 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9287 requiredInstructionSet = VMRuntime.getInstructionSet( 9288 scannedPackage.applicationInfo.primaryCpuAbi); 9289 } 9290 9291 PackageSetting requirer = null; 9292 for (PackageSetting ps : packagesForUser) { 9293 // If packagesForUser contains scannedPackage, we skip it. This will happen 9294 // when scannedPackage is an update of an existing package. Without this check, 9295 // we will never be able to change the ABI of any package belonging to a shared 9296 // user, even if it's compatible with other packages. 9297 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9298 if (ps.primaryCpuAbiString == null) { 9299 continue; 9300 } 9301 9302 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9303 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9304 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9305 // this but there's not much we can do. 9306 String errorMessage = "Instruction set mismatch, " 9307 + ((requirer == null) ? "[caller]" : requirer) 9308 + " requires " + requiredInstructionSet + " whereas " + ps 9309 + " requires " + instructionSet; 9310 Slog.w(TAG, errorMessage); 9311 } 9312 9313 if (requiredInstructionSet == null) { 9314 requiredInstructionSet = instructionSet; 9315 requirer = ps; 9316 } 9317 } 9318 } 9319 9320 if (requiredInstructionSet != null) { 9321 String adjustedAbi; 9322 if (requirer != null) { 9323 // requirer != null implies that either scannedPackage was null or that scannedPackage 9324 // did not require an ABI, in which case we have to adjust scannedPackage to match 9325 // the ABI of the set (which is the same as requirer's ABI) 9326 adjustedAbi = requirer.primaryCpuAbiString; 9327 if (scannedPackage != null) { 9328 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9329 } 9330 } else { 9331 // requirer == null implies that we're updating all ABIs in the set to 9332 // match scannedPackage. 9333 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9334 } 9335 9336 for (PackageSetting ps : packagesForUser) { 9337 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9338 if (ps.primaryCpuAbiString != null) { 9339 continue; 9340 } 9341 9342 ps.primaryCpuAbiString = adjustedAbi; 9343 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9344 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9345 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9346 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9347 + " (requirer=" 9348 + (requirer == null ? "null" : requirer.pkg.packageName) 9349 + ", scannedPackage=" 9350 + (scannedPackage != null ? scannedPackage.packageName : "null") 9351 + ")"); 9352 try { 9353 mInstaller.rmdex(ps.codePathString, 9354 getDexCodeInstructionSet(getPreferredInstructionSet())); 9355 } catch (InstallerException ignored) { 9356 } 9357 } 9358 } 9359 } 9360 } 9361 } 9362 9363 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9364 synchronized (mPackages) { 9365 mResolverReplaced = true; 9366 // Set up information for custom user intent resolution activity. 9367 mResolveActivity.applicationInfo = pkg.applicationInfo; 9368 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9369 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9370 mResolveActivity.processName = pkg.applicationInfo.packageName; 9371 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9372 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9373 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9374 mResolveActivity.theme = 0; 9375 mResolveActivity.exported = true; 9376 mResolveActivity.enabled = true; 9377 mResolveInfo.activityInfo = mResolveActivity; 9378 mResolveInfo.priority = 0; 9379 mResolveInfo.preferredOrder = 0; 9380 mResolveInfo.match = 0; 9381 mResolveComponentName = mCustomResolverComponentName; 9382 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9383 mResolveComponentName); 9384 } 9385 } 9386 9387 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9388 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9389 9390 // Set up information for ephemeral installer activity 9391 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9392 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9393 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9394 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9395 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9396 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9397 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9398 mEphemeralInstallerActivity.theme = 0; 9399 mEphemeralInstallerActivity.exported = true; 9400 mEphemeralInstallerActivity.enabled = true; 9401 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9402 mEphemeralInstallerInfo.priority = 0; 9403 mEphemeralInstallerInfo.preferredOrder = 0; 9404 mEphemeralInstallerInfo.match = 0; 9405 9406 if (DEBUG_EPHEMERAL) { 9407 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9408 } 9409 } 9410 9411 private static String calculateBundledApkRoot(final String codePathString) { 9412 final File codePath = new File(codePathString); 9413 final File codeRoot; 9414 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9415 codeRoot = Environment.getRootDirectory(); 9416 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9417 codeRoot = Environment.getOemDirectory(); 9418 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9419 codeRoot = Environment.getVendorDirectory(); 9420 } else { 9421 // Unrecognized code path; take its top real segment as the apk root: 9422 // e.g. /something/app/blah.apk => /something 9423 try { 9424 File f = codePath.getCanonicalFile(); 9425 File parent = f.getParentFile(); // non-null because codePath is a file 9426 File tmp; 9427 while ((tmp = parent.getParentFile()) != null) { 9428 f = parent; 9429 parent = tmp; 9430 } 9431 codeRoot = f; 9432 Slog.w(TAG, "Unrecognized code path " 9433 + codePath + " - using " + codeRoot); 9434 } catch (IOException e) { 9435 // Can't canonicalize the code path -- shenanigans? 9436 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9437 return Environment.getRootDirectory().getPath(); 9438 } 9439 } 9440 return codeRoot.getPath(); 9441 } 9442 9443 /** 9444 * Derive and set the location of native libraries for the given package, 9445 * which varies depending on where and how the package was installed. 9446 */ 9447 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9448 final ApplicationInfo info = pkg.applicationInfo; 9449 final String codePath = pkg.codePath; 9450 final File codeFile = new File(codePath); 9451 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9452 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9453 9454 info.nativeLibraryRootDir = null; 9455 info.nativeLibraryRootRequiresIsa = false; 9456 info.nativeLibraryDir = null; 9457 info.secondaryNativeLibraryDir = null; 9458 9459 if (isApkFile(codeFile)) { 9460 // Monolithic install 9461 if (bundledApp) { 9462 // If "/system/lib64/apkname" exists, assume that is the per-package 9463 // native library directory to use; otherwise use "/system/lib/apkname". 9464 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9465 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9466 getPrimaryInstructionSet(info)); 9467 9468 // This is a bundled system app so choose the path based on the ABI. 9469 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9470 // is just the default path. 9471 final String apkName = deriveCodePathName(codePath); 9472 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9473 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9474 apkName).getAbsolutePath(); 9475 9476 if (info.secondaryCpuAbi != null) { 9477 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9478 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9479 secondaryLibDir, apkName).getAbsolutePath(); 9480 } 9481 } else if (asecApp) { 9482 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9483 .getAbsolutePath(); 9484 } else { 9485 final String apkName = deriveCodePathName(codePath); 9486 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9487 .getAbsolutePath(); 9488 } 9489 9490 info.nativeLibraryRootRequiresIsa = false; 9491 info.nativeLibraryDir = info.nativeLibraryRootDir; 9492 } else { 9493 // Cluster install 9494 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9495 info.nativeLibraryRootRequiresIsa = true; 9496 9497 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9498 getPrimaryInstructionSet(info)).getAbsolutePath(); 9499 9500 if (info.secondaryCpuAbi != null) { 9501 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9502 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9503 } 9504 } 9505 } 9506 9507 /** 9508 * Calculate the abis and roots for a bundled app. These can uniquely 9509 * be determined from the contents of the system partition, i.e whether 9510 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9511 * of this information, and instead assume that the system was built 9512 * sensibly. 9513 */ 9514 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9515 PackageSetting pkgSetting) { 9516 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9517 9518 // If "/system/lib64/apkname" exists, assume that is the per-package 9519 // native library directory to use; otherwise use "/system/lib/apkname". 9520 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9521 setBundledAppAbi(pkg, apkRoot, apkName); 9522 // pkgSetting might be null during rescan following uninstall of updates 9523 // to a bundled app, so accommodate that possibility. The settings in 9524 // that case will be established later from the parsed package. 9525 // 9526 // If the settings aren't null, sync them up with what we've just derived. 9527 // note that apkRoot isn't stored in the package settings. 9528 if (pkgSetting != null) { 9529 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9530 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9531 } 9532 } 9533 9534 /** 9535 * Deduces the ABI of a bundled app and sets the relevant fields on the 9536 * parsed pkg object. 9537 * 9538 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9539 * under which system libraries are installed. 9540 * @param apkName the name of the installed package. 9541 */ 9542 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9543 final File codeFile = new File(pkg.codePath); 9544 9545 final boolean has64BitLibs; 9546 final boolean has32BitLibs; 9547 if (isApkFile(codeFile)) { 9548 // Monolithic install 9549 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9550 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9551 } else { 9552 // Cluster install 9553 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9554 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9555 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9556 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9557 has64BitLibs = (new File(rootDir, isa)).exists(); 9558 } else { 9559 has64BitLibs = false; 9560 } 9561 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9562 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9563 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9564 has32BitLibs = (new File(rootDir, isa)).exists(); 9565 } else { 9566 has32BitLibs = false; 9567 } 9568 } 9569 9570 if (has64BitLibs && !has32BitLibs) { 9571 // The package has 64 bit libs, but not 32 bit libs. Its primary 9572 // ABI should be 64 bit. We can safely assume here that the bundled 9573 // native libraries correspond to the most preferred ABI in the list. 9574 9575 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9576 pkg.applicationInfo.secondaryCpuAbi = null; 9577 } else if (has32BitLibs && !has64BitLibs) { 9578 // The package has 32 bit libs but not 64 bit libs. Its primary 9579 // ABI should be 32 bit. 9580 9581 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9582 pkg.applicationInfo.secondaryCpuAbi = null; 9583 } else if (has32BitLibs && has64BitLibs) { 9584 // The application has both 64 and 32 bit bundled libraries. We check 9585 // here that the app declares multiArch support, and warn if it doesn't. 9586 // 9587 // We will be lenient here and record both ABIs. The primary will be the 9588 // ABI that's higher on the list, i.e, a device that's configured to prefer 9589 // 64 bit apps will see a 64 bit primary ABI, 9590 9591 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9592 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9593 } 9594 9595 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9596 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9597 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9598 } else { 9599 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9600 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9601 } 9602 } else { 9603 pkg.applicationInfo.primaryCpuAbi = null; 9604 pkg.applicationInfo.secondaryCpuAbi = null; 9605 } 9606 } 9607 9608 private void killApplication(String pkgName, int appId, String reason) { 9609 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9610 } 9611 9612 private void killApplication(String pkgName, int appId, int userId, String reason) { 9613 // Request the ActivityManager to kill the process(only for existing packages) 9614 // so that we do not end up in a confused state while the user is still using the older 9615 // version of the application while the new one gets installed. 9616 final long token = Binder.clearCallingIdentity(); 9617 try { 9618 IActivityManager am = ActivityManagerNative.getDefault(); 9619 if (am != null) { 9620 try { 9621 am.killApplication(pkgName, appId, userId, reason); 9622 } catch (RemoteException e) { 9623 } 9624 } 9625 } finally { 9626 Binder.restoreCallingIdentity(token); 9627 } 9628 } 9629 9630 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9631 // Remove the parent package setting 9632 PackageSetting ps = (PackageSetting) pkg.mExtras; 9633 if (ps != null) { 9634 removePackageLI(ps, chatty); 9635 } 9636 // Remove the child package setting 9637 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9638 for (int i = 0; i < childCount; i++) { 9639 PackageParser.Package childPkg = pkg.childPackages.get(i); 9640 ps = (PackageSetting) childPkg.mExtras; 9641 if (ps != null) { 9642 removePackageLI(ps, chatty); 9643 } 9644 } 9645 } 9646 9647 void removePackageLI(PackageSetting ps, boolean chatty) { 9648 if (DEBUG_INSTALL) { 9649 if (chatty) 9650 Log.d(TAG, "Removing package " + ps.name); 9651 } 9652 9653 // writer 9654 synchronized (mPackages) { 9655 mPackages.remove(ps.name); 9656 final PackageParser.Package pkg = ps.pkg; 9657 if (pkg != null) { 9658 cleanPackageDataStructuresLILPw(pkg, chatty); 9659 } 9660 } 9661 } 9662 9663 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9664 if (DEBUG_INSTALL) { 9665 if (chatty) 9666 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9667 } 9668 9669 // writer 9670 synchronized (mPackages) { 9671 // Remove the parent package 9672 mPackages.remove(pkg.applicationInfo.packageName); 9673 cleanPackageDataStructuresLILPw(pkg, chatty); 9674 9675 // Remove the child packages 9676 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9677 for (int i = 0; i < childCount; i++) { 9678 PackageParser.Package childPkg = pkg.childPackages.get(i); 9679 mPackages.remove(childPkg.applicationInfo.packageName); 9680 cleanPackageDataStructuresLILPw(childPkg, chatty); 9681 } 9682 } 9683 } 9684 9685 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9686 int N = pkg.providers.size(); 9687 StringBuilder r = null; 9688 int i; 9689 for (i=0; i<N; i++) { 9690 PackageParser.Provider p = pkg.providers.get(i); 9691 mProviders.removeProvider(p); 9692 if (p.info.authority == null) { 9693 9694 /* There was another ContentProvider with this authority when 9695 * this app was installed so this authority is null, 9696 * Ignore it as we don't have to unregister the provider. 9697 */ 9698 continue; 9699 } 9700 String names[] = p.info.authority.split(";"); 9701 for (int j = 0; j < names.length; j++) { 9702 if (mProvidersByAuthority.get(names[j]) == p) { 9703 mProvidersByAuthority.remove(names[j]); 9704 if (DEBUG_REMOVE) { 9705 if (chatty) 9706 Log.d(TAG, "Unregistered content provider: " + names[j] 9707 + ", className = " + p.info.name + ", isSyncable = " 9708 + p.info.isSyncable); 9709 } 9710 } 9711 } 9712 if (DEBUG_REMOVE && chatty) { 9713 if (r == null) { 9714 r = new StringBuilder(256); 9715 } else { 9716 r.append(' '); 9717 } 9718 r.append(p.info.name); 9719 } 9720 } 9721 if (r != null) { 9722 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9723 } 9724 9725 N = pkg.services.size(); 9726 r = null; 9727 for (i=0; i<N; i++) { 9728 PackageParser.Service s = pkg.services.get(i); 9729 mServices.removeService(s); 9730 if (chatty) { 9731 if (r == null) { 9732 r = new StringBuilder(256); 9733 } else { 9734 r.append(' '); 9735 } 9736 r.append(s.info.name); 9737 } 9738 } 9739 if (r != null) { 9740 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9741 } 9742 9743 N = pkg.receivers.size(); 9744 r = null; 9745 for (i=0; i<N; i++) { 9746 PackageParser.Activity a = pkg.receivers.get(i); 9747 mReceivers.removeActivity(a, "receiver"); 9748 if (DEBUG_REMOVE && chatty) { 9749 if (r == null) { 9750 r = new StringBuilder(256); 9751 } else { 9752 r.append(' '); 9753 } 9754 r.append(a.info.name); 9755 } 9756 } 9757 if (r != null) { 9758 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9759 } 9760 9761 N = pkg.activities.size(); 9762 r = null; 9763 for (i=0; i<N; i++) { 9764 PackageParser.Activity a = pkg.activities.get(i); 9765 mActivities.removeActivity(a, "activity"); 9766 if (DEBUG_REMOVE && chatty) { 9767 if (r == null) { 9768 r = new StringBuilder(256); 9769 } else { 9770 r.append(' '); 9771 } 9772 r.append(a.info.name); 9773 } 9774 } 9775 if (r != null) { 9776 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9777 } 9778 9779 N = pkg.permissions.size(); 9780 r = null; 9781 for (i=0; i<N; i++) { 9782 PackageParser.Permission p = pkg.permissions.get(i); 9783 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9784 if (bp == null) { 9785 bp = mSettings.mPermissionTrees.get(p.info.name); 9786 } 9787 if (bp != null && bp.perm == p) { 9788 bp.perm = null; 9789 if (DEBUG_REMOVE && chatty) { 9790 if (r == null) { 9791 r = new StringBuilder(256); 9792 } else { 9793 r.append(' '); 9794 } 9795 r.append(p.info.name); 9796 } 9797 } 9798 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9799 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9800 if (appOpPkgs != null) { 9801 appOpPkgs.remove(pkg.packageName); 9802 } 9803 } 9804 } 9805 if (r != null) { 9806 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9807 } 9808 9809 N = pkg.requestedPermissions.size(); 9810 r = null; 9811 for (i=0; i<N; i++) { 9812 String perm = pkg.requestedPermissions.get(i); 9813 BasePermission bp = mSettings.mPermissions.get(perm); 9814 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9815 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9816 if (appOpPkgs != null) { 9817 appOpPkgs.remove(pkg.packageName); 9818 if (appOpPkgs.isEmpty()) { 9819 mAppOpPermissionPackages.remove(perm); 9820 } 9821 } 9822 } 9823 } 9824 if (r != null) { 9825 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9826 } 9827 9828 N = pkg.instrumentation.size(); 9829 r = null; 9830 for (i=0; i<N; i++) { 9831 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9832 mInstrumentation.remove(a.getComponentName()); 9833 if (DEBUG_REMOVE && chatty) { 9834 if (r == null) { 9835 r = new StringBuilder(256); 9836 } else { 9837 r.append(' '); 9838 } 9839 r.append(a.info.name); 9840 } 9841 } 9842 if (r != null) { 9843 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9844 } 9845 9846 r = null; 9847 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9848 // Only system apps can hold shared libraries. 9849 if (pkg.libraryNames != null) { 9850 for (i=0; i<pkg.libraryNames.size(); i++) { 9851 String name = pkg.libraryNames.get(i); 9852 SharedLibraryEntry cur = mSharedLibraries.get(name); 9853 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9854 mSharedLibraries.remove(name); 9855 if (DEBUG_REMOVE && chatty) { 9856 if (r == null) { 9857 r = new StringBuilder(256); 9858 } else { 9859 r.append(' '); 9860 } 9861 r.append(name); 9862 } 9863 } 9864 } 9865 } 9866 } 9867 if (r != null) { 9868 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9869 } 9870 } 9871 9872 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9873 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9874 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9875 return true; 9876 } 9877 } 9878 return false; 9879 } 9880 9881 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9882 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9883 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9884 9885 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9886 // Update the parent permissions 9887 updatePermissionsLPw(pkg.packageName, pkg, flags); 9888 // Update the child permissions 9889 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9890 for (int i = 0; i < childCount; i++) { 9891 PackageParser.Package childPkg = pkg.childPackages.get(i); 9892 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9893 } 9894 } 9895 9896 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9897 int flags) { 9898 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9899 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9900 } 9901 9902 private void updatePermissionsLPw(String changingPkg, 9903 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9904 // Make sure there are no dangling permission trees. 9905 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9906 while (it.hasNext()) { 9907 final BasePermission bp = it.next(); 9908 if (bp.packageSetting == null) { 9909 // We may not yet have parsed the package, so just see if 9910 // we still know about its settings. 9911 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9912 } 9913 if (bp.packageSetting == null) { 9914 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9915 + " from package " + bp.sourcePackage); 9916 it.remove(); 9917 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9918 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9919 Slog.i(TAG, "Removing old permission tree: " + bp.name 9920 + " from package " + bp.sourcePackage); 9921 flags |= UPDATE_PERMISSIONS_ALL; 9922 it.remove(); 9923 } 9924 } 9925 } 9926 9927 // Make sure all dynamic permissions have been assigned to a package, 9928 // and make sure there are no dangling permissions. 9929 it = mSettings.mPermissions.values().iterator(); 9930 while (it.hasNext()) { 9931 final BasePermission bp = it.next(); 9932 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9933 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9934 + bp.name + " pkg=" + bp.sourcePackage 9935 + " info=" + bp.pendingInfo); 9936 if (bp.packageSetting == null && bp.pendingInfo != null) { 9937 final BasePermission tree = findPermissionTreeLP(bp.name); 9938 if (tree != null && tree.perm != null) { 9939 bp.packageSetting = tree.packageSetting; 9940 bp.perm = new PackageParser.Permission(tree.perm.owner, 9941 new PermissionInfo(bp.pendingInfo)); 9942 bp.perm.info.packageName = tree.perm.info.packageName; 9943 bp.perm.info.name = bp.name; 9944 bp.uid = tree.uid; 9945 } 9946 } 9947 } 9948 if (bp.packageSetting == null) { 9949 // We may not yet have parsed the package, so just see if 9950 // we still know about its settings. 9951 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9952 } 9953 if (bp.packageSetting == null) { 9954 Slog.w(TAG, "Removing dangling permission: " + bp.name 9955 + " from package " + bp.sourcePackage); 9956 it.remove(); 9957 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9958 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9959 Slog.i(TAG, "Removing old permission: " + bp.name 9960 + " from package " + bp.sourcePackage); 9961 flags |= UPDATE_PERMISSIONS_ALL; 9962 it.remove(); 9963 } 9964 } 9965 } 9966 9967 // Now update the permissions for all packages, in particular 9968 // replace the granted permissions of the system packages. 9969 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9970 for (PackageParser.Package pkg : mPackages.values()) { 9971 if (pkg != pkgInfo) { 9972 // Only replace for packages on requested volume 9973 final String volumeUuid = getVolumeUuidForPackage(pkg); 9974 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9975 && Objects.equals(replaceVolumeUuid, volumeUuid); 9976 grantPermissionsLPw(pkg, replace, changingPkg); 9977 } 9978 } 9979 } 9980 9981 if (pkgInfo != null) { 9982 // Only replace for packages on requested volume 9983 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9984 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9985 && Objects.equals(replaceVolumeUuid, volumeUuid); 9986 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9987 } 9988 } 9989 9990 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9991 String packageOfInterest) { 9992 // IMPORTANT: There are two types of permissions: install and runtime. 9993 // Install time permissions are granted when the app is installed to 9994 // all device users and users added in the future. Runtime permissions 9995 // are granted at runtime explicitly to specific users. Normal and signature 9996 // protected permissions are install time permissions. Dangerous permissions 9997 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9998 // otherwise they are runtime permissions. This function does not manage 9999 // runtime permissions except for the case an app targeting Lollipop MR1 10000 // being upgraded to target a newer SDK, in which case dangerous permissions 10001 // are transformed from install time to runtime ones. 10002 10003 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10004 if (ps == null) { 10005 return; 10006 } 10007 10008 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10009 10010 PermissionsState permissionsState = ps.getPermissionsState(); 10011 PermissionsState origPermissions = permissionsState; 10012 10013 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10014 10015 boolean runtimePermissionsRevoked = false; 10016 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10017 10018 boolean changedInstallPermission = false; 10019 10020 if (replace) { 10021 ps.installPermissionsFixed = false; 10022 if (!ps.isSharedUser()) { 10023 origPermissions = new PermissionsState(permissionsState); 10024 permissionsState.reset(); 10025 } else { 10026 // We need to know only about runtime permission changes since the 10027 // calling code always writes the install permissions state but 10028 // the runtime ones are written only if changed. The only cases of 10029 // changed runtime permissions here are promotion of an install to 10030 // runtime and revocation of a runtime from a shared user. 10031 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10032 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10033 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10034 runtimePermissionsRevoked = true; 10035 } 10036 } 10037 } 10038 10039 permissionsState.setGlobalGids(mGlobalGids); 10040 10041 final int N = pkg.requestedPermissions.size(); 10042 for (int i=0; i<N; i++) { 10043 final String name = pkg.requestedPermissions.get(i); 10044 final BasePermission bp = mSettings.mPermissions.get(name); 10045 10046 if (DEBUG_INSTALL) { 10047 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10048 } 10049 10050 if (bp == null || bp.packageSetting == null) { 10051 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10052 Slog.w(TAG, "Unknown permission " + name 10053 + " in package " + pkg.packageName); 10054 } 10055 continue; 10056 } 10057 10058 final String perm = bp.name; 10059 boolean allowedSig = false; 10060 int grant = GRANT_DENIED; 10061 10062 // Keep track of app op permissions. 10063 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10064 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10065 if (pkgs == null) { 10066 pkgs = new ArraySet<>(); 10067 mAppOpPermissionPackages.put(bp.name, pkgs); 10068 } 10069 pkgs.add(pkg.packageName); 10070 } 10071 10072 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10073 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10074 >= Build.VERSION_CODES.M; 10075 switch (level) { 10076 case PermissionInfo.PROTECTION_NORMAL: { 10077 // For all apps normal permissions are install time ones. 10078 grant = GRANT_INSTALL; 10079 } break; 10080 10081 case PermissionInfo.PROTECTION_DANGEROUS: { 10082 // If a permission review is required for legacy apps we represent 10083 // their permissions as always granted runtime ones since we need 10084 // to keep the review required permission flag per user while an 10085 // install permission's state is shared across all users. 10086 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10087 // For legacy apps dangerous permissions are install time ones. 10088 grant = GRANT_INSTALL; 10089 } else if (origPermissions.hasInstallPermission(bp.name)) { 10090 // For legacy apps that became modern, install becomes runtime. 10091 grant = GRANT_UPGRADE; 10092 } else if (mPromoteSystemApps 10093 && isSystemApp(ps) 10094 && mExistingSystemPackages.contains(ps.name)) { 10095 // For legacy system apps, install becomes runtime. 10096 // We cannot check hasInstallPermission() for system apps since those 10097 // permissions were granted implicitly and not persisted pre-M. 10098 grant = GRANT_UPGRADE; 10099 } else { 10100 // For modern apps keep runtime permissions unchanged. 10101 grant = GRANT_RUNTIME; 10102 } 10103 } break; 10104 10105 case PermissionInfo.PROTECTION_SIGNATURE: { 10106 // For all apps signature permissions are install time ones. 10107 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10108 if (allowedSig) { 10109 grant = GRANT_INSTALL; 10110 } 10111 } break; 10112 } 10113 10114 if (DEBUG_INSTALL) { 10115 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10116 } 10117 10118 if (grant != GRANT_DENIED) { 10119 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10120 // If this is an existing, non-system package, then 10121 // we can't add any new permissions to it. 10122 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10123 // Except... if this is a permission that was added 10124 // to the platform (note: need to only do this when 10125 // updating the platform). 10126 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10127 grant = GRANT_DENIED; 10128 } 10129 } 10130 } 10131 10132 switch (grant) { 10133 case GRANT_INSTALL: { 10134 // Revoke this as runtime permission to handle the case of 10135 // a runtime permission being downgraded to an install one. 10136 // Also in permission review mode we keep dangerous permissions 10137 // for legacy apps 10138 for (int userId : UserManagerService.getInstance().getUserIds()) { 10139 if (origPermissions.getRuntimePermissionState( 10140 bp.name, userId) != null) { 10141 // Revoke the runtime permission and clear the flags. 10142 origPermissions.revokeRuntimePermission(bp, userId); 10143 origPermissions.updatePermissionFlags(bp, userId, 10144 PackageManager.MASK_PERMISSION_FLAGS, 0); 10145 // If we revoked a permission permission, we have to write. 10146 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10147 changedRuntimePermissionUserIds, userId); 10148 } 10149 } 10150 // Grant an install permission. 10151 if (permissionsState.grantInstallPermission(bp) != 10152 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10153 changedInstallPermission = true; 10154 } 10155 } break; 10156 10157 case GRANT_RUNTIME: { 10158 // Grant previously granted runtime permissions. 10159 for (int userId : UserManagerService.getInstance().getUserIds()) { 10160 PermissionState permissionState = origPermissions 10161 .getRuntimePermissionState(bp.name, userId); 10162 int flags = permissionState != null 10163 ? permissionState.getFlags() : 0; 10164 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10165 if (permissionsState.grantRuntimePermission(bp, userId) == 10166 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10167 // If we cannot put the permission as it was, we have to write. 10168 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10169 changedRuntimePermissionUserIds, userId); 10170 } 10171 // If the app supports runtime permissions no need for a review. 10172 if (Build.PERMISSIONS_REVIEW_REQUIRED 10173 && appSupportsRuntimePermissions 10174 && (flags & PackageManager 10175 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10176 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10177 // Since we changed the flags, we have to write. 10178 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10179 changedRuntimePermissionUserIds, userId); 10180 } 10181 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10182 && !appSupportsRuntimePermissions) { 10183 // For legacy apps that need a permission review, every new 10184 // runtime permission is granted but it is pending a review. 10185 // We also need to review only platform defined runtime 10186 // permissions as these are the only ones the platform knows 10187 // how to disable the API to simulate revocation as legacy 10188 // apps don't expect to run with revoked permissions. 10189 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10190 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10191 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10192 // We changed the flags, hence have to write. 10193 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10194 changedRuntimePermissionUserIds, userId); 10195 } 10196 } 10197 if (permissionsState.grantRuntimePermission(bp, userId) 10198 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10199 // We changed the permission, hence have to write. 10200 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10201 changedRuntimePermissionUserIds, userId); 10202 } 10203 } 10204 // Propagate the permission flags. 10205 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10206 } 10207 } break; 10208 10209 case GRANT_UPGRADE: { 10210 // Grant runtime permissions for a previously held install permission. 10211 PermissionState permissionState = origPermissions 10212 .getInstallPermissionState(bp.name); 10213 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10214 10215 if (origPermissions.revokeInstallPermission(bp) 10216 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10217 // We will be transferring the permission flags, so clear them. 10218 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10219 PackageManager.MASK_PERMISSION_FLAGS, 0); 10220 changedInstallPermission = true; 10221 } 10222 10223 // If the permission is not to be promoted to runtime we ignore it and 10224 // also its other flags as they are not applicable to install permissions. 10225 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10226 for (int userId : currentUserIds) { 10227 if (permissionsState.grantRuntimePermission(bp, userId) != 10228 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10229 // Transfer the permission flags. 10230 permissionsState.updatePermissionFlags(bp, userId, 10231 flags, flags); 10232 // If we granted the permission, we have to write. 10233 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10234 changedRuntimePermissionUserIds, userId); 10235 } 10236 } 10237 } 10238 } break; 10239 10240 default: { 10241 if (packageOfInterest == null 10242 || packageOfInterest.equals(pkg.packageName)) { 10243 Slog.w(TAG, "Not granting permission " + perm 10244 + " to package " + pkg.packageName 10245 + " because it was previously installed without"); 10246 } 10247 } break; 10248 } 10249 } else { 10250 if (permissionsState.revokeInstallPermission(bp) != 10251 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10252 // Also drop the permission flags. 10253 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10254 PackageManager.MASK_PERMISSION_FLAGS, 0); 10255 changedInstallPermission = true; 10256 Slog.i(TAG, "Un-granting permission " + perm 10257 + " from package " + pkg.packageName 10258 + " (protectionLevel=" + bp.protectionLevel 10259 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10260 + ")"); 10261 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10262 // Don't print warning for app op permissions, since it is fine for them 10263 // not to be granted, there is a UI for the user to decide. 10264 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10265 Slog.w(TAG, "Not granting permission " + perm 10266 + " to package " + pkg.packageName 10267 + " (protectionLevel=" + bp.protectionLevel 10268 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10269 + ")"); 10270 } 10271 } 10272 } 10273 } 10274 10275 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10276 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10277 // This is the first that we have heard about this package, so the 10278 // permissions we have now selected are fixed until explicitly 10279 // changed. 10280 ps.installPermissionsFixed = true; 10281 } 10282 10283 // Persist the runtime permissions state for users with changes. If permissions 10284 // were revoked because no app in the shared user declares them we have to 10285 // write synchronously to avoid losing runtime permissions state. 10286 for (int userId : changedRuntimePermissionUserIds) { 10287 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10288 } 10289 10290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10291 } 10292 10293 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10294 boolean allowed = false; 10295 final int NP = PackageParser.NEW_PERMISSIONS.length; 10296 for (int ip=0; ip<NP; ip++) { 10297 final PackageParser.NewPermissionInfo npi 10298 = PackageParser.NEW_PERMISSIONS[ip]; 10299 if (npi.name.equals(perm) 10300 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10301 allowed = true; 10302 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10303 + pkg.packageName); 10304 break; 10305 } 10306 } 10307 return allowed; 10308 } 10309 10310 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10311 BasePermission bp, PermissionsState origPermissions) { 10312 boolean allowed; 10313 allowed = (compareSignatures( 10314 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10315 == PackageManager.SIGNATURE_MATCH) 10316 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10317 == PackageManager.SIGNATURE_MATCH); 10318 if (!allowed && (bp.protectionLevel 10319 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10320 if (isSystemApp(pkg)) { 10321 // For updated system applications, a system permission 10322 // is granted only if it had been defined by the original application. 10323 if (pkg.isUpdatedSystemApp()) { 10324 final PackageSetting sysPs = mSettings 10325 .getDisabledSystemPkgLPr(pkg.packageName); 10326 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10327 // If the original was granted this permission, we take 10328 // that grant decision as read and propagate it to the 10329 // update. 10330 if (sysPs.isPrivileged()) { 10331 allowed = true; 10332 } 10333 } else { 10334 // The system apk may have been updated with an older 10335 // version of the one on the data partition, but which 10336 // granted a new system permission that it didn't have 10337 // before. In this case we do want to allow the app to 10338 // now get the new permission if the ancestral apk is 10339 // privileged to get it. 10340 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10341 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10342 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10343 allowed = true; 10344 break; 10345 } 10346 } 10347 } 10348 // Also if a privileged parent package on the system image or any of 10349 // its children requested a privileged permission, the updated child 10350 // packages can also get the permission. 10351 if (pkg.parentPackage != null) { 10352 final PackageSetting disabledSysParentPs = mSettings 10353 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10354 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10355 && disabledSysParentPs.isPrivileged()) { 10356 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10357 allowed = true; 10358 } else if (disabledSysParentPs.pkg.childPackages != null) { 10359 final int count = disabledSysParentPs.pkg.childPackages.size(); 10360 for (int i = 0; i < count; i++) { 10361 PackageParser.Package disabledSysChildPkg = 10362 disabledSysParentPs.pkg.childPackages.get(i); 10363 if (isPackageRequestingPermission(disabledSysChildPkg, 10364 perm)) { 10365 allowed = true; 10366 break; 10367 } 10368 } 10369 } 10370 } 10371 } 10372 } 10373 } else { 10374 allowed = isPrivilegedApp(pkg); 10375 } 10376 } 10377 } 10378 if (!allowed) { 10379 if (!allowed && (bp.protectionLevel 10380 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10381 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10382 // If this was a previously normal/dangerous permission that got moved 10383 // to a system permission as part of the runtime permission redesign, then 10384 // we still want to blindly grant it to old apps. 10385 allowed = true; 10386 } 10387 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10388 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10389 // If this permission is to be granted to the system installer and 10390 // this app is an installer, then it gets the permission. 10391 allowed = true; 10392 } 10393 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10394 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10395 // If this permission is to be granted to the system verifier and 10396 // this app is a verifier, then it gets the permission. 10397 allowed = true; 10398 } 10399 if (!allowed && (bp.protectionLevel 10400 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10401 && isSystemApp(pkg)) { 10402 // Any pre-installed system app is allowed to get this permission. 10403 allowed = true; 10404 } 10405 if (!allowed && (bp.protectionLevel 10406 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10407 // For development permissions, a development permission 10408 // is granted only if it was already granted. 10409 allowed = origPermissions.hasInstallPermission(perm); 10410 } 10411 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10412 && pkg.packageName.equals(mSetupWizardPackage)) { 10413 // If this permission is to be granted to the system setup wizard and 10414 // this app is a setup wizard, then it gets the permission. 10415 allowed = true; 10416 } 10417 } 10418 return allowed; 10419 } 10420 10421 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10422 final int permCount = pkg.requestedPermissions.size(); 10423 for (int j = 0; j < permCount; j++) { 10424 String requestedPermission = pkg.requestedPermissions.get(j); 10425 if (permission.equals(requestedPermission)) { 10426 return true; 10427 } 10428 } 10429 return false; 10430 } 10431 10432 final class ActivityIntentResolver 10433 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10434 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10435 boolean defaultOnly, int userId) { 10436 if (!sUserManager.exists(userId)) return null; 10437 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10438 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10439 } 10440 10441 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10442 int userId) { 10443 if (!sUserManager.exists(userId)) return null; 10444 mFlags = flags; 10445 return super.queryIntent(intent, resolvedType, 10446 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10447 } 10448 10449 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10450 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10451 if (!sUserManager.exists(userId)) return null; 10452 if (packageActivities == null) { 10453 return null; 10454 } 10455 mFlags = flags; 10456 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10457 final int N = packageActivities.size(); 10458 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10459 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10460 10461 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10462 for (int i = 0; i < N; ++i) { 10463 intentFilters = packageActivities.get(i).intents; 10464 if (intentFilters != null && intentFilters.size() > 0) { 10465 PackageParser.ActivityIntentInfo[] array = 10466 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10467 intentFilters.toArray(array); 10468 listCut.add(array); 10469 } 10470 } 10471 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10472 } 10473 10474 /** 10475 * Finds a privileged activity that matches the specified activity names. 10476 */ 10477 private PackageParser.Activity findMatchingActivity( 10478 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10479 for (PackageParser.Activity sysActivity : activityList) { 10480 if (sysActivity.info.name.equals(activityInfo.name)) { 10481 return sysActivity; 10482 } 10483 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10484 return sysActivity; 10485 } 10486 if (sysActivity.info.targetActivity != null) { 10487 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10488 return sysActivity; 10489 } 10490 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10491 return sysActivity; 10492 } 10493 } 10494 } 10495 return null; 10496 } 10497 10498 public class IterGenerator<E> { 10499 public Iterator<E> generate(ActivityIntentInfo info) { 10500 return null; 10501 } 10502 } 10503 10504 public class ActionIterGenerator extends IterGenerator<String> { 10505 @Override 10506 public Iterator<String> generate(ActivityIntentInfo info) { 10507 return info.actionsIterator(); 10508 } 10509 } 10510 10511 public class CategoriesIterGenerator extends IterGenerator<String> { 10512 @Override 10513 public Iterator<String> generate(ActivityIntentInfo info) { 10514 return info.categoriesIterator(); 10515 } 10516 } 10517 10518 public class SchemesIterGenerator extends IterGenerator<String> { 10519 @Override 10520 public Iterator<String> generate(ActivityIntentInfo info) { 10521 return info.schemesIterator(); 10522 } 10523 } 10524 10525 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10526 @Override 10527 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10528 return info.authoritiesIterator(); 10529 } 10530 } 10531 10532 /** 10533 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10534 * MODIFIED. Do not pass in a list that should not be changed. 10535 */ 10536 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10537 IterGenerator<T> generator, Iterator<T> searchIterator) { 10538 // loop through the set of actions; every one must be found in the intent filter 10539 while (searchIterator.hasNext()) { 10540 // we must have at least one filter in the list to consider a match 10541 if (intentList.size() == 0) { 10542 break; 10543 } 10544 10545 final T searchAction = searchIterator.next(); 10546 10547 // loop through the set of intent filters 10548 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10549 while (intentIter.hasNext()) { 10550 final ActivityIntentInfo intentInfo = intentIter.next(); 10551 boolean selectionFound = false; 10552 10553 // loop through the intent filter's selection criteria; at least one 10554 // of them must match the searched criteria 10555 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10556 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10557 final T intentSelection = intentSelectionIter.next(); 10558 if (intentSelection != null && intentSelection.equals(searchAction)) { 10559 selectionFound = true; 10560 break; 10561 } 10562 } 10563 10564 // the selection criteria wasn't found in this filter's set; this filter 10565 // is not a potential match 10566 if (!selectionFound) { 10567 intentIter.remove(); 10568 } 10569 } 10570 } 10571 } 10572 10573 private boolean isProtectedAction(ActivityIntentInfo filter) { 10574 final Iterator<String> actionsIter = filter.actionsIterator(); 10575 while (actionsIter != null && actionsIter.hasNext()) { 10576 final String filterAction = actionsIter.next(); 10577 if (PROTECTED_ACTIONS.contains(filterAction)) { 10578 return true; 10579 } 10580 } 10581 return false; 10582 } 10583 10584 /** 10585 * Adjusts the priority of the given intent filter according to policy. 10586 * <p> 10587 * <ul> 10588 * <li>The priority for non privileged applications is capped to '0'</li> 10589 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10590 * <li>The priority for unbundled updates to privileged applications is capped to the 10591 * priority defined on the system partition</li> 10592 * </ul> 10593 * <p> 10594 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10595 * allowed to obtain any priority on any action. 10596 */ 10597 private void adjustPriority( 10598 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10599 // nothing to do; priority is fine as-is 10600 if (intent.getPriority() <= 0) { 10601 return; 10602 } 10603 10604 final ActivityInfo activityInfo = intent.activity.info; 10605 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10606 10607 final boolean privilegedApp = 10608 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10609 if (!privilegedApp) { 10610 // non-privileged applications can never define a priority >0 10611 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10612 + " package: " + applicationInfo.packageName 10613 + " activity: " + intent.activity.className 10614 + " origPrio: " + intent.getPriority()); 10615 intent.setPriority(0); 10616 return; 10617 } 10618 10619 if (systemActivities == null) { 10620 // the system package is not disabled; we're parsing the system partition 10621 if (isProtectedAction(intent)) { 10622 if (mDeferProtectedFilters) { 10623 // We can't deal with these just yet. No component should ever obtain a 10624 // >0 priority for a protected actions, with ONE exception -- the setup 10625 // wizard. The setup wizard, however, cannot be known until we're able to 10626 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10627 // until all intent filters have been processed. Chicken, meet egg. 10628 // Let the filter temporarily have a high priority and rectify the 10629 // priorities after all system packages have been scanned. 10630 mProtectedFilters.add(intent); 10631 if (DEBUG_FILTERS) { 10632 Slog.i(TAG, "Protected action; save for later;" 10633 + " package: " + applicationInfo.packageName 10634 + " activity: " + intent.activity.className 10635 + " origPrio: " + intent.getPriority()); 10636 } 10637 return; 10638 } else { 10639 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10640 Slog.i(TAG, "No setup wizard;" 10641 + " All protected intents capped to priority 0"); 10642 } 10643 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10644 if (DEBUG_FILTERS) { 10645 Slog.i(TAG, "Found setup wizard;" 10646 + " allow priority " + intent.getPriority() + ";" 10647 + " package: " + intent.activity.info.packageName 10648 + " activity: " + intent.activity.className 10649 + " priority: " + intent.getPriority()); 10650 } 10651 // setup wizard gets whatever it wants 10652 return; 10653 } 10654 Slog.w(TAG, "Protected action; cap priority to 0;" 10655 + " package: " + intent.activity.info.packageName 10656 + " activity: " + intent.activity.className 10657 + " origPrio: " + intent.getPriority()); 10658 intent.setPriority(0); 10659 return; 10660 } 10661 } 10662 // privileged apps on the system image get whatever priority they request 10663 return; 10664 } 10665 10666 // privileged app unbundled update ... try to find the same activity 10667 final PackageParser.Activity foundActivity = 10668 findMatchingActivity(systemActivities, activityInfo); 10669 if (foundActivity == null) { 10670 // this is a new activity; it cannot obtain >0 priority 10671 if (DEBUG_FILTERS) { 10672 Slog.i(TAG, "New activity; cap priority to 0;" 10673 + " package: " + applicationInfo.packageName 10674 + " activity: " + intent.activity.className 10675 + " origPrio: " + intent.getPriority()); 10676 } 10677 intent.setPriority(0); 10678 return; 10679 } 10680 10681 // found activity, now check for filter equivalence 10682 10683 // a shallow copy is enough; we modify the list, not its contents 10684 final List<ActivityIntentInfo> intentListCopy = 10685 new ArrayList<>(foundActivity.intents); 10686 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10687 10688 // find matching action subsets 10689 final Iterator<String> actionsIterator = intent.actionsIterator(); 10690 if (actionsIterator != null) { 10691 getIntentListSubset( 10692 intentListCopy, new ActionIterGenerator(), actionsIterator); 10693 if (intentListCopy.size() == 0) { 10694 // no more intents to match; we're not equivalent 10695 if (DEBUG_FILTERS) { 10696 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10697 + " package: " + applicationInfo.packageName 10698 + " activity: " + intent.activity.className 10699 + " origPrio: " + intent.getPriority()); 10700 } 10701 intent.setPriority(0); 10702 return; 10703 } 10704 } 10705 10706 // find matching category subsets 10707 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10708 if (categoriesIterator != null) { 10709 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10710 categoriesIterator); 10711 if (intentListCopy.size() == 0) { 10712 // no more intents to match; we're not equivalent 10713 if (DEBUG_FILTERS) { 10714 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10715 + " package: " + applicationInfo.packageName 10716 + " activity: " + intent.activity.className 10717 + " origPrio: " + intent.getPriority()); 10718 } 10719 intent.setPriority(0); 10720 return; 10721 } 10722 } 10723 10724 // find matching schemes subsets 10725 final Iterator<String> schemesIterator = intent.schemesIterator(); 10726 if (schemesIterator != null) { 10727 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10728 schemesIterator); 10729 if (intentListCopy.size() == 0) { 10730 // no more intents to match; we're not equivalent 10731 if (DEBUG_FILTERS) { 10732 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10733 + " package: " + applicationInfo.packageName 10734 + " activity: " + intent.activity.className 10735 + " origPrio: " + intent.getPriority()); 10736 } 10737 intent.setPriority(0); 10738 return; 10739 } 10740 } 10741 10742 // find matching authorities subsets 10743 final Iterator<IntentFilter.AuthorityEntry> 10744 authoritiesIterator = intent.authoritiesIterator(); 10745 if (authoritiesIterator != null) { 10746 getIntentListSubset(intentListCopy, 10747 new AuthoritiesIterGenerator(), 10748 authoritiesIterator); 10749 if (intentListCopy.size() == 0) { 10750 // no more intents to match; we're not equivalent 10751 if (DEBUG_FILTERS) { 10752 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10753 + " package: " + applicationInfo.packageName 10754 + " activity: " + intent.activity.className 10755 + " origPrio: " + intent.getPriority()); 10756 } 10757 intent.setPriority(0); 10758 return; 10759 } 10760 } 10761 10762 // we found matching filter(s); app gets the max priority of all intents 10763 int cappedPriority = 0; 10764 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10765 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10766 } 10767 if (intent.getPriority() > cappedPriority) { 10768 if (DEBUG_FILTERS) { 10769 Slog.i(TAG, "Found matching filter(s);" 10770 + " cap priority to " + cappedPriority + ";" 10771 + " package: " + applicationInfo.packageName 10772 + " activity: " + intent.activity.className 10773 + " origPrio: " + intent.getPriority()); 10774 } 10775 intent.setPriority(cappedPriority); 10776 return; 10777 } 10778 // all this for nothing; the requested priority was <= what was on the system 10779 } 10780 10781 public final void addActivity(PackageParser.Activity a, String type) { 10782 mActivities.put(a.getComponentName(), a); 10783 if (DEBUG_SHOW_INFO) 10784 Log.v( 10785 TAG, " " + type + " " + 10786 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10787 if (DEBUG_SHOW_INFO) 10788 Log.v(TAG, " Class=" + a.info.name); 10789 final int NI = a.intents.size(); 10790 for (int j=0; j<NI; j++) { 10791 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10792 if ("activity".equals(type)) { 10793 final PackageSetting ps = 10794 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10795 final List<PackageParser.Activity> systemActivities = 10796 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10797 adjustPriority(systemActivities, intent); 10798 } 10799 if (DEBUG_SHOW_INFO) { 10800 Log.v(TAG, " IntentFilter:"); 10801 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10802 } 10803 if (!intent.debugCheck()) { 10804 Log.w(TAG, "==> For Activity " + a.info.name); 10805 } 10806 addFilter(intent); 10807 } 10808 } 10809 10810 public final void removeActivity(PackageParser.Activity a, String type) { 10811 mActivities.remove(a.getComponentName()); 10812 if (DEBUG_SHOW_INFO) { 10813 Log.v(TAG, " " + type + " " 10814 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10815 : a.info.name) + ":"); 10816 Log.v(TAG, " Class=" + a.info.name); 10817 } 10818 final int NI = a.intents.size(); 10819 for (int j=0; j<NI; j++) { 10820 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10821 if (DEBUG_SHOW_INFO) { 10822 Log.v(TAG, " IntentFilter:"); 10823 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10824 } 10825 removeFilter(intent); 10826 } 10827 } 10828 10829 @Override 10830 protected boolean allowFilterResult( 10831 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10832 ActivityInfo filterAi = filter.activity.info; 10833 for (int i=dest.size()-1; i>=0; i--) { 10834 ActivityInfo destAi = dest.get(i).activityInfo; 10835 if (destAi.name == filterAi.name 10836 && destAi.packageName == filterAi.packageName) { 10837 return false; 10838 } 10839 } 10840 return true; 10841 } 10842 10843 @Override 10844 protected ActivityIntentInfo[] newArray(int size) { 10845 return new ActivityIntentInfo[size]; 10846 } 10847 10848 @Override 10849 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10850 if (!sUserManager.exists(userId)) return true; 10851 PackageParser.Package p = filter.activity.owner; 10852 if (p != null) { 10853 PackageSetting ps = (PackageSetting)p.mExtras; 10854 if (ps != null) { 10855 // System apps are never considered stopped for purposes of 10856 // filtering, because there may be no way for the user to 10857 // actually re-launch them. 10858 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10859 && ps.getStopped(userId); 10860 } 10861 } 10862 return false; 10863 } 10864 10865 @Override 10866 protected boolean isPackageForFilter(String packageName, 10867 PackageParser.ActivityIntentInfo info) { 10868 return packageName.equals(info.activity.owner.packageName); 10869 } 10870 10871 @Override 10872 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10873 int match, int userId) { 10874 if (!sUserManager.exists(userId)) return null; 10875 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10876 return null; 10877 } 10878 final PackageParser.Activity activity = info.activity; 10879 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10880 if (ps == null) { 10881 return null; 10882 } 10883 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10884 ps.readUserState(userId), userId); 10885 if (ai == null) { 10886 return null; 10887 } 10888 final ResolveInfo res = new ResolveInfo(); 10889 res.activityInfo = ai; 10890 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10891 res.filter = info; 10892 } 10893 if (info != null) { 10894 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10895 } 10896 res.priority = info.getPriority(); 10897 res.preferredOrder = activity.owner.mPreferredOrder; 10898 //System.out.println("Result: " + res.activityInfo.className + 10899 // " = " + res.priority); 10900 res.match = match; 10901 res.isDefault = info.hasDefault; 10902 res.labelRes = info.labelRes; 10903 res.nonLocalizedLabel = info.nonLocalizedLabel; 10904 if (userNeedsBadging(userId)) { 10905 res.noResourceId = true; 10906 } else { 10907 res.icon = info.icon; 10908 } 10909 res.iconResourceId = info.icon; 10910 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10911 return res; 10912 } 10913 10914 @Override 10915 protected void sortResults(List<ResolveInfo> results) { 10916 Collections.sort(results, mResolvePrioritySorter); 10917 } 10918 10919 @Override 10920 protected void dumpFilter(PrintWriter out, String prefix, 10921 PackageParser.ActivityIntentInfo filter) { 10922 out.print(prefix); out.print( 10923 Integer.toHexString(System.identityHashCode(filter.activity))); 10924 out.print(' '); 10925 filter.activity.printComponentShortName(out); 10926 out.print(" filter "); 10927 out.println(Integer.toHexString(System.identityHashCode(filter))); 10928 } 10929 10930 @Override 10931 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10932 return filter.activity; 10933 } 10934 10935 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10936 PackageParser.Activity activity = (PackageParser.Activity)label; 10937 out.print(prefix); out.print( 10938 Integer.toHexString(System.identityHashCode(activity))); 10939 out.print(' '); 10940 activity.printComponentShortName(out); 10941 if (count > 1) { 10942 out.print(" ("); out.print(count); out.print(" filters)"); 10943 } 10944 out.println(); 10945 } 10946 10947 // Keys are String (activity class name), values are Activity. 10948 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10949 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10950 private int mFlags; 10951 } 10952 10953 private final class ServiceIntentResolver 10954 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10955 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10956 boolean defaultOnly, int userId) { 10957 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10958 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10959 } 10960 10961 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10962 int userId) { 10963 if (!sUserManager.exists(userId)) return null; 10964 mFlags = flags; 10965 return super.queryIntent(intent, resolvedType, 10966 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10967 } 10968 10969 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10970 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10971 if (!sUserManager.exists(userId)) return null; 10972 if (packageServices == null) { 10973 return null; 10974 } 10975 mFlags = flags; 10976 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10977 final int N = packageServices.size(); 10978 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10979 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10980 10981 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10982 for (int i = 0; i < N; ++i) { 10983 intentFilters = packageServices.get(i).intents; 10984 if (intentFilters != null && intentFilters.size() > 0) { 10985 PackageParser.ServiceIntentInfo[] array = 10986 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10987 intentFilters.toArray(array); 10988 listCut.add(array); 10989 } 10990 } 10991 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10992 } 10993 10994 public final void addService(PackageParser.Service s) { 10995 mServices.put(s.getComponentName(), s); 10996 if (DEBUG_SHOW_INFO) { 10997 Log.v(TAG, " " 10998 + (s.info.nonLocalizedLabel != null 10999 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11000 Log.v(TAG, " Class=" + s.info.name); 11001 } 11002 final int NI = s.intents.size(); 11003 int j; 11004 for (j=0; j<NI; j++) { 11005 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11006 if (DEBUG_SHOW_INFO) { 11007 Log.v(TAG, " IntentFilter:"); 11008 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11009 } 11010 if (!intent.debugCheck()) { 11011 Log.w(TAG, "==> For Service " + s.info.name); 11012 } 11013 addFilter(intent); 11014 } 11015 } 11016 11017 public final void removeService(PackageParser.Service s) { 11018 mServices.remove(s.getComponentName()); 11019 if (DEBUG_SHOW_INFO) { 11020 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11021 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11022 Log.v(TAG, " Class=" + s.info.name); 11023 } 11024 final int NI = s.intents.size(); 11025 int j; 11026 for (j=0; j<NI; j++) { 11027 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11028 if (DEBUG_SHOW_INFO) { 11029 Log.v(TAG, " IntentFilter:"); 11030 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11031 } 11032 removeFilter(intent); 11033 } 11034 } 11035 11036 @Override 11037 protected boolean allowFilterResult( 11038 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11039 ServiceInfo filterSi = filter.service.info; 11040 for (int i=dest.size()-1; i>=0; i--) { 11041 ServiceInfo destAi = dest.get(i).serviceInfo; 11042 if (destAi.name == filterSi.name 11043 && destAi.packageName == filterSi.packageName) { 11044 return false; 11045 } 11046 } 11047 return true; 11048 } 11049 11050 @Override 11051 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11052 return new PackageParser.ServiceIntentInfo[size]; 11053 } 11054 11055 @Override 11056 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11057 if (!sUserManager.exists(userId)) return true; 11058 PackageParser.Package p = filter.service.owner; 11059 if (p != null) { 11060 PackageSetting ps = (PackageSetting)p.mExtras; 11061 if (ps != null) { 11062 // System apps are never considered stopped for purposes of 11063 // filtering, because there may be no way for the user to 11064 // actually re-launch them. 11065 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11066 && ps.getStopped(userId); 11067 } 11068 } 11069 return false; 11070 } 11071 11072 @Override 11073 protected boolean isPackageForFilter(String packageName, 11074 PackageParser.ServiceIntentInfo info) { 11075 return packageName.equals(info.service.owner.packageName); 11076 } 11077 11078 @Override 11079 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11080 int match, int userId) { 11081 if (!sUserManager.exists(userId)) return null; 11082 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11083 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11084 return null; 11085 } 11086 final PackageParser.Service service = info.service; 11087 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11088 if (ps == null) { 11089 return null; 11090 } 11091 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11092 ps.readUserState(userId), userId); 11093 if (si == null) { 11094 return null; 11095 } 11096 final ResolveInfo res = new ResolveInfo(); 11097 res.serviceInfo = si; 11098 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11099 res.filter = filter; 11100 } 11101 res.priority = info.getPriority(); 11102 res.preferredOrder = service.owner.mPreferredOrder; 11103 res.match = match; 11104 res.isDefault = info.hasDefault; 11105 res.labelRes = info.labelRes; 11106 res.nonLocalizedLabel = info.nonLocalizedLabel; 11107 res.icon = info.icon; 11108 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11109 return res; 11110 } 11111 11112 @Override 11113 protected void sortResults(List<ResolveInfo> results) { 11114 Collections.sort(results, mResolvePrioritySorter); 11115 } 11116 11117 @Override 11118 protected void dumpFilter(PrintWriter out, String prefix, 11119 PackageParser.ServiceIntentInfo filter) { 11120 out.print(prefix); out.print( 11121 Integer.toHexString(System.identityHashCode(filter.service))); 11122 out.print(' '); 11123 filter.service.printComponentShortName(out); 11124 out.print(" filter "); 11125 out.println(Integer.toHexString(System.identityHashCode(filter))); 11126 } 11127 11128 @Override 11129 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11130 return filter.service; 11131 } 11132 11133 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11134 PackageParser.Service service = (PackageParser.Service)label; 11135 out.print(prefix); out.print( 11136 Integer.toHexString(System.identityHashCode(service))); 11137 out.print(' '); 11138 service.printComponentShortName(out); 11139 if (count > 1) { 11140 out.print(" ("); out.print(count); out.print(" filters)"); 11141 } 11142 out.println(); 11143 } 11144 11145// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11146// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11147// final List<ResolveInfo> retList = Lists.newArrayList(); 11148// while (i.hasNext()) { 11149// final ResolveInfo resolveInfo = (ResolveInfo) i; 11150// if (isEnabledLP(resolveInfo.serviceInfo)) { 11151// retList.add(resolveInfo); 11152// } 11153// } 11154// return retList; 11155// } 11156 11157 // Keys are String (activity class name), values are Activity. 11158 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11159 = new ArrayMap<ComponentName, PackageParser.Service>(); 11160 private int mFlags; 11161 }; 11162 11163 private final class ProviderIntentResolver 11164 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11165 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11166 boolean defaultOnly, int userId) { 11167 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11168 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11169 } 11170 11171 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11172 int userId) { 11173 if (!sUserManager.exists(userId)) 11174 return null; 11175 mFlags = flags; 11176 return super.queryIntent(intent, resolvedType, 11177 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11178 } 11179 11180 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11181 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11182 if (!sUserManager.exists(userId)) 11183 return null; 11184 if (packageProviders == null) { 11185 return null; 11186 } 11187 mFlags = flags; 11188 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11189 final int N = packageProviders.size(); 11190 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11191 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11192 11193 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11194 for (int i = 0; i < N; ++i) { 11195 intentFilters = packageProviders.get(i).intents; 11196 if (intentFilters != null && intentFilters.size() > 0) { 11197 PackageParser.ProviderIntentInfo[] array = 11198 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11199 intentFilters.toArray(array); 11200 listCut.add(array); 11201 } 11202 } 11203 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11204 } 11205 11206 public final void addProvider(PackageParser.Provider p) { 11207 if (mProviders.containsKey(p.getComponentName())) { 11208 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11209 return; 11210 } 11211 11212 mProviders.put(p.getComponentName(), p); 11213 if (DEBUG_SHOW_INFO) { 11214 Log.v(TAG, " " 11215 + (p.info.nonLocalizedLabel != null 11216 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11217 Log.v(TAG, " Class=" + p.info.name); 11218 } 11219 final int NI = p.intents.size(); 11220 int j; 11221 for (j = 0; j < NI; j++) { 11222 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11223 if (DEBUG_SHOW_INFO) { 11224 Log.v(TAG, " IntentFilter:"); 11225 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11226 } 11227 if (!intent.debugCheck()) { 11228 Log.w(TAG, "==> For Provider " + p.info.name); 11229 } 11230 addFilter(intent); 11231 } 11232 } 11233 11234 public final void removeProvider(PackageParser.Provider p) { 11235 mProviders.remove(p.getComponentName()); 11236 if (DEBUG_SHOW_INFO) { 11237 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11238 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11239 Log.v(TAG, " Class=" + p.info.name); 11240 } 11241 final int NI = p.intents.size(); 11242 int j; 11243 for (j = 0; j < NI; j++) { 11244 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11245 if (DEBUG_SHOW_INFO) { 11246 Log.v(TAG, " IntentFilter:"); 11247 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11248 } 11249 removeFilter(intent); 11250 } 11251 } 11252 11253 @Override 11254 protected boolean allowFilterResult( 11255 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11256 ProviderInfo filterPi = filter.provider.info; 11257 for (int i = dest.size() - 1; i >= 0; i--) { 11258 ProviderInfo destPi = dest.get(i).providerInfo; 11259 if (destPi.name == filterPi.name 11260 && destPi.packageName == filterPi.packageName) { 11261 return false; 11262 } 11263 } 11264 return true; 11265 } 11266 11267 @Override 11268 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11269 return new PackageParser.ProviderIntentInfo[size]; 11270 } 11271 11272 @Override 11273 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11274 if (!sUserManager.exists(userId)) 11275 return true; 11276 PackageParser.Package p = filter.provider.owner; 11277 if (p != null) { 11278 PackageSetting ps = (PackageSetting) p.mExtras; 11279 if (ps != null) { 11280 // System apps are never considered stopped for purposes of 11281 // filtering, because there may be no way for the user to 11282 // actually re-launch them. 11283 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11284 && ps.getStopped(userId); 11285 } 11286 } 11287 return false; 11288 } 11289 11290 @Override 11291 protected boolean isPackageForFilter(String packageName, 11292 PackageParser.ProviderIntentInfo info) { 11293 return packageName.equals(info.provider.owner.packageName); 11294 } 11295 11296 @Override 11297 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11298 int match, int userId) { 11299 if (!sUserManager.exists(userId)) 11300 return null; 11301 final PackageParser.ProviderIntentInfo info = filter; 11302 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11303 return null; 11304 } 11305 final PackageParser.Provider provider = info.provider; 11306 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11307 if (ps == null) { 11308 return null; 11309 } 11310 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11311 ps.readUserState(userId), userId); 11312 if (pi == null) { 11313 return null; 11314 } 11315 final ResolveInfo res = new ResolveInfo(); 11316 res.providerInfo = pi; 11317 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11318 res.filter = filter; 11319 } 11320 res.priority = info.getPriority(); 11321 res.preferredOrder = provider.owner.mPreferredOrder; 11322 res.match = match; 11323 res.isDefault = info.hasDefault; 11324 res.labelRes = info.labelRes; 11325 res.nonLocalizedLabel = info.nonLocalizedLabel; 11326 res.icon = info.icon; 11327 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11328 return res; 11329 } 11330 11331 @Override 11332 protected void sortResults(List<ResolveInfo> results) { 11333 Collections.sort(results, mResolvePrioritySorter); 11334 } 11335 11336 @Override 11337 protected void dumpFilter(PrintWriter out, String prefix, 11338 PackageParser.ProviderIntentInfo filter) { 11339 out.print(prefix); 11340 out.print( 11341 Integer.toHexString(System.identityHashCode(filter.provider))); 11342 out.print(' '); 11343 filter.provider.printComponentShortName(out); 11344 out.print(" filter "); 11345 out.println(Integer.toHexString(System.identityHashCode(filter))); 11346 } 11347 11348 @Override 11349 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11350 return filter.provider; 11351 } 11352 11353 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11354 PackageParser.Provider provider = (PackageParser.Provider)label; 11355 out.print(prefix); out.print( 11356 Integer.toHexString(System.identityHashCode(provider))); 11357 out.print(' '); 11358 provider.printComponentShortName(out); 11359 if (count > 1) { 11360 out.print(" ("); out.print(count); out.print(" filters)"); 11361 } 11362 out.println(); 11363 } 11364 11365 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11366 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11367 private int mFlags; 11368 } 11369 11370 private static final class EphemeralIntentResolver 11371 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11372 @Override 11373 protected EphemeralResolveIntentInfo[] newArray(int size) { 11374 return new EphemeralResolveIntentInfo[size]; 11375 } 11376 11377 @Override 11378 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11379 return true; 11380 } 11381 11382 @Override 11383 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11384 int userId) { 11385 if (!sUserManager.exists(userId)) { 11386 return null; 11387 } 11388 return info.getEphemeralResolveInfo(); 11389 } 11390 } 11391 11392 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11393 new Comparator<ResolveInfo>() { 11394 public int compare(ResolveInfo r1, ResolveInfo r2) { 11395 int v1 = r1.priority; 11396 int v2 = r2.priority; 11397 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11398 if (v1 != v2) { 11399 return (v1 > v2) ? -1 : 1; 11400 } 11401 v1 = r1.preferredOrder; 11402 v2 = r2.preferredOrder; 11403 if (v1 != v2) { 11404 return (v1 > v2) ? -1 : 1; 11405 } 11406 if (r1.isDefault != r2.isDefault) { 11407 return r1.isDefault ? -1 : 1; 11408 } 11409 v1 = r1.match; 11410 v2 = r2.match; 11411 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11412 if (v1 != v2) { 11413 return (v1 > v2) ? -1 : 1; 11414 } 11415 if (r1.system != r2.system) { 11416 return r1.system ? -1 : 1; 11417 } 11418 if (r1.activityInfo != null) { 11419 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11420 } 11421 if (r1.serviceInfo != null) { 11422 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11423 } 11424 if (r1.providerInfo != null) { 11425 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11426 } 11427 return 0; 11428 } 11429 }; 11430 11431 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11432 new Comparator<ProviderInfo>() { 11433 public int compare(ProviderInfo p1, ProviderInfo p2) { 11434 final int v1 = p1.initOrder; 11435 final int v2 = p2.initOrder; 11436 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11437 } 11438 }; 11439 11440 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11441 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11442 final int[] userIds) { 11443 mHandler.post(new Runnable() { 11444 @Override 11445 public void run() { 11446 try { 11447 final IActivityManager am = ActivityManagerNative.getDefault(); 11448 if (am == null) return; 11449 final int[] resolvedUserIds; 11450 if (userIds == null) { 11451 resolvedUserIds = am.getRunningUserIds(); 11452 } else { 11453 resolvedUserIds = userIds; 11454 } 11455 for (int id : resolvedUserIds) { 11456 final Intent intent = new Intent(action, 11457 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11458 if (extras != null) { 11459 intent.putExtras(extras); 11460 } 11461 if (targetPkg != null) { 11462 intent.setPackage(targetPkg); 11463 } 11464 // Modify the UID when posting to other users 11465 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11466 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11467 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11468 intent.putExtra(Intent.EXTRA_UID, uid); 11469 } 11470 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11471 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11472 if (DEBUG_BROADCASTS) { 11473 RuntimeException here = new RuntimeException("here"); 11474 here.fillInStackTrace(); 11475 Slog.d(TAG, "Sending to user " + id + ": " 11476 + intent.toShortString(false, true, false, false) 11477 + " " + intent.getExtras(), here); 11478 } 11479 am.broadcastIntent(null, intent, null, finishedReceiver, 11480 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11481 null, finishedReceiver != null, false, id); 11482 } 11483 } catch (RemoteException ex) { 11484 } 11485 } 11486 }); 11487 } 11488 11489 /** 11490 * Check if the external storage media is available. This is true if there 11491 * is a mounted external storage medium or if the external storage is 11492 * emulated. 11493 */ 11494 private boolean isExternalMediaAvailable() { 11495 return mMediaMounted || Environment.isExternalStorageEmulated(); 11496 } 11497 11498 @Override 11499 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11500 // writer 11501 synchronized (mPackages) { 11502 if (!isExternalMediaAvailable()) { 11503 // If the external storage is no longer mounted at this point, 11504 // the caller may not have been able to delete all of this 11505 // packages files and can not delete any more. Bail. 11506 return null; 11507 } 11508 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11509 if (lastPackage != null) { 11510 pkgs.remove(lastPackage); 11511 } 11512 if (pkgs.size() > 0) { 11513 return pkgs.get(0); 11514 } 11515 } 11516 return null; 11517 } 11518 11519 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11520 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11521 userId, andCode ? 1 : 0, packageName); 11522 if (mSystemReady) { 11523 msg.sendToTarget(); 11524 } else { 11525 if (mPostSystemReadyMessages == null) { 11526 mPostSystemReadyMessages = new ArrayList<>(); 11527 } 11528 mPostSystemReadyMessages.add(msg); 11529 } 11530 } 11531 11532 void startCleaningPackages() { 11533 // reader 11534 if (!isExternalMediaAvailable()) { 11535 return; 11536 } 11537 synchronized (mPackages) { 11538 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11539 return; 11540 } 11541 } 11542 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11543 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11544 IActivityManager am = ActivityManagerNative.getDefault(); 11545 if (am != null) { 11546 try { 11547 am.startService(null, intent, null, mContext.getOpPackageName(), 11548 UserHandle.USER_SYSTEM); 11549 } catch (RemoteException e) { 11550 } 11551 } 11552 } 11553 11554 @Override 11555 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11556 int installFlags, String installerPackageName, int userId) { 11557 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11558 11559 final int callingUid = Binder.getCallingUid(); 11560 enforceCrossUserPermission(callingUid, userId, 11561 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11562 11563 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11564 try { 11565 if (observer != null) { 11566 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11567 } 11568 } catch (RemoteException re) { 11569 } 11570 return; 11571 } 11572 11573 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11574 installFlags |= PackageManager.INSTALL_FROM_ADB; 11575 11576 } else { 11577 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11578 // about installerPackageName. 11579 11580 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11581 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11582 } 11583 11584 UserHandle user; 11585 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11586 user = UserHandle.ALL; 11587 } else { 11588 user = new UserHandle(userId); 11589 } 11590 11591 // Only system components can circumvent runtime permissions when installing. 11592 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11593 && mContext.checkCallingOrSelfPermission(Manifest.permission 11594 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11595 throw new SecurityException("You need the " 11596 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11597 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11598 } 11599 11600 final File originFile = new File(originPath); 11601 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11602 11603 final Message msg = mHandler.obtainMessage(INIT_COPY); 11604 final VerificationInfo verificationInfo = new VerificationInfo( 11605 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11606 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11607 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11608 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11609 null /*certificates*/); 11610 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11611 msg.obj = params; 11612 11613 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11614 System.identityHashCode(msg.obj)); 11615 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11616 System.identityHashCode(msg.obj)); 11617 11618 mHandler.sendMessage(msg); 11619 } 11620 11621 void installStage(String packageName, File stagedDir, String stagedCid, 11622 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11623 String installerPackageName, int installerUid, UserHandle user, 11624 Certificate[][] certificates) { 11625 if (DEBUG_EPHEMERAL) { 11626 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11627 Slog.d(TAG, "Ephemeral install of " + packageName); 11628 } 11629 } 11630 final VerificationInfo verificationInfo = new VerificationInfo( 11631 sessionParams.originatingUri, sessionParams.referrerUri, 11632 sessionParams.originatingUid, installerUid); 11633 11634 final OriginInfo origin; 11635 if (stagedDir != null) { 11636 origin = OriginInfo.fromStagedFile(stagedDir); 11637 } else { 11638 origin = OriginInfo.fromStagedContainer(stagedCid); 11639 } 11640 11641 final Message msg = mHandler.obtainMessage(INIT_COPY); 11642 final InstallParams params = new InstallParams(origin, null, observer, 11643 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11644 verificationInfo, user, sessionParams.abiOverride, 11645 sessionParams.grantedRuntimePermissions, certificates); 11646 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11647 msg.obj = params; 11648 11649 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11650 System.identityHashCode(msg.obj)); 11651 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11652 System.identityHashCode(msg.obj)); 11653 11654 mHandler.sendMessage(msg); 11655 } 11656 11657 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11658 int userId) { 11659 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11660 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11661 } 11662 11663 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11664 int appId, int userId) { 11665 Bundle extras = new Bundle(1); 11666 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11667 11668 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11669 packageName, extras, 0, null, null, new int[] {userId}); 11670 try { 11671 IActivityManager am = ActivityManagerNative.getDefault(); 11672 if (isSystem && am.isUserRunning(userId, 0)) { 11673 // The just-installed/enabled app is bundled on the system, so presumed 11674 // to be able to run automatically without needing an explicit launch. 11675 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11676 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11677 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11678 .setPackage(packageName); 11679 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11680 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11681 } 11682 } catch (RemoteException e) { 11683 // shouldn't happen 11684 Slog.w(TAG, "Unable to bootstrap installed package", e); 11685 } 11686 } 11687 11688 @Override 11689 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11690 int userId) { 11691 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11692 PackageSetting pkgSetting; 11693 final int uid = Binder.getCallingUid(); 11694 enforceCrossUserPermission(uid, userId, 11695 true /* requireFullPermission */, true /* checkShell */, 11696 "setApplicationHiddenSetting for user " + userId); 11697 11698 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11699 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11700 return false; 11701 } 11702 11703 long callingId = Binder.clearCallingIdentity(); 11704 try { 11705 boolean sendAdded = false; 11706 boolean sendRemoved = false; 11707 // writer 11708 synchronized (mPackages) { 11709 pkgSetting = mSettings.mPackages.get(packageName); 11710 if (pkgSetting == null) { 11711 return false; 11712 } 11713 // Only allow protected packages to hide themselves. 11714 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11715 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11716 Slog.w(TAG, "Not hiding protected package: " + packageName); 11717 return false; 11718 } 11719 if (pkgSetting.getHidden(userId) != hidden) { 11720 pkgSetting.setHidden(hidden, userId); 11721 mSettings.writePackageRestrictionsLPr(userId); 11722 if (hidden) { 11723 sendRemoved = true; 11724 } else { 11725 sendAdded = true; 11726 } 11727 } 11728 } 11729 if (sendAdded) { 11730 sendPackageAddedForUser(packageName, pkgSetting, userId); 11731 return true; 11732 } 11733 if (sendRemoved) { 11734 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11735 "hiding pkg"); 11736 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11737 return true; 11738 } 11739 } finally { 11740 Binder.restoreCallingIdentity(callingId); 11741 } 11742 return false; 11743 } 11744 11745 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11746 int userId) { 11747 final PackageRemovedInfo info = new PackageRemovedInfo(); 11748 info.removedPackage = packageName; 11749 info.removedUsers = new int[] {userId}; 11750 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11751 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11752 } 11753 11754 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11755 if (pkgList.length > 0) { 11756 Bundle extras = new Bundle(1); 11757 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11758 11759 sendPackageBroadcast( 11760 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11761 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11762 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11763 new int[] {userId}); 11764 } 11765 } 11766 11767 /** 11768 * Returns true if application is not found or there was an error. Otherwise it returns 11769 * the hidden state of the package for the given user. 11770 */ 11771 @Override 11772 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11773 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11774 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11775 true /* requireFullPermission */, false /* checkShell */, 11776 "getApplicationHidden for user " + userId); 11777 PackageSetting pkgSetting; 11778 long callingId = Binder.clearCallingIdentity(); 11779 try { 11780 // writer 11781 synchronized (mPackages) { 11782 pkgSetting = mSettings.mPackages.get(packageName); 11783 if (pkgSetting == null) { 11784 return true; 11785 } 11786 return pkgSetting.getHidden(userId); 11787 } 11788 } finally { 11789 Binder.restoreCallingIdentity(callingId); 11790 } 11791 } 11792 11793 /** 11794 * @hide 11795 */ 11796 @Override 11797 public int installExistingPackageAsUser(String packageName, int userId) { 11798 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11799 null); 11800 PackageSetting pkgSetting; 11801 final int uid = Binder.getCallingUid(); 11802 enforceCrossUserPermission(uid, userId, 11803 true /* requireFullPermission */, true /* checkShell */, 11804 "installExistingPackage for user " + userId); 11805 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11806 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11807 } 11808 11809 long callingId = Binder.clearCallingIdentity(); 11810 try { 11811 boolean installed = false; 11812 11813 // writer 11814 synchronized (mPackages) { 11815 pkgSetting = mSettings.mPackages.get(packageName); 11816 if (pkgSetting == null) { 11817 return PackageManager.INSTALL_FAILED_INVALID_URI; 11818 } 11819 if (!pkgSetting.getInstalled(userId)) { 11820 pkgSetting.setInstalled(true, userId); 11821 pkgSetting.setHidden(false, userId); 11822 mSettings.writePackageRestrictionsLPr(userId); 11823 installed = true; 11824 } 11825 } 11826 11827 if (installed) { 11828 if (pkgSetting.pkg != null) { 11829 synchronized (mInstallLock) { 11830 // We don't need to freeze for a brand new install 11831 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11832 } 11833 } 11834 sendPackageAddedForUser(packageName, pkgSetting, userId); 11835 } 11836 } finally { 11837 Binder.restoreCallingIdentity(callingId); 11838 } 11839 11840 return PackageManager.INSTALL_SUCCEEDED; 11841 } 11842 11843 boolean isUserRestricted(int userId, String restrictionKey) { 11844 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11845 if (restrictions.getBoolean(restrictionKey, false)) { 11846 Log.w(TAG, "User is restricted: " + restrictionKey); 11847 return true; 11848 } 11849 return false; 11850 } 11851 11852 @Override 11853 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11854 int userId) { 11855 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11856 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11857 true /* requireFullPermission */, true /* checkShell */, 11858 "setPackagesSuspended for user " + userId); 11859 11860 if (ArrayUtils.isEmpty(packageNames)) { 11861 return packageNames; 11862 } 11863 11864 // List of package names for whom the suspended state has changed. 11865 List<String> changedPackages = new ArrayList<>(packageNames.length); 11866 // List of package names for whom the suspended state is not set as requested in this 11867 // method. 11868 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11869 long callingId = Binder.clearCallingIdentity(); 11870 try { 11871 for (int i = 0; i < packageNames.length; i++) { 11872 String packageName = packageNames[i]; 11873 boolean changed = false; 11874 final int appId; 11875 synchronized (mPackages) { 11876 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11877 if (pkgSetting == null) { 11878 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11879 + "\". Skipping suspending/un-suspending."); 11880 unactionedPackages.add(packageName); 11881 continue; 11882 } 11883 appId = pkgSetting.appId; 11884 if (pkgSetting.getSuspended(userId) != suspended) { 11885 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11886 unactionedPackages.add(packageName); 11887 continue; 11888 } 11889 pkgSetting.setSuspended(suspended, userId); 11890 mSettings.writePackageRestrictionsLPr(userId); 11891 changed = true; 11892 changedPackages.add(packageName); 11893 } 11894 } 11895 11896 if (changed && suspended) { 11897 killApplication(packageName, UserHandle.getUid(userId, appId), 11898 "suspending package"); 11899 } 11900 } 11901 } finally { 11902 Binder.restoreCallingIdentity(callingId); 11903 } 11904 11905 if (!changedPackages.isEmpty()) { 11906 sendPackagesSuspendedForUser(changedPackages.toArray( 11907 new String[changedPackages.size()]), userId, suspended); 11908 } 11909 11910 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11911 } 11912 11913 @Override 11914 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11915 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11916 true /* requireFullPermission */, false /* checkShell */, 11917 "isPackageSuspendedForUser for user " + userId); 11918 synchronized (mPackages) { 11919 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11920 if (pkgSetting == null) { 11921 throw new IllegalArgumentException("Unknown target package: " + packageName); 11922 } 11923 return pkgSetting.getSuspended(userId); 11924 } 11925 } 11926 11927 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11928 if (isPackageDeviceAdmin(packageName, userId)) { 11929 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11930 + "\": has an active device admin"); 11931 return false; 11932 } 11933 11934 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11935 if (packageName.equals(activeLauncherPackageName)) { 11936 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11937 + "\": contains the active launcher"); 11938 return false; 11939 } 11940 11941 if (packageName.equals(mRequiredInstallerPackage)) { 11942 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11943 + "\": required for package installation"); 11944 return false; 11945 } 11946 11947 if (packageName.equals(mRequiredVerifierPackage)) { 11948 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11949 + "\": required for package verification"); 11950 return false; 11951 } 11952 11953 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11954 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11955 + "\": is the default dialer"); 11956 return false; 11957 } 11958 11959 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11960 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11961 + "\": protected package"); 11962 return false; 11963 } 11964 11965 return true; 11966 } 11967 11968 private String getActiveLauncherPackageName(int userId) { 11969 Intent intent = new Intent(Intent.ACTION_MAIN); 11970 intent.addCategory(Intent.CATEGORY_HOME); 11971 ResolveInfo resolveInfo = resolveIntent( 11972 intent, 11973 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11974 PackageManager.MATCH_DEFAULT_ONLY, 11975 userId); 11976 11977 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11978 } 11979 11980 private String getDefaultDialerPackageName(int userId) { 11981 synchronized (mPackages) { 11982 return mSettings.getDefaultDialerPackageNameLPw(userId); 11983 } 11984 } 11985 11986 @Override 11987 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11988 mContext.enforceCallingOrSelfPermission( 11989 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11990 "Only package verification agents can verify applications"); 11991 11992 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11993 final PackageVerificationResponse response = new PackageVerificationResponse( 11994 verificationCode, Binder.getCallingUid()); 11995 msg.arg1 = id; 11996 msg.obj = response; 11997 mHandler.sendMessage(msg); 11998 } 11999 12000 @Override 12001 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12002 long millisecondsToDelay) { 12003 mContext.enforceCallingOrSelfPermission( 12004 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12005 "Only package verification agents can extend verification timeouts"); 12006 12007 final PackageVerificationState state = mPendingVerification.get(id); 12008 final PackageVerificationResponse response = new PackageVerificationResponse( 12009 verificationCodeAtTimeout, Binder.getCallingUid()); 12010 12011 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12012 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12013 } 12014 if (millisecondsToDelay < 0) { 12015 millisecondsToDelay = 0; 12016 } 12017 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12018 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12019 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12020 } 12021 12022 if ((state != null) && !state.timeoutExtended()) { 12023 state.extendTimeout(); 12024 12025 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12026 msg.arg1 = id; 12027 msg.obj = response; 12028 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12029 } 12030 } 12031 12032 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12033 int verificationCode, UserHandle user) { 12034 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12035 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12036 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12037 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12038 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12039 12040 mContext.sendBroadcastAsUser(intent, user, 12041 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12042 } 12043 12044 private ComponentName matchComponentForVerifier(String packageName, 12045 List<ResolveInfo> receivers) { 12046 ActivityInfo targetReceiver = null; 12047 12048 final int NR = receivers.size(); 12049 for (int i = 0; i < NR; i++) { 12050 final ResolveInfo info = receivers.get(i); 12051 if (info.activityInfo == null) { 12052 continue; 12053 } 12054 12055 if (packageName.equals(info.activityInfo.packageName)) { 12056 targetReceiver = info.activityInfo; 12057 break; 12058 } 12059 } 12060 12061 if (targetReceiver == null) { 12062 return null; 12063 } 12064 12065 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12066 } 12067 12068 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12069 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12070 if (pkgInfo.verifiers.length == 0) { 12071 return null; 12072 } 12073 12074 final int N = pkgInfo.verifiers.length; 12075 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12076 for (int i = 0; i < N; i++) { 12077 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12078 12079 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12080 receivers); 12081 if (comp == null) { 12082 continue; 12083 } 12084 12085 final int verifierUid = getUidForVerifier(verifierInfo); 12086 if (verifierUid == -1) { 12087 continue; 12088 } 12089 12090 if (DEBUG_VERIFY) { 12091 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12092 + " with the correct signature"); 12093 } 12094 sufficientVerifiers.add(comp); 12095 verificationState.addSufficientVerifier(verifierUid); 12096 } 12097 12098 return sufficientVerifiers; 12099 } 12100 12101 private int getUidForVerifier(VerifierInfo verifierInfo) { 12102 synchronized (mPackages) { 12103 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12104 if (pkg == null) { 12105 return -1; 12106 } else if (pkg.mSignatures.length != 1) { 12107 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12108 + " has more than one signature; ignoring"); 12109 return -1; 12110 } 12111 12112 /* 12113 * If the public key of the package's signature does not match 12114 * our expected public key, then this is a different package and 12115 * we should skip. 12116 */ 12117 12118 final byte[] expectedPublicKey; 12119 try { 12120 final Signature verifierSig = pkg.mSignatures[0]; 12121 final PublicKey publicKey = verifierSig.getPublicKey(); 12122 expectedPublicKey = publicKey.getEncoded(); 12123 } catch (CertificateException e) { 12124 return -1; 12125 } 12126 12127 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12128 12129 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12130 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12131 + " does not have the expected public key; ignoring"); 12132 return -1; 12133 } 12134 12135 return pkg.applicationInfo.uid; 12136 } 12137 } 12138 12139 @Override 12140 public void finishPackageInstall(int token, boolean didLaunch) { 12141 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12142 12143 if (DEBUG_INSTALL) { 12144 Slog.v(TAG, "BM finishing package install for " + token); 12145 } 12146 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12147 12148 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12149 mHandler.sendMessage(msg); 12150 } 12151 12152 /** 12153 * Get the verification agent timeout. 12154 * 12155 * @return verification timeout in milliseconds 12156 */ 12157 private long getVerificationTimeout() { 12158 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12159 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12160 DEFAULT_VERIFICATION_TIMEOUT); 12161 } 12162 12163 /** 12164 * Get the default verification agent response code. 12165 * 12166 * @return default verification response code 12167 */ 12168 private int getDefaultVerificationResponse() { 12169 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12170 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12171 DEFAULT_VERIFICATION_RESPONSE); 12172 } 12173 12174 /** 12175 * Check whether or not package verification has been enabled. 12176 * 12177 * @return true if verification should be performed 12178 */ 12179 private boolean isVerificationEnabled(int userId, int installFlags) { 12180 if (!DEFAULT_VERIFY_ENABLE) { 12181 return false; 12182 } 12183 // Ephemeral apps don't get the full verification treatment 12184 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12185 if (DEBUG_EPHEMERAL) { 12186 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12187 } 12188 return false; 12189 } 12190 12191 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12192 12193 // Check if installing from ADB 12194 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12195 // Do not run verification in a test harness environment 12196 if (ActivityManager.isRunningInTestHarness()) { 12197 return false; 12198 } 12199 if (ensureVerifyAppsEnabled) { 12200 return true; 12201 } 12202 // Check if the developer does not want package verification for ADB installs 12203 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12204 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12205 return false; 12206 } 12207 } 12208 12209 if (ensureVerifyAppsEnabled) { 12210 return true; 12211 } 12212 12213 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12214 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12215 } 12216 12217 @Override 12218 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12219 throws RemoteException { 12220 mContext.enforceCallingOrSelfPermission( 12221 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12222 "Only intentfilter verification agents can verify applications"); 12223 12224 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12225 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12226 Binder.getCallingUid(), verificationCode, failedDomains); 12227 msg.arg1 = id; 12228 msg.obj = response; 12229 mHandler.sendMessage(msg); 12230 } 12231 12232 @Override 12233 public int getIntentVerificationStatus(String packageName, int userId) { 12234 synchronized (mPackages) { 12235 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12236 } 12237 } 12238 12239 @Override 12240 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12241 mContext.enforceCallingOrSelfPermission( 12242 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12243 12244 boolean result = false; 12245 synchronized (mPackages) { 12246 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12247 } 12248 if (result) { 12249 scheduleWritePackageRestrictionsLocked(userId); 12250 } 12251 return result; 12252 } 12253 12254 @Override 12255 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12256 String packageName) { 12257 synchronized (mPackages) { 12258 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12259 } 12260 } 12261 12262 @Override 12263 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12264 if (TextUtils.isEmpty(packageName)) { 12265 return ParceledListSlice.emptyList(); 12266 } 12267 synchronized (mPackages) { 12268 PackageParser.Package pkg = mPackages.get(packageName); 12269 if (pkg == null || pkg.activities == null) { 12270 return ParceledListSlice.emptyList(); 12271 } 12272 final int count = pkg.activities.size(); 12273 ArrayList<IntentFilter> result = new ArrayList<>(); 12274 for (int n=0; n<count; n++) { 12275 PackageParser.Activity activity = pkg.activities.get(n); 12276 if (activity.intents != null && activity.intents.size() > 0) { 12277 result.addAll(activity.intents); 12278 } 12279 } 12280 return new ParceledListSlice<>(result); 12281 } 12282 } 12283 12284 @Override 12285 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12286 mContext.enforceCallingOrSelfPermission( 12287 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12288 12289 synchronized (mPackages) { 12290 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12291 if (packageName != null) { 12292 result |= updateIntentVerificationStatus(packageName, 12293 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12294 userId); 12295 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12296 packageName, userId); 12297 } 12298 return result; 12299 } 12300 } 12301 12302 @Override 12303 public String getDefaultBrowserPackageName(int userId) { 12304 synchronized (mPackages) { 12305 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12306 } 12307 } 12308 12309 /** 12310 * Get the "allow unknown sources" setting. 12311 * 12312 * @return the current "allow unknown sources" setting 12313 */ 12314 private int getUnknownSourcesSettings() { 12315 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12316 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12317 -1); 12318 } 12319 12320 @Override 12321 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12322 final int uid = Binder.getCallingUid(); 12323 // writer 12324 synchronized (mPackages) { 12325 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12326 if (targetPackageSetting == null) { 12327 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12328 } 12329 12330 PackageSetting installerPackageSetting; 12331 if (installerPackageName != null) { 12332 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12333 if (installerPackageSetting == null) { 12334 throw new IllegalArgumentException("Unknown installer package: " 12335 + installerPackageName); 12336 } 12337 } else { 12338 installerPackageSetting = null; 12339 } 12340 12341 Signature[] callerSignature; 12342 Object obj = mSettings.getUserIdLPr(uid); 12343 if (obj != null) { 12344 if (obj instanceof SharedUserSetting) { 12345 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12346 } else if (obj instanceof PackageSetting) { 12347 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12348 } else { 12349 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12350 } 12351 } else { 12352 throw new SecurityException("Unknown calling UID: " + uid); 12353 } 12354 12355 // Verify: can't set installerPackageName to a package that is 12356 // not signed with the same cert as the caller. 12357 if (installerPackageSetting != null) { 12358 if (compareSignatures(callerSignature, 12359 installerPackageSetting.signatures.mSignatures) 12360 != PackageManager.SIGNATURE_MATCH) { 12361 throw new SecurityException( 12362 "Caller does not have same cert as new installer package " 12363 + installerPackageName); 12364 } 12365 } 12366 12367 // Verify: if target already has an installer package, it must 12368 // be signed with the same cert as the caller. 12369 if (targetPackageSetting.installerPackageName != null) { 12370 PackageSetting setting = mSettings.mPackages.get( 12371 targetPackageSetting.installerPackageName); 12372 // If the currently set package isn't valid, then it's always 12373 // okay to change it. 12374 if (setting != null) { 12375 if (compareSignatures(callerSignature, 12376 setting.signatures.mSignatures) 12377 != PackageManager.SIGNATURE_MATCH) { 12378 throw new SecurityException( 12379 "Caller does not have same cert as old installer package " 12380 + targetPackageSetting.installerPackageName); 12381 } 12382 } 12383 } 12384 12385 // Okay! 12386 targetPackageSetting.installerPackageName = installerPackageName; 12387 if (installerPackageName != null) { 12388 mSettings.mInstallerPackages.add(installerPackageName); 12389 } 12390 scheduleWriteSettingsLocked(); 12391 } 12392 } 12393 12394 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12395 // Queue up an async operation since the package installation may take a little while. 12396 mHandler.post(new Runnable() { 12397 public void run() { 12398 mHandler.removeCallbacks(this); 12399 // Result object to be returned 12400 PackageInstalledInfo res = new PackageInstalledInfo(); 12401 res.setReturnCode(currentStatus); 12402 res.uid = -1; 12403 res.pkg = null; 12404 res.removedInfo = null; 12405 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12406 args.doPreInstall(res.returnCode); 12407 synchronized (mInstallLock) { 12408 installPackageTracedLI(args, res); 12409 } 12410 args.doPostInstall(res.returnCode, res.uid); 12411 } 12412 12413 // A restore should be performed at this point if (a) the install 12414 // succeeded, (b) the operation is not an update, and (c) the new 12415 // package has not opted out of backup participation. 12416 final boolean update = res.removedInfo != null 12417 && res.removedInfo.removedPackage != null; 12418 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12419 boolean doRestore = !update 12420 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12421 12422 // Set up the post-install work request bookkeeping. This will be used 12423 // and cleaned up by the post-install event handling regardless of whether 12424 // there's a restore pass performed. Token values are >= 1. 12425 int token; 12426 if (mNextInstallToken < 0) mNextInstallToken = 1; 12427 token = mNextInstallToken++; 12428 12429 PostInstallData data = new PostInstallData(args, res); 12430 mRunningInstalls.put(token, data); 12431 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12432 12433 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12434 // Pass responsibility to the Backup Manager. It will perform a 12435 // restore if appropriate, then pass responsibility back to the 12436 // Package Manager to run the post-install observer callbacks 12437 // and broadcasts. 12438 IBackupManager bm = IBackupManager.Stub.asInterface( 12439 ServiceManager.getService(Context.BACKUP_SERVICE)); 12440 if (bm != null) { 12441 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12442 + " to BM for possible restore"); 12443 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12444 try { 12445 // TODO: http://b/22388012 12446 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12447 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12448 } else { 12449 doRestore = false; 12450 } 12451 } catch (RemoteException e) { 12452 // can't happen; the backup manager is local 12453 } catch (Exception e) { 12454 Slog.e(TAG, "Exception trying to enqueue restore", e); 12455 doRestore = false; 12456 } 12457 } else { 12458 Slog.e(TAG, "Backup Manager not found!"); 12459 doRestore = false; 12460 } 12461 } 12462 12463 if (!doRestore) { 12464 // No restore possible, or the Backup Manager was mysteriously not 12465 // available -- just fire the post-install work request directly. 12466 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12467 12468 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12469 12470 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12471 mHandler.sendMessage(msg); 12472 } 12473 } 12474 }); 12475 } 12476 12477 /** 12478 * Callback from PackageSettings whenever an app is first transitioned out of the 12479 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12480 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12481 * here whether the app is the target of an ongoing install, and only send the 12482 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12483 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12484 * handling. 12485 */ 12486 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12487 // Serialize this with the rest of the install-process message chain. In the 12488 // restore-at-install case, this Runnable will necessarily run before the 12489 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12490 // are coherent. In the non-restore case, the app has already completed install 12491 // and been launched through some other means, so it is not in a problematic 12492 // state for observers to see the FIRST_LAUNCH signal. 12493 mHandler.post(new Runnable() { 12494 @Override 12495 public void run() { 12496 for (int i = 0; i < mRunningInstalls.size(); i++) { 12497 final PostInstallData data = mRunningInstalls.valueAt(i); 12498 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12499 // right package; but is it for the right user? 12500 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12501 if (userId == data.res.newUsers[uIndex]) { 12502 if (DEBUG_BACKUP) { 12503 Slog.i(TAG, "Package " + pkgName 12504 + " being restored so deferring FIRST_LAUNCH"); 12505 } 12506 return; 12507 } 12508 } 12509 } 12510 } 12511 // didn't find it, so not being restored 12512 if (DEBUG_BACKUP) { 12513 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12514 } 12515 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12516 } 12517 }); 12518 } 12519 12520 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12521 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12522 installerPkg, null, userIds); 12523 } 12524 12525 private abstract class HandlerParams { 12526 private static final int MAX_RETRIES = 4; 12527 12528 /** 12529 * Number of times startCopy() has been attempted and had a non-fatal 12530 * error. 12531 */ 12532 private int mRetries = 0; 12533 12534 /** User handle for the user requesting the information or installation. */ 12535 private final UserHandle mUser; 12536 String traceMethod; 12537 int traceCookie; 12538 12539 HandlerParams(UserHandle user) { 12540 mUser = user; 12541 } 12542 12543 UserHandle getUser() { 12544 return mUser; 12545 } 12546 12547 HandlerParams setTraceMethod(String traceMethod) { 12548 this.traceMethod = traceMethod; 12549 return this; 12550 } 12551 12552 HandlerParams setTraceCookie(int traceCookie) { 12553 this.traceCookie = traceCookie; 12554 return this; 12555 } 12556 12557 final boolean startCopy() { 12558 boolean res; 12559 try { 12560 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12561 12562 if (++mRetries > MAX_RETRIES) { 12563 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12564 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12565 handleServiceError(); 12566 return false; 12567 } else { 12568 handleStartCopy(); 12569 res = true; 12570 } 12571 } catch (RemoteException e) { 12572 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12573 mHandler.sendEmptyMessage(MCS_RECONNECT); 12574 res = false; 12575 } 12576 handleReturnCode(); 12577 return res; 12578 } 12579 12580 final void serviceError() { 12581 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12582 handleServiceError(); 12583 handleReturnCode(); 12584 } 12585 12586 abstract void handleStartCopy() throws RemoteException; 12587 abstract void handleServiceError(); 12588 abstract void handleReturnCode(); 12589 } 12590 12591 class MeasureParams extends HandlerParams { 12592 private final PackageStats mStats; 12593 private boolean mSuccess; 12594 12595 private final IPackageStatsObserver mObserver; 12596 12597 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12598 super(new UserHandle(stats.userHandle)); 12599 mObserver = observer; 12600 mStats = stats; 12601 } 12602 12603 @Override 12604 public String toString() { 12605 return "MeasureParams{" 12606 + Integer.toHexString(System.identityHashCode(this)) 12607 + " " + mStats.packageName + "}"; 12608 } 12609 12610 @Override 12611 void handleStartCopy() throws RemoteException { 12612 synchronized (mInstallLock) { 12613 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12614 } 12615 12616 if (mSuccess) { 12617 boolean mounted = false; 12618 try { 12619 final String status = Environment.getExternalStorageState(); 12620 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12621 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12622 } catch (Exception e) { 12623 } 12624 12625 if (mounted) { 12626 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12627 12628 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12629 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12630 12631 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12632 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12633 12634 // Always subtract cache size, since it's a subdirectory 12635 mStats.externalDataSize -= mStats.externalCacheSize; 12636 12637 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12638 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12639 12640 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12641 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12642 } 12643 } 12644 } 12645 12646 @Override 12647 void handleReturnCode() { 12648 if (mObserver != null) { 12649 try { 12650 mObserver.onGetStatsCompleted(mStats, mSuccess); 12651 } catch (RemoteException e) { 12652 Slog.i(TAG, "Observer no longer exists."); 12653 } 12654 } 12655 } 12656 12657 @Override 12658 void handleServiceError() { 12659 Slog.e(TAG, "Could not measure application " + mStats.packageName 12660 + " external storage"); 12661 } 12662 } 12663 12664 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12665 throws RemoteException { 12666 long result = 0; 12667 for (File path : paths) { 12668 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12669 } 12670 return result; 12671 } 12672 12673 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12674 for (File path : paths) { 12675 try { 12676 mcs.clearDirectory(path.getAbsolutePath()); 12677 } catch (RemoteException e) { 12678 } 12679 } 12680 } 12681 12682 static class OriginInfo { 12683 /** 12684 * Location where install is coming from, before it has been 12685 * copied/renamed into place. This could be a single monolithic APK 12686 * file, or a cluster directory. This location may be untrusted. 12687 */ 12688 final File file; 12689 final String cid; 12690 12691 /** 12692 * Flag indicating that {@link #file} or {@link #cid} has already been 12693 * staged, meaning downstream users don't need to defensively copy the 12694 * contents. 12695 */ 12696 final boolean staged; 12697 12698 /** 12699 * Flag indicating that {@link #file} or {@link #cid} is an already 12700 * installed app that is being moved. 12701 */ 12702 final boolean existing; 12703 12704 final String resolvedPath; 12705 final File resolvedFile; 12706 12707 static OriginInfo fromNothing() { 12708 return new OriginInfo(null, null, false, false); 12709 } 12710 12711 static OriginInfo fromUntrustedFile(File file) { 12712 return new OriginInfo(file, null, false, false); 12713 } 12714 12715 static OriginInfo fromExistingFile(File file) { 12716 return new OriginInfo(file, null, false, true); 12717 } 12718 12719 static OriginInfo fromStagedFile(File file) { 12720 return new OriginInfo(file, null, true, false); 12721 } 12722 12723 static OriginInfo fromStagedContainer(String cid) { 12724 return new OriginInfo(null, cid, true, false); 12725 } 12726 12727 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12728 this.file = file; 12729 this.cid = cid; 12730 this.staged = staged; 12731 this.existing = existing; 12732 12733 if (cid != null) { 12734 resolvedPath = PackageHelper.getSdDir(cid); 12735 resolvedFile = new File(resolvedPath); 12736 } else if (file != null) { 12737 resolvedPath = file.getAbsolutePath(); 12738 resolvedFile = file; 12739 } else { 12740 resolvedPath = null; 12741 resolvedFile = null; 12742 } 12743 } 12744 } 12745 12746 static class MoveInfo { 12747 final int moveId; 12748 final String fromUuid; 12749 final String toUuid; 12750 final String packageName; 12751 final String dataAppName; 12752 final int appId; 12753 final String seinfo; 12754 final int targetSdkVersion; 12755 12756 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12757 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12758 this.moveId = moveId; 12759 this.fromUuid = fromUuid; 12760 this.toUuid = toUuid; 12761 this.packageName = packageName; 12762 this.dataAppName = dataAppName; 12763 this.appId = appId; 12764 this.seinfo = seinfo; 12765 this.targetSdkVersion = targetSdkVersion; 12766 } 12767 } 12768 12769 static class VerificationInfo { 12770 /** A constant used to indicate that a uid value is not present. */ 12771 public static final int NO_UID = -1; 12772 12773 /** URI referencing where the package was downloaded from. */ 12774 final Uri originatingUri; 12775 12776 /** HTTP referrer URI associated with the originatingURI. */ 12777 final Uri referrer; 12778 12779 /** UID of the application that the install request originated from. */ 12780 final int originatingUid; 12781 12782 /** UID of application requesting the install */ 12783 final int installerUid; 12784 12785 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12786 this.originatingUri = originatingUri; 12787 this.referrer = referrer; 12788 this.originatingUid = originatingUid; 12789 this.installerUid = installerUid; 12790 } 12791 } 12792 12793 class InstallParams extends HandlerParams { 12794 final OriginInfo origin; 12795 final MoveInfo move; 12796 final IPackageInstallObserver2 observer; 12797 int installFlags; 12798 final String installerPackageName; 12799 final String volumeUuid; 12800 private InstallArgs mArgs; 12801 private int mRet; 12802 final String packageAbiOverride; 12803 final String[] grantedRuntimePermissions; 12804 final VerificationInfo verificationInfo; 12805 final Certificate[][] certificates; 12806 12807 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12808 int installFlags, String installerPackageName, String volumeUuid, 12809 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12810 String[] grantedPermissions, Certificate[][] certificates) { 12811 super(user); 12812 this.origin = origin; 12813 this.move = move; 12814 this.observer = observer; 12815 this.installFlags = installFlags; 12816 this.installerPackageName = installerPackageName; 12817 this.volumeUuid = volumeUuid; 12818 this.verificationInfo = verificationInfo; 12819 this.packageAbiOverride = packageAbiOverride; 12820 this.grantedRuntimePermissions = grantedPermissions; 12821 this.certificates = certificates; 12822 } 12823 12824 @Override 12825 public String toString() { 12826 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12827 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12828 } 12829 12830 private int installLocationPolicy(PackageInfoLite pkgLite) { 12831 String packageName = pkgLite.packageName; 12832 int installLocation = pkgLite.installLocation; 12833 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12834 // reader 12835 synchronized (mPackages) { 12836 // Currently installed package which the new package is attempting to replace or 12837 // null if no such package is installed. 12838 PackageParser.Package installedPkg = mPackages.get(packageName); 12839 // Package which currently owns the data which the new package will own if installed. 12840 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12841 // will be null whereas dataOwnerPkg will contain information about the package 12842 // which was uninstalled while keeping its data. 12843 PackageParser.Package dataOwnerPkg = installedPkg; 12844 if (dataOwnerPkg == null) { 12845 PackageSetting ps = mSettings.mPackages.get(packageName); 12846 if (ps != null) { 12847 dataOwnerPkg = ps.pkg; 12848 } 12849 } 12850 12851 if (dataOwnerPkg != null) { 12852 // If installed, the package will get access to data left on the device by its 12853 // predecessor. As a security measure, this is permited only if this is not a 12854 // version downgrade or if the predecessor package is marked as debuggable and 12855 // a downgrade is explicitly requested. 12856 // 12857 // On debuggable platform builds, downgrades are permitted even for 12858 // non-debuggable packages to make testing easier. Debuggable platform builds do 12859 // not offer security guarantees and thus it's OK to disable some security 12860 // mechanisms to make debugging/testing easier on those builds. However, even on 12861 // debuggable builds downgrades of packages are permitted only if requested via 12862 // installFlags. This is because we aim to keep the behavior of debuggable 12863 // platform builds as close as possible to the behavior of non-debuggable 12864 // platform builds. 12865 final boolean downgradeRequested = 12866 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12867 final boolean packageDebuggable = 12868 (dataOwnerPkg.applicationInfo.flags 12869 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12870 final boolean downgradePermitted = 12871 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12872 if (!downgradePermitted) { 12873 try { 12874 checkDowngrade(dataOwnerPkg, pkgLite); 12875 } catch (PackageManagerException e) { 12876 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12877 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12878 } 12879 } 12880 } 12881 12882 if (installedPkg != null) { 12883 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12884 // Check for updated system application. 12885 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12886 if (onSd) { 12887 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12888 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12889 } 12890 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12891 } else { 12892 if (onSd) { 12893 // Install flag overrides everything. 12894 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12895 } 12896 // If current upgrade specifies particular preference 12897 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12898 // Application explicitly specified internal. 12899 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12900 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12901 // App explictly prefers external. Let policy decide 12902 } else { 12903 // Prefer previous location 12904 if (isExternal(installedPkg)) { 12905 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12906 } 12907 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12908 } 12909 } 12910 } else { 12911 // Invalid install. Return error code 12912 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12913 } 12914 } 12915 } 12916 // All the special cases have been taken care of. 12917 // Return result based on recommended install location. 12918 if (onSd) { 12919 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12920 } 12921 return pkgLite.recommendedInstallLocation; 12922 } 12923 12924 /* 12925 * Invoke remote method to get package information and install 12926 * location values. Override install location based on default 12927 * policy if needed and then create install arguments based 12928 * on the install location. 12929 */ 12930 public void handleStartCopy() throws RemoteException { 12931 int ret = PackageManager.INSTALL_SUCCEEDED; 12932 12933 // If we're already staged, we've firmly committed to an install location 12934 if (origin.staged) { 12935 if (origin.file != null) { 12936 installFlags |= PackageManager.INSTALL_INTERNAL; 12937 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12938 } else if (origin.cid != null) { 12939 installFlags |= PackageManager.INSTALL_EXTERNAL; 12940 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12941 } else { 12942 throw new IllegalStateException("Invalid stage location"); 12943 } 12944 } 12945 12946 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12947 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12948 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12949 PackageInfoLite pkgLite = null; 12950 12951 if (onInt && onSd) { 12952 // Check if both bits are set. 12953 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12954 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12955 } else if (onSd && ephemeral) { 12956 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12957 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12958 } else { 12959 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12960 packageAbiOverride); 12961 12962 if (DEBUG_EPHEMERAL && ephemeral) { 12963 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12964 } 12965 12966 /* 12967 * If we have too little free space, try to free cache 12968 * before giving up. 12969 */ 12970 if (!origin.staged && pkgLite.recommendedInstallLocation 12971 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12972 // TODO: focus freeing disk space on the target device 12973 final StorageManager storage = StorageManager.from(mContext); 12974 final long lowThreshold = storage.getStorageLowBytes( 12975 Environment.getDataDirectory()); 12976 12977 final long sizeBytes = mContainerService.calculateInstalledSize( 12978 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12979 12980 try { 12981 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12982 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12983 installFlags, packageAbiOverride); 12984 } catch (InstallerException e) { 12985 Slog.w(TAG, "Failed to free cache", e); 12986 } 12987 12988 /* 12989 * The cache free must have deleted the file we 12990 * downloaded to install. 12991 * 12992 * TODO: fix the "freeCache" call to not delete 12993 * the file we care about. 12994 */ 12995 if (pkgLite.recommendedInstallLocation 12996 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12997 pkgLite.recommendedInstallLocation 12998 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12999 } 13000 } 13001 } 13002 13003 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13004 int loc = pkgLite.recommendedInstallLocation; 13005 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13006 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13007 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13008 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13009 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13010 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13011 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13012 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13013 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13014 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13015 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13016 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13017 } else { 13018 // Override with defaults if needed. 13019 loc = installLocationPolicy(pkgLite); 13020 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13021 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13022 } else if (!onSd && !onInt) { 13023 // Override install location with flags 13024 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13025 // Set the flag to install on external media. 13026 installFlags |= PackageManager.INSTALL_EXTERNAL; 13027 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13028 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13029 if (DEBUG_EPHEMERAL) { 13030 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13031 } 13032 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13033 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13034 |PackageManager.INSTALL_INTERNAL); 13035 } else { 13036 // Make sure the flag for installing on external 13037 // media is unset 13038 installFlags |= PackageManager.INSTALL_INTERNAL; 13039 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13040 } 13041 } 13042 } 13043 } 13044 13045 final InstallArgs args = createInstallArgs(this); 13046 mArgs = args; 13047 13048 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13049 // TODO: http://b/22976637 13050 // Apps installed for "all" users use the device owner to verify the app 13051 UserHandle verifierUser = getUser(); 13052 if (verifierUser == UserHandle.ALL) { 13053 verifierUser = UserHandle.SYSTEM; 13054 } 13055 13056 /* 13057 * Determine if we have any installed package verifiers. If we 13058 * do, then we'll defer to them to verify the packages. 13059 */ 13060 final int requiredUid = mRequiredVerifierPackage == null ? -1 13061 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13062 verifierUser.getIdentifier()); 13063 if (!origin.existing && requiredUid != -1 13064 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13065 final Intent verification = new Intent( 13066 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13067 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13068 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13069 PACKAGE_MIME_TYPE); 13070 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13071 13072 // Query all live verifiers based on current user state 13073 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13074 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13075 13076 if (DEBUG_VERIFY) { 13077 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13078 + verification.toString() + " with " + pkgLite.verifiers.length 13079 + " optional verifiers"); 13080 } 13081 13082 final int verificationId = mPendingVerificationToken++; 13083 13084 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13085 13086 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13087 installerPackageName); 13088 13089 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13090 installFlags); 13091 13092 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13093 pkgLite.packageName); 13094 13095 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13096 pkgLite.versionCode); 13097 13098 if (verificationInfo != null) { 13099 if (verificationInfo.originatingUri != null) { 13100 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13101 verificationInfo.originatingUri); 13102 } 13103 if (verificationInfo.referrer != null) { 13104 verification.putExtra(Intent.EXTRA_REFERRER, 13105 verificationInfo.referrer); 13106 } 13107 if (verificationInfo.originatingUid >= 0) { 13108 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13109 verificationInfo.originatingUid); 13110 } 13111 if (verificationInfo.installerUid >= 0) { 13112 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13113 verificationInfo.installerUid); 13114 } 13115 } 13116 13117 final PackageVerificationState verificationState = new PackageVerificationState( 13118 requiredUid, args); 13119 13120 mPendingVerification.append(verificationId, verificationState); 13121 13122 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13123 receivers, verificationState); 13124 13125 /* 13126 * If any sufficient verifiers were listed in the package 13127 * manifest, attempt to ask them. 13128 */ 13129 if (sufficientVerifiers != null) { 13130 final int N = sufficientVerifiers.size(); 13131 if (N == 0) { 13132 Slog.i(TAG, "Additional verifiers required, but none installed."); 13133 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13134 } else { 13135 for (int i = 0; i < N; i++) { 13136 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13137 13138 final Intent sufficientIntent = new Intent(verification); 13139 sufficientIntent.setComponent(verifierComponent); 13140 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13141 } 13142 } 13143 } 13144 13145 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13146 mRequiredVerifierPackage, receivers); 13147 if (ret == PackageManager.INSTALL_SUCCEEDED 13148 && mRequiredVerifierPackage != null) { 13149 Trace.asyncTraceBegin( 13150 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13151 /* 13152 * Send the intent to the required verification agent, 13153 * but only start the verification timeout after the 13154 * target BroadcastReceivers have run. 13155 */ 13156 verification.setComponent(requiredVerifierComponent); 13157 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13158 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13159 new BroadcastReceiver() { 13160 @Override 13161 public void onReceive(Context context, Intent intent) { 13162 final Message msg = mHandler 13163 .obtainMessage(CHECK_PENDING_VERIFICATION); 13164 msg.arg1 = verificationId; 13165 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13166 } 13167 }, null, 0, null, null); 13168 13169 /* 13170 * We don't want the copy to proceed until verification 13171 * succeeds, so null out this field. 13172 */ 13173 mArgs = null; 13174 } 13175 } else { 13176 /* 13177 * No package verification is enabled, so immediately start 13178 * the remote call to initiate copy using temporary file. 13179 */ 13180 ret = args.copyApk(mContainerService, true); 13181 } 13182 } 13183 13184 mRet = ret; 13185 } 13186 13187 @Override 13188 void handleReturnCode() { 13189 // If mArgs is null, then MCS couldn't be reached. When it 13190 // reconnects, it will try again to install. At that point, this 13191 // will succeed. 13192 if (mArgs != null) { 13193 processPendingInstall(mArgs, mRet); 13194 } 13195 } 13196 13197 @Override 13198 void handleServiceError() { 13199 mArgs = createInstallArgs(this); 13200 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13201 } 13202 13203 public boolean isForwardLocked() { 13204 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13205 } 13206 } 13207 13208 /** 13209 * Used during creation of InstallArgs 13210 * 13211 * @param installFlags package installation flags 13212 * @return true if should be installed on external storage 13213 */ 13214 private static boolean installOnExternalAsec(int installFlags) { 13215 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13216 return false; 13217 } 13218 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13219 return true; 13220 } 13221 return false; 13222 } 13223 13224 /** 13225 * Used during creation of InstallArgs 13226 * 13227 * @param installFlags package installation flags 13228 * @return true if should be installed as forward locked 13229 */ 13230 private static boolean installForwardLocked(int installFlags) { 13231 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13232 } 13233 13234 private InstallArgs createInstallArgs(InstallParams params) { 13235 if (params.move != null) { 13236 return new MoveInstallArgs(params); 13237 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13238 return new AsecInstallArgs(params); 13239 } else { 13240 return new FileInstallArgs(params); 13241 } 13242 } 13243 13244 /** 13245 * Create args that describe an existing installed package. Typically used 13246 * when cleaning up old installs, or used as a move source. 13247 */ 13248 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13249 String resourcePath, String[] instructionSets) { 13250 final boolean isInAsec; 13251 if (installOnExternalAsec(installFlags)) { 13252 /* Apps on SD card are always in ASEC containers. */ 13253 isInAsec = true; 13254 } else if (installForwardLocked(installFlags) 13255 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13256 /* 13257 * Forward-locked apps are only in ASEC containers if they're the 13258 * new style 13259 */ 13260 isInAsec = true; 13261 } else { 13262 isInAsec = false; 13263 } 13264 13265 if (isInAsec) { 13266 return new AsecInstallArgs(codePath, instructionSets, 13267 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13268 } else { 13269 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13270 } 13271 } 13272 13273 static abstract class InstallArgs { 13274 /** @see InstallParams#origin */ 13275 final OriginInfo origin; 13276 /** @see InstallParams#move */ 13277 final MoveInfo move; 13278 13279 final IPackageInstallObserver2 observer; 13280 // Always refers to PackageManager flags only 13281 final int installFlags; 13282 final String installerPackageName; 13283 final String volumeUuid; 13284 final UserHandle user; 13285 final String abiOverride; 13286 final String[] installGrantPermissions; 13287 /** If non-null, drop an async trace when the install completes */ 13288 final String traceMethod; 13289 final int traceCookie; 13290 final Certificate[][] certificates; 13291 13292 // The list of instruction sets supported by this app. This is currently 13293 // only used during the rmdex() phase to clean up resources. We can get rid of this 13294 // if we move dex files under the common app path. 13295 /* nullable */ String[] instructionSets; 13296 13297 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13298 int installFlags, String installerPackageName, String volumeUuid, 13299 UserHandle user, String[] instructionSets, 13300 String abiOverride, String[] installGrantPermissions, 13301 String traceMethod, int traceCookie, Certificate[][] certificates) { 13302 this.origin = origin; 13303 this.move = move; 13304 this.installFlags = installFlags; 13305 this.observer = observer; 13306 this.installerPackageName = installerPackageName; 13307 this.volumeUuid = volumeUuid; 13308 this.user = user; 13309 this.instructionSets = instructionSets; 13310 this.abiOverride = abiOverride; 13311 this.installGrantPermissions = installGrantPermissions; 13312 this.traceMethod = traceMethod; 13313 this.traceCookie = traceCookie; 13314 this.certificates = certificates; 13315 } 13316 13317 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13318 abstract int doPreInstall(int status); 13319 13320 /** 13321 * Rename package into final resting place. All paths on the given 13322 * scanned package should be updated to reflect the rename. 13323 */ 13324 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13325 abstract int doPostInstall(int status, int uid); 13326 13327 /** @see PackageSettingBase#codePathString */ 13328 abstract String getCodePath(); 13329 /** @see PackageSettingBase#resourcePathString */ 13330 abstract String getResourcePath(); 13331 13332 // Need installer lock especially for dex file removal. 13333 abstract void cleanUpResourcesLI(); 13334 abstract boolean doPostDeleteLI(boolean delete); 13335 13336 /** 13337 * Called before the source arguments are copied. This is used mostly 13338 * for MoveParams when it needs to read the source file to put it in the 13339 * destination. 13340 */ 13341 int doPreCopy() { 13342 return PackageManager.INSTALL_SUCCEEDED; 13343 } 13344 13345 /** 13346 * Called after the source arguments are copied. This is used mostly for 13347 * MoveParams when it needs to read the source file to put it in the 13348 * destination. 13349 */ 13350 int doPostCopy(int uid) { 13351 return PackageManager.INSTALL_SUCCEEDED; 13352 } 13353 13354 protected boolean isFwdLocked() { 13355 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13356 } 13357 13358 protected boolean isExternalAsec() { 13359 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13360 } 13361 13362 protected boolean isEphemeral() { 13363 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13364 } 13365 13366 UserHandle getUser() { 13367 return user; 13368 } 13369 } 13370 13371 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13372 if (!allCodePaths.isEmpty()) { 13373 if (instructionSets == null) { 13374 throw new IllegalStateException("instructionSet == null"); 13375 } 13376 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13377 for (String codePath : allCodePaths) { 13378 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13379 try { 13380 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13381 } catch (InstallerException ignored) { 13382 } 13383 } 13384 } 13385 } 13386 } 13387 13388 /** 13389 * Logic to handle installation of non-ASEC applications, including copying 13390 * and renaming logic. 13391 */ 13392 class FileInstallArgs extends InstallArgs { 13393 private File codeFile; 13394 private File resourceFile; 13395 13396 // Example topology: 13397 // /data/app/com.example/base.apk 13398 // /data/app/com.example/split_foo.apk 13399 // /data/app/com.example/lib/arm/libfoo.so 13400 // /data/app/com.example/lib/arm64/libfoo.so 13401 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13402 13403 /** New install */ 13404 FileInstallArgs(InstallParams params) { 13405 super(params.origin, params.move, params.observer, params.installFlags, 13406 params.installerPackageName, params.volumeUuid, 13407 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13408 params.grantedRuntimePermissions, 13409 params.traceMethod, params.traceCookie, params.certificates); 13410 if (isFwdLocked()) { 13411 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13412 } 13413 } 13414 13415 /** Existing install */ 13416 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13417 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13418 null, null, null, 0, null /*certificates*/); 13419 this.codeFile = (codePath != null) ? new File(codePath) : null; 13420 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13421 } 13422 13423 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13424 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13425 try { 13426 return doCopyApk(imcs, temp); 13427 } finally { 13428 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13429 } 13430 } 13431 13432 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13433 if (origin.staged) { 13434 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13435 codeFile = origin.file; 13436 resourceFile = origin.file; 13437 return PackageManager.INSTALL_SUCCEEDED; 13438 } 13439 13440 try { 13441 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13442 final File tempDir = 13443 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13444 codeFile = tempDir; 13445 resourceFile = tempDir; 13446 } catch (IOException e) { 13447 Slog.w(TAG, "Failed to create copy file: " + e); 13448 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13449 } 13450 13451 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13452 @Override 13453 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13454 if (!FileUtils.isValidExtFilename(name)) { 13455 throw new IllegalArgumentException("Invalid filename: " + name); 13456 } 13457 try { 13458 final File file = new File(codeFile, name); 13459 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13460 O_RDWR | O_CREAT, 0644); 13461 Os.chmod(file.getAbsolutePath(), 0644); 13462 return new ParcelFileDescriptor(fd); 13463 } catch (ErrnoException e) { 13464 throw new RemoteException("Failed to open: " + e.getMessage()); 13465 } 13466 } 13467 }; 13468 13469 int ret = PackageManager.INSTALL_SUCCEEDED; 13470 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13471 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13472 Slog.e(TAG, "Failed to copy package"); 13473 return ret; 13474 } 13475 13476 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13477 NativeLibraryHelper.Handle handle = null; 13478 try { 13479 handle = NativeLibraryHelper.Handle.create(codeFile); 13480 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13481 abiOverride); 13482 } catch (IOException e) { 13483 Slog.e(TAG, "Copying native libraries failed", e); 13484 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13485 } finally { 13486 IoUtils.closeQuietly(handle); 13487 } 13488 13489 return ret; 13490 } 13491 13492 int doPreInstall(int status) { 13493 if (status != PackageManager.INSTALL_SUCCEEDED) { 13494 cleanUp(); 13495 } 13496 return status; 13497 } 13498 13499 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13500 if (status != PackageManager.INSTALL_SUCCEEDED) { 13501 cleanUp(); 13502 return false; 13503 } 13504 13505 final File targetDir = codeFile.getParentFile(); 13506 final File beforeCodeFile = codeFile; 13507 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13508 13509 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13510 try { 13511 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13512 } catch (ErrnoException e) { 13513 Slog.w(TAG, "Failed to rename", e); 13514 return false; 13515 } 13516 13517 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13518 Slog.w(TAG, "Failed to restorecon"); 13519 return false; 13520 } 13521 13522 // Reflect the rename internally 13523 codeFile = afterCodeFile; 13524 resourceFile = afterCodeFile; 13525 13526 // Reflect the rename in scanned details 13527 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13528 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13529 afterCodeFile, pkg.baseCodePath)); 13530 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13531 afterCodeFile, pkg.splitCodePaths)); 13532 13533 // Reflect the rename in app info 13534 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13535 pkg.setApplicationInfoCodePath(pkg.codePath); 13536 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13537 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13538 pkg.setApplicationInfoResourcePath(pkg.codePath); 13539 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13540 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13541 13542 return true; 13543 } 13544 13545 int doPostInstall(int status, int uid) { 13546 if (status != PackageManager.INSTALL_SUCCEEDED) { 13547 cleanUp(); 13548 } 13549 return status; 13550 } 13551 13552 @Override 13553 String getCodePath() { 13554 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13555 } 13556 13557 @Override 13558 String getResourcePath() { 13559 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13560 } 13561 13562 private boolean cleanUp() { 13563 if (codeFile == null || !codeFile.exists()) { 13564 return false; 13565 } 13566 13567 removeCodePathLI(codeFile); 13568 13569 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13570 resourceFile.delete(); 13571 } 13572 13573 return true; 13574 } 13575 13576 void cleanUpResourcesLI() { 13577 // Try enumerating all code paths before deleting 13578 List<String> allCodePaths = Collections.EMPTY_LIST; 13579 if (codeFile != null && codeFile.exists()) { 13580 try { 13581 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13582 allCodePaths = pkg.getAllCodePaths(); 13583 } catch (PackageParserException e) { 13584 // Ignored; we tried our best 13585 } 13586 } 13587 13588 cleanUp(); 13589 removeDexFiles(allCodePaths, instructionSets); 13590 } 13591 13592 boolean doPostDeleteLI(boolean delete) { 13593 // XXX err, shouldn't we respect the delete flag? 13594 cleanUpResourcesLI(); 13595 return true; 13596 } 13597 } 13598 13599 private boolean isAsecExternal(String cid) { 13600 final String asecPath = PackageHelper.getSdFilesystem(cid); 13601 return !asecPath.startsWith(mAsecInternalPath); 13602 } 13603 13604 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13605 PackageManagerException { 13606 if (copyRet < 0) { 13607 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13608 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13609 throw new PackageManagerException(copyRet, message); 13610 } 13611 } 13612 } 13613 13614 /** 13615 * Extract the MountService "container ID" from the full code path of an 13616 * .apk. 13617 */ 13618 static String cidFromCodePath(String fullCodePath) { 13619 int eidx = fullCodePath.lastIndexOf("/"); 13620 String subStr1 = fullCodePath.substring(0, eidx); 13621 int sidx = subStr1.lastIndexOf("/"); 13622 return subStr1.substring(sidx+1, eidx); 13623 } 13624 13625 /** 13626 * Logic to handle installation of ASEC applications, including copying and 13627 * renaming logic. 13628 */ 13629 class AsecInstallArgs extends InstallArgs { 13630 static final String RES_FILE_NAME = "pkg.apk"; 13631 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13632 13633 String cid; 13634 String packagePath; 13635 String resourcePath; 13636 13637 /** New install */ 13638 AsecInstallArgs(InstallParams params) { 13639 super(params.origin, params.move, params.observer, params.installFlags, 13640 params.installerPackageName, params.volumeUuid, 13641 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13642 params.grantedRuntimePermissions, 13643 params.traceMethod, params.traceCookie, params.certificates); 13644 } 13645 13646 /** Existing install */ 13647 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13648 boolean isExternal, boolean isForwardLocked) { 13649 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13650 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13651 instructionSets, null, null, null, 0, null /*certificates*/); 13652 // Hackily pretend we're still looking at a full code path 13653 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13654 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13655 } 13656 13657 // Extract cid from fullCodePath 13658 int eidx = fullCodePath.lastIndexOf("/"); 13659 String subStr1 = fullCodePath.substring(0, eidx); 13660 int sidx = subStr1.lastIndexOf("/"); 13661 cid = subStr1.substring(sidx+1, eidx); 13662 setMountPath(subStr1); 13663 } 13664 13665 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13666 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13667 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13668 instructionSets, null, null, null, 0, null /*certificates*/); 13669 this.cid = cid; 13670 setMountPath(PackageHelper.getSdDir(cid)); 13671 } 13672 13673 void createCopyFile() { 13674 cid = mInstallerService.allocateExternalStageCidLegacy(); 13675 } 13676 13677 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13678 if (origin.staged && origin.cid != null) { 13679 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13680 cid = origin.cid; 13681 setMountPath(PackageHelper.getSdDir(cid)); 13682 return PackageManager.INSTALL_SUCCEEDED; 13683 } 13684 13685 if (temp) { 13686 createCopyFile(); 13687 } else { 13688 /* 13689 * Pre-emptively destroy the container since it's destroyed if 13690 * copying fails due to it existing anyway. 13691 */ 13692 PackageHelper.destroySdDir(cid); 13693 } 13694 13695 final String newMountPath = imcs.copyPackageToContainer( 13696 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13697 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13698 13699 if (newMountPath != null) { 13700 setMountPath(newMountPath); 13701 return PackageManager.INSTALL_SUCCEEDED; 13702 } else { 13703 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13704 } 13705 } 13706 13707 @Override 13708 String getCodePath() { 13709 return packagePath; 13710 } 13711 13712 @Override 13713 String getResourcePath() { 13714 return resourcePath; 13715 } 13716 13717 int doPreInstall(int status) { 13718 if (status != PackageManager.INSTALL_SUCCEEDED) { 13719 // Destroy container 13720 PackageHelper.destroySdDir(cid); 13721 } else { 13722 boolean mounted = PackageHelper.isContainerMounted(cid); 13723 if (!mounted) { 13724 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13725 Process.SYSTEM_UID); 13726 if (newMountPath != null) { 13727 setMountPath(newMountPath); 13728 } else { 13729 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13730 } 13731 } 13732 } 13733 return status; 13734 } 13735 13736 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13737 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13738 String newMountPath = null; 13739 if (PackageHelper.isContainerMounted(cid)) { 13740 // Unmount the container 13741 if (!PackageHelper.unMountSdDir(cid)) { 13742 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13743 return false; 13744 } 13745 } 13746 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13747 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13748 " which might be stale. Will try to clean up."); 13749 // Clean up the stale container and proceed to recreate. 13750 if (!PackageHelper.destroySdDir(newCacheId)) { 13751 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13752 return false; 13753 } 13754 // Successfully cleaned up stale container. Try to rename again. 13755 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13756 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13757 + " inspite of cleaning it up."); 13758 return false; 13759 } 13760 } 13761 if (!PackageHelper.isContainerMounted(newCacheId)) { 13762 Slog.w(TAG, "Mounting container " + newCacheId); 13763 newMountPath = PackageHelper.mountSdDir(newCacheId, 13764 getEncryptKey(), Process.SYSTEM_UID); 13765 } else { 13766 newMountPath = PackageHelper.getSdDir(newCacheId); 13767 } 13768 if (newMountPath == null) { 13769 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13770 return false; 13771 } 13772 Log.i(TAG, "Succesfully renamed " + cid + 13773 " to " + newCacheId + 13774 " at new path: " + newMountPath); 13775 cid = newCacheId; 13776 13777 final File beforeCodeFile = new File(packagePath); 13778 setMountPath(newMountPath); 13779 final File afterCodeFile = new File(packagePath); 13780 13781 // Reflect the rename in scanned details 13782 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13783 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13784 afterCodeFile, pkg.baseCodePath)); 13785 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13786 afterCodeFile, pkg.splitCodePaths)); 13787 13788 // Reflect the rename in app info 13789 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13790 pkg.setApplicationInfoCodePath(pkg.codePath); 13791 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13792 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13793 pkg.setApplicationInfoResourcePath(pkg.codePath); 13794 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13795 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13796 13797 return true; 13798 } 13799 13800 private void setMountPath(String mountPath) { 13801 final File mountFile = new File(mountPath); 13802 13803 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13804 if (monolithicFile.exists()) { 13805 packagePath = monolithicFile.getAbsolutePath(); 13806 if (isFwdLocked()) { 13807 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13808 } else { 13809 resourcePath = packagePath; 13810 } 13811 } else { 13812 packagePath = mountFile.getAbsolutePath(); 13813 resourcePath = packagePath; 13814 } 13815 } 13816 13817 int doPostInstall(int status, int uid) { 13818 if (status != PackageManager.INSTALL_SUCCEEDED) { 13819 cleanUp(); 13820 } else { 13821 final int groupOwner; 13822 final String protectedFile; 13823 if (isFwdLocked()) { 13824 groupOwner = UserHandle.getSharedAppGid(uid); 13825 protectedFile = RES_FILE_NAME; 13826 } else { 13827 groupOwner = -1; 13828 protectedFile = null; 13829 } 13830 13831 if (uid < Process.FIRST_APPLICATION_UID 13832 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13833 Slog.e(TAG, "Failed to finalize " + cid); 13834 PackageHelper.destroySdDir(cid); 13835 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13836 } 13837 13838 boolean mounted = PackageHelper.isContainerMounted(cid); 13839 if (!mounted) { 13840 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13841 } 13842 } 13843 return status; 13844 } 13845 13846 private void cleanUp() { 13847 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13848 13849 // Destroy secure container 13850 PackageHelper.destroySdDir(cid); 13851 } 13852 13853 private List<String> getAllCodePaths() { 13854 final File codeFile = new File(getCodePath()); 13855 if (codeFile != null && codeFile.exists()) { 13856 try { 13857 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13858 return pkg.getAllCodePaths(); 13859 } catch (PackageParserException e) { 13860 // Ignored; we tried our best 13861 } 13862 } 13863 return Collections.EMPTY_LIST; 13864 } 13865 13866 void cleanUpResourcesLI() { 13867 // Enumerate all code paths before deleting 13868 cleanUpResourcesLI(getAllCodePaths()); 13869 } 13870 13871 private void cleanUpResourcesLI(List<String> allCodePaths) { 13872 cleanUp(); 13873 removeDexFiles(allCodePaths, instructionSets); 13874 } 13875 13876 String getPackageName() { 13877 return getAsecPackageName(cid); 13878 } 13879 13880 boolean doPostDeleteLI(boolean delete) { 13881 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13882 final List<String> allCodePaths = getAllCodePaths(); 13883 boolean mounted = PackageHelper.isContainerMounted(cid); 13884 if (mounted) { 13885 // Unmount first 13886 if (PackageHelper.unMountSdDir(cid)) { 13887 mounted = false; 13888 } 13889 } 13890 if (!mounted && delete) { 13891 cleanUpResourcesLI(allCodePaths); 13892 } 13893 return !mounted; 13894 } 13895 13896 @Override 13897 int doPreCopy() { 13898 if (isFwdLocked()) { 13899 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13900 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13901 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13902 } 13903 } 13904 13905 return PackageManager.INSTALL_SUCCEEDED; 13906 } 13907 13908 @Override 13909 int doPostCopy(int uid) { 13910 if (isFwdLocked()) { 13911 if (uid < Process.FIRST_APPLICATION_UID 13912 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13913 RES_FILE_NAME)) { 13914 Slog.e(TAG, "Failed to finalize " + cid); 13915 PackageHelper.destroySdDir(cid); 13916 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13917 } 13918 } 13919 13920 return PackageManager.INSTALL_SUCCEEDED; 13921 } 13922 } 13923 13924 /** 13925 * Logic to handle movement of existing installed applications. 13926 */ 13927 class MoveInstallArgs extends InstallArgs { 13928 private File codeFile; 13929 private File resourceFile; 13930 13931 /** New install */ 13932 MoveInstallArgs(InstallParams params) { 13933 super(params.origin, params.move, params.observer, params.installFlags, 13934 params.installerPackageName, params.volumeUuid, 13935 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13936 params.grantedRuntimePermissions, 13937 params.traceMethod, params.traceCookie, params.certificates); 13938 } 13939 13940 int copyApk(IMediaContainerService imcs, boolean temp) { 13941 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13942 + move.fromUuid + " to " + move.toUuid); 13943 synchronized (mInstaller) { 13944 try { 13945 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13946 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13947 } catch (InstallerException e) { 13948 Slog.w(TAG, "Failed to move app", e); 13949 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13950 } 13951 } 13952 13953 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13954 resourceFile = codeFile; 13955 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13956 13957 return PackageManager.INSTALL_SUCCEEDED; 13958 } 13959 13960 int doPreInstall(int status) { 13961 if (status != PackageManager.INSTALL_SUCCEEDED) { 13962 cleanUp(move.toUuid); 13963 } 13964 return status; 13965 } 13966 13967 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13968 if (status != PackageManager.INSTALL_SUCCEEDED) { 13969 cleanUp(move.toUuid); 13970 return false; 13971 } 13972 13973 // Reflect the move in app info 13974 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13975 pkg.setApplicationInfoCodePath(pkg.codePath); 13976 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13977 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13978 pkg.setApplicationInfoResourcePath(pkg.codePath); 13979 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13980 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13981 13982 return true; 13983 } 13984 13985 int doPostInstall(int status, int uid) { 13986 if (status == PackageManager.INSTALL_SUCCEEDED) { 13987 cleanUp(move.fromUuid); 13988 } else { 13989 cleanUp(move.toUuid); 13990 } 13991 return status; 13992 } 13993 13994 @Override 13995 String getCodePath() { 13996 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13997 } 13998 13999 @Override 14000 String getResourcePath() { 14001 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14002 } 14003 14004 private boolean cleanUp(String volumeUuid) { 14005 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14006 move.dataAppName); 14007 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14008 final int[] userIds = sUserManager.getUserIds(); 14009 synchronized (mInstallLock) { 14010 // Clean up both app data and code 14011 // All package moves are frozen until finished 14012 for (int userId : userIds) { 14013 try { 14014 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14015 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14016 } catch (InstallerException e) { 14017 Slog.w(TAG, String.valueOf(e)); 14018 } 14019 } 14020 removeCodePathLI(codeFile); 14021 } 14022 return true; 14023 } 14024 14025 void cleanUpResourcesLI() { 14026 throw new UnsupportedOperationException(); 14027 } 14028 14029 boolean doPostDeleteLI(boolean delete) { 14030 throw new UnsupportedOperationException(); 14031 } 14032 } 14033 14034 static String getAsecPackageName(String packageCid) { 14035 int idx = packageCid.lastIndexOf("-"); 14036 if (idx == -1) { 14037 return packageCid; 14038 } 14039 return packageCid.substring(0, idx); 14040 } 14041 14042 // Utility method used to create code paths based on package name and available index. 14043 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14044 String idxStr = ""; 14045 int idx = 1; 14046 // Fall back to default value of idx=1 if prefix is not 14047 // part of oldCodePath 14048 if (oldCodePath != null) { 14049 String subStr = oldCodePath; 14050 // Drop the suffix right away 14051 if (suffix != null && subStr.endsWith(suffix)) { 14052 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14053 } 14054 // If oldCodePath already contains prefix find out the 14055 // ending index to either increment or decrement. 14056 int sidx = subStr.lastIndexOf(prefix); 14057 if (sidx != -1) { 14058 subStr = subStr.substring(sidx + prefix.length()); 14059 if (subStr != null) { 14060 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14061 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14062 } 14063 try { 14064 idx = Integer.parseInt(subStr); 14065 if (idx <= 1) { 14066 idx++; 14067 } else { 14068 idx--; 14069 } 14070 } catch(NumberFormatException e) { 14071 } 14072 } 14073 } 14074 } 14075 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14076 return prefix + idxStr; 14077 } 14078 14079 private File getNextCodePath(File targetDir, String packageName) { 14080 int suffix = 1; 14081 File result; 14082 do { 14083 result = new File(targetDir, packageName + "-" + suffix); 14084 suffix++; 14085 } while (result.exists()); 14086 return result; 14087 } 14088 14089 // Utility method that returns the relative package path with respect 14090 // to the installation directory. Like say for /data/data/com.test-1.apk 14091 // string com.test-1 is returned. 14092 static String deriveCodePathName(String codePath) { 14093 if (codePath == null) { 14094 return null; 14095 } 14096 final File codeFile = new File(codePath); 14097 final String name = codeFile.getName(); 14098 if (codeFile.isDirectory()) { 14099 return name; 14100 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14101 final int lastDot = name.lastIndexOf('.'); 14102 return name.substring(0, lastDot); 14103 } else { 14104 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14105 return null; 14106 } 14107 } 14108 14109 static class PackageInstalledInfo { 14110 String name; 14111 int uid; 14112 // The set of users that originally had this package installed. 14113 int[] origUsers; 14114 // The set of users that now have this package installed. 14115 int[] newUsers; 14116 PackageParser.Package pkg; 14117 int returnCode; 14118 String returnMsg; 14119 PackageRemovedInfo removedInfo; 14120 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14121 14122 public void setError(int code, String msg) { 14123 setReturnCode(code); 14124 setReturnMessage(msg); 14125 Slog.w(TAG, msg); 14126 } 14127 14128 public void setError(String msg, PackageParserException e) { 14129 setReturnCode(e.error); 14130 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14131 Slog.w(TAG, msg, e); 14132 } 14133 14134 public void setError(String msg, PackageManagerException e) { 14135 returnCode = e.error; 14136 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14137 Slog.w(TAG, msg, e); 14138 } 14139 14140 public void setReturnCode(int returnCode) { 14141 this.returnCode = returnCode; 14142 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14143 for (int i = 0; i < childCount; i++) { 14144 addedChildPackages.valueAt(i).returnCode = returnCode; 14145 } 14146 } 14147 14148 private void setReturnMessage(String returnMsg) { 14149 this.returnMsg = returnMsg; 14150 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14151 for (int i = 0; i < childCount; i++) { 14152 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14153 } 14154 } 14155 14156 // In some error cases we want to convey more info back to the observer 14157 String origPackage; 14158 String origPermission; 14159 } 14160 14161 /* 14162 * Install a non-existing package. 14163 */ 14164 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14165 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14166 PackageInstalledInfo res) { 14167 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14168 14169 // Remember this for later, in case we need to rollback this install 14170 String pkgName = pkg.packageName; 14171 14172 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14173 14174 synchronized(mPackages) { 14175 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14176 // A package with the same name is already installed, though 14177 // it has been renamed to an older name. The package we 14178 // are trying to install should be installed as an update to 14179 // the existing one, but that has not been requested, so bail. 14180 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14181 + " without first uninstalling package running as " 14182 + mSettings.mRenamedPackages.get(pkgName)); 14183 return; 14184 } 14185 if (mPackages.containsKey(pkgName)) { 14186 // Don't allow installation over an existing package with the same name. 14187 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14188 + " without first uninstalling."); 14189 return; 14190 } 14191 } 14192 14193 try { 14194 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14195 System.currentTimeMillis(), user); 14196 14197 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14198 14199 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14200 prepareAppDataAfterInstallLIF(newPackage); 14201 14202 } else { 14203 // Remove package from internal structures, but keep around any 14204 // data that might have already existed 14205 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14206 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14207 } 14208 } catch (PackageManagerException e) { 14209 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14210 } 14211 14212 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14213 } 14214 14215 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14216 // Can't rotate keys during boot or if sharedUser. 14217 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14218 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14219 return false; 14220 } 14221 // app is using upgradeKeySets; make sure all are valid 14222 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14223 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14224 for (int i = 0; i < upgradeKeySets.length; i++) { 14225 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14226 Slog.wtf(TAG, "Package " 14227 + (oldPs.name != null ? oldPs.name : "<null>") 14228 + " contains upgrade-key-set reference to unknown key-set: " 14229 + upgradeKeySets[i] 14230 + " reverting to signatures check."); 14231 return false; 14232 } 14233 } 14234 return true; 14235 } 14236 14237 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14238 // Upgrade keysets are being used. Determine if new package has a superset of the 14239 // required keys. 14240 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14241 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14242 for (int i = 0; i < upgradeKeySets.length; i++) { 14243 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14244 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14245 return true; 14246 } 14247 } 14248 return false; 14249 } 14250 14251 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14252 try (DigestInputStream digestStream = 14253 new DigestInputStream(new FileInputStream(file), digest)) { 14254 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14255 } 14256 } 14257 14258 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14259 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14260 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14261 14262 final PackageParser.Package oldPackage; 14263 final String pkgName = pkg.packageName; 14264 final int[] allUsers; 14265 final int[] installedUsers; 14266 14267 synchronized(mPackages) { 14268 oldPackage = mPackages.get(pkgName); 14269 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14270 14271 // don't allow upgrade to target a release SDK from a pre-release SDK 14272 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14273 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14274 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14275 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14276 if (oldTargetsPreRelease 14277 && !newTargetsPreRelease 14278 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14279 Slog.w(TAG, "Can't install package targeting released sdk"); 14280 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14281 return; 14282 } 14283 14284 // don't allow an upgrade from full to ephemeral 14285 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14286 if (isEphemeral && !oldIsEphemeral) { 14287 // can't downgrade from full to ephemeral 14288 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14289 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14290 return; 14291 } 14292 14293 // verify signatures are valid 14294 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14295 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14296 if (!checkUpgradeKeySetLP(ps, pkg)) { 14297 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14298 "New package not signed by keys specified by upgrade-keysets: " 14299 + pkgName); 14300 return; 14301 } 14302 } else { 14303 // default to original signature matching 14304 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14305 != PackageManager.SIGNATURE_MATCH) { 14306 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14307 "New package has a different signature: " + pkgName); 14308 return; 14309 } 14310 } 14311 14312 // don't allow a system upgrade unless the upgrade hash matches 14313 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14314 byte[] digestBytes = null; 14315 try { 14316 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14317 updateDigest(digest, new File(pkg.baseCodePath)); 14318 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14319 for (String path : pkg.splitCodePaths) { 14320 updateDigest(digest, new File(path)); 14321 } 14322 } 14323 digestBytes = digest.digest(); 14324 } catch (NoSuchAlgorithmException | IOException e) { 14325 res.setError(INSTALL_FAILED_INVALID_APK, 14326 "Could not compute hash: " + pkgName); 14327 return; 14328 } 14329 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14330 res.setError(INSTALL_FAILED_INVALID_APK, 14331 "New package fails restrict-update check: " + pkgName); 14332 return; 14333 } 14334 // retain upgrade restriction 14335 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14336 } 14337 14338 // Check for shared user id changes 14339 String invalidPackageName = 14340 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14341 if (invalidPackageName != null) { 14342 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14343 "Package " + invalidPackageName + " tried to change user " 14344 + oldPackage.mSharedUserId); 14345 return; 14346 } 14347 14348 // In case of rollback, remember per-user/profile install state 14349 allUsers = sUserManager.getUserIds(); 14350 installedUsers = ps.queryInstalledUsers(allUsers, true); 14351 } 14352 14353 // Update what is removed 14354 res.removedInfo = new PackageRemovedInfo(); 14355 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14356 res.removedInfo.removedPackage = oldPackage.packageName; 14357 res.removedInfo.isUpdate = true; 14358 res.removedInfo.origUsers = installedUsers; 14359 final int childCount = (oldPackage.childPackages != null) 14360 ? oldPackage.childPackages.size() : 0; 14361 for (int i = 0; i < childCount; i++) { 14362 boolean childPackageUpdated = false; 14363 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14364 if (res.addedChildPackages != null) { 14365 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14366 if (childRes != null) { 14367 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14368 childRes.removedInfo.removedPackage = childPkg.packageName; 14369 childRes.removedInfo.isUpdate = true; 14370 childPackageUpdated = true; 14371 } 14372 } 14373 if (!childPackageUpdated) { 14374 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14375 childRemovedRes.removedPackage = childPkg.packageName; 14376 childRemovedRes.isUpdate = false; 14377 childRemovedRes.dataRemoved = true; 14378 synchronized (mPackages) { 14379 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14380 if (childPs != null) { 14381 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14382 } 14383 } 14384 if (res.removedInfo.removedChildPackages == null) { 14385 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14386 } 14387 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14388 } 14389 } 14390 14391 boolean sysPkg = (isSystemApp(oldPackage)); 14392 if (sysPkg) { 14393 // Set the system/privileged flags as needed 14394 final boolean privileged = 14395 (oldPackage.applicationInfo.privateFlags 14396 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14397 final int systemPolicyFlags = policyFlags 14398 | PackageParser.PARSE_IS_SYSTEM 14399 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14400 14401 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14402 user, allUsers, installerPackageName, res); 14403 } else { 14404 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14405 user, allUsers, installerPackageName, res); 14406 } 14407 } 14408 14409 public List<String> getPreviousCodePaths(String packageName) { 14410 final PackageSetting ps = mSettings.mPackages.get(packageName); 14411 final List<String> result = new ArrayList<String>(); 14412 if (ps != null && ps.oldCodePaths != null) { 14413 result.addAll(ps.oldCodePaths); 14414 } 14415 return result; 14416 } 14417 14418 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14419 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14420 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14421 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14422 + deletedPackage); 14423 14424 String pkgName = deletedPackage.packageName; 14425 boolean deletedPkg = true; 14426 boolean addedPkg = false; 14427 boolean updatedSettings = false; 14428 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14429 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14430 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14431 14432 final long origUpdateTime = (pkg.mExtras != null) 14433 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14434 14435 // First delete the existing package while retaining the data directory 14436 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14437 res.removedInfo, true, pkg)) { 14438 // If the existing package wasn't successfully deleted 14439 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14440 deletedPkg = false; 14441 } else { 14442 // Successfully deleted the old package; proceed with replace. 14443 14444 // If deleted package lived in a container, give users a chance to 14445 // relinquish resources before killing. 14446 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14447 if (DEBUG_INSTALL) { 14448 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14449 } 14450 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14451 final ArrayList<String> pkgList = new ArrayList<String>(1); 14452 pkgList.add(deletedPackage.applicationInfo.packageName); 14453 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14454 } 14455 14456 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14457 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14458 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14459 14460 try { 14461 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14462 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14463 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14464 14465 // Update the in-memory copy of the previous code paths. 14466 PackageSetting ps = mSettings.mPackages.get(pkgName); 14467 if (!killApp) { 14468 if (ps.oldCodePaths == null) { 14469 ps.oldCodePaths = new ArraySet<>(); 14470 } 14471 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14472 if (deletedPackage.splitCodePaths != null) { 14473 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14474 } 14475 } else { 14476 ps.oldCodePaths = null; 14477 } 14478 if (ps.childPackageNames != null) { 14479 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14480 final String childPkgName = ps.childPackageNames.get(i); 14481 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14482 childPs.oldCodePaths = ps.oldCodePaths; 14483 } 14484 } 14485 prepareAppDataAfterInstallLIF(newPackage); 14486 addedPkg = true; 14487 } catch (PackageManagerException e) { 14488 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14489 } 14490 } 14491 14492 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14493 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14494 14495 // Revert all internal state mutations and added folders for the failed install 14496 if (addedPkg) { 14497 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14498 res.removedInfo, true, null); 14499 } 14500 14501 // Restore the old package 14502 if (deletedPkg) { 14503 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14504 File restoreFile = new File(deletedPackage.codePath); 14505 // Parse old package 14506 boolean oldExternal = isExternal(deletedPackage); 14507 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14508 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14509 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14510 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14511 try { 14512 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14513 null); 14514 } catch (PackageManagerException e) { 14515 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14516 + e.getMessage()); 14517 return; 14518 } 14519 14520 synchronized (mPackages) { 14521 // Ensure the installer package name up to date 14522 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14523 14524 // Update permissions for restored package 14525 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14526 14527 mSettings.writeLPr(); 14528 } 14529 14530 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14531 } 14532 } else { 14533 synchronized (mPackages) { 14534 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14535 if (ps != null) { 14536 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14537 if (res.removedInfo.removedChildPackages != null) { 14538 final int childCount = res.removedInfo.removedChildPackages.size(); 14539 // Iterate in reverse as we may modify the collection 14540 for (int i = childCount - 1; i >= 0; i--) { 14541 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14542 if (res.addedChildPackages.containsKey(childPackageName)) { 14543 res.removedInfo.removedChildPackages.removeAt(i); 14544 } else { 14545 PackageRemovedInfo childInfo = res.removedInfo 14546 .removedChildPackages.valueAt(i); 14547 childInfo.removedForAllUsers = mPackages.get( 14548 childInfo.removedPackage) == null; 14549 } 14550 } 14551 } 14552 } 14553 } 14554 } 14555 } 14556 14557 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14558 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14559 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14560 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14561 + ", old=" + deletedPackage); 14562 14563 final boolean disabledSystem; 14564 14565 // Remove existing system package 14566 removePackageLI(deletedPackage, true); 14567 14568 synchronized (mPackages) { 14569 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14570 } 14571 if (!disabledSystem) { 14572 // We didn't need to disable the .apk as a current system package, 14573 // which means we are replacing another update that is already 14574 // installed. We need to make sure to delete the older one's .apk. 14575 res.removedInfo.args = createInstallArgsForExisting(0, 14576 deletedPackage.applicationInfo.getCodePath(), 14577 deletedPackage.applicationInfo.getResourcePath(), 14578 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14579 } else { 14580 res.removedInfo.args = null; 14581 } 14582 14583 // Successfully disabled the old package. Now proceed with re-installation 14584 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14585 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14586 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14587 14588 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14589 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14590 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14591 14592 PackageParser.Package newPackage = null; 14593 try { 14594 // Add the package to the internal data structures 14595 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14596 14597 // Set the update and install times 14598 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14599 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14600 System.currentTimeMillis()); 14601 14602 // Update the package dynamic state if succeeded 14603 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14604 // Now that the install succeeded make sure we remove data 14605 // directories for any child package the update removed. 14606 final int deletedChildCount = (deletedPackage.childPackages != null) 14607 ? deletedPackage.childPackages.size() : 0; 14608 final int newChildCount = (newPackage.childPackages != null) 14609 ? newPackage.childPackages.size() : 0; 14610 for (int i = 0; i < deletedChildCount; i++) { 14611 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14612 boolean childPackageDeleted = true; 14613 for (int j = 0; j < newChildCount; j++) { 14614 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14615 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14616 childPackageDeleted = false; 14617 break; 14618 } 14619 } 14620 if (childPackageDeleted) { 14621 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14622 deletedChildPkg.packageName); 14623 if (ps != null && res.removedInfo.removedChildPackages != null) { 14624 PackageRemovedInfo removedChildRes = res.removedInfo 14625 .removedChildPackages.get(deletedChildPkg.packageName); 14626 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14627 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14628 } 14629 } 14630 } 14631 14632 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14633 prepareAppDataAfterInstallLIF(newPackage); 14634 } 14635 } catch (PackageManagerException e) { 14636 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14637 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14638 } 14639 14640 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14641 // Re installation failed. Restore old information 14642 // Remove new pkg information 14643 if (newPackage != null) { 14644 removeInstalledPackageLI(newPackage, true); 14645 } 14646 // Add back the old system package 14647 try { 14648 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14649 } catch (PackageManagerException e) { 14650 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14651 } 14652 14653 synchronized (mPackages) { 14654 if (disabledSystem) { 14655 enableSystemPackageLPw(deletedPackage); 14656 } 14657 14658 // Ensure the installer package name up to date 14659 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14660 14661 // Update permissions for restored package 14662 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14663 14664 mSettings.writeLPr(); 14665 } 14666 14667 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14668 + " after failed upgrade"); 14669 } 14670 } 14671 14672 /** 14673 * Checks whether the parent or any of the child packages have a change shared 14674 * user. For a package to be a valid update the shred users of the parent and 14675 * the children should match. We may later support changing child shared users. 14676 * @param oldPkg The updated package. 14677 * @param newPkg The update package. 14678 * @return The shared user that change between the versions. 14679 */ 14680 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14681 PackageParser.Package newPkg) { 14682 // Check parent shared user 14683 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14684 return newPkg.packageName; 14685 } 14686 // Check child shared users 14687 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14688 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14689 for (int i = 0; i < newChildCount; i++) { 14690 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14691 // If this child was present, did it have the same shared user? 14692 for (int j = 0; j < oldChildCount; j++) { 14693 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14694 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14695 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14696 return newChildPkg.packageName; 14697 } 14698 } 14699 } 14700 return null; 14701 } 14702 14703 private void removeNativeBinariesLI(PackageSetting ps) { 14704 // Remove the lib path for the parent package 14705 if (ps != null) { 14706 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14707 // Remove the lib path for the child packages 14708 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14709 for (int i = 0; i < childCount; i++) { 14710 PackageSetting childPs = null; 14711 synchronized (mPackages) { 14712 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14713 } 14714 if (childPs != null) { 14715 NativeLibraryHelper.removeNativeBinariesLI(childPs 14716 .legacyNativeLibraryPathString); 14717 } 14718 } 14719 } 14720 } 14721 14722 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14723 // Enable the parent package 14724 mSettings.enableSystemPackageLPw(pkg.packageName); 14725 // Enable the child packages 14726 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14727 for (int i = 0; i < childCount; i++) { 14728 PackageParser.Package childPkg = pkg.childPackages.get(i); 14729 mSettings.enableSystemPackageLPw(childPkg.packageName); 14730 } 14731 } 14732 14733 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14734 PackageParser.Package newPkg) { 14735 // Disable the parent package (parent always replaced) 14736 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14737 // Disable the child packages 14738 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14739 for (int i = 0; i < childCount; i++) { 14740 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14741 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14742 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14743 } 14744 return disabled; 14745 } 14746 14747 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14748 String installerPackageName) { 14749 // Enable the parent package 14750 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14751 // Enable the child packages 14752 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14753 for (int i = 0; i < childCount; i++) { 14754 PackageParser.Package childPkg = pkg.childPackages.get(i); 14755 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14756 } 14757 } 14758 14759 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14760 // Collect all used permissions in the UID 14761 ArraySet<String> usedPermissions = new ArraySet<>(); 14762 final int packageCount = su.packages.size(); 14763 for (int i = 0; i < packageCount; i++) { 14764 PackageSetting ps = su.packages.valueAt(i); 14765 if (ps.pkg == null) { 14766 continue; 14767 } 14768 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14769 for (int j = 0; j < requestedPermCount; j++) { 14770 String permission = ps.pkg.requestedPermissions.get(j); 14771 BasePermission bp = mSettings.mPermissions.get(permission); 14772 if (bp != null) { 14773 usedPermissions.add(permission); 14774 } 14775 } 14776 } 14777 14778 PermissionsState permissionsState = su.getPermissionsState(); 14779 // Prune install permissions 14780 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14781 final int installPermCount = installPermStates.size(); 14782 for (int i = installPermCount - 1; i >= 0; i--) { 14783 PermissionState permissionState = installPermStates.get(i); 14784 if (!usedPermissions.contains(permissionState.getName())) { 14785 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14786 if (bp != null) { 14787 permissionsState.revokeInstallPermission(bp); 14788 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14789 PackageManager.MASK_PERMISSION_FLAGS, 0); 14790 } 14791 } 14792 } 14793 14794 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14795 14796 // Prune runtime permissions 14797 for (int userId : allUserIds) { 14798 List<PermissionState> runtimePermStates = permissionsState 14799 .getRuntimePermissionStates(userId); 14800 final int runtimePermCount = runtimePermStates.size(); 14801 for (int i = runtimePermCount - 1; i >= 0; i--) { 14802 PermissionState permissionState = runtimePermStates.get(i); 14803 if (!usedPermissions.contains(permissionState.getName())) { 14804 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14805 if (bp != null) { 14806 permissionsState.revokeRuntimePermission(bp, userId); 14807 permissionsState.updatePermissionFlags(bp, userId, 14808 PackageManager.MASK_PERMISSION_FLAGS, 0); 14809 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14810 runtimePermissionChangedUserIds, userId); 14811 } 14812 } 14813 } 14814 } 14815 14816 return runtimePermissionChangedUserIds; 14817 } 14818 14819 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14820 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14821 // Update the parent package setting 14822 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14823 res, user); 14824 // Update the child packages setting 14825 final int childCount = (newPackage.childPackages != null) 14826 ? newPackage.childPackages.size() : 0; 14827 for (int i = 0; i < childCount; i++) { 14828 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14829 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14830 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14831 childRes.origUsers, childRes, user); 14832 } 14833 } 14834 14835 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14836 String installerPackageName, int[] allUsers, int[] installedForUsers, 14837 PackageInstalledInfo res, UserHandle user) { 14838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14839 14840 String pkgName = newPackage.packageName; 14841 synchronized (mPackages) { 14842 //write settings. the installStatus will be incomplete at this stage. 14843 //note that the new package setting would have already been 14844 //added to mPackages. It hasn't been persisted yet. 14845 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14846 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14847 mSettings.writeLPr(); 14848 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14849 } 14850 14851 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14852 synchronized (mPackages) { 14853 updatePermissionsLPw(newPackage.packageName, newPackage, 14854 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14855 ? UPDATE_PERMISSIONS_ALL : 0)); 14856 // For system-bundled packages, we assume that installing an upgraded version 14857 // of the package implies that the user actually wants to run that new code, 14858 // so we enable the package. 14859 PackageSetting ps = mSettings.mPackages.get(pkgName); 14860 final int userId = user.getIdentifier(); 14861 if (ps != null) { 14862 if (isSystemApp(newPackage)) { 14863 if (DEBUG_INSTALL) { 14864 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14865 } 14866 // Enable system package for requested users 14867 if (res.origUsers != null) { 14868 for (int origUserId : res.origUsers) { 14869 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14870 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14871 origUserId, installerPackageName); 14872 } 14873 } 14874 } 14875 // Also convey the prior install/uninstall state 14876 if (allUsers != null && installedForUsers != null) { 14877 for (int currentUserId : allUsers) { 14878 final boolean installed = ArrayUtils.contains( 14879 installedForUsers, currentUserId); 14880 if (DEBUG_INSTALL) { 14881 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14882 } 14883 ps.setInstalled(installed, currentUserId); 14884 } 14885 // these install state changes will be persisted in the 14886 // upcoming call to mSettings.writeLPr(). 14887 } 14888 } 14889 // It's implied that when a user requests installation, they want the app to be 14890 // installed and enabled. 14891 if (userId != UserHandle.USER_ALL) { 14892 ps.setInstalled(true, userId); 14893 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14894 } 14895 } 14896 res.name = pkgName; 14897 res.uid = newPackage.applicationInfo.uid; 14898 res.pkg = newPackage; 14899 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14900 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14901 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14902 //to update install status 14903 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14904 mSettings.writeLPr(); 14905 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14906 } 14907 14908 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14909 } 14910 14911 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14912 try { 14913 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14914 installPackageLI(args, res); 14915 } finally { 14916 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14917 } 14918 } 14919 14920 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14921 final int installFlags = args.installFlags; 14922 final String installerPackageName = args.installerPackageName; 14923 final String volumeUuid = args.volumeUuid; 14924 final File tmpPackageFile = new File(args.getCodePath()); 14925 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14926 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14927 || (args.volumeUuid != null)); 14928 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14929 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14930 boolean replace = false; 14931 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14932 if (args.move != null) { 14933 // moving a complete application; perform an initial scan on the new install location 14934 scanFlags |= SCAN_INITIAL; 14935 } 14936 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14937 scanFlags |= SCAN_DONT_KILL_APP; 14938 } 14939 14940 // Result object to be returned 14941 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14942 14943 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14944 14945 // Sanity check 14946 if (ephemeral && (forwardLocked || onExternal)) { 14947 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14948 + " external=" + onExternal); 14949 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14950 return; 14951 } 14952 14953 // Retrieve PackageSettings and parse package 14954 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14955 | PackageParser.PARSE_ENFORCE_CODE 14956 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14957 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14958 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14959 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14960 PackageParser pp = new PackageParser(); 14961 pp.setSeparateProcesses(mSeparateProcesses); 14962 pp.setDisplayMetrics(mMetrics); 14963 14964 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14965 final PackageParser.Package pkg; 14966 try { 14967 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14968 } catch (PackageParserException e) { 14969 res.setError("Failed parse during installPackageLI", e); 14970 return; 14971 } finally { 14972 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14973 } 14974 14975 // If we are installing a clustered package add results for the children 14976 if (pkg.childPackages != null) { 14977 synchronized (mPackages) { 14978 final int childCount = pkg.childPackages.size(); 14979 for (int i = 0; i < childCount; i++) { 14980 PackageParser.Package childPkg = pkg.childPackages.get(i); 14981 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14982 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14983 childRes.pkg = childPkg; 14984 childRes.name = childPkg.packageName; 14985 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14986 if (childPs != null) { 14987 childRes.origUsers = childPs.queryInstalledUsers( 14988 sUserManager.getUserIds(), true); 14989 } 14990 if ((mPackages.containsKey(childPkg.packageName))) { 14991 childRes.removedInfo = new PackageRemovedInfo(); 14992 childRes.removedInfo.removedPackage = childPkg.packageName; 14993 } 14994 if (res.addedChildPackages == null) { 14995 res.addedChildPackages = new ArrayMap<>(); 14996 } 14997 res.addedChildPackages.put(childPkg.packageName, childRes); 14998 } 14999 } 15000 } 15001 15002 // If package doesn't declare API override, mark that we have an install 15003 // time CPU ABI override. 15004 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15005 pkg.cpuAbiOverride = args.abiOverride; 15006 } 15007 15008 String pkgName = res.name = pkg.packageName; 15009 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15010 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15011 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15012 return; 15013 } 15014 } 15015 15016 try { 15017 // either use what we've been given or parse directly from the APK 15018 if (args.certificates != null) { 15019 try { 15020 PackageParser.populateCertificates(pkg, args.certificates); 15021 } catch (PackageParserException e) { 15022 // there was something wrong with the certificates we were given; 15023 // try to pull them from the APK 15024 PackageParser.collectCertificates(pkg, parseFlags); 15025 } 15026 } else { 15027 PackageParser.collectCertificates(pkg, parseFlags); 15028 } 15029 } catch (PackageParserException e) { 15030 res.setError("Failed collect during installPackageLI", e); 15031 return; 15032 } 15033 15034 // Get rid of all references to package scan path via parser. 15035 pp = null; 15036 String oldCodePath = null; 15037 boolean systemApp = false; 15038 synchronized (mPackages) { 15039 // Check if installing already existing package 15040 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15041 String oldName = mSettings.mRenamedPackages.get(pkgName); 15042 if (pkg.mOriginalPackages != null 15043 && pkg.mOriginalPackages.contains(oldName) 15044 && mPackages.containsKey(oldName)) { 15045 // This package is derived from an original package, 15046 // and this device has been updating from that original 15047 // name. We must continue using the original name, so 15048 // rename the new package here. 15049 pkg.setPackageName(oldName); 15050 pkgName = pkg.packageName; 15051 replace = true; 15052 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15053 + oldName + " pkgName=" + pkgName); 15054 } else if (mPackages.containsKey(pkgName)) { 15055 // This package, under its official name, already exists 15056 // on the device; we should replace it. 15057 replace = true; 15058 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15059 } 15060 15061 // Child packages are installed through the parent package 15062 if (pkg.parentPackage != null) { 15063 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15064 "Package " + pkg.packageName + " is child of package " 15065 + pkg.parentPackage.parentPackage + ". Child packages " 15066 + "can be updated only through the parent package."); 15067 return; 15068 } 15069 15070 if (replace) { 15071 // Prevent apps opting out from runtime permissions 15072 PackageParser.Package oldPackage = mPackages.get(pkgName); 15073 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15074 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15075 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15076 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15077 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15078 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15079 + " doesn't support runtime permissions but the old" 15080 + " target SDK " + oldTargetSdk + " does."); 15081 return; 15082 } 15083 15084 // Prevent installing of child packages 15085 if (oldPackage.parentPackage != null) { 15086 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15087 "Package " + pkg.packageName + " is child of package " 15088 + oldPackage.parentPackage + ". Child packages " 15089 + "can be updated only through the parent package."); 15090 return; 15091 } 15092 } 15093 } 15094 15095 PackageSetting ps = mSettings.mPackages.get(pkgName); 15096 if (ps != null) { 15097 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15098 15099 // Quick sanity check that we're signed correctly if updating; 15100 // we'll check this again later when scanning, but we want to 15101 // bail early here before tripping over redefined permissions. 15102 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15103 if (!checkUpgradeKeySetLP(ps, pkg)) { 15104 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15105 + pkg.packageName + " upgrade keys do not match the " 15106 + "previously installed version"); 15107 return; 15108 } 15109 } else { 15110 try { 15111 verifySignaturesLP(ps, pkg); 15112 } catch (PackageManagerException e) { 15113 res.setError(e.error, e.getMessage()); 15114 return; 15115 } 15116 } 15117 15118 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15119 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15120 systemApp = (ps.pkg.applicationInfo.flags & 15121 ApplicationInfo.FLAG_SYSTEM) != 0; 15122 } 15123 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15124 } 15125 15126 // Check whether the newly-scanned package wants to define an already-defined perm 15127 int N = pkg.permissions.size(); 15128 for (int i = N-1; i >= 0; i--) { 15129 PackageParser.Permission perm = pkg.permissions.get(i); 15130 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15131 if (bp != null) { 15132 // If the defining package is signed with our cert, it's okay. This 15133 // also includes the "updating the same package" case, of course. 15134 // "updating same package" could also involve key-rotation. 15135 final boolean sigsOk; 15136 if (bp.sourcePackage.equals(pkg.packageName) 15137 && (bp.packageSetting instanceof PackageSetting) 15138 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15139 scanFlags))) { 15140 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15141 } else { 15142 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15143 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15144 } 15145 if (!sigsOk) { 15146 // If the owning package is the system itself, we log but allow 15147 // install to proceed; we fail the install on all other permission 15148 // redefinitions. 15149 if (!bp.sourcePackage.equals("android")) { 15150 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15151 + pkg.packageName + " attempting to redeclare permission " 15152 + perm.info.name + " already owned by " + bp.sourcePackage); 15153 res.origPermission = perm.info.name; 15154 res.origPackage = bp.sourcePackage; 15155 return; 15156 } else { 15157 Slog.w(TAG, "Package " + pkg.packageName 15158 + " attempting to redeclare system permission " 15159 + perm.info.name + "; ignoring new declaration"); 15160 pkg.permissions.remove(i); 15161 } 15162 } 15163 } 15164 } 15165 } 15166 15167 if (systemApp) { 15168 if (onExternal) { 15169 // Abort update; system app can't be replaced with app on sdcard 15170 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15171 "Cannot install updates to system apps on sdcard"); 15172 return; 15173 } else if (ephemeral) { 15174 // Abort update; system app can't be replaced with an ephemeral app 15175 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15176 "Cannot update a system app with an ephemeral app"); 15177 return; 15178 } 15179 } 15180 15181 if (args.move != null) { 15182 // We did an in-place move, so dex is ready to roll 15183 scanFlags |= SCAN_NO_DEX; 15184 scanFlags |= SCAN_MOVE; 15185 15186 synchronized (mPackages) { 15187 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15188 if (ps == null) { 15189 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15190 "Missing settings for moved package " + pkgName); 15191 } 15192 15193 // We moved the entire application as-is, so bring over the 15194 // previously derived ABI information. 15195 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15196 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15197 } 15198 15199 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15200 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15201 scanFlags |= SCAN_NO_DEX; 15202 15203 try { 15204 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15205 args.abiOverride : pkg.cpuAbiOverride); 15206 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15207 true /* extract libs */); 15208 } catch (PackageManagerException pme) { 15209 Slog.e(TAG, "Error deriving application ABI", pme); 15210 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15211 return; 15212 } 15213 15214 // Shared libraries for the package need to be updated. 15215 synchronized (mPackages) { 15216 try { 15217 updateSharedLibrariesLPw(pkg, null); 15218 } catch (PackageManagerException e) { 15219 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15220 } 15221 } 15222 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15223 // Do not run PackageDexOptimizer through the local performDexOpt 15224 // method because `pkg` may not be in `mPackages` yet. 15225 // 15226 // Also, don't fail application installs if the dexopt step fails. 15227 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15228 null /* instructionSets */, false /* checkProfiles */, 15229 getCompilerFilterForReason(REASON_INSTALL)); 15230 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15231 15232 // Notify BackgroundDexOptService that the package has been changed. 15233 // If this is an update of a package which used to fail to compile, 15234 // BDOS will remove it from its blacklist. 15235 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15236 } 15237 15238 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15239 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15240 return; 15241 } 15242 15243 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15244 15245 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15246 "installPackageLI")) { 15247 if (replace) { 15248 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15249 installerPackageName, res); 15250 } else { 15251 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15252 args.user, installerPackageName, volumeUuid, res); 15253 } 15254 } 15255 synchronized (mPackages) { 15256 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15257 if (ps != null) { 15258 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15259 } 15260 15261 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15262 for (int i = 0; i < childCount; i++) { 15263 PackageParser.Package childPkg = pkg.childPackages.get(i); 15264 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15265 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15266 if (childPs != null) { 15267 childRes.newUsers = childPs.queryInstalledUsers( 15268 sUserManager.getUserIds(), true); 15269 } 15270 } 15271 } 15272 } 15273 15274 private void startIntentFilterVerifications(int userId, boolean replacing, 15275 PackageParser.Package pkg) { 15276 if (mIntentFilterVerifierComponent == null) { 15277 Slog.w(TAG, "No IntentFilter verification will not be done as " 15278 + "there is no IntentFilterVerifier available!"); 15279 return; 15280 } 15281 15282 final int verifierUid = getPackageUid( 15283 mIntentFilterVerifierComponent.getPackageName(), 15284 MATCH_DEBUG_TRIAGED_MISSING, 15285 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15286 15287 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15288 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15289 mHandler.sendMessage(msg); 15290 15291 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15292 for (int i = 0; i < childCount; i++) { 15293 PackageParser.Package childPkg = pkg.childPackages.get(i); 15294 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15295 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15296 mHandler.sendMessage(msg); 15297 } 15298 } 15299 15300 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15301 PackageParser.Package pkg) { 15302 int size = pkg.activities.size(); 15303 if (size == 0) { 15304 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15305 "No activity, so no need to verify any IntentFilter!"); 15306 return; 15307 } 15308 15309 final boolean hasDomainURLs = hasDomainURLs(pkg); 15310 if (!hasDomainURLs) { 15311 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15312 "No domain URLs, so no need to verify any IntentFilter!"); 15313 return; 15314 } 15315 15316 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15317 + " if any IntentFilter from the " + size 15318 + " Activities needs verification ..."); 15319 15320 int count = 0; 15321 final String packageName = pkg.packageName; 15322 15323 synchronized (mPackages) { 15324 // If this is a new install and we see that we've already run verification for this 15325 // package, we have nothing to do: it means the state was restored from backup. 15326 if (!replacing) { 15327 IntentFilterVerificationInfo ivi = 15328 mSettings.getIntentFilterVerificationLPr(packageName); 15329 if (ivi != null) { 15330 if (DEBUG_DOMAIN_VERIFICATION) { 15331 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15332 + ivi.getStatusString()); 15333 } 15334 return; 15335 } 15336 } 15337 15338 // If any filters need to be verified, then all need to be. 15339 boolean needToVerify = false; 15340 for (PackageParser.Activity a : pkg.activities) { 15341 for (ActivityIntentInfo filter : a.intents) { 15342 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15343 if (DEBUG_DOMAIN_VERIFICATION) { 15344 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15345 } 15346 needToVerify = true; 15347 break; 15348 } 15349 } 15350 } 15351 15352 if (needToVerify) { 15353 final int verificationId = mIntentFilterVerificationToken++; 15354 for (PackageParser.Activity a : pkg.activities) { 15355 for (ActivityIntentInfo filter : a.intents) { 15356 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15357 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15358 "Verification needed for IntentFilter:" + filter.toString()); 15359 mIntentFilterVerifier.addOneIntentFilterVerification( 15360 verifierUid, userId, verificationId, filter, packageName); 15361 count++; 15362 } 15363 } 15364 } 15365 } 15366 } 15367 15368 if (count > 0) { 15369 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15370 + " IntentFilter verification" + (count > 1 ? "s" : "") 15371 + " for userId:" + userId); 15372 mIntentFilterVerifier.startVerifications(userId); 15373 } else { 15374 if (DEBUG_DOMAIN_VERIFICATION) { 15375 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15376 } 15377 } 15378 } 15379 15380 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15381 final ComponentName cn = filter.activity.getComponentName(); 15382 final String packageName = cn.getPackageName(); 15383 15384 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15385 packageName); 15386 if (ivi == null) { 15387 return true; 15388 } 15389 int status = ivi.getStatus(); 15390 switch (status) { 15391 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15392 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15393 return true; 15394 15395 default: 15396 // Nothing to do 15397 return false; 15398 } 15399 } 15400 15401 private static boolean isMultiArch(ApplicationInfo info) { 15402 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15403 } 15404 15405 private static boolean isExternal(PackageParser.Package pkg) { 15406 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15407 } 15408 15409 private static boolean isExternal(PackageSetting ps) { 15410 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15411 } 15412 15413 private static boolean isEphemeral(PackageParser.Package pkg) { 15414 return pkg.applicationInfo.isEphemeralApp(); 15415 } 15416 15417 private static boolean isEphemeral(PackageSetting ps) { 15418 return ps.pkg != null && isEphemeral(ps.pkg); 15419 } 15420 15421 private static boolean isSystemApp(PackageParser.Package pkg) { 15422 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15423 } 15424 15425 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15426 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15427 } 15428 15429 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15430 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15431 } 15432 15433 private static boolean isSystemApp(PackageSetting ps) { 15434 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15435 } 15436 15437 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15438 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15439 } 15440 15441 private int packageFlagsToInstallFlags(PackageSetting ps) { 15442 int installFlags = 0; 15443 if (isEphemeral(ps)) { 15444 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15445 } 15446 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15447 // This existing package was an external ASEC install when we have 15448 // the external flag without a UUID 15449 installFlags |= PackageManager.INSTALL_EXTERNAL; 15450 } 15451 if (ps.isForwardLocked()) { 15452 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15453 } 15454 return installFlags; 15455 } 15456 15457 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15458 if (isExternal(pkg)) { 15459 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15460 return StorageManager.UUID_PRIMARY_PHYSICAL; 15461 } else { 15462 return pkg.volumeUuid; 15463 } 15464 } else { 15465 return StorageManager.UUID_PRIVATE_INTERNAL; 15466 } 15467 } 15468 15469 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15470 if (isExternal(pkg)) { 15471 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15472 return mSettings.getExternalVersion(); 15473 } else { 15474 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15475 } 15476 } else { 15477 return mSettings.getInternalVersion(); 15478 } 15479 } 15480 15481 private void deleteTempPackageFiles() { 15482 final FilenameFilter filter = new FilenameFilter() { 15483 public boolean accept(File dir, String name) { 15484 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15485 } 15486 }; 15487 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15488 file.delete(); 15489 } 15490 } 15491 15492 @Override 15493 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15494 int flags) { 15495 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15496 flags); 15497 } 15498 15499 @Override 15500 public void deletePackage(final String packageName, 15501 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15502 mContext.enforceCallingOrSelfPermission( 15503 android.Manifest.permission.DELETE_PACKAGES, null); 15504 Preconditions.checkNotNull(packageName); 15505 Preconditions.checkNotNull(observer); 15506 final int uid = Binder.getCallingUid(); 15507 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15508 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15509 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15510 mContext.enforceCallingOrSelfPermission( 15511 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15512 "deletePackage for user " + userId); 15513 } 15514 15515 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15516 try { 15517 observer.onPackageDeleted(packageName, 15518 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15519 } catch (RemoteException re) { 15520 } 15521 return; 15522 } 15523 15524 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15525 try { 15526 observer.onPackageDeleted(packageName, 15527 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15528 } catch (RemoteException re) { 15529 } 15530 return; 15531 } 15532 15533 if (DEBUG_REMOVE) { 15534 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15535 + " deleteAllUsers: " + deleteAllUsers ); 15536 } 15537 // Queue up an async operation since the package deletion may take a little while. 15538 mHandler.post(new Runnable() { 15539 public void run() { 15540 mHandler.removeCallbacks(this); 15541 int returnCode; 15542 if (!deleteAllUsers) { 15543 returnCode = deletePackageX(packageName, userId, deleteFlags); 15544 } else { 15545 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15546 // If nobody is blocking uninstall, proceed with delete for all users 15547 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15548 returnCode = deletePackageX(packageName, userId, deleteFlags); 15549 } else { 15550 // Otherwise uninstall individually for users with blockUninstalls=false 15551 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15552 for (int userId : users) { 15553 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15554 returnCode = deletePackageX(packageName, userId, userFlags); 15555 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15556 Slog.w(TAG, "Package delete failed for user " + userId 15557 + ", returnCode " + returnCode); 15558 } 15559 } 15560 } 15561 // The app has only been marked uninstalled for certain users. 15562 // We still need to report that delete was blocked 15563 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15564 } 15565 } 15566 try { 15567 observer.onPackageDeleted(packageName, returnCode, null); 15568 } catch (RemoteException e) { 15569 Log.i(TAG, "Observer no longer exists."); 15570 } //end catch 15571 } //end run 15572 }); 15573 } 15574 15575 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15576 int[] result = EMPTY_INT_ARRAY; 15577 for (int userId : userIds) { 15578 if (getBlockUninstallForUser(packageName, userId)) { 15579 result = ArrayUtils.appendInt(result, userId); 15580 } 15581 } 15582 return result; 15583 } 15584 15585 @Override 15586 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15587 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15588 } 15589 15590 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15591 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15592 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15593 try { 15594 if (dpm != null) { 15595 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15596 /* callingUserOnly =*/ false); 15597 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15598 : deviceOwnerComponentName.getPackageName(); 15599 // Does the package contains the device owner? 15600 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15601 // this check is probably not needed, since DO should be registered as a device 15602 // admin on some user too. (Original bug for this: b/17657954) 15603 if (packageName.equals(deviceOwnerPackageName)) { 15604 return true; 15605 } 15606 // Does it contain a device admin for any user? 15607 int[] users; 15608 if (userId == UserHandle.USER_ALL) { 15609 users = sUserManager.getUserIds(); 15610 } else { 15611 users = new int[]{userId}; 15612 } 15613 for (int i = 0; i < users.length; ++i) { 15614 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15615 return true; 15616 } 15617 } 15618 } 15619 } catch (RemoteException e) { 15620 } 15621 return false; 15622 } 15623 15624 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15625 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15626 } 15627 15628 /** 15629 * This method is an internal method that could be get invoked either 15630 * to delete an installed package or to clean up a failed installation. 15631 * After deleting an installed package, a broadcast is sent to notify any 15632 * listeners that the package has been removed. For cleaning up a failed 15633 * installation, the broadcast is not necessary since the package's 15634 * installation wouldn't have sent the initial broadcast either 15635 * The key steps in deleting a package are 15636 * deleting the package information in internal structures like mPackages, 15637 * deleting the packages base directories through installd 15638 * updating mSettings to reflect current status 15639 * persisting settings for later use 15640 * sending a broadcast if necessary 15641 */ 15642 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15643 final PackageRemovedInfo info = new PackageRemovedInfo(); 15644 final boolean res; 15645 15646 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15647 ? UserHandle.USER_ALL : userId; 15648 15649 if (isPackageDeviceAdmin(packageName, removeUser)) { 15650 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15651 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15652 } 15653 15654 PackageSetting uninstalledPs = null; 15655 15656 // for the uninstall-updates case and restricted profiles, remember the per- 15657 // user handle installed state 15658 int[] allUsers; 15659 synchronized (mPackages) { 15660 uninstalledPs = mSettings.mPackages.get(packageName); 15661 if (uninstalledPs == null) { 15662 Slog.w(TAG, "Not removing non-existent package " + packageName); 15663 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15664 } 15665 allUsers = sUserManager.getUserIds(); 15666 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15667 } 15668 15669 final int freezeUser; 15670 if (isUpdatedSystemApp(uninstalledPs) 15671 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15672 // We're downgrading a system app, which will apply to all users, so 15673 // freeze them all during the downgrade 15674 freezeUser = UserHandle.USER_ALL; 15675 } else { 15676 freezeUser = removeUser; 15677 } 15678 15679 synchronized (mInstallLock) { 15680 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15681 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15682 deleteFlags, "deletePackageX")) { 15683 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15684 deleteFlags | REMOVE_CHATTY, info, true, null); 15685 } 15686 synchronized (mPackages) { 15687 if (res) { 15688 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15689 } 15690 } 15691 } 15692 15693 if (res) { 15694 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15695 info.sendPackageRemovedBroadcasts(killApp); 15696 info.sendSystemPackageUpdatedBroadcasts(); 15697 info.sendSystemPackageAppearedBroadcasts(); 15698 } 15699 // Force a gc here. 15700 Runtime.getRuntime().gc(); 15701 // Delete the resources here after sending the broadcast to let 15702 // other processes clean up before deleting resources. 15703 if (info.args != null) { 15704 synchronized (mInstallLock) { 15705 info.args.doPostDeleteLI(true); 15706 } 15707 } 15708 15709 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15710 } 15711 15712 class PackageRemovedInfo { 15713 String removedPackage; 15714 int uid = -1; 15715 int removedAppId = -1; 15716 int[] origUsers; 15717 int[] removedUsers = null; 15718 boolean isRemovedPackageSystemUpdate = false; 15719 boolean isUpdate; 15720 boolean dataRemoved; 15721 boolean removedForAllUsers; 15722 // Clean up resources deleted packages. 15723 InstallArgs args = null; 15724 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15725 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15726 15727 void sendPackageRemovedBroadcasts(boolean killApp) { 15728 sendPackageRemovedBroadcastInternal(killApp); 15729 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15730 for (int i = 0; i < childCount; i++) { 15731 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15732 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15733 } 15734 } 15735 15736 void sendSystemPackageUpdatedBroadcasts() { 15737 if (isRemovedPackageSystemUpdate) { 15738 sendSystemPackageUpdatedBroadcastsInternal(); 15739 final int childCount = (removedChildPackages != null) 15740 ? removedChildPackages.size() : 0; 15741 for (int i = 0; i < childCount; i++) { 15742 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15743 if (childInfo.isRemovedPackageSystemUpdate) { 15744 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15745 } 15746 } 15747 } 15748 } 15749 15750 void sendSystemPackageAppearedBroadcasts() { 15751 final int packageCount = (appearedChildPackages != null) 15752 ? appearedChildPackages.size() : 0; 15753 for (int i = 0; i < packageCount; i++) { 15754 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15755 for (int userId : installedInfo.newUsers) { 15756 sendPackageAddedForUser(installedInfo.name, true, 15757 UserHandle.getAppId(installedInfo.uid), userId); 15758 } 15759 } 15760 } 15761 15762 private void sendSystemPackageUpdatedBroadcastsInternal() { 15763 Bundle extras = new Bundle(2); 15764 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15765 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15766 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15767 extras, 0, null, null, null); 15768 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15769 extras, 0, null, null, null); 15770 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15771 null, 0, removedPackage, null, null); 15772 } 15773 15774 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15775 Bundle extras = new Bundle(2); 15776 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15777 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15778 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15779 if (isUpdate || isRemovedPackageSystemUpdate) { 15780 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15781 } 15782 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15783 if (removedPackage != null) { 15784 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15785 extras, 0, null, null, removedUsers); 15786 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15787 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15788 removedPackage, extras, 0, null, null, removedUsers); 15789 } 15790 } 15791 if (removedAppId >= 0) { 15792 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15793 removedUsers); 15794 } 15795 } 15796 } 15797 15798 /* 15799 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15800 * flag is not set, the data directory is removed as well. 15801 * make sure this flag is set for partially installed apps. If not its meaningless to 15802 * delete a partially installed application. 15803 */ 15804 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15805 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15806 String packageName = ps.name; 15807 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15808 // Retrieve object to delete permissions for shared user later on 15809 final PackageParser.Package deletedPkg; 15810 final PackageSetting deletedPs; 15811 // reader 15812 synchronized (mPackages) { 15813 deletedPkg = mPackages.get(packageName); 15814 deletedPs = mSettings.mPackages.get(packageName); 15815 if (outInfo != null) { 15816 outInfo.removedPackage = packageName; 15817 outInfo.removedUsers = deletedPs != null 15818 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15819 : null; 15820 } 15821 } 15822 15823 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15824 15825 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15826 final PackageParser.Package resolvedPkg; 15827 if (deletedPkg != null) { 15828 resolvedPkg = deletedPkg; 15829 } else { 15830 // We don't have a parsed package when it lives on an ejected 15831 // adopted storage device, so fake something together 15832 resolvedPkg = new PackageParser.Package(ps.name); 15833 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15834 } 15835 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15836 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15837 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15838 if (outInfo != null) { 15839 outInfo.dataRemoved = true; 15840 } 15841 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15842 } 15843 15844 // writer 15845 synchronized (mPackages) { 15846 if (deletedPs != null) { 15847 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15848 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15849 clearDefaultBrowserIfNeeded(packageName); 15850 if (outInfo != null) { 15851 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15852 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15853 } 15854 updatePermissionsLPw(deletedPs.name, null, 0); 15855 if (deletedPs.sharedUser != null) { 15856 // Remove permissions associated with package. Since runtime 15857 // permissions are per user we have to kill the removed package 15858 // or packages running under the shared user of the removed 15859 // package if revoking the permissions requested only by the removed 15860 // package is successful and this causes a change in gids. 15861 for (int userId : UserManagerService.getInstance().getUserIds()) { 15862 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15863 userId); 15864 if (userIdToKill == UserHandle.USER_ALL 15865 || userIdToKill >= UserHandle.USER_SYSTEM) { 15866 // If gids changed for this user, kill all affected packages. 15867 mHandler.post(new Runnable() { 15868 @Override 15869 public void run() { 15870 // This has to happen with no lock held. 15871 killApplication(deletedPs.name, deletedPs.appId, 15872 KILL_APP_REASON_GIDS_CHANGED); 15873 } 15874 }); 15875 break; 15876 } 15877 } 15878 } 15879 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15880 } 15881 // make sure to preserve per-user disabled state if this removal was just 15882 // a downgrade of a system app to the factory package 15883 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15884 if (DEBUG_REMOVE) { 15885 Slog.d(TAG, "Propagating install state across downgrade"); 15886 } 15887 for (int userId : allUserHandles) { 15888 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15889 if (DEBUG_REMOVE) { 15890 Slog.d(TAG, " user " + userId + " => " + installed); 15891 } 15892 ps.setInstalled(installed, userId); 15893 } 15894 } 15895 } 15896 // can downgrade to reader 15897 if (writeSettings) { 15898 // Save settings now 15899 mSettings.writeLPr(); 15900 } 15901 } 15902 if (outInfo != null) { 15903 // A user ID was deleted here. Go through all users and remove it 15904 // from KeyStore. 15905 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15906 } 15907 } 15908 15909 static boolean locationIsPrivileged(File path) { 15910 try { 15911 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15912 .getCanonicalPath(); 15913 return path.getCanonicalPath().startsWith(privilegedAppDir); 15914 } catch (IOException e) { 15915 Slog.e(TAG, "Unable to access code path " + path); 15916 } 15917 return false; 15918 } 15919 15920 /* 15921 * Tries to delete system package. 15922 */ 15923 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15924 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15925 boolean writeSettings) { 15926 if (deletedPs.parentPackageName != null) { 15927 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15928 return false; 15929 } 15930 15931 final boolean applyUserRestrictions 15932 = (allUserHandles != null) && (outInfo.origUsers != null); 15933 final PackageSetting disabledPs; 15934 // Confirm if the system package has been updated 15935 // An updated system app can be deleted. This will also have to restore 15936 // the system pkg from system partition 15937 // reader 15938 synchronized (mPackages) { 15939 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15940 } 15941 15942 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15943 + " disabledPs=" + disabledPs); 15944 15945 if (disabledPs == null) { 15946 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15947 return false; 15948 } else if (DEBUG_REMOVE) { 15949 Slog.d(TAG, "Deleting system pkg from data partition"); 15950 } 15951 15952 if (DEBUG_REMOVE) { 15953 if (applyUserRestrictions) { 15954 Slog.d(TAG, "Remembering install states:"); 15955 for (int userId : allUserHandles) { 15956 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15957 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15958 } 15959 } 15960 } 15961 15962 // Delete the updated package 15963 outInfo.isRemovedPackageSystemUpdate = true; 15964 if (outInfo.removedChildPackages != null) { 15965 final int childCount = (deletedPs.childPackageNames != null) 15966 ? deletedPs.childPackageNames.size() : 0; 15967 for (int i = 0; i < childCount; i++) { 15968 String childPackageName = deletedPs.childPackageNames.get(i); 15969 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15970 .contains(childPackageName)) { 15971 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15972 childPackageName); 15973 if (childInfo != null) { 15974 childInfo.isRemovedPackageSystemUpdate = true; 15975 } 15976 } 15977 } 15978 } 15979 15980 if (disabledPs.versionCode < deletedPs.versionCode) { 15981 // Delete data for downgrades 15982 flags &= ~PackageManager.DELETE_KEEP_DATA; 15983 } else { 15984 // Preserve data by setting flag 15985 flags |= PackageManager.DELETE_KEEP_DATA; 15986 } 15987 15988 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15989 outInfo, writeSettings, disabledPs.pkg); 15990 if (!ret) { 15991 return false; 15992 } 15993 15994 // writer 15995 synchronized (mPackages) { 15996 // Reinstate the old system package 15997 enableSystemPackageLPw(disabledPs.pkg); 15998 // Remove any native libraries from the upgraded package. 15999 removeNativeBinariesLI(deletedPs); 16000 } 16001 16002 // Install the system package 16003 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16004 int parseFlags = mDefParseFlags 16005 | PackageParser.PARSE_MUST_BE_APK 16006 | PackageParser.PARSE_IS_SYSTEM 16007 | PackageParser.PARSE_IS_SYSTEM_DIR; 16008 if (locationIsPrivileged(disabledPs.codePath)) { 16009 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16010 } 16011 16012 final PackageParser.Package newPkg; 16013 try { 16014 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 16015 } catch (PackageManagerException e) { 16016 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16017 + e.getMessage()); 16018 return false; 16019 } 16020 16021 prepareAppDataAfterInstallLIF(newPkg); 16022 16023 // writer 16024 synchronized (mPackages) { 16025 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16026 16027 // Propagate the permissions state as we do not want to drop on the floor 16028 // runtime permissions. The update permissions method below will take 16029 // care of removing obsolete permissions and grant install permissions. 16030 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16031 updatePermissionsLPw(newPkg.packageName, newPkg, 16032 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16033 16034 if (applyUserRestrictions) { 16035 if (DEBUG_REMOVE) { 16036 Slog.d(TAG, "Propagating install state across reinstall"); 16037 } 16038 for (int userId : allUserHandles) { 16039 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16040 if (DEBUG_REMOVE) { 16041 Slog.d(TAG, " user " + userId + " => " + installed); 16042 } 16043 ps.setInstalled(installed, userId); 16044 16045 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16046 } 16047 // Regardless of writeSettings we need to ensure that this restriction 16048 // state propagation is persisted 16049 mSettings.writeAllUsersPackageRestrictionsLPr(); 16050 } 16051 // can downgrade to reader here 16052 if (writeSettings) { 16053 mSettings.writeLPr(); 16054 } 16055 } 16056 return true; 16057 } 16058 16059 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16060 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16061 PackageRemovedInfo outInfo, boolean writeSettings, 16062 PackageParser.Package replacingPackage) { 16063 synchronized (mPackages) { 16064 if (outInfo != null) { 16065 outInfo.uid = ps.appId; 16066 } 16067 16068 if (outInfo != null && outInfo.removedChildPackages != null) { 16069 final int childCount = (ps.childPackageNames != null) 16070 ? ps.childPackageNames.size() : 0; 16071 for (int i = 0; i < childCount; i++) { 16072 String childPackageName = ps.childPackageNames.get(i); 16073 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16074 if (childPs == null) { 16075 return false; 16076 } 16077 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16078 childPackageName); 16079 if (childInfo != null) { 16080 childInfo.uid = childPs.appId; 16081 } 16082 } 16083 } 16084 } 16085 16086 // Delete package data from internal structures and also remove data if flag is set 16087 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16088 16089 // Delete the child packages data 16090 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16091 for (int i = 0; i < childCount; i++) { 16092 PackageSetting childPs; 16093 synchronized (mPackages) { 16094 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16095 } 16096 if (childPs != null) { 16097 PackageRemovedInfo childOutInfo = (outInfo != null 16098 && outInfo.removedChildPackages != null) 16099 ? outInfo.removedChildPackages.get(childPs.name) : null; 16100 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16101 && (replacingPackage != null 16102 && !replacingPackage.hasChildPackage(childPs.name)) 16103 ? flags & ~DELETE_KEEP_DATA : flags; 16104 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16105 deleteFlags, writeSettings); 16106 } 16107 } 16108 16109 // Delete application code and resources only for parent packages 16110 if (ps.parentPackageName == null) { 16111 if (deleteCodeAndResources && (outInfo != null)) { 16112 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16113 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16114 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16115 } 16116 } 16117 16118 return true; 16119 } 16120 16121 @Override 16122 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16123 int userId) { 16124 mContext.enforceCallingOrSelfPermission( 16125 android.Manifest.permission.DELETE_PACKAGES, null); 16126 synchronized (mPackages) { 16127 PackageSetting ps = mSettings.mPackages.get(packageName); 16128 if (ps == null) { 16129 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16130 return false; 16131 } 16132 if (!ps.getInstalled(userId)) { 16133 // Can't block uninstall for an app that is not installed or enabled. 16134 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16135 return false; 16136 } 16137 ps.setBlockUninstall(blockUninstall, userId); 16138 mSettings.writePackageRestrictionsLPr(userId); 16139 } 16140 return true; 16141 } 16142 16143 @Override 16144 public boolean getBlockUninstallForUser(String packageName, int userId) { 16145 synchronized (mPackages) { 16146 PackageSetting ps = mSettings.mPackages.get(packageName); 16147 if (ps == null) { 16148 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16149 return false; 16150 } 16151 return ps.getBlockUninstall(userId); 16152 } 16153 } 16154 16155 @Override 16156 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16157 int callingUid = Binder.getCallingUid(); 16158 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16159 throw new SecurityException( 16160 "setRequiredForSystemUser can only be run by the system or root"); 16161 } 16162 synchronized (mPackages) { 16163 PackageSetting ps = mSettings.mPackages.get(packageName); 16164 if (ps == null) { 16165 Log.w(TAG, "Package doesn't exist: " + packageName); 16166 return false; 16167 } 16168 if (systemUserApp) { 16169 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16170 } else { 16171 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16172 } 16173 mSettings.writeLPr(); 16174 } 16175 return true; 16176 } 16177 16178 /* 16179 * This method handles package deletion in general 16180 */ 16181 private boolean deletePackageLIF(String packageName, UserHandle user, 16182 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16183 PackageRemovedInfo outInfo, boolean writeSettings, 16184 PackageParser.Package replacingPackage) { 16185 if (packageName == null) { 16186 Slog.w(TAG, "Attempt to delete null packageName."); 16187 return false; 16188 } 16189 16190 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16191 16192 PackageSetting ps; 16193 16194 synchronized (mPackages) { 16195 ps = mSettings.mPackages.get(packageName); 16196 if (ps == null) { 16197 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16198 return false; 16199 } 16200 16201 if (ps.parentPackageName != null && (!isSystemApp(ps) 16202 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16203 if (DEBUG_REMOVE) { 16204 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16205 + ((user == null) ? UserHandle.USER_ALL : user)); 16206 } 16207 final int removedUserId = (user != null) ? user.getIdentifier() 16208 : UserHandle.USER_ALL; 16209 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16210 return false; 16211 } 16212 markPackageUninstalledForUserLPw(ps, user); 16213 scheduleWritePackageRestrictionsLocked(user); 16214 return true; 16215 } 16216 } 16217 16218 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16219 && user.getIdentifier() != UserHandle.USER_ALL)) { 16220 // The caller is asking that the package only be deleted for a single 16221 // user. To do this, we just mark its uninstalled state and delete 16222 // its data. If this is a system app, we only allow this to happen if 16223 // they have set the special DELETE_SYSTEM_APP which requests different 16224 // semantics than normal for uninstalling system apps. 16225 markPackageUninstalledForUserLPw(ps, user); 16226 16227 if (!isSystemApp(ps)) { 16228 // Do not uninstall the APK if an app should be cached 16229 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16230 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16231 // Other user still have this package installed, so all 16232 // we need to do is clear this user's data and save that 16233 // it is uninstalled. 16234 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16235 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16236 return false; 16237 } 16238 scheduleWritePackageRestrictionsLocked(user); 16239 return true; 16240 } else { 16241 // We need to set it back to 'installed' so the uninstall 16242 // broadcasts will be sent correctly. 16243 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16244 ps.setInstalled(true, user.getIdentifier()); 16245 } 16246 } else { 16247 // This is a system app, so we assume that the 16248 // other users still have this package installed, so all 16249 // we need to do is clear this user's data and save that 16250 // it is uninstalled. 16251 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16252 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16253 return false; 16254 } 16255 scheduleWritePackageRestrictionsLocked(user); 16256 return true; 16257 } 16258 } 16259 16260 // If we are deleting a composite package for all users, keep track 16261 // of result for each child. 16262 if (ps.childPackageNames != null && outInfo != null) { 16263 synchronized (mPackages) { 16264 final int childCount = ps.childPackageNames.size(); 16265 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16266 for (int i = 0; i < childCount; i++) { 16267 String childPackageName = ps.childPackageNames.get(i); 16268 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16269 childInfo.removedPackage = childPackageName; 16270 outInfo.removedChildPackages.put(childPackageName, childInfo); 16271 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16272 if (childPs != null) { 16273 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16274 } 16275 } 16276 } 16277 } 16278 16279 boolean ret = false; 16280 if (isSystemApp(ps)) { 16281 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16282 // When an updated system application is deleted we delete the existing resources 16283 // as well and fall back to existing code in system partition 16284 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16285 } else { 16286 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16287 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16288 outInfo, writeSettings, replacingPackage); 16289 } 16290 16291 // Take a note whether we deleted the package for all users 16292 if (outInfo != null) { 16293 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16294 if (outInfo.removedChildPackages != null) { 16295 synchronized (mPackages) { 16296 final int childCount = outInfo.removedChildPackages.size(); 16297 for (int i = 0; i < childCount; i++) { 16298 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16299 if (childInfo != null) { 16300 childInfo.removedForAllUsers = mPackages.get( 16301 childInfo.removedPackage) == null; 16302 } 16303 } 16304 } 16305 } 16306 // If we uninstalled an update to a system app there may be some 16307 // child packages that appeared as they are declared in the system 16308 // app but were not declared in the update. 16309 if (isSystemApp(ps)) { 16310 synchronized (mPackages) { 16311 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16312 final int childCount = (updatedPs.childPackageNames != null) 16313 ? updatedPs.childPackageNames.size() : 0; 16314 for (int i = 0; i < childCount; i++) { 16315 String childPackageName = updatedPs.childPackageNames.get(i); 16316 if (outInfo.removedChildPackages == null 16317 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16318 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16319 if (childPs == null) { 16320 continue; 16321 } 16322 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16323 installRes.name = childPackageName; 16324 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16325 installRes.pkg = mPackages.get(childPackageName); 16326 installRes.uid = childPs.pkg.applicationInfo.uid; 16327 if (outInfo.appearedChildPackages == null) { 16328 outInfo.appearedChildPackages = new ArrayMap<>(); 16329 } 16330 outInfo.appearedChildPackages.put(childPackageName, installRes); 16331 } 16332 } 16333 } 16334 } 16335 } 16336 16337 return ret; 16338 } 16339 16340 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16341 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16342 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16343 for (int nextUserId : userIds) { 16344 if (DEBUG_REMOVE) { 16345 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16346 } 16347 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16348 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16349 false /*hidden*/, false /*suspended*/, null, null, null, 16350 false /*blockUninstall*/, 16351 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16352 } 16353 } 16354 16355 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16356 PackageRemovedInfo outInfo) { 16357 final PackageParser.Package pkg; 16358 synchronized (mPackages) { 16359 pkg = mPackages.get(ps.name); 16360 } 16361 16362 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16363 : new int[] {userId}; 16364 for (int nextUserId : userIds) { 16365 if (DEBUG_REMOVE) { 16366 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16367 + nextUserId); 16368 } 16369 16370 destroyAppDataLIF(pkg, userId, 16371 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16372 destroyAppProfilesLIF(pkg, userId); 16373 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16374 schedulePackageCleaning(ps.name, nextUserId, false); 16375 synchronized (mPackages) { 16376 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16377 scheduleWritePackageRestrictionsLocked(nextUserId); 16378 } 16379 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16380 } 16381 } 16382 16383 if (outInfo != null) { 16384 outInfo.removedPackage = ps.name; 16385 outInfo.removedAppId = ps.appId; 16386 outInfo.removedUsers = userIds; 16387 } 16388 16389 return true; 16390 } 16391 16392 private final class ClearStorageConnection implements ServiceConnection { 16393 IMediaContainerService mContainerService; 16394 16395 @Override 16396 public void onServiceConnected(ComponentName name, IBinder service) { 16397 synchronized (this) { 16398 mContainerService = IMediaContainerService.Stub.asInterface(service); 16399 notifyAll(); 16400 } 16401 } 16402 16403 @Override 16404 public void onServiceDisconnected(ComponentName name) { 16405 } 16406 } 16407 16408 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16409 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16410 16411 final boolean mounted; 16412 if (Environment.isExternalStorageEmulated()) { 16413 mounted = true; 16414 } else { 16415 final String status = Environment.getExternalStorageState(); 16416 16417 mounted = status.equals(Environment.MEDIA_MOUNTED) 16418 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16419 } 16420 16421 if (!mounted) { 16422 return; 16423 } 16424 16425 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16426 int[] users; 16427 if (userId == UserHandle.USER_ALL) { 16428 users = sUserManager.getUserIds(); 16429 } else { 16430 users = new int[] { userId }; 16431 } 16432 final ClearStorageConnection conn = new ClearStorageConnection(); 16433 if (mContext.bindServiceAsUser( 16434 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16435 try { 16436 for (int curUser : users) { 16437 long timeout = SystemClock.uptimeMillis() + 5000; 16438 synchronized (conn) { 16439 long now; 16440 while (conn.mContainerService == null && 16441 (now = SystemClock.uptimeMillis()) < timeout) { 16442 try { 16443 conn.wait(timeout - now); 16444 } catch (InterruptedException e) { 16445 } 16446 } 16447 } 16448 if (conn.mContainerService == null) { 16449 return; 16450 } 16451 16452 final UserEnvironment userEnv = new UserEnvironment(curUser); 16453 clearDirectory(conn.mContainerService, 16454 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16455 if (allData) { 16456 clearDirectory(conn.mContainerService, 16457 userEnv.buildExternalStorageAppDataDirs(packageName)); 16458 clearDirectory(conn.mContainerService, 16459 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16460 } 16461 } 16462 } finally { 16463 mContext.unbindService(conn); 16464 } 16465 } 16466 } 16467 16468 @Override 16469 public void clearApplicationProfileData(String packageName) { 16470 enforceSystemOrRoot("Only the system can clear all profile data"); 16471 16472 final PackageParser.Package pkg; 16473 synchronized (mPackages) { 16474 pkg = mPackages.get(packageName); 16475 } 16476 16477 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16478 synchronized (mInstallLock) { 16479 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16480 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16481 true /* removeBaseMarker */); 16482 } 16483 } 16484 } 16485 16486 @Override 16487 public void clearApplicationUserData(final String packageName, 16488 final IPackageDataObserver observer, final int userId) { 16489 mContext.enforceCallingOrSelfPermission( 16490 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16491 16492 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16493 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16494 16495 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16496 throw new SecurityException("Cannot clear data for a protected package: " 16497 + packageName); 16498 } 16499 // Queue up an async operation since the package deletion may take a little while. 16500 mHandler.post(new Runnable() { 16501 public void run() { 16502 mHandler.removeCallbacks(this); 16503 final boolean succeeded; 16504 try (PackageFreezer freezer = freezePackage(packageName, 16505 "clearApplicationUserData")) { 16506 synchronized (mInstallLock) { 16507 succeeded = clearApplicationUserDataLIF(packageName, userId); 16508 } 16509 clearExternalStorageDataSync(packageName, userId, true); 16510 } 16511 if (succeeded) { 16512 // invoke DeviceStorageMonitor's update method to clear any notifications 16513 DeviceStorageMonitorInternal dsm = LocalServices 16514 .getService(DeviceStorageMonitorInternal.class); 16515 if (dsm != null) { 16516 dsm.checkMemory(); 16517 } 16518 } 16519 if(observer != null) { 16520 try { 16521 observer.onRemoveCompleted(packageName, succeeded); 16522 } catch (RemoteException e) { 16523 Log.i(TAG, "Observer no longer exists."); 16524 } 16525 } //end if observer 16526 } //end run 16527 }); 16528 } 16529 16530 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16531 if (packageName == null) { 16532 Slog.w(TAG, "Attempt to delete null packageName."); 16533 return false; 16534 } 16535 16536 // Try finding details about the requested package 16537 PackageParser.Package pkg; 16538 synchronized (mPackages) { 16539 pkg = mPackages.get(packageName); 16540 if (pkg == null) { 16541 final PackageSetting ps = mSettings.mPackages.get(packageName); 16542 if (ps != null) { 16543 pkg = ps.pkg; 16544 } 16545 } 16546 16547 if (pkg == null) { 16548 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16549 return false; 16550 } 16551 16552 PackageSetting ps = (PackageSetting) pkg.mExtras; 16553 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16554 } 16555 16556 clearAppDataLIF(pkg, userId, 16557 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16558 16559 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16560 removeKeystoreDataIfNeeded(userId, appId); 16561 16562 UserManagerInternal umInternal = getUserManagerInternal(); 16563 final int flags; 16564 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16565 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16566 } else if (umInternal.isUserRunning(userId)) { 16567 flags = StorageManager.FLAG_STORAGE_DE; 16568 } else { 16569 flags = 0; 16570 } 16571 prepareAppDataContentsLIF(pkg, userId, flags); 16572 16573 return true; 16574 } 16575 16576 /** 16577 * Reverts user permission state changes (permissions and flags) in 16578 * all packages for a given user. 16579 * 16580 * @param userId The device user for which to do a reset. 16581 */ 16582 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16583 final int packageCount = mPackages.size(); 16584 for (int i = 0; i < packageCount; i++) { 16585 PackageParser.Package pkg = mPackages.valueAt(i); 16586 PackageSetting ps = (PackageSetting) pkg.mExtras; 16587 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16588 } 16589 } 16590 16591 private void resetNetworkPolicies(int userId) { 16592 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16593 } 16594 16595 /** 16596 * Reverts user permission state changes (permissions and flags). 16597 * 16598 * @param ps The package for which to reset. 16599 * @param userId The device user for which to do a reset. 16600 */ 16601 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16602 final PackageSetting ps, final int userId) { 16603 if (ps.pkg == null) { 16604 return; 16605 } 16606 16607 // These are flags that can change base on user actions. 16608 final int userSettableMask = FLAG_PERMISSION_USER_SET 16609 | FLAG_PERMISSION_USER_FIXED 16610 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16611 | FLAG_PERMISSION_REVIEW_REQUIRED; 16612 16613 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16614 | FLAG_PERMISSION_POLICY_FIXED; 16615 16616 boolean writeInstallPermissions = false; 16617 boolean writeRuntimePermissions = false; 16618 16619 final int permissionCount = ps.pkg.requestedPermissions.size(); 16620 for (int i = 0; i < permissionCount; i++) { 16621 String permission = ps.pkg.requestedPermissions.get(i); 16622 16623 BasePermission bp = mSettings.mPermissions.get(permission); 16624 if (bp == null) { 16625 continue; 16626 } 16627 16628 // If shared user we just reset the state to which only this app contributed. 16629 if (ps.sharedUser != null) { 16630 boolean used = false; 16631 final int packageCount = ps.sharedUser.packages.size(); 16632 for (int j = 0; j < packageCount; j++) { 16633 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16634 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16635 && pkg.pkg.requestedPermissions.contains(permission)) { 16636 used = true; 16637 break; 16638 } 16639 } 16640 if (used) { 16641 continue; 16642 } 16643 } 16644 16645 PermissionsState permissionsState = ps.getPermissionsState(); 16646 16647 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16648 16649 // Always clear the user settable flags. 16650 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16651 bp.name) != null; 16652 // If permission review is enabled and this is a legacy app, mark the 16653 // permission as requiring a review as this is the initial state. 16654 int flags = 0; 16655 if (Build.PERMISSIONS_REVIEW_REQUIRED 16656 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16657 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16658 } 16659 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16660 if (hasInstallState) { 16661 writeInstallPermissions = true; 16662 } else { 16663 writeRuntimePermissions = true; 16664 } 16665 } 16666 16667 // Below is only runtime permission handling. 16668 if (!bp.isRuntime()) { 16669 continue; 16670 } 16671 16672 // Never clobber system or policy. 16673 if ((oldFlags & policyOrSystemFlags) != 0) { 16674 continue; 16675 } 16676 16677 // If this permission was granted by default, make sure it is. 16678 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16679 if (permissionsState.grantRuntimePermission(bp, userId) 16680 != PERMISSION_OPERATION_FAILURE) { 16681 writeRuntimePermissions = true; 16682 } 16683 // If permission review is enabled the permissions for a legacy apps 16684 // are represented as constantly granted runtime ones, so don't revoke. 16685 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16686 // Otherwise, reset the permission. 16687 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16688 switch (revokeResult) { 16689 case PERMISSION_OPERATION_SUCCESS: 16690 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16691 writeRuntimePermissions = true; 16692 final int appId = ps.appId; 16693 mHandler.post(new Runnable() { 16694 @Override 16695 public void run() { 16696 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16697 } 16698 }); 16699 } break; 16700 } 16701 } 16702 } 16703 16704 // Synchronously write as we are taking permissions away. 16705 if (writeRuntimePermissions) { 16706 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16707 } 16708 16709 // Synchronously write as we are taking permissions away. 16710 if (writeInstallPermissions) { 16711 mSettings.writeLPr(); 16712 } 16713 } 16714 16715 /** 16716 * Remove entries from the keystore daemon. Will only remove it if the 16717 * {@code appId} is valid. 16718 */ 16719 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16720 if (appId < 0) { 16721 return; 16722 } 16723 16724 final KeyStore keyStore = KeyStore.getInstance(); 16725 if (keyStore != null) { 16726 if (userId == UserHandle.USER_ALL) { 16727 for (final int individual : sUserManager.getUserIds()) { 16728 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16729 } 16730 } else { 16731 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16732 } 16733 } else { 16734 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16735 } 16736 } 16737 16738 @Override 16739 public void deleteApplicationCacheFiles(final String packageName, 16740 final IPackageDataObserver observer) { 16741 final int userId = UserHandle.getCallingUserId(); 16742 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16743 } 16744 16745 @Override 16746 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16747 final IPackageDataObserver observer) { 16748 mContext.enforceCallingOrSelfPermission( 16749 android.Manifest.permission.DELETE_CACHE_FILES, null); 16750 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16751 /* requireFullPermission= */ true, /* checkShell= */ false, 16752 "delete application cache files"); 16753 16754 final PackageParser.Package pkg; 16755 synchronized (mPackages) { 16756 pkg = mPackages.get(packageName); 16757 } 16758 16759 // Queue up an async operation since the package deletion may take a little while. 16760 mHandler.post(new Runnable() { 16761 public void run() { 16762 synchronized (mInstallLock) { 16763 final int flags = StorageManager.FLAG_STORAGE_DE 16764 | StorageManager.FLAG_STORAGE_CE; 16765 // We're only clearing cache files, so we don't care if the 16766 // app is unfrozen and still able to run 16767 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16768 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16769 } 16770 clearExternalStorageDataSync(packageName, userId, false); 16771 if (observer != null) { 16772 try { 16773 observer.onRemoveCompleted(packageName, true); 16774 } catch (RemoteException e) { 16775 Log.i(TAG, "Observer no longer exists."); 16776 } 16777 } 16778 } 16779 }); 16780 } 16781 16782 @Override 16783 public void getPackageSizeInfo(final String packageName, int userHandle, 16784 final IPackageStatsObserver observer) { 16785 mContext.enforceCallingOrSelfPermission( 16786 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16787 if (packageName == null) { 16788 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16789 } 16790 16791 PackageStats stats = new PackageStats(packageName, userHandle); 16792 16793 /* 16794 * Queue up an async operation since the package measurement may take a 16795 * little while. 16796 */ 16797 Message msg = mHandler.obtainMessage(INIT_COPY); 16798 msg.obj = new MeasureParams(stats, observer); 16799 mHandler.sendMessage(msg); 16800 } 16801 16802 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16803 final PackageSetting ps; 16804 synchronized (mPackages) { 16805 ps = mSettings.mPackages.get(packageName); 16806 if (ps == null) { 16807 Slog.w(TAG, "Failed to find settings for " + packageName); 16808 return false; 16809 } 16810 } 16811 try { 16812 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16813 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16814 ps.getCeDataInode(userId), ps.codePathString, stats); 16815 } catch (InstallerException e) { 16816 Slog.w(TAG, String.valueOf(e)); 16817 return false; 16818 } 16819 16820 // For now, ignore code size of packages on system partition 16821 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16822 stats.codeSize = 0; 16823 } 16824 16825 return true; 16826 } 16827 16828 private int getUidTargetSdkVersionLockedLPr(int uid) { 16829 Object obj = mSettings.getUserIdLPr(uid); 16830 if (obj instanceof SharedUserSetting) { 16831 final SharedUserSetting sus = (SharedUserSetting) obj; 16832 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16833 final Iterator<PackageSetting> it = sus.packages.iterator(); 16834 while (it.hasNext()) { 16835 final PackageSetting ps = it.next(); 16836 if (ps.pkg != null) { 16837 int v = ps.pkg.applicationInfo.targetSdkVersion; 16838 if (v < vers) vers = v; 16839 } 16840 } 16841 return vers; 16842 } else if (obj instanceof PackageSetting) { 16843 final PackageSetting ps = (PackageSetting) obj; 16844 if (ps.pkg != null) { 16845 return ps.pkg.applicationInfo.targetSdkVersion; 16846 } 16847 } 16848 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16849 } 16850 16851 @Override 16852 public void addPreferredActivity(IntentFilter filter, int match, 16853 ComponentName[] set, ComponentName activity, int userId) { 16854 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16855 "Adding preferred"); 16856 } 16857 16858 private void addPreferredActivityInternal(IntentFilter filter, int match, 16859 ComponentName[] set, ComponentName activity, boolean always, int userId, 16860 String opname) { 16861 // writer 16862 int callingUid = Binder.getCallingUid(); 16863 enforceCrossUserPermission(callingUid, userId, 16864 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16865 if (filter.countActions() == 0) { 16866 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16867 return; 16868 } 16869 synchronized (mPackages) { 16870 if (mContext.checkCallingOrSelfPermission( 16871 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16872 != PackageManager.PERMISSION_GRANTED) { 16873 if (getUidTargetSdkVersionLockedLPr(callingUid) 16874 < Build.VERSION_CODES.FROYO) { 16875 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16876 + callingUid); 16877 return; 16878 } 16879 mContext.enforceCallingOrSelfPermission( 16880 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16881 } 16882 16883 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16884 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16885 + userId + ":"); 16886 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16887 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16888 scheduleWritePackageRestrictionsLocked(userId); 16889 } 16890 } 16891 16892 @Override 16893 public void replacePreferredActivity(IntentFilter filter, int match, 16894 ComponentName[] set, ComponentName activity, int userId) { 16895 if (filter.countActions() != 1) { 16896 throw new IllegalArgumentException( 16897 "replacePreferredActivity expects filter to have only 1 action."); 16898 } 16899 if (filter.countDataAuthorities() != 0 16900 || filter.countDataPaths() != 0 16901 || filter.countDataSchemes() > 1 16902 || filter.countDataTypes() != 0) { 16903 throw new IllegalArgumentException( 16904 "replacePreferredActivity expects filter to have no data authorities, " + 16905 "paths, or types; and at most one scheme."); 16906 } 16907 16908 final int callingUid = Binder.getCallingUid(); 16909 enforceCrossUserPermission(callingUid, userId, 16910 true /* requireFullPermission */, false /* checkShell */, 16911 "replace preferred activity"); 16912 synchronized (mPackages) { 16913 if (mContext.checkCallingOrSelfPermission( 16914 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16915 != PackageManager.PERMISSION_GRANTED) { 16916 if (getUidTargetSdkVersionLockedLPr(callingUid) 16917 < Build.VERSION_CODES.FROYO) { 16918 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16919 + Binder.getCallingUid()); 16920 return; 16921 } 16922 mContext.enforceCallingOrSelfPermission( 16923 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16924 } 16925 16926 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16927 if (pir != null) { 16928 // Get all of the existing entries that exactly match this filter. 16929 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16930 if (existing != null && existing.size() == 1) { 16931 PreferredActivity cur = existing.get(0); 16932 if (DEBUG_PREFERRED) { 16933 Slog.i(TAG, "Checking replace of preferred:"); 16934 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16935 if (!cur.mPref.mAlways) { 16936 Slog.i(TAG, " -- CUR; not mAlways!"); 16937 } else { 16938 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16939 Slog.i(TAG, " -- CUR: mSet=" 16940 + Arrays.toString(cur.mPref.mSetComponents)); 16941 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16942 Slog.i(TAG, " -- NEW: mMatch=" 16943 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16944 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16945 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16946 } 16947 } 16948 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16949 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16950 && cur.mPref.sameSet(set)) { 16951 // Setting the preferred activity to what it happens to be already 16952 if (DEBUG_PREFERRED) { 16953 Slog.i(TAG, "Replacing with same preferred activity " 16954 + cur.mPref.mShortComponent + " for user " 16955 + userId + ":"); 16956 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16957 } 16958 return; 16959 } 16960 } 16961 16962 if (existing != null) { 16963 if (DEBUG_PREFERRED) { 16964 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16965 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16966 } 16967 for (int i = 0; i < existing.size(); i++) { 16968 PreferredActivity pa = existing.get(i); 16969 if (DEBUG_PREFERRED) { 16970 Slog.i(TAG, "Removing existing preferred activity " 16971 + pa.mPref.mComponent + ":"); 16972 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16973 } 16974 pir.removeFilter(pa); 16975 } 16976 } 16977 } 16978 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16979 "Replacing preferred"); 16980 } 16981 } 16982 16983 @Override 16984 public void clearPackagePreferredActivities(String packageName) { 16985 final int uid = Binder.getCallingUid(); 16986 // writer 16987 synchronized (mPackages) { 16988 PackageParser.Package pkg = mPackages.get(packageName); 16989 if (pkg == null || pkg.applicationInfo.uid != uid) { 16990 if (mContext.checkCallingOrSelfPermission( 16991 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16992 != PackageManager.PERMISSION_GRANTED) { 16993 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16994 < Build.VERSION_CODES.FROYO) { 16995 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16996 + Binder.getCallingUid()); 16997 return; 16998 } 16999 mContext.enforceCallingOrSelfPermission( 17000 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17001 } 17002 } 17003 17004 int user = UserHandle.getCallingUserId(); 17005 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17006 scheduleWritePackageRestrictionsLocked(user); 17007 } 17008 } 17009 } 17010 17011 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17012 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17013 ArrayList<PreferredActivity> removed = null; 17014 boolean changed = false; 17015 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17016 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17017 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17018 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17019 continue; 17020 } 17021 Iterator<PreferredActivity> it = pir.filterIterator(); 17022 while (it.hasNext()) { 17023 PreferredActivity pa = it.next(); 17024 // Mark entry for removal only if it matches the package name 17025 // and the entry is of type "always". 17026 if (packageName == null || 17027 (pa.mPref.mComponent.getPackageName().equals(packageName) 17028 && pa.mPref.mAlways)) { 17029 if (removed == null) { 17030 removed = new ArrayList<PreferredActivity>(); 17031 } 17032 removed.add(pa); 17033 } 17034 } 17035 if (removed != null) { 17036 for (int j=0; j<removed.size(); j++) { 17037 PreferredActivity pa = removed.get(j); 17038 pir.removeFilter(pa); 17039 } 17040 changed = true; 17041 } 17042 } 17043 return changed; 17044 } 17045 17046 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17047 private void clearIntentFilterVerificationsLPw(int userId) { 17048 final int packageCount = mPackages.size(); 17049 for (int i = 0; i < packageCount; i++) { 17050 PackageParser.Package pkg = mPackages.valueAt(i); 17051 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17052 } 17053 } 17054 17055 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17056 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17057 if (userId == UserHandle.USER_ALL) { 17058 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17059 sUserManager.getUserIds())) { 17060 for (int oneUserId : sUserManager.getUserIds()) { 17061 scheduleWritePackageRestrictionsLocked(oneUserId); 17062 } 17063 } 17064 } else { 17065 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17066 scheduleWritePackageRestrictionsLocked(userId); 17067 } 17068 } 17069 } 17070 17071 void clearDefaultBrowserIfNeeded(String packageName) { 17072 for (int oneUserId : sUserManager.getUserIds()) { 17073 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17074 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17075 if (packageName.equals(defaultBrowserPackageName)) { 17076 setDefaultBrowserPackageName(null, oneUserId); 17077 } 17078 } 17079 } 17080 17081 @Override 17082 public void resetApplicationPreferences(int userId) { 17083 mContext.enforceCallingOrSelfPermission( 17084 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17085 final long identity = Binder.clearCallingIdentity(); 17086 // writer 17087 try { 17088 synchronized (mPackages) { 17089 clearPackagePreferredActivitiesLPw(null, userId); 17090 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17091 // TODO: We have to reset the default SMS and Phone. This requires 17092 // significant refactoring to keep all default apps in the package 17093 // manager (cleaner but more work) or have the services provide 17094 // callbacks to the package manager to request a default app reset. 17095 applyFactoryDefaultBrowserLPw(userId); 17096 clearIntentFilterVerificationsLPw(userId); 17097 primeDomainVerificationsLPw(userId); 17098 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17099 scheduleWritePackageRestrictionsLocked(userId); 17100 } 17101 resetNetworkPolicies(userId); 17102 } finally { 17103 Binder.restoreCallingIdentity(identity); 17104 } 17105 } 17106 17107 @Override 17108 public int getPreferredActivities(List<IntentFilter> outFilters, 17109 List<ComponentName> outActivities, String packageName) { 17110 17111 int num = 0; 17112 final int userId = UserHandle.getCallingUserId(); 17113 // reader 17114 synchronized (mPackages) { 17115 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17116 if (pir != null) { 17117 final Iterator<PreferredActivity> it = pir.filterIterator(); 17118 while (it.hasNext()) { 17119 final PreferredActivity pa = it.next(); 17120 if (packageName == null 17121 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17122 && pa.mPref.mAlways)) { 17123 if (outFilters != null) { 17124 outFilters.add(new IntentFilter(pa)); 17125 } 17126 if (outActivities != null) { 17127 outActivities.add(pa.mPref.mComponent); 17128 } 17129 } 17130 } 17131 } 17132 } 17133 17134 return num; 17135 } 17136 17137 @Override 17138 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17139 int userId) { 17140 int callingUid = Binder.getCallingUid(); 17141 if (callingUid != Process.SYSTEM_UID) { 17142 throw new SecurityException( 17143 "addPersistentPreferredActivity can only be run by the system"); 17144 } 17145 if (filter.countActions() == 0) { 17146 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17147 return; 17148 } 17149 synchronized (mPackages) { 17150 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17151 ":"); 17152 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17153 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17154 new PersistentPreferredActivity(filter, activity)); 17155 scheduleWritePackageRestrictionsLocked(userId); 17156 } 17157 } 17158 17159 @Override 17160 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17161 int callingUid = Binder.getCallingUid(); 17162 if (callingUid != Process.SYSTEM_UID) { 17163 throw new SecurityException( 17164 "clearPackagePersistentPreferredActivities can only be run by the system"); 17165 } 17166 ArrayList<PersistentPreferredActivity> removed = null; 17167 boolean changed = false; 17168 synchronized (mPackages) { 17169 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17170 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17171 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17172 .valueAt(i); 17173 if (userId != thisUserId) { 17174 continue; 17175 } 17176 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17177 while (it.hasNext()) { 17178 PersistentPreferredActivity ppa = it.next(); 17179 // Mark entry for removal only if it matches the package name. 17180 if (ppa.mComponent.getPackageName().equals(packageName)) { 17181 if (removed == null) { 17182 removed = new ArrayList<PersistentPreferredActivity>(); 17183 } 17184 removed.add(ppa); 17185 } 17186 } 17187 if (removed != null) { 17188 for (int j=0; j<removed.size(); j++) { 17189 PersistentPreferredActivity ppa = removed.get(j); 17190 ppir.removeFilter(ppa); 17191 } 17192 changed = true; 17193 } 17194 } 17195 17196 if (changed) { 17197 scheduleWritePackageRestrictionsLocked(userId); 17198 } 17199 } 17200 } 17201 17202 /** 17203 * Common machinery for picking apart a restored XML blob and passing 17204 * it to a caller-supplied functor to be applied to the running system. 17205 */ 17206 private void restoreFromXml(XmlPullParser parser, int userId, 17207 String expectedStartTag, BlobXmlRestorer functor) 17208 throws IOException, XmlPullParserException { 17209 int type; 17210 while ((type = parser.next()) != XmlPullParser.START_TAG 17211 && type != XmlPullParser.END_DOCUMENT) { 17212 } 17213 if (type != XmlPullParser.START_TAG) { 17214 // oops didn't find a start tag?! 17215 if (DEBUG_BACKUP) { 17216 Slog.e(TAG, "Didn't find start tag during restore"); 17217 } 17218 return; 17219 } 17220Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17221 // this is supposed to be TAG_PREFERRED_BACKUP 17222 if (!expectedStartTag.equals(parser.getName())) { 17223 if (DEBUG_BACKUP) { 17224 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17225 } 17226 return; 17227 } 17228 17229 // skip interfering stuff, then we're aligned with the backing implementation 17230 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17231Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17232 functor.apply(parser, userId); 17233 } 17234 17235 private interface BlobXmlRestorer { 17236 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17237 } 17238 17239 /** 17240 * Non-Binder method, support for the backup/restore mechanism: write the 17241 * full set of preferred activities in its canonical XML format. Returns the 17242 * XML output as a byte array, or null if there is none. 17243 */ 17244 @Override 17245 public byte[] getPreferredActivityBackup(int userId) { 17246 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17247 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17248 } 17249 17250 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17251 try { 17252 final XmlSerializer serializer = new FastXmlSerializer(); 17253 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17254 serializer.startDocument(null, true); 17255 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17256 17257 synchronized (mPackages) { 17258 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17259 } 17260 17261 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17262 serializer.endDocument(); 17263 serializer.flush(); 17264 } catch (Exception e) { 17265 if (DEBUG_BACKUP) { 17266 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17267 } 17268 return null; 17269 } 17270 17271 return dataStream.toByteArray(); 17272 } 17273 17274 @Override 17275 public void restorePreferredActivities(byte[] backup, int userId) { 17276 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17277 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17278 } 17279 17280 try { 17281 final XmlPullParser parser = Xml.newPullParser(); 17282 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17283 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17284 new BlobXmlRestorer() { 17285 @Override 17286 public void apply(XmlPullParser parser, int userId) 17287 throws XmlPullParserException, IOException { 17288 synchronized (mPackages) { 17289 mSettings.readPreferredActivitiesLPw(parser, userId); 17290 } 17291 } 17292 } ); 17293 } catch (Exception e) { 17294 if (DEBUG_BACKUP) { 17295 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17296 } 17297 } 17298 } 17299 17300 /** 17301 * Non-Binder method, support for the backup/restore mechanism: write the 17302 * default browser (etc) settings in its canonical XML format. Returns the default 17303 * browser XML representation as a byte array, or null if there is none. 17304 */ 17305 @Override 17306 public byte[] getDefaultAppsBackup(int userId) { 17307 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17308 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17309 } 17310 17311 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17312 try { 17313 final XmlSerializer serializer = new FastXmlSerializer(); 17314 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17315 serializer.startDocument(null, true); 17316 serializer.startTag(null, TAG_DEFAULT_APPS); 17317 17318 synchronized (mPackages) { 17319 mSettings.writeDefaultAppsLPr(serializer, userId); 17320 } 17321 17322 serializer.endTag(null, TAG_DEFAULT_APPS); 17323 serializer.endDocument(); 17324 serializer.flush(); 17325 } catch (Exception e) { 17326 if (DEBUG_BACKUP) { 17327 Slog.e(TAG, "Unable to write default apps for backup", e); 17328 } 17329 return null; 17330 } 17331 17332 return dataStream.toByteArray(); 17333 } 17334 17335 @Override 17336 public void restoreDefaultApps(byte[] backup, int userId) { 17337 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17338 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17339 } 17340 17341 try { 17342 final XmlPullParser parser = Xml.newPullParser(); 17343 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17344 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17345 new BlobXmlRestorer() { 17346 @Override 17347 public void apply(XmlPullParser parser, int userId) 17348 throws XmlPullParserException, IOException { 17349 synchronized (mPackages) { 17350 mSettings.readDefaultAppsLPw(parser, userId); 17351 } 17352 } 17353 } ); 17354 } catch (Exception e) { 17355 if (DEBUG_BACKUP) { 17356 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17357 } 17358 } 17359 } 17360 17361 @Override 17362 public byte[] getIntentFilterVerificationBackup(int userId) { 17363 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17364 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17365 } 17366 17367 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17368 try { 17369 final XmlSerializer serializer = new FastXmlSerializer(); 17370 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17371 serializer.startDocument(null, true); 17372 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17373 17374 synchronized (mPackages) { 17375 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17376 } 17377 17378 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17379 serializer.endDocument(); 17380 serializer.flush(); 17381 } catch (Exception e) { 17382 if (DEBUG_BACKUP) { 17383 Slog.e(TAG, "Unable to write default apps for backup", e); 17384 } 17385 return null; 17386 } 17387 17388 return dataStream.toByteArray(); 17389 } 17390 17391 @Override 17392 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17393 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17394 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17395 } 17396 17397 try { 17398 final XmlPullParser parser = Xml.newPullParser(); 17399 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17400 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17401 new BlobXmlRestorer() { 17402 @Override 17403 public void apply(XmlPullParser parser, int userId) 17404 throws XmlPullParserException, IOException { 17405 synchronized (mPackages) { 17406 mSettings.readAllDomainVerificationsLPr(parser, userId); 17407 mSettings.writeLPr(); 17408 } 17409 } 17410 } ); 17411 } catch (Exception e) { 17412 if (DEBUG_BACKUP) { 17413 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17414 } 17415 } 17416 } 17417 17418 @Override 17419 public byte[] getPermissionGrantBackup(int userId) { 17420 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17421 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17422 } 17423 17424 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17425 try { 17426 final XmlSerializer serializer = new FastXmlSerializer(); 17427 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17428 serializer.startDocument(null, true); 17429 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17430 17431 synchronized (mPackages) { 17432 serializeRuntimePermissionGrantsLPr(serializer, userId); 17433 } 17434 17435 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17436 serializer.endDocument(); 17437 serializer.flush(); 17438 } catch (Exception e) { 17439 if (DEBUG_BACKUP) { 17440 Slog.e(TAG, "Unable to write default apps for backup", e); 17441 } 17442 return null; 17443 } 17444 17445 return dataStream.toByteArray(); 17446 } 17447 17448 @Override 17449 public void restorePermissionGrants(byte[] backup, int userId) { 17450 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17451 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17452 } 17453 17454 try { 17455 final XmlPullParser parser = Xml.newPullParser(); 17456 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17457 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17458 new BlobXmlRestorer() { 17459 @Override 17460 public void apply(XmlPullParser parser, int userId) 17461 throws XmlPullParserException, IOException { 17462 synchronized (mPackages) { 17463 processRestoredPermissionGrantsLPr(parser, userId); 17464 } 17465 } 17466 } ); 17467 } catch (Exception e) { 17468 if (DEBUG_BACKUP) { 17469 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17470 } 17471 } 17472 } 17473 17474 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17475 throws IOException { 17476 serializer.startTag(null, TAG_ALL_GRANTS); 17477 17478 final int N = mSettings.mPackages.size(); 17479 for (int i = 0; i < N; i++) { 17480 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17481 boolean pkgGrantsKnown = false; 17482 17483 PermissionsState packagePerms = ps.getPermissionsState(); 17484 17485 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17486 final int grantFlags = state.getFlags(); 17487 // only look at grants that are not system/policy fixed 17488 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17489 final boolean isGranted = state.isGranted(); 17490 // And only back up the user-twiddled state bits 17491 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17492 final String packageName = mSettings.mPackages.keyAt(i); 17493 if (!pkgGrantsKnown) { 17494 serializer.startTag(null, TAG_GRANT); 17495 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17496 pkgGrantsKnown = true; 17497 } 17498 17499 final boolean userSet = 17500 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17501 final boolean userFixed = 17502 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17503 final boolean revoke = 17504 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17505 17506 serializer.startTag(null, TAG_PERMISSION); 17507 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17508 if (isGranted) { 17509 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17510 } 17511 if (userSet) { 17512 serializer.attribute(null, ATTR_USER_SET, "true"); 17513 } 17514 if (userFixed) { 17515 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17516 } 17517 if (revoke) { 17518 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17519 } 17520 serializer.endTag(null, TAG_PERMISSION); 17521 } 17522 } 17523 } 17524 17525 if (pkgGrantsKnown) { 17526 serializer.endTag(null, TAG_GRANT); 17527 } 17528 } 17529 17530 serializer.endTag(null, TAG_ALL_GRANTS); 17531 } 17532 17533 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17534 throws XmlPullParserException, IOException { 17535 String pkgName = null; 17536 int outerDepth = parser.getDepth(); 17537 int type; 17538 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17539 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17540 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17541 continue; 17542 } 17543 17544 final String tagName = parser.getName(); 17545 if (tagName.equals(TAG_GRANT)) { 17546 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17547 if (DEBUG_BACKUP) { 17548 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17549 } 17550 } else if (tagName.equals(TAG_PERMISSION)) { 17551 17552 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17553 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17554 17555 int newFlagSet = 0; 17556 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17557 newFlagSet |= FLAG_PERMISSION_USER_SET; 17558 } 17559 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17560 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17561 } 17562 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17563 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17564 } 17565 if (DEBUG_BACKUP) { 17566 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17567 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17568 } 17569 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17570 if (ps != null) { 17571 // Already installed so we apply the grant immediately 17572 if (DEBUG_BACKUP) { 17573 Slog.v(TAG, " + already installed; applying"); 17574 } 17575 PermissionsState perms = ps.getPermissionsState(); 17576 BasePermission bp = mSettings.mPermissions.get(permName); 17577 if (bp != null) { 17578 if (isGranted) { 17579 perms.grantRuntimePermission(bp, userId); 17580 } 17581 if (newFlagSet != 0) { 17582 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17583 } 17584 } 17585 } else { 17586 // Need to wait for post-restore install to apply the grant 17587 if (DEBUG_BACKUP) { 17588 Slog.v(TAG, " - not yet installed; saving for later"); 17589 } 17590 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17591 isGranted, newFlagSet, userId); 17592 } 17593 } else { 17594 PackageManagerService.reportSettingsProblem(Log.WARN, 17595 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17596 XmlUtils.skipCurrentTag(parser); 17597 } 17598 } 17599 17600 scheduleWriteSettingsLocked(); 17601 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17602 } 17603 17604 @Override 17605 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17606 int sourceUserId, int targetUserId, int flags) { 17607 mContext.enforceCallingOrSelfPermission( 17608 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17609 int callingUid = Binder.getCallingUid(); 17610 enforceOwnerRights(ownerPackage, callingUid); 17611 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17612 if (intentFilter.countActions() == 0) { 17613 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17614 return; 17615 } 17616 synchronized (mPackages) { 17617 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17618 ownerPackage, targetUserId, flags); 17619 CrossProfileIntentResolver resolver = 17620 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17621 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17622 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17623 if (existing != null) { 17624 int size = existing.size(); 17625 for (int i = 0; i < size; i++) { 17626 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17627 return; 17628 } 17629 } 17630 } 17631 resolver.addFilter(newFilter); 17632 scheduleWritePackageRestrictionsLocked(sourceUserId); 17633 } 17634 } 17635 17636 @Override 17637 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17638 mContext.enforceCallingOrSelfPermission( 17639 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17640 int callingUid = Binder.getCallingUid(); 17641 enforceOwnerRights(ownerPackage, callingUid); 17642 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17643 synchronized (mPackages) { 17644 CrossProfileIntentResolver resolver = 17645 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17646 ArraySet<CrossProfileIntentFilter> set = 17647 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17648 for (CrossProfileIntentFilter filter : set) { 17649 if (filter.getOwnerPackage().equals(ownerPackage)) { 17650 resolver.removeFilter(filter); 17651 } 17652 } 17653 scheduleWritePackageRestrictionsLocked(sourceUserId); 17654 } 17655 } 17656 17657 // Enforcing that callingUid is owning pkg on userId 17658 private void enforceOwnerRights(String pkg, int callingUid) { 17659 // The system owns everything. 17660 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17661 return; 17662 } 17663 int callingUserId = UserHandle.getUserId(callingUid); 17664 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17665 if (pi == null) { 17666 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17667 + callingUserId); 17668 } 17669 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17670 throw new SecurityException("Calling uid " + callingUid 17671 + " does not own package " + pkg); 17672 } 17673 } 17674 17675 @Override 17676 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17677 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17678 } 17679 17680 private Intent getHomeIntent() { 17681 Intent intent = new Intent(Intent.ACTION_MAIN); 17682 intent.addCategory(Intent.CATEGORY_HOME); 17683 intent.addCategory(Intent.CATEGORY_DEFAULT); 17684 return intent; 17685 } 17686 17687 private IntentFilter getHomeFilter() { 17688 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17689 filter.addCategory(Intent.CATEGORY_HOME); 17690 filter.addCategory(Intent.CATEGORY_DEFAULT); 17691 return filter; 17692 } 17693 17694 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17695 int userId) { 17696 Intent intent = getHomeIntent(); 17697 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17698 PackageManager.GET_META_DATA, userId); 17699 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17700 true, false, false, userId); 17701 17702 allHomeCandidates.clear(); 17703 if (list != null) { 17704 for (ResolveInfo ri : list) { 17705 allHomeCandidates.add(ri); 17706 } 17707 } 17708 return (preferred == null || preferred.activityInfo == null) 17709 ? null 17710 : new ComponentName(preferred.activityInfo.packageName, 17711 preferred.activityInfo.name); 17712 } 17713 17714 @Override 17715 public void setHomeActivity(ComponentName comp, int userId) { 17716 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17717 getHomeActivitiesAsUser(homeActivities, userId); 17718 17719 boolean found = false; 17720 17721 final int size = homeActivities.size(); 17722 final ComponentName[] set = new ComponentName[size]; 17723 for (int i = 0; i < size; i++) { 17724 final ResolveInfo candidate = homeActivities.get(i); 17725 final ActivityInfo info = candidate.activityInfo; 17726 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17727 set[i] = activityName; 17728 if (!found && activityName.equals(comp)) { 17729 found = true; 17730 } 17731 } 17732 if (!found) { 17733 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17734 + userId); 17735 } 17736 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17737 set, comp, userId); 17738 } 17739 17740 private @Nullable String getSetupWizardPackageName() { 17741 final Intent intent = new Intent(Intent.ACTION_MAIN); 17742 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17743 17744 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17745 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17746 | MATCH_DISABLED_COMPONENTS, 17747 UserHandle.myUserId()); 17748 if (matches.size() == 1) { 17749 return matches.get(0).getComponentInfo().packageName; 17750 } else { 17751 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17752 + ": matches=" + matches); 17753 return null; 17754 } 17755 } 17756 17757 @Override 17758 public void setApplicationEnabledSetting(String appPackageName, 17759 int newState, int flags, int userId, String callingPackage) { 17760 if (!sUserManager.exists(userId)) return; 17761 if (callingPackage == null) { 17762 callingPackage = Integer.toString(Binder.getCallingUid()); 17763 } 17764 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17765 } 17766 17767 @Override 17768 public void setComponentEnabledSetting(ComponentName componentName, 17769 int newState, int flags, int userId) { 17770 if (!sUserManager.exists(userId)) return; 17771 setEnabledSetting(componentName.getPackageName(), 17772 componentName.getClassName(), newState, flags, userId, null); 17773 } 17774 17775 private void setEnabledSetting(final String packageName, String className, int newState, 17776 final int flags, int userId, String callingPackage) { 17777 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17778 || newState == COMPONENT_ENABLED_STATE_ENABLED 17779 || newState == COMPONENT_ENABLED_STATE_DISABLED 17780 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17781 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17782 throw new IllegalArgumentException("Invalid new component state: " 17783 + newState); 17784 } 17785 PackageSetting pkgSetting; 17786 final int uid = Binder.getCallingUid(); 17787 final int permission; 17788 if (uid == Process.SYSTEM_UID) { 17789 permission = PackageManager.PERMISSION_GRANTED; 17790 } else { 17791 permission = mContext.checkCallingOrSelfPermission( 17792 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17793 } 17794 enforceCrossUserPermission(uid, userId, 17795 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17796 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17797 boolean sendNow = false; 17798 boolean isApp = (className == null); 17799 String componentName = isApp ? packageName : className; 17800 int packageUid = -1; 17801 ArrayList<String> components; 17802 17803 // writer 17804 synchronized (mPackages) { 17805 pkgSetting = mSettings.mPackages.get(packageName); 17806 if (pkgSetting == null) { 17807 if (className == null) { 17808 throw new IllegalArgumentException("Unknown package: " + packageName); 17809 } 17810 throw new IllegalArgumentException( 17811 "Unknown component: " + packageName + "/" + className); 17812 } 17813 } 17814 17815 // Limit who can change which apps 17816 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17817 // Don't allow apps that don't have permission to modify other apps 17818 if (!allowedByPermission) { 17819 throw new SecurityException( 17820 "Permission Denial: attempt to change component state from pid=" 17821 + Binder.getCallingPid() 17822 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17823 } 17824 // Don't allow changing protected packages. 17825 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17826 throw new SecurityException("Cannot disable a protected package: " + packageName); 17827 } 17828 } 17829 17830 synchronized (mPackages) { 17831 if (uid == Process.SHELL_UID) { 17832 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17833 int oldState = pkgSetting.getEnabled(userId); 17834 if (className == null 17835 && 17836 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17837 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17838 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17839 && 17840 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17841 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17842 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17843 // ok 17844 } else { 17845 throw new SecurityException( 17846 "Shell cannot change component state for " + packageName + "/" 17847 + className + " to " + newState); 17848 } 17849 } 17850 if (className == null) { 17851 // We're dealing with an application/package level state change 17852 if (pkgSetting.getEnabled(userId) == newState) { 17853 // Nothing to do 17854 return; 17855 } 17856 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17857 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17858 // Don't care about who enables an app. 17859 callingPackage = null; 17860 } 17861 pkgSetting.setEnabled(newState, userId, callingPackage); 17862 // pkgSetting.pkg.mSetEnabled = newState; 17863 } else { 17864 // We're dealing with a component level state change 17865 // First, verify that this is a valid class name. 17866 PackageParser.Package pkg = pkgSetting.pkg; 17867 if (pkg == null || !pkg.hasComponentClassName(className)) { 17868 if (pkg != null && 17869 pkg.applicationInfo.targetSdkVersion >= 17870 Build.VERSION_CODES.JELLY_BEAN) { 17871 throw new IllegalArgumentException("Component class " + className 17872 + " does not exist in " + packageName); 17873 } else { 17874 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17875 + className + " does not exist in " + packageName); 17876 } 17877 } 17878 switch (newState) { 17879 case COMPONENT_ENABLED_STATE_ENABLED: 17880 if (!pkgSetting.enableComponentLPw(className, userId)) { 17881 return; 17882 } 17883 break; 17884 case COMPONENT_ENABLED_STATE_DISABLED: 17885 if (!pkgSetting.disableComponentLPw(className, userId)) { 17886 return; 17887 } 17888 break; 17889 case COMPONENT_ENABLED_STATE_DEFAULT: 17890 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17891 return; 17892 } 17893 break; 17894 default: 17895 Slog.e(TAG, "Invalid new component state: " + newState); 17896 return; 17897 } 17898 } 17899 scheduleWritePackageRestrictionsLocked(userId); 17900 components = mPendingBroadcasts.get(userId, packageName); 17901 final boolean newPackage = components == null; 17902 if (newPackage) { 17903 components = new ArrayList<String>(); 17904 } 17905 if (!components.contains(componentName)) { 17906 components.add(componentName); 17907 } 17908 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17909 sendNow = true; 17910 // Purge entry from pending broadcast list if another one exists already 17911 // since we are sending one right away. 17912 mPendingBroadcasts.remove(userId, packageName); 17913 } else { 17914 if (newPackage) { 17915 mPendingBroadcasts.put(userId, packageName, components); 17916 } 17917 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17918 // Schedule a message 17919 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17920 } 17921 } 17922 } 17923 17924 long callingId = Binder.clearCallingIdentity(); 17925 try { 17926 if (sendNow) { 17927 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17928 sendPackageChangedBroadcast(packageName, 17929 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17930 } 17931 } finally { 17932 Binder.restoreCallingIdentity(callingId); 17933 } 17934 } 17935 17936 @Override 17937 public void flushPackageRestrictionsAsUser(int userId) { 17938 if (!sUserManager.exists(userId)) { 17939 return; 17940 } 17941 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17942 false /* checkShell */, "flushPackageRestrictions"); 17943 synchronized (mPackages) { 17944 mSettings.writePackageRestrictionsLPr(userId); 17945 mDirtyUsers.remove(userId); 17946 if (mDirtyUsers.isEmpty()) { 17947 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17948 } 17949 } 17950 } 17951 17952 private void sendPackageChangedBroadcast(String packageName, 17953 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17954 if (DEBUG_INSTALL) 17955 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17956 + componentNames); 17957 Bundle extras = new Bundle(4); 17958 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17959 String nameList[] = new String[componentNames.size()]; 17960 componentNames.toArray(nameList); 17961 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17962 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17963 extras.putInt(Intent.EXTRA_UID, packageUid); 17964 // If this is not reporting a change of the overall package, then only send it 17965 // to registered receivers. We don't want to launch a swath of apps for every 17966 // little component state change. 17967 final int flags = !componentNames.contains(packageName) 17968 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17969 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17970 new int[] {UserHandle.getUserId(packageUid)}); 17971 } 17972 17973 @Override 17974 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17975 if (!sUserManager.exists(userId)) return; 17976 final int uid = Binder.getCallingUid(); 17977 final int permission = mContext.checkCallingOrSelfPermission( 17978 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17979 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17980 enforceCrossUserPermission(uid, userId, 17981 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17982 // writer 17983 synchronized (mPackages) { 17984 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17985 allowedByPermission, uid, userId)) { 17986 scheduleWritePackageRestrictionsLocked(userId); 17987 } 17988 } 17989 } 17990 17991 @Override 17992 public String getInstallerPackageName(String packageName) { 17993 // reader 17994 synchronized (mPackages) { 17995 return mSettings.getInstallerPackageNameLPr(packageName); 17996 } 17997 } 17998 17999 public boolean isOrphaned(String packageName) { 18000 // reader 18001 synchronized (mPackages) { 18002 return mSettings.isOrphaned(packageName); 18003 } 18004 } 18005 18006 @Override 18007 public int getApplicationEnabledSetting(String packageName, int userId) { 18008 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18009 int uid = Binder.getCallingUid(); 18010 enforceCrossUserPermission(uid, userId, 18011 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18012 // reader 18013 synchronized (mPackages) { 18014 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18015 } 18016 } 18017 18018 @Override 18019 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18020 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18021 int uid = Binder.getCallingUid(); 18022 enforceCrossUserPermission(uid, userId, 18023 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18024 // reader 18025 synchronized (mPackages) { 18026 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18027 } 18028 } 18029 18030 @Override 18031 public void enterSafeMode() { 18032 enforceSystemOrRoot("Only the system can request entering safe mode"); 18033 18034 if (!mSystemReady) { 18035 mSafeMode = true; 18036 } 18037 } 18038 18039 @Override 18040 public void systemReady() { 18041 mSystemReady = true; 18042 18043 // Read the compatibilty setting when the system is ready. 18044 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18045 mContext.getContentResolver(), 18046 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18047 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18048 if (DEBUG_SETTINGS) { 18049 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18050 } 18051 18052 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18053 18054 synchronized (mPackages) { 18055 // Verify that all of the preferred activity components actually 18056 // exist. It is possible for applications to be updated and at 18057 // that point remove a previously declared activity component that 18058 // had been set as a preferred activity. We try to clean this up 18059 // the next time we encounter that preferred activity, but it is 18060 // possible for the user flow to never be able to return to that 18061 // situation so here we do a sanity check to make sure we haven't 18062 // left any junk around. 18063 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18064 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18065 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18066 removed.clear(); 18067 for (PreferredActivity pa : pir.filterSet()) { 18068 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18069 removed.add(pa); 18070 } 18071 } 18072 if (removed.size() > 0) { 18073 for (int r=0; r<removed.size(); r++) { 18074 PreferredActivity pa = removed.get(r); 18075 Slog.w(TAG, "Removing dangling preferred activity: " 18076 + pa.mPref.mComponent); 18077 pir.removeFilter(pa); 18078 } 18079 mSettings.writePackageRestrictionsLPr( 18080 mSettings.mPreferredActivities.keyAt(i)); 18081 } 18082 } 18083 18084 for (int userId : UserManagerService.getInstance().getUserIds()) { 18085 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18086 grantPermissionsUserIds = ArrayUtils.appendInt( 18087 grantPermissionsUserIds, userId); 18088 } 18089 } 18090 } 18091 sUserManager.systemReady(); 18092 18093 // If we upgraded grant all default permissions before kicking off. 18094 for (int userId : grantPermissionsUserIds) { 18095 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18096 } 18097 18098 // Kick off any messages waiting for system ready 18099 if (mPostSystemReadyMessages != null) { 18100 for (Message msg : mPostSystemReadyMessages) { 18101 msg.sendToTarget(); 18102 } 18103 mPostSystemReadyMessages = null; 18104 } 18105 18106 // Watch for external volumes that come and go over time 18107 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18108 storage.registerListener(mStorageListener); 18109 18110 mInstallerService.systemReady(); 18111 mPackageDexOptimizer.systemReady(); 18112 18113 MountServiceInternal mountServiceInternal = LocalServices.getService( 18114 MountServiceInternal.class); 18115 mountServiceInternal.addExternalStoragePolicy( 18116 new MountServiceInternal.ExternalStorageMountPolicy() { 18117 @Override 18118 public int getMountMode(int uid, String packageName) { 18119 if (Process.isIsolated(uid)) { 18120 return Zygote.MOUNT_EXTERNAL_NONE; 18121 } 18122 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18123 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18124 } 18125 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18126 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18127 } 18128 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18129 return Zygote.MOUNT_EXTERNAL_READ; 18130 } 18131 return Zygote.MOUNT_EXTERNAL_WRITE; 18132 } 18133 18134 @Override 18135 public boolean hasExternalStorage(int uid, String packageName) { 18136 return true; 18137 } 18138 }); 18139 18140 // Now that we're mostly running, clean up stale users and apps 18141 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18142 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18143 } 18144 18145 @Override 18146 public boolean isSafeMode() { 18147 return mSafeMode; 18148 } 18149 18150 @Override 18151 public boolean hasSystemUidErrors() { 18152 return mHasSystemUidErrors; 18153 } 18154 18155 static String arrayToString(int[] array) { 18156 StringBuffer buf = new StringBuffer(128); 18157 buf.append('['); 18158 if (array != null) { 18159 for (int i=0; i<array.length; i++) { 18160 if (i > 0) buf.append(", "); 18161 buf.append(array[i]); 18162 } 18163 } 18164 buf.append(']'); 18165 return buf.toString(); 18166 } 18167 18168 static class DumpState { 18169 public static final int DUMP_LIBS = 1 << 0; 18170 public static final int DUMP_FEATURES = 1 << 1; 18171 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18172 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18173 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18174 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18175 public static final int DUMP_PERMISSIONS = 1 << 6; 18176 public static final int DUMP_PACKAGES = 1 << 7; 18177 public static final int DUMP_SHARED_USERS = 1 << 8; 18178 public static final int DUMP_MESSAGES = 1 << 9; 18179 public static final int DUMP_PROVIDERS = 1 << 10; 18180 public static final int DUMP_VERIFIERS = 1 << 11; 18181 public static final int DUMP_PREFERRED = 1 << 12; 18182 public static final int DUMP_PREFERRED_XML = 1 << 13; 18183 public static final int DUMP_KEYSETS = 1 << 14; 18184 public static final int DUMP_VERSION = 1 << 15; 18185 public static final int DUMP_INSTALLS = 1 << 16; 18186 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18187 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18188 public static final int DUMP_FROZEN = 1 << 19; 18189 public static final int DUMP_DEXOPT = 1 << 20; 18190 18191 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18192 18193 private int mTypes; 18194 18195 private int mOptions; 18196 18197 private boolean mTitlePrinted; 18198 18199 private SharedUserSetting mSharedUser; 18200 18201 public boolean isDumping(int type) { 18202 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18203 return true; 18204 } 18205 18206 return (mTypes & type) != 0; 18207 } 18208 18209 public void setDump(int type) { 18210 mTypes |= type; 18211 } 18212 18213 public boolean isOptionEnabled(int option) { 18214 return (mOptions & option) != 0; 18215 } 18216 18217 public void setOptionEnabled(int option) { 18218 mOptions |= option; 18219 } 18220 18221 public boolean onTitlePrinted() { 18222 final boolean printed = mTitlePrinted; 18223 mTitlePrinted = true; 18224 return printed; 18225 } 18226 18227 public boolean getTitlePrinted() { 18228 return mTitlePrinted; 18229 } 18230 18231 public void setTitlePrinted(boolean enabled) { 18232 mTitlePrinted = enabled; 18233 } 18234 18235 public SharedUserSetting getSharedUser() { 18236 return mSharedUser; 18237 } 18238 18239 public void setSharedUser(SharedUserSetting user) { 18240 mSharedUser = user; 18241 } 18242 } 18243 18244 @Override 18245 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18246 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18247 (new PackageManagerShellCommand(this)).exec( 18248 this, in, out, err, args, resultReceiver); 18249 } 18250 18251 @Override 18252 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18253 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18254 != PackageManager.PERMISSION_GRANTED) { 18255 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18256 + Binder.getCallingPid() 18257 + ", uid=" + Binder.getCallingUid() 18258 + " without permission " 18259 + android.Manifest.permission.DUMP); 18260 return; 18261 } 18262 18263 DumpState dumpState = new DumpState(); 18264 boolean fullPreferred = false; 18265 boolean checkin = false; 18266 18267 String packageName = null; 18268 ArraySet<String> permissionNames = null; 18269 18270 int opti = 0; 18271 while (opti < args.length) { 18272 String opt = args[opti]; 18273 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18274 break; 18275 } 18276 opti++; 18277 18278 if ("-a".equals(opt)) { 18279 // Right now we only know how to print all. 18280 } else if ("-h".equals(opt)) { 18281 pw.println("Package manager dump options:"); 18282 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18283 pw.println(" --checkin: dump for a checkin"); 18284 pw.println(" -f: print details of intent filters"); 18285 pw.println(" -h: print this help"); 18286 pw.println(" cmd may be one of:"); 18287 pw.println(" l[ibraries]: list known shared libraries"); 18288 pw.println(" f[eatures]: list device features"); 18289 pw.println(" k[eysets]: print known keysets"); 18290 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18291 pw.println(" perm[issions]: dump permissions"); 18292 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18293 pw.println(" pref[erred]: print preferred package settings"); 18294 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18295 pw.println(" prov[iders]: dump content providers"); 18296 pw.println(" p[ackages]: dump installed packages"); 18297 pw.println(" s[hared-users]: dump shared user IDs"); 18298 pw.println(" m[essages]: print collected runtime messages"); 18299 pw.println(" v[erifiers]: print package verifier info"); 18300 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18301 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18302 pw.println(" version: print database version info"); 18303 pw.println(" write: write current settings now"); 18304 pw.println(" installs: details about install sessions"); 18305 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18306 pw.println(" dexopt: dump dexopt state"); 18307 pw.println(" <package.name>: info about given package"); 18308 return; 18309 } else if ("--checkin".equals(opt)) { 18310 checkin = true; 18311 } else if ("-f".equals(opt)) { 18312 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18313 } else { 18314 pw.println("Unknown argument: " + opt + "; use -h for help"); 18315 } 18316 } 18317 18318 // Is the caller requesting to dump a particular piece of data? 18319 if (opti < args.length) { 18320 String cmd = args[opti]; 18321 opti++; 18322 // Is this a package name? 18323 if ("android".equals(cmd) || cmd.contains(".")) { 18324 packageName = cmd; 18325 // When dumping a single package, we always dump all of its 18326 // filter information since the amount of data will be reasonable. 18327 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18328 } else if ("check-permission".equals(cmd)) { 18329 if (opti >= args.length) { 18330 pw.println("Error: check-permission missing permission argument"); 18331 return; 18332 } 18333 String perm = args[opti]; 18334 opti++; 18335 if (opti >= args.length) { 18336 pw.println("Error: check-permission missing package argument"); 18337 return; 18338 } 18339 String pkg = args[opti]; 18340 opti++; 18341 int user = UserHandle.getUserId(Binder.getCallingUid()); 18342 if (opti < args.length) { 18343 try { 18344 user = Integer.parseInt(args[opti]); 18345 } catch (NumberFormatException e) { 18346 pw.println("Error: check-permission user argument is not a number: " 18347 + args[opti]); 18348 return; 18349 } 18350 } 18351 pw.println(checkPermission(perm, pkg, user)); 18352 return; 18353 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18354 dumpState.setDump(DumpState.DUMP_LIBS); 18355 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18356 dumpState.setDump(DumpState.DUMP_FEATURES); 18357 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18358 if (opti >= args.length) { 18359 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18360 | DumpState.DUMP_SERVICE_RESOLVERS 18361 | DumpState.DUMP_RECEIVER_RESOLVERS 18362 | DumpState.DUMP_CONTENT_RESOLVERS); 18363 } else { 18364 while (opti < args.length) { 18365 String name = args[opti]; 18366 if ("a".equals(name) || "activity".equals(name)) { 18367 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18368 } else if ("s".equals(name) || "service".equals(name)) { 18369 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18370 } else if ("r".equals(name) || "receiver".equals(name)) { 18371 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18372 } else if ("c".equals(name) || "content".equals(name)) { 18373 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18374 } else { 18375 pw.println("Error: unknown resolver table type: " + name); 18376 return; 18377 } 18378 opti++; 18379 } 18380 } 18381 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18382 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18383 } else if ("permission".equals(cmd)) { 18384 if (opti >= args.length) { 18385 pw.println("Error: permission requires permission name"); 18386 return; 18387 } 18388 permissionNames = new ArraySet<>(); 18389 while (opti < args.length) { 18390 permissionNames.add(args[opti]); 18391 opti++; 18392 } 18393 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18394 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18395 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18396 dumpState.setDump(DumpState.DUMP_PREFERRED); 18397 } else if ("preferred-xml".equals(cmd)) { 18398 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18399 if (opti < args.length && "--full".equals(args[opti])) { 18400 fullPreferred = true; 18401 opti++; 18402 } 18403 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18404 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18405 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18406 dumpState.setDump(DumpState.DUMP_PACKAGES); 18407 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18408 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18409 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18410 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18411 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18412 dumpState.setDump(DumpState.DUMP_MESSAGES); 18413 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18414 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18415 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18416 || "intent-filter-verifiers".equals(cmd)) { 18417 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18418 } else if ("version".equals(cmd)) { 18419 dumpState.setDump(DumpState.DUMP_VERSION); 18420 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18421 dumpState.setDump(DumpState.DUMP_KEYSETS); 18422 } else if ("installs".equals(cmd)) { 18423 dumpState.setDump(DumpState.DUMP_INSTALLS); 18424 } else if ("frozen".equals(cmd)) { 18425 dumpState.setDump(DumpState.DUMP_FROZEN); 18426 } else if ("dexopt".equals(cmd)) { 18427 dumpState.setDump(DumpState.DUMP_DEXOPT); 18428 } else if ("write".equals(cmd)) { 18429 synchronized (mPackages) { 18430 mSettings.writeLPr(); 18431 pw.println("Settings written."); 18432 return; 18433 } 18434 } 18435 } 18436 18437 if (checkin) { 18438 pw.println("vers,1"); 18439 } 18440 18441 // reader 18442 synchronized (mPackages) { 18443 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18444 if (!checkin) { 18445 if (dumpState.onTitlePrinted()) 18446 pw.println(); 18447 pw.println("Database versions:"); 18448 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18449 } 18450 } 18451 18452 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18453 if (!checkin) { 18454 if (dumpState.onTitlePrinted()) 18455 pw.println(); 18456 pw.println("Verifiers:"); 18457 pw.print(" Required: "); 18458 pw.print(mRequiredVerifierPackage); 18459 pw.print(" (uid="); 18460 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18461 UserHandle.USER_SYSTEM)); 18462 pw.println(")"); 18463 } else if (mRequiredVerifierPackage != null) { 18464 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18465 pw.print(","); 18466 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18467 UserHandle.USER_SYSTEM)); 18468 } 18469 } 18470 18471 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18472 packageName == null) { 18473 if (mIntentFilterVerifierComponent != null) { 18474 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18475 if (!checkin) { 18476 if (dumpState.onTitlePrinted()) 18477 pw.println(); 18478 pw.println("Intent Filter Verifier:"); 18479 pw.print(" Using: "); 18480 pw.print(verifierPackageName); 18481 pw.print(" (uid="); 18482 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18483 UserHandle.USER_SYSTEM)); 18484 pw.println(")"); 18485 } else if (verifierPackageName != null) { 18486 pw.print("ifv,"); pw.print(verifierPackageName); 18487 pw.print(","); 18488 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18489 UserHandle.USER_SYSTEM)); 18490 } 18491 } else { 18492 pw.println(); 18493 pw.println("No Intent Filter Verifier available!"); 18494 } 18495 } 18496 18497 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18498 boolean printedHeader = false; 18499 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18500 while (it.hasNext()) { 18501 String name = it.next(); 18502 SharedLibraryEntry ent = mSharedLibraries.get(name); 18503 if (!checkin) { 18504 if (!printedHeader) { 18505 if (dumpState.onTitlePrinted()) 18506 pw.println(); 18507 pw.println("Libraries:"); 18508 printedHeader = true; 18509 } 18510 pw.print(" "); 18511 } else { 18512 pw.print("lib,"); 18513 } 18514 pw.print(name); 18515 if (!checkin) { 18516 pw.print(" -> "); 18517 } 18518 if (ent.path != null) { 18519 if (!checkin) { 18520 pw.print("(jar) "); 18521 pw.print(ent.path); 18522 } else { 18523 pw.print(",jar,"); 18524 pw.print(ent.path); 18525 } 18526 } else { 18527 if (!checkin) { 18528 pw.print("(apk) "); 18529 pw.print(ent.apk); 18530 } else { 18531 pw.print(",apk,"); 18532 pw.print(ent.apk); 18533 } 18534 } 18535 pw.println(); 18536 } 18537 } 18538 18539 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18540 if (dumpState.onTitlePrinted()) 18541 pw.println(); 18542 if (!checkin) { 18543 pw.println("Features:"); 18544 } 18545 18546 for (FeatureInfo feat : mAvailableFeatures.values()) { 18547 if (checkin) { 18548 pw.print("feat,"); 18549 pw.print(feat.name); 18550 pw.print(","); 18551 pw.println(feat.version); 18552 } else { 18553 pw.print(" "); 18554 pw.print(feat.name); 18555 if (feat.version > 0) { 18556 pw.print(" version="); 18557 pw.print(feat.version); 18558 } 18559 pw.println(); 18560 } 18561 } 18562 } 18563 18564 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18565 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18566 : "Activity Resolver Table:", " ", packageName, 18567 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18568 dumpState.setTitlePrinted(true); 18569 } 18570 } 18571 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18572 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18573 : "Receiver Resolver Table:", " ", packageName, 18574 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18575 dumpState.setTitlePrinted(true); 18576 } 18577 } 18578 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18579 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18580 : "Service Resolver Table:", " ", packageName, 18581 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18582 dumpState.setTitlePrinted(true); 18583 } 18584 } 18585 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18586 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18587 : "Provider Resolver Table:", " ", packageName, 18588 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18589 dumpState.setTitlePrinted(true); 18590 } 18591 } 18592 18593 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18594 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18595 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18596 int user = mSettings.mPreferredActivities.keyAt(i); 18597 if (pir.dump(pw, 18598 dumpState.getTitlePrinted() 18599 ? "\nPreferred Activities User " + user + ":" 18600 : "Preferred Activities User " + user + ":", " ", 18601 packageName, true, false)) { 18602 dumpState.setTitlePrinted(true); 18603 } 18604 } 18605 } 18606 18607 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18608 pw.flush(); 18609 FileOutputStream fout = new FileOutputStream(fd); 18610 BufferedOutputStream str = new BufferedOutputStream(fout); 18611 XmlSerializer serializer = new FastXmlSerializer(); 18612 try { 18613 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18614 serializer.startDocument(null, true); 18615 serializer.setFeature( 18616 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18617 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18618 serializer.endDocument(); 18619 serializer.flush(); 18620 } catch (IllegalArgumentException e) { 18621 pw.println("Failed writing: " + e); 18622 } catch (IllegalStateException e) { 18623 pw.println("Failed writing: " + e); 18624 } catch (IOException e) { 18625 pw.println("Failed writing: " + e); 18626 } 18627 } 18628 18629 if (!checkin 18630 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18631 && packageName == null) { 18632 pw.println(); 18633 int count = mSettings.mPackages.size(); 18634 if (count == 0) { 18635 pw.println("No applications!"); 18636 pw.println(); 18637 } else { 18638 final String prefix = " "; 18639 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18640 if (allPackageSettings.size() == 0) { 18641 pw.println("No domain preferred apps!"); 18642 pw.println(); 18643 } else { 18644 pw.println("App verification status:"); 18645 pw.println(); 18646 count = 0; 18647 for (PackageSetting ps : allPackageSettings) { 18648 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18649 if (ivi == null || ivi.getPackageName() == null) continue; 18650 pw.println(prefix + "Package: " + ivi.getPackageName()); 18651 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18652 pw.println(prefix + "Status: " + ivi.getStatusString()); 18653 pw.println(); 18654 count++; 18655 } 18656 if (count == 0) { 18657 pw.println(prefix + "No app verification established."); 18658 pw.println(); 18659 } 18660 for (int userId : sUserManager.getUserIds()) { 18661 pw.println("App linkages for user " + userId + ":"); 18662 pw.println(); 18663 count = 0; 18664 for (PackageSetting ps : allPackageSettings) { 18665 final long status = ps.getDomainVerificationStatusForUser(userId); 18666 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18667 continue; 18668 } 18669 pw.println(prefix + "Package: " + ps.name); 18670 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18671 String statusStr = IntentFilterVerificationInfo. 18672 getStatusStringFromValue(status); 18673 pw.println(prefix + "Status: " + statusStr); 18674 pw.println(); 18675 count++; 18676 } 18677 if (count == 0) { 18678 pw.println(prefix + "No configured app linkages."); 18679 pw.println(); 18680 } 18681 } 18682 } 18683 } 18684 } 18685 18686 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18687 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18688 if (packageName == null && permissionNames == null) { 18689 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18690 if (iperm == 0) { 18691 if (dumpState.onTitlePrinted()) 18692 pw.println(); 18693 pw.println("AppOp Permissions:"); 18694 } 18695 pw.print(" AppOp Permission "); 18696 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18697 pw.println(":"); 18698 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18699 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18700 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18701 } 18702 } 18703 } 18704 } 18705 18706 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18707 boolean printedSomething = false; 18708 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18709 if (packageName != null && !packageName.equals(p.info.packageName)) { 18710 continue; 18711 } 18712 if (!printedSomething) { 18713 if (dumpState.onTitlePrinted()) 18714 pw.println(); 18715 pw.println("Registered ContentProviders:"); 18716 printedSomething = true; 18717 } 18718 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18719 pw.print(" "); pw.println(p.toString()); 18720 } 18721 printedSomething = false; 18722 for (Map.Entry<String, PackageParser.Provider> entry : 18723 mProvidersByAuthority.entrySet()) { 18724 PackageParser.Provider p = entry.getValue(); 18725 if (packageName != null && !packageName.equals(p.info.packageName)) { 18726 continue; 18727 } 18728 if (!printedSomething) { 18729 if (dumpState.onTitlePrinted()) 18730 pw.println(); 18731 pw.println("ContentProvider Authorities:"); 18732 printedSomething = true; 18733 } 18734 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18735 pw.print(" "); pw.println(p.toString()); 18736 if (p.info != null && p.info.applicationInfo != null) { 18737 final String appInfo = p.info.applicationInfo.toString(); 18738 pw.print(" applicationInfo="); pw.println(appInfo); 18739 } 18740 } 18741 } 18742 18743 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18744 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18745 } 18746 18747 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18748 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18749 } 18750 18751 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18752 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18753 } 18754 18755 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18756 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18757 } 18758 18759 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18760 // XXX should handle packageName != null by dumping only install data that 18761 // the given package is involved with. 18762 if (dumpState.onTitlePrinted()) pw.println(); 18763 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18764 } 18765 18766 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18767 // XXX should handle packageName != null by dumping only install data that 18768 // the given package is involved with. 18769 if (dumpState.onTitlePrinted()) pw.println(); 18770 18771 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18772 ipw.println(); 18773 ipw.println("Frozen packages:"); 18774 ipw.increaseIndent(); 18775 if (mFrozenPackages.size() == 0) { 18776 ipw.println("(none)"); 18777 } else { 18778 for (int i = 0; i < mFrozenPackages.size(); i++) { 18779 ipw.println(mFrozenPackages.valueAt(i)); 18780 } 18781 } 18782 ipw.decreaseIndent(); 18783 } 18784 18785 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18786 if (dumpState.onTitlePrinted()) pw.println(); 18787 dumpDexoptStateLPr(pw, packageName); 18788 } 18789 18790 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18791 if (dumpState.onTitlePrinted()) pw.println(); 18792 mSettings.dumpReadMessagesLPr(pw, dumpState); 18793 18794 pw.println(); 18795 pw.println("Package warning messages:"); 18796 BufferedReader in = null; 18797 String line = null; 18798 try { 18799 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18800 while ((line = in.readLine()) != null) { 18801 if (line.contains("ignored: updated version")) continue; 18802 pw.println(line); 18803 } 18804 } catch (IOException ignored) { 18805 } finally { 18806 IoUtils.closeQuietly(in); 18807 } 18808 } 18809 18810 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18811 BufferedReader in = null; 18812 String line = null; 18813 try { 18814 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18815 while ((line = in.readLine()) != null) { 18816 if (line.contains("ignored: updated version")) continue; 18817 pw.print("msg,"); 18818 pw.println(line); 18819 } 18820 } catch (IOException ignored) { 18821 } finally { 18822 IoUtils.closeQuietly(in); 18823 } 18824 } 18825 } 18826 } 18827 18828 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18829 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18830 ipw.println(); 18831 ipw.println("Dexopt state:"); 18832 ipw.increaseIndent(); 18833 Collection<PackageParser.Package> packages = null; 18834 if (packageName != null) { 18835 PackageParser.Package targetPackage = mPackages.get(packageName); 18836 if (targetPackage != null) { 18837 packages = Collections.singletonList(targetPackage); 18838 } else { 18839 ipw.println("Unable to find package: " + packageName); 18840 return; 18841 } 18842 } else { 18843 packages = mPackages.values(); 18844 } 18845 18846 for (PackageParser.Package pkg : packages) { 18847 ipw.println("[" + pkg.packageName + "]"); 18848 ipw.increaseIndent(); 18849 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18850 ipw.decreaseIndent(); 18851 } 18852 } 18853 18854 private String dumpDomainString(String packageName) { 18855 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18856 .getList(); 18857 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18858 18859 ArraySet<String> result = new ArraySet<>(); 18860 if (iviList.size() > 0) { 18861 for (IntentFilterVerificationInfo ivi : iviList) { 18862 for (String host : ivi.getDomains()) { 18863 result.add(host); 18864 } 18865 } 18866 } 18867 if (filters != null && filters.size() > 0) { 18868 for (IntentFilter filter : filters) { 18869 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18870 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18871 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18872 result.addAll(filter.getHostsList()); 18873 } 18874 } 18875 } 18876 18877 StringBuilder sb = new StringBuilder(result.size() * 16); 18878 for (String domain : result) { 18879 if (sb.length() > 0) sb.append(" "); 18880 sb.append(domain); 18881 } 18882 return sb.toString(); 18883 } 18884 18885 // ------- apps on sdcard specific code ------- 18886 static final boolean DEBUG_SD_INSTALL = false; 18887 18888 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18889 18890 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18891 18892 private boolean mMediaMounted = false; 18893 18894 static String getEncryptKey() { 18895 try { 18896 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18897 SD_ENCRYPTION_KEYSTORE_NAME); 18898 if (sdEncKey == null) { 18899 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18900 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18901 if (sdEncKey == null) { 18902 Slog.e(TAG, "Failed to create encryption keys"); 18903 return null; 18904 } 18905 } 18906 return sdEncKey; 18907 } catch (NoSuchAlgorithmException nsae) { 18908 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18909 return null; 18910 } catch (IOException ioe) { 18911 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18912 return null; 18913 } 18914 } 18915 18916 /* 18917 * Update media status on PackageManager. 18918 */ 18919 @Override 18920 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18921 int callingUid = Binder.getCallingUid(); 18922 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18923 throw new SecurityException("Media status can only be updated by the system"); 18924 } 18925 // reader; this apparently protects mMediaMounted, but should probably 18926 // be a different lock in that case. 18927 synchronized (mPackages) { 18928 Log.i(TAG, "Updating external media status from " 18929 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18930 + (mediaStatus ? "mounted" : "unmounted")); 18931 if (DEBUG_SD_INSTALL) 18932 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18933 + ", mMediaMounted=" + mMediaMounted); 18934 if (mediaStatus == mMediaMounted) { 18935 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18936 : 0, -1); 18937 mHandler.sendMessage(msg); 18938 return; 18939 } 18940 mMediaMounted = mediaStatus; 18941 } 18942 // Queue up an async operation since the package installation may take a 18943 // little while. 18944 mHandler.post(new Runnable() { 18945 public void run() { 18946 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18947 } 18948 }); 18949 } 18950 18951 /** 18952 * Called by MountService when the initial ASECs to scan are available. 18953 * Should block until all the ASEC containers are finished being scanned. 18954 */ 18955 public void scanAvailableAsecs() { 18956 updateExternalMediaStatusInner(true, false, false); 18957 } 18958 18959 /* 18960 * Collect information of applications on external media, map them against 18961 * existing containers and update information based on current mount status. 18962 * Please note that we always have to report status if reportStatus has been 18963 * set to true especially when unloading packages. 18964 */ 18965 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18966 boolean externalStorage) { 18967 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18968 int[] uidArr = EmptyArray.INT; 18969 18970 final String[] list = PackageHelper.getSecureContainerList(); 18971 if (ArrayUtils.isEmpty(list)) { 18972 Log.i(TAG, "No secure containers found"); 18973 } else { 18974 // Process list of secure containers and categorize them 18975 // as active or stale based on their package internal state. 18976 18977 // reader 18978 synchronized (mPackages) { 18979 for (String cid : list) { 18980 // Leave stages untouched for now; installer service owns them 18981 if (PackageInstallerService.isStageName(cid)) continue; 18982 18983 if (DEBUG_SD_INSTALL) 18984 Log.i(TAG, "Processing container " + cid); 18985 String pkgName = getAsecPackageName(cid); 18986 if (pkgName == null) { 18987 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18988 continue; 18989 } 18990 if (DEBUG_SD_INSTALL) 18991 Log.i(TAG, "Looking for pkg : " + pkgName); 18992 18993 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18994 if (ps == null) { 18995 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18996 continue; 18997 } 18998 18999 /* 19000 * Skip packages that are not external if we're unmounting 19001 * external storage. 19002 */ 19003 if (externalStorage && !isMounted && !isExternal(ps)) { 19004 continue; 19005 } 19006 19007 final AsecInstallArgs args = new AsecInstallArgs(cid, 19008 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19009 // The package status is changed only if the code path 19010 // matches between settings and the container id. 19011 if (ps.codePathString != null 19012 && ps.codePathString.startsWith(args.getCodePath())) { 19013 if (DEBUG_SD_INSTALL) { 19014 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19015 + " at code path: " + ps.codePathString); 19016 } 19017 19018 // We do have a valid package installed on sdcard 19019 processCids.put(args, ps.codePathString); 19020 final int uid = ps.appId; 19021 if (uid != -1) { 19022 uidArr = ArrayUtils.appendInt(uidArr, uid); 19023 } 19024 } else { 19025 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19026 + ps.codePathString); 19027 } 19028 } 19029 } 19030 19031 Arrays.sort(uidArr); 19032 } 19033 19034 // Process packages with valid entries. 19035 if (isMounted) { 19036 if (DEBUG_SD_INSTALL) 19037 Log.i(TAG, "Loading packages"); 19038 loadMediaPackages(processCids, uidArr, externalStorage); 19039 startCleaningPackages(); 19040 mInstallerService.onSecureContainersAvailable(); 19041 } else { 19042 if (DEBUG_SD_INSTALL) 19043 Log.i(TAG, "Unloading packages"); 19044 unloadMediaPackages(processCids, uidArr, reportStatus); 19045 } 19046 } 19047 19048 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19049 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19050 final int size = infos.size(); 19051 final String[] packageNames = new String[size]; 19052 final int[] packageUids = new int[size]; 19053 for (int i = 0; i < size; i++) { 19054 final ApplicationInfo info = infos.get(i); 19055 packageNames[i] = info.packageName; 19056 packageUids[i] = info.uid; 19057 } 19058 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19059 finishedReceiver); 19060 } 19061 19062 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19063 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19064 sendResourcesChangedBroadcast(mediaStatus, replacing, 19065 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19066 } 19067 19068 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19069 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19070 int size = pkgList.length; 19071 if (size > 0) { 19072 // Send broadcasts here 19073 Bundle extras = new Bundle(); 19074 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19075 if (uidArr != null) { 19076 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19077 } 19078 if (replacing) { 19079 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19080 } 19081 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19082 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19083 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19084 } 19085 } 19086 19087 /* 19088 * Look at potentially valid container ids from processCids If package 19089 * information doesn't match the one on record or package scanning fails, 19090 * the cid is added to list of removeCids. We currently don't delete stale 19091 * containers. 19092 */ 19093 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19094 boolean externalStorage) { 19095 ArrayList<String> pkgList = new ArrayList<String>(); 19096 Set<AsecInstallArgs> keys = processCids.keySet(); 19097 19098 for (AsecInstallArgs args : keys) { 19099 String codePath = processCids.get(args); 19100 if (DEBUG_SD_INSTALL) 19101 Log.i(TAG, "Loading container : " + args.cid); 19102 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19103 try { 19104 // Make sure there are no container errors first. 19105 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19106 Slog.e(TAG, "Failed to mount cid : " + args.cid 19107 + " when installing from sdcard"); 19108 continue; 19109 } 19110 // Check code path here. 19111 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19112 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19113 + " does not match one in settings " + codePath); 19114 continue; 19115 } 19116 // Parse package 19117 int parseFlags = mDefParseFlags; 19118 if (args.isExternalAsec()) { 19119 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19120 } 19121 if (args.isFwdLocked()) { 19122 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19123 } 19124 19125 synchronized (mInstallLock) { 19126 PackageParser.Package pkg = null; 19127 try { 19128 // Sadly we don't know the package name yet to freeze it 19129 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19130 SCAN_IGNORE_FROZEN, 0, null); 19131 } catch (PackageManagerException e) { 19132 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19133 } 19134 // Scan the package 19135 if (pkg != null) { 19136 /* 19137 * TODO why is the lock being held? doPostInstall is 19138 * called in other places without the lock. This needs 19139 * to be straightened out. 19140 */ 19141 // writer 19142 synchronized (mPackages) { 19143 retCode = PackageManager.INSTALL_SUCCEEDED; 19144 pkgList.add(pkg.packageName); 19145 // Post process args 19146 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19147 pkg.applicationInfo.uid); 19148 } 19149 } else { 19150 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19151 } 19152 } 19153 19154 } finally { 19155 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19156 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19157 } 19158 } 19159 } 19160 // writer 19161 synchronized (mPackages) { 19162 // If the platform SDK has changed since the last time we booted, 19163 // we need to re-grant app permission to catch any new ones that 19164 // appear. This is really a hack, and means that apps can in some 19165 // cases get permissions that the user didn't initially explicitly 19166 // allow... it would be nice to have some better way to handle 19167 // this situation. 19168 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19169 : mSettings.getInternalVersion(); 19170 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19171 : StorageManager.UUID_PRIVATE_INTERNAL; 19172 19173 int updateFlags = UPDATE_PERMISSIONS_ALL; 19174 if (ver.sdkVersion != mSdkVersion) { 19175 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19176 + mSdkVersion + "; regranting permissions for external"); 19177 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19178 } 19179 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19180 19181 // Yay, everything is now upgraded 19182 ver.forceCurrent(); 19183 19184 // can downgrade to reader 19185 // Persist settings 19186 mSettings.writeLPr(); 19187 } 19188 // Send a broadcast to let everyone know we are done processing 19189 if (pkgList.size() > 0) { 19190 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19191 } 19192 } 19193 19194 /* 19195 * Utility method to unload a list of specified containers 19196 */ 19197 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19198 // Just unmount all valid containers. 19199 for (AsecInstallArgs arg : cidArgs) { 19200 synchronized (mInstallLock) { 19201 arg.doPostDeleteLI(false); 19202 } 19203 } 19204 } 19205 19206 /* 19207 * Unload packages mounted on external media. This involves deleting package 19208 * data from internal structures, sending broadcasts about disabled packages, 19209 * gc'ing to free up references, unmounting all secure containers 19210 * corresponding to packages on external media, and posting a 19211 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19212 * that we always have to post this message if status has been requested no 19213 * matter what. 19214 */ 19215 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19216 final boolean reportStatus) { 19217 if (DEBUG_SD_INSTALL) 19218 Log.i(TAG, "unloading media packages"); 19219 ArrayList<String> pkgList = new ArrayList<String>(); 19220 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19221 final Set<AsecInstallArgs> keys = processCids.keySet(); 19222 for (AsecInstallArgs args : keys) { 19223 String pkgName = args.getPackageName(); 19224 if (DEBUG_SD_INSTALL) 19225 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19226 // Delete package internally 19227 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19228 synchronized (mInstallLock) { 19229 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19230 final boolean res; 19231 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19232 "unloadMediaPackages")) { 19233 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19234 null); 19235 } 19236 if (res) { 19237 pkgList.add(pkgName); 19238 } else { 19239 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19240 failedList.add(args); 19241 } 19242 } 19243 } 19244 19245 // reader 19246 synchronized (mPackages) { 19247 // We didn't update the settings after removing each package; 19248 // write them now for all packages. 19249 mSettings.writeLPr(); 19250 } 19251 19252 // We have to absolutely send UPDATED_MEDIA_STATUS only 19253 // after confirming that all the receivers processed the ordered 19254 // broadcast when packages get disabled, force a gc to clean things up. 19255 // and unload all the containers. 19256 if (pkgList.size() > 0) { 19257 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19258 new IIntentReceiver.Stub() { 19259 public void performReceive(Intent intent, int resultCode, String data, 19260 Bundle extras, boolean ordered, boolean sticky, 19261 int sendingUser) throws RemoteException { 19262 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19263 reportStatus ? 1 : 0, 1, keys); 19264 mHandler.sendMessage(msg); 19265 } 19266 }); 19267 } else { 19268 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19269 keys); 19270 mHandler.sendMessage(msg); 19271 } 19272 } 19273 19274 private void loadPrivatePackages(final VolumeInfo vol) { 19275 mHandler.post(new Runnable() { 19276 @Override 19277 public void run() { 19278 loadPrivatePackagesInner(vol); 19279 } 19280 }); 19281 } 19282 19283 private void loadPrivatePackagesInner(VolumeInfo vol) { 19284 final String volumeUuid = vol.fsUuid; 19285 if (TextUtils.isEmpty(volumeUuid)) { 19286 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19287 return; 19288 } 19289 19290 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19291 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19292 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19293 19294 final VersionInfo ver; 19295 final List<PackageSetting> packages; 19296 synchronized (mPackages) { 19297 ver = mSettings.findOrCreateVersion(volumeUuid); 19298 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19299 } 19300 19301 for (PackageSetting ps : packages) { 19302 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19303 synchronized (mInstallLock) { 19304 final PackageParser.Package pkg; 19305 try { 19306 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19307 loaded.add(pkg.applicationInfo); 19308 19309 } catch (PackageManagerException e) { 19310 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19311 } 19312 19313 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19314 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19315 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19316 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19317 } 19318 } 19319 } 19320 19321 // Reconcile app data for all started/unlocked users 19322 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19323 final UserManager um = mContext.getSystemService(UserManager.class); 19324 UserManagerInternal umInternal = getUserManagerInternal(); 19325 for (UserInfo user : um.getUsers()) { 19326 final int flags; 19327 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19328 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19329 } else if (umInternal.isUserRunning(user.id)) { 19330 flags = StorageManager.FLAG_STORAGE_DE; 19331 } else { 19332 continue; 19333 } 19334 19335 try { 19336 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19337 synchronized (mInstallLock) { 19338 reconcileAppsDataLI(volumeUuid, user.id, flags); 19339 } 19340 } catch (IllegalStateException e) { 19341 // Device was probably ejected, and we'll process that event momentarily 19342 Slog.w(TAG, "Failed to prepare storage: " + e); 19343 } 19344 } 19345 19346 synchronized (mPackages) { 19347 int updateFlags = UPDATE_PERMISSIONS_ALL; 19348 if (ver.sdkVersion != mSdkVersion) { 19349 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19350 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19351 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19352 } 19353 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19354 19355 // Yay, everything is now upgraded 19356 ver.forceCurrent(); 19357 19358 mSettings.writeLPr(); 19359 } 19360 19361 for (PackageFreezer freezer : freezers) { 19362 freezer.close(); 19363 } 19364 19365 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19366 sendResourcesChangedBroadcast(true, false, loaded, null); 19367 } 19368 19369 private void unloadPrivatePackages(final VolumeInfo vol) { 19370 mHandler.post(new Runnable() { 19371 @Override 19372 public void run() { 19373 unloadPrivatePackagesInner(vol); 19374 } 19375 }); 19376 } 19377 19378 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19379 final String volumeUuid = vol.fsUuid; 19380 if (TextUtils.isEmpty(volumeUuid)) { 19381 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19382 return; 19383 } 19384 19385 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19386 synchronized (mInstallLock) { 19387 synchronized (mPackages) { 19388 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19389 for (PackageSetting ps : packages) { 19390 if (ps.pkg == null) continue; 19391 19392 final ApplicationInfo info = ps.pkg.applicationInfo; 19393 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19394 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19395 19396 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19397 "unloadPrivatePackagesInner")) { 19398 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19399 false, null)) { 19400 unloaded.add(info); 19401 } else { 19402 Slog.w(TAG, "Failed to unload " + ps.codePath); 19403 } 19404 } 19405 19406 // Try very hard to release any references to this package 19407 // so we don't risk the system server being killed due to 19408 // open FDs 19409 AttributeCache.instance().removePackage(ps.name); 19410 } 19411 19412 mSettings.writeLPr(); 19413 } 19414 } 19415 19416 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19417 sendResourcesChangedBroadcast(false, false, unloaded, null); 19418 19419 // Try very hard to release any references to this path so we don't risk 19420 // the system server being killed due to open FDs 19421 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19422 19423 for (int i = 0; i < 3; i++) { 19424 System.gc(); 19425 System.runFinalization(); 19426 } 19427 } 19428 19429 /** 19430 * Prepare storage areas for given user on all mounted devices. 19431 */ 19432 void prepareUserData(int userId, int userSerial, int flags) { 19433 synchronized (mInstallLock) { 19434 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19435 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19436 final String volumeUuid = vol.getFsUuid(); 19437 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19438 } 19439 } 19440 } 19441 19442 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19443 boolean allowRecover) { 19444 // Prepare storage and verify that serial numbers are consistent; if 19445 // there's a mismatch we need to destroy to avoid leaking data 19446 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19447 try { 19448 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19449 19450 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19451 UserManagerService.enforceSerialNumber( 19452 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19453 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19454 UserManagerService.enforceSerialNumber( 19455 Environment.getDataSystemDeDirectory(userId), userSerial); 19456 } 19457 } 19458 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19459 UserManagerService.enforceSerialNumber( 19460 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19461 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19462 UserManagerService.enforceSerialNumber( 19463 Environment.getDataSystemCeDirectory(userId), userSerial); 19464 } 19465 } 19466 19467 synchronized (mInstallLock) { 19468 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19469 } 19470 } catch (Exception e) { 19471 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19472 + " because we failed to prepare: " + e); 19473 destroyUserDataLI(volumeUuid, userId, 19474 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19475 19476 if (allowRecover) { 19477 // Try one last time; if we fail again we're really in trouble 19478 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19479 } 19480 } 19481 } 19482 19483 /** 19484 * Destroy storage areas for given user on all mounted devices. 19485 */ 19486 void destroyUserData(int userId, int flags) { 19487 synchronized (mInstallLock) { 19488 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19489 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19490 final String volumeUuid = vol.getFsUuid(); 19491 destroyUserDataLI(volumeUuid, userId, flags); 19492 } 19493 } 19494 } 19495 19496 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19497 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19498 try { 19499 // Clean up app data, profile data, and media data 19500 mInstaller.destroyUserData(volumeUuid, userId, flags); 19501 19502 // Clean up system data 19503 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19504 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19505 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19506 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19507 } 19508 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19509 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19510 } 19511 } 19512 19513 // Data with special labels is now gone, so finish the job 19514 storage.destroyUserStorage(volumeUuid, userId, flags); 19515 19516 } catch (Exception e) { 19517 logCriticalInfo(Log.WARN, 19518 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19519 } 19520 } 19521 19522 /** 19523 * Examine all users present on given mounted volume, and destroy data 19524 * belonging to users that are no longer valid, or whose user ID has been 19525 * recycled. 19526 */ 19527 private void reconcileUsers(String volumeUuid) { 19528 final List<File> files = new ArrayList<>(); 19529 Collections.addAll(files, FileUtils 19530 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19531 Collections.addAll(files, FileUtils 19532 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19533 Collections.addAll(files, FileUtils 19534 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19535 Collections.addAll(files, FileUtils 19536 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19537 for (File file : files) { 19538 if (!file.isDirectory()) continue; 19539 19540 final int userId; 19541 final UserInfo info; 19542 try { 19543 userId = Integer.parseInt(file.getName()); 19544 info = sUserManager.getUserInfo(userId); 19545 } catch (NumberFormatException e) { 19546 Slog.w(TAG, "Invalid user directory " + file); 19547 continue; 19548 } 19549 19550 boolean destroyUser = false; 19551 if (info == null) { 19552 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19553 + " because no matching user was found"); 19554 destroyUser = true; 19555 } else if (!mOnlyCore) { 19556 try { 19557 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19558 } catch (IOException e) { 19559 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19560 + " because we failed to enforce serial number: " + e); 19561 destroyUser = true; 19562 } 19563 } 19564 19565 if (destroyUser) { 19566 synchronized (mInstallLock) { 19567 destroyUserDataLI(volumeUuid, userId, 19568 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19569 } 19570 } 19571 } 19572 } 19573 19574 private void assertPackageKnown(String volumeUuid, String packageName) 19575 throws PackageManagerException { 19576 synchronized (mPackages) { 19577 final PackageSetting ps = mSettings.mPackages.get(packageName); 19578 if (ps == null) { 19579 throw new PackageManagerException("Package " + packageName + " is unknown"); 19580 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19581 throw new PackageManagerException( 19582 "Package " + packageName + " found on unknown volume " + volumeUuid 19583 + "; expected volume " + ps.volumeUuid); 19584 } 19585 } 19586 } 19587 19588 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19589 throws PackageManagerException { 19590 synchronized (mPackages) { 19591 final PackageSetting ps = mSettings.mPackages.get(packageName); 19592 if (ps == null) { 19593 throw new PackageManagerException("Package " + packageName + " is unknown"); 19594 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19595 throw new PackageManagerException( 19596 "Package " + packageName + " found on unknown volume " + volumeUuid 19597 + "; expected volume " + ps.volumeUuid); 19598 } else if (!ps.getInstalled(userId)) { 19599 throw new PackageManagerException( 19600 "Package " + packageName + " not installed for user " + userId); 19601 } 19602 } 19603 } 19604 19605 /** 19606 * Examine all apps present on given mounted volume, and destroy apps that 19607 * aren't expected, either due to uninstallation or reinstallation on 19608 * another volume. 19609 */ 19610 private void reconcileApps(String volumeUuid) { 19611 final File[] files = FileUtils 19612 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19613 for (File file : files) { 19614 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19615 && !PackageInstallerService.isStageName(file.getName()); 19616 if (!isPackage) { 19617 // Ignore entries which are not packages 19618 continue; 19619 } 19620 19621 try { 19622 final PackageLite pkg = PackageParser.parsePackageLite(file, 19623 PackageParser.PARSE_MUST_BE_APK); 19624 assertPackageKnown(volumeUuid, pkg.packageName); 19625 19626 } catch (PackageParserException | PackageManagerException e) { 19627 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19628 synchronized (mInstallLock) { 19629 removeCodePathLI(file); 19630 } 19631 } 19632 } 19633 } 19634 19635 /** 19636 * Reconcile all app data for the given user. 19637 * <p> 19638 * Verifies that directories exist and that ownership and labeling is 19639 * correct for all installed apps on all mounted volumes. 19640 */ 19641 void reconcileAppsData(int userId, int flags) { 19642 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19643 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19644 final String volumeUuid = vol.getFsUuid(); 19645 synchronized (mInstallLock) { 19646 reconcileAppsDataLI(volumeUuid, userId, flags); 19647 } 19648 } 19649 } 19650 19651 /** 19652 * Reconcile all app data on given mounted volume. 19653 * <p> 19654 * Destroys app data that isn't expected, either due to uninstallation or 19655 * reinstallation on another volume. 19656 * <p> 19657 * Verifies that directories exist and that ownership and labeling is 19658 * correct for all installed apps. 19659 */ 19660 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19661 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19662 + Integer.toHexString(flags)); 19663 19664 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19665 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19666 19667 boolean restoreconNeeded = false; 19668 19669 // First look for stale data that doesn't belong, and check if things 19670 // have changed since we did our last restorecon 19671 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19672 if (StorageManager.isFileEncryptedNativeOrEmulated() 19673 && !StorageManager.isUserKeyUnlocked(userId)) { 19674 throw new RuntimeException( 19675 "Yikes, someone asked us to reconcile CE storage while " + userId 19676 + " was still locked; this would have caused massive data loss!"); 19677 } 19678 19679 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19680 19681 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19682 for (File file : files) { 19683 final String packageName = file.getName(); 19684 try { 19685 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19686 } catch (PackageManagerException e) { 19687 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19688 try { 19689 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19690 StorageManager.FLAG_STORAGE_CE, 0); 19691 } catch (InstallerException e2) { 19692 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19693 } 19694 } 19695 } 19696 } 19697 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19698 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19699 19700 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19701 for (File file : files) { 19702 final String packageName = file.getName(); 19703 try { 19704 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19705 } catch (PackageManagerException e) { 19706 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19707 try { 19708 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19709 StorageManager.FLAG_STORAGE_DE, 0); 19710 } catch (InstallerException e2) { 19711 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19712 } 19713 } 19714 } 19715 } 19716 19717 // Ensure that data directories are ready to roll for all packages 19718 // installed for this volume and user 19719 final List<PackageSetting> packages; 19720 synchronized (mPackages) { 19721 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19722 } 19723 int preparedCount = 0; 19724 for (PackageSetting ps : packages) { 19725 final String packageName = ps.name; 19726 if (ps.pkg == null) { 19727 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19728 // TODO: might be due to legacy ASEC apps; we should circle back 19729 // and reconcile again once they're scanned 19730 continue; 19731 } 19732 19733 if (ps.getInstalled(userId)) { 19734 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19735 19736 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19737 // We may have just shuffled around app data directories, so 19738 // prepare them one more time 19739 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19740 } 19741 19742 preparedCount++; 19743 } 19744 } 19745 19746 if (restoreconNeeded) { 19747 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19748 SELinuxMMAC.setRestoreconDone(ceDir); 19749 } 19750 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19751 SELinuxMMAC.setRestoreconDone(deDir); 19752 } 19753 } 19754 19755 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19756 + " packages; restoreconNeeded was " + restoreconNeeded); 19757 } 19758 19759 /** 19760 * Prepare app data for the given app just after it was installed or 19761 * upgraded. This method carefully only touches users that it's installed 19762 * for, and it forces a restorecon to handle any seinfo changes. 19763 * <p> 19764 * Verifies that directories exist and that ownership and labeling is 19765 * correct for all installed apps. If there is an ownership mismatch, it 19766 * will try recovering system apps by wiping data; third-party app data is 19767 * left intact. 19768 * <p> 19769 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19770 */ 19771 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19772 final PackageSetting ps; 19773 synchronized (mPackages) { 19774 ps = mSettings.mPackages.get(pkg.packageName); 19775 mSettings.writeKernelMappingLPr(ps); 19776 } 19777 19778 final UserManager um = mContext.getSystemService(UserManager.class); 19779 UserManagerInternal umInternal = getUserManagerInternal(); 19780 for (UserInfo user : um.getUsers()) { 19781 final int flags; 19782 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19783 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19784 } else if (umInternal.isUserRunning(user.id)) { 19785 flags = StorageManager.FLAG_STORAGE_DE; 19786 } else { 19787 continue; 19788 } 19789 19790 if (ps.getInstalled(user.id)) { 19791 // Whenever an app changes, force a restorecon of its data 19792 // TODO: when user data is locked, mark that we're still dirty 19793 prepareAppDataLIF(pkg, user.id, flags, true); 19794 } 19795 } 19796 } 19797 19798 /** 19799 * Prepare app data for the given app. 19800 * <p> 19801 * Verifies that directories exist and that ownership and labeling is 19802 * correct for all installed apps. If there is an ownership mismatch, this 19803 * will try recovering system apps by wiping data; third-party app data is 19804 * left intact. 19805 */ 19806 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19807 boolean restoreconNeeded) { 19808 if (pkg == null) { 19809 Slog.wtf(TAG, "Package was null!", new Throwable()); 19810 return; 19811 } 19812 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19813 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19814 for (int i = 0; i < childCount; i++) { 19815 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19816 } 19817 } 19818 19819 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19820 boolean restoreconNeeded) { 19821 if (DEBUG_APP_DATA) { 19822 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19823 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19824 } 19825 19826 final String volumeUuid = pkg.volumeUuid; 19827 final String packageName = pkg.packageName; 19828 final ApplicationInfo app = pkg.applicationInfo; 19829 final int appId = UserHandle.getAppId(app.uid); 19830 19831 Preconditions.checkNotNull(app.seinfo); 19832 19833 try { 19834 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19835 appId, app.seinfo, app.targetSdkVersion); 19836 } catch (InstallerException e) { 19837 if (app.isSystemApp()) { 19838 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19839 + ", but trying to recover: " + e); 19840 destroyAppDataLeafLIF(pkg, userId, flags); 19841 try { 19842 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19843 appId, app.seinfo, app.targetSdkVersion); 19844 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19845 } catch (InstallerException e2) { 19846 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19847 } 19848 } else { 19849 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19850 } 19851 } 19852 19853 if (restoreconNeeded) { 19854 try { 19855 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19856 app.seinfo); 19857 } catch (InstallerException e) { 19858 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19859 } 19860 } 19861 19862 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19863 try { 19864 // CE storage is unlocked right now, so read out the inode and 19865 // remember for use later when it's locked 19866 // TODO: mark this structure as dirty so we persist it! 19867 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19868 StorageManager.FLAG_STORAGE_CE); 19869 synchronized (mPackages) { 19870 final PackageSetting ps = mSettings.mPackages.get(packageName); 19871 if (ps != null) { 19872 ps.setCeDataInode(ceDataInode, userId); 19873 } 19874 } 19875 } catch (InstallerException e) { 19876 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19877 } 19878 } 19879 19880 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19881 } 19882 19883 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19884 if (pkg == null) { 19885 Slog.wtf(TAG, "Package was null!", new Throwable()); 19886 return; 19887 } 19888 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19889 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19890 for (int i = 0; i < childCount; i++) { 19891 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19892 } 19893 } 19894 19895 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19896 final String volumeUuid = pkg.volumeUuid; 19897 final String packageName = pkg.packageName; 19898 final ApplicationInfo app = pkg.applicationInfo; 19899 19900 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19901 // Create a native library symlink only if we have native libraries 19902 // and if the native libraries are 32 bit libraries. We do not provide 19903 // this symlink for 64 bit libraries. 19904 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19905 final String nativeLibPath = app.nativeLibraryDir; 19906 try { 19907 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19908 nativeLibPath, userId); 19909 } catch (InstallerException e) { 19910 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19911 } 19912 } 19913 } 19914 } 19915 19916 /** 19917 * For system apps on non-FBE devices, this method migrates any existing 19918 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19919 * requested by the app. 19920 */ 19921 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19922 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19923 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19924 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19925 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19926 try { 19927 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19928 storageTarget); 19929 } catch (InstallerException e) { 19930 logCriticalInfo(Log.WARN, 19931 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19932 } 19933 return true; 19934 } else { 19935 return false; 19936 } 19937 } 19938 19939 public PackageFreezer freezePackage(String packageName, String killReason) { 19940 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19941 } 19942 19943 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19944 return new PackageFreezer(packageName, userId, killReason); 19945 } 19946 19947 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19948 String killReason) { 19949 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19950 } 19951 19952 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19953 String killReason) { 19954 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19955 return new PackageFreezer(); 19956 } else { 19957 return freezePackage(packageName, userId, killReason); 19958 } 19959 } 19960 19961 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19962 String killReason) { 19963 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19964 } 19965 19966 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19967 String killReason) { 19968 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19969 return new PackageFreezer(); 19970 } else { 19971 return freezePackage(packageName, userId, killReason); 19972 } 19973 } 19974 19975 /** 19976 * Class that freezes and kills the given package upon creation, and 19977 * unfreezes it upon closing. This is typically used when doing surgery on 19978 * app code/data to prevent the app from running while you're working. 19979 */ 19980 private class PackageFreezer implements AutoCloseable { 19981 private final String mPackageName; 19982 private final PackageFreezer[] mChildren; 19983 19984 private final boolean mWeFroze; 19985 19986 private final AtomicBoolean mClosed = new AtomicBoolean(); 19987 private final CloseGuard mCloseGuard = CloseGuard.get(); 19988 19989 /** 19990 * Create and return a stub freezer that doesn't actually do anything, 19991 * typically used when someone requested 19992 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19993 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19994 */ 19995 public PackageFreezer() { 19996 mPackageName = null; 19997 mChildren = null; 19998 mWeFroze = false; 19999 mCloseGuard.open("close"); 20000 } 20001 20002 public PackageFreezer(String packageName, int userId, String killReason) { 20003 synchronized (mPackages) { 20004 mPackageName = packageName; 20005 mWeFroze = mFrozenPackages.add(mPackageName); 20006 20007 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20008 if (ps != null) { 20009 killApplication(ps.name, ps.appId, userId, killReason); 20010 } 20011 20012 final PackageParser.Package p = mPackages.get(packageName); 20013 if (p != null && p.childPackages != null) { 20014 final int N = p.childPackages.size(); 20015 mChildren = new PackageFreezer[N]; 20016 for (int i = 0; i < N; i++) { 20017 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20018 userId, killReason); 20019 } 20020 } else { 20021 mChildren = null; 20022 } 20023 } 20024 mCloseGuard.open("close"); 20025 } 20026 20027 @Override 20028 protected void finalize() throws Throwable { 20029 try { 20030 mCloseGuard.warnIfOpen(); 20031 close(); 20032 } finally { 20033 super.finalize(); 20034 } 20035 } 20036 20037 @Override 20038 public void close() { 20039 mCloseGuard.close(); 20040 if (mClosed.compareAndSet(false, true)) { 20041 synchronized (mPackages) { 20042 if (mWeFroze) { 20043 mFrozenPackages.remove(mPackageName); 20044 } 20045 20046 if (mChildren != null) { 20047 for (PackageFreezer freezer : mChildren) { 20048 freezer.close(); 20049 } 20050 } 20051 } 20052 } 20053 } 20054 } 20055 20056 /** 20057 * Verify that given package is currently frozen. 20058 */ 20059 private void checkPackageFrozen(String packageName) { 20060 synchronized (mPackages) { 20061 if (!mFrozenPackages.contains(packageName)) { 20062 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20063 } 20064 } 20065 } 20066 20067 @Override 20068 public int movePackage(final String packageName, final String volumeUuid) { 20069 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20070 20071 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20072 final int moveId = mNextMoveId.getAndIncrement(); 20073 mHandler.post(new Runnable() { 20074 @Override 20075 public void run() { 20076 try { 20077 movePackageInternal(packageName, volumeUuid, moveId, user); 20078 } catch (PackageManagerException e) { 20079 Slog.w(TAG, "Failed to move " + packageName, e); 20080 mMoveCallbacks.notifyStatusChanged(moveId, 20081 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20082 } 20083 } 20084 }); 20085 return moveId; 20086 } 20087 20088 private void movePackageInternal(final String packageName, final String volumeUuid, 20089 final int moveId, UserHandle user) throws PackageManagerException { 20090 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20091 final PackageManager pm = mContext.getPackageManager(); 20092 20093 final boolean currentAsec; 20094 final String currentVolumeUuid; 20095 final File codeFile; 20096 final String installerPackageName; 20097 final String packageAbiOverride; 20098 final int appId; 20099 final String seinfo; 20100 final String label; 20101 final int targetSdkVersion; 20102 final PackageFreezer freezer; 20103 final int[] installedUserIds; 20104 20105 // reader 20106 synchronized (mPackages) { 20107 final PackageParser.Package pkg = mPackages.get(packageName); 20108 final PackageSetting ps = mSettings.mPackages.get(packageName); 20109 if (pkg == null || ps == null) { 20110 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20111 } 20112 20113 if (pkg.applicationInfo.isSystemApp()) { 20114 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20115 "Cannot move system application"); 20116 } 20117 20118 if (pkg.applicationInfo.isExternalAsec()) { 20119 currentAsec = true; 20120 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20121 } else if (pkg.applicationInfo.isForwardLocked()) { 20122 currentAsec = true; 20123 currentVolumeUuid = "forward_locked"; 20124 } else { 20125 currentAsec = false; 20126 currentVolumeUuid = ps.volumeUuid; 20127 20128 final File probe = new File(pkg.codePath); 20129 final File probeOat = new File(probe, "oat"); 20130 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20131 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20132 "Move only supported for modern cluster style installs"); 20133 } 20134 } 20135 20136 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20137 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20138 "Package already moved to " + volumeUuid); 20139 } 20140 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20141 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20142 "Device admin cannot be moved"); 20143 } 20144 20145 if (mFrozenPackages.contains(packageName)) { 20146 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20147 "Failed to move already frozen package"); 20148 } 20149 20150 codeFile = new File(pkg.codePath); 20151 installerPackageName = ps.installerPackageName; 20152 packageAbiOverride = ps.cpuAbiOverrideString; 20153 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20154 seinfo = pkg.applicationInfo.seinfo; 20155 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20156 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20157 freezer = freezePackage(packageName, "movePackageInternal"); 20158 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20159 } 20160 20161 final Bundle extras = new Bundle(); 20162 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20163 extras.putString(Intent.EXTRA_TITLE, label); 20164 mMoveCallbacks.notifyCreated(moveId, extras); 20165 20166 int installFlags; 20167 final boolean moveCompleteApp; 20168 final File measurePath; 20169 20170 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20171 installFlags = INSTALL_INTERNAL; 20172 moveCompleteApp = !currentAsec; 20173 measurePath = Environment.getDataAppDirectory(volumeUuid); 20174 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20175 installFlags = INSTALL_EXTERNAL; 20176 moveCompleteApp = false; 20177 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20178 } else { 20179 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20180 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20181 || !volume.isMountedWritable()) { 20182 freezer.close(); 20183 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20184 "Move location not mounted private volume"); 20185 } 20186 20187 Preconditions.checkState(!currentAsec); 20188 20189 installFlags = INSTALL_INTERNAL; 20190 moveCompleteApp = true; 20191 measurePath = Environment.getDataAppDirectory(volumeUuid); 20192 } 20193 20194 final PackageStats stats = new PackageStats(null, -1); 20195 synchronized (mInstaller) { 20196 for (int userId : installedUserIds) { 20197 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20198 freezer.close(); 20199 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20200 "Failed to measure package size"); 20201 } 20202 } 20203 } 20204 20205 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20206 + stats.dataSize); 20207 20208 final long startFreeBytes = measurePath.getFreeSpace(); 20209 final long sizeBytes; 20210 if (moveCompleteApp) { 20211 sizeBytes = stats.codeSize + stats.dataSize; 20212 } else { 20213 sizeBytes = stats.codeSize; 20214 } 20215 20216 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20217 freezer.close(); 20218 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20219 "Not enough free space to move"); 20220 } 20221 20222 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20223 20224 final CountDownLatch installedLatch = new CountDownLatch(1); 20225 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20226 @Override 20227 public void onUserActionRequired(Intent intent) throws RemoteException { 20228 throw new IllegalStateException(); 20229 } 20230 20231 @Override 20232 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20233 Bundle extras) throws RemoteException { 20234 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20235 + PackageManager.installStatusToString(returnCode, msg)); 20236 20237 installedLatch.countDown(); 20238 freezer.close(); 20239 20240 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20241 switch (status) { 20242 case PackageInstaller.STATUS_SUCCESS: 20243 mMoveCallbacks.notifyStatusChanged(moveId, 20244 PackageManager.MOVE_SUCCEEDED); 20245 break; 20246 case PackageInstaller.STATUS_FAILURE_STORAGE: 20247 mMoveCallbacks.notifyStatusChanged(moveId, 20248 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20249 break; 20250 default: 20251 mMoveCallbacks.notifyStatusChanged(moveId, 20252 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20253 break; 20254 } 20255 } 20256 }; 20257 20258 final MoveInfo move; 20259 if (moveCompleteApp) { 20260 // Kick off a thread to report progress estimates 20261 new Thread() { 20262 @Override 20263 public void run() { 20264 while (true) { 20265 try { 20266 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20267 break; 20268 } 20269 } catch (InterruptedException ignored) { 20270 } 20271 20272 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20273 final int progress = 10 + (int) MathUtils.constrain( 20274 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20275 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20276 } 20277 } 20278 }.start(); 20279 20280 final String dataAppName = codeFile.getName(); 20281 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20282 dataAppName, appId, seinfo, targetSdkVersion); 20283 } else { 20284 move = null; 20285 } 20286 20287 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20288 20289 final Message msg = mHandler.obtainMessage(INIT_COPY); 20290 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20291 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20292 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20293 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20294 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20295 msg.obj = params; 20296 20297 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20298 System.identityHashCode(msg.obj)); 20299 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20300 System.identityHashCode(msg.obj)); 20301 20302 mHandler.sendMessage(msg); 20303 } 20304 20305 @Override 20306 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20307 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20308 20309 final int realMoveId = mNextMoveId.getAndIncrement(); 20310 final Bundle extras = new Bundle(); 20311 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20312 mMoveCallbacks.notifyCreated(realMoveId, extras); 20313 20314 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20315 @Override 20316 public void onCreated(int moveId, Bundle extras) { 20317 // Ignored 20318 } 20319 20320 @Override 20321 public void onStatusChanged(int moveId, int status, long estMillis) { 20322 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20323 } 20324 }; 20325 20326 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20327 storage.setPrimaryStorageUuid(volumeUuid, callback); 20328 return realMoveId; 20329 } 20330 20331 @Override 20332 public int getMoveStatus(int moveId) { 20333 mContext.enforceCallingOrSelfPermission( 20334 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20335 return mMoveCallbacks.mLastStatus.get(moveId); 20336 } 20337 20338 @Override 20339 public void registerMoveCallback(IPackageMoveObserver callback) { 20340 mContext.enforceCallingOrSelfPermission( 20341 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20342 mMoveCallbacks.register(callback); 20343 } 20344 20345 @Override 20346 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20347 mContext.enforceCallingOrSelfPermission( 20348 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20349 mMoveCallbacks.unregister(callback); 20350 } 20351 20352 @Override 20353 public boolean setInstallLocation(int loc) { 20354 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20355 null); 20356 if (getInstallLocation() == loc) { 20357 return true; 20358 } 20359 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20360 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20361 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20362 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20363 return true; 20364 } 20365 return false; 20366 } 20367 20368 @Override 20369 public int getInstallLocation() { 20370 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20371 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20372 PackageHelper.APP_INSTALL_AUTO); 20373 } 20374 20375 /** Called by UserManagerService */ 20376 void cleanUpUser(UserManagerService userManager, int userHandle) { 20377 synchronized (mPackages) { 20378 mDirtyUsers.remove(userHandle); 20379 mUserNeedsBadging.delete(userHandle); 20380 mSettings.removeUserLPw(userHandle); 20381 mPendingBroadcasts.remove(userHandle); 20382 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20383 removeUnusedPackagesLPw(userManager, userHandle); 20384 } 20385 } 20386 20387 /** 20388 * We're removing userHandle and would like to remove any downloaded packages 20389 * that are no longer in use by any other user. 20390 * @param userHandle the user being removed 20391 */ 20392 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20393 final boolean DEBUG_CLEAN_APKS = false; 20394 int [] users = userManager.getUserIds(); 20395 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20396 while (psit.hasNext()) { 20397 PackageSetting ps = psit.next(); 20398 if (ps.pkg == null) { 20399 continue; 20400 } 20401 final String packageName = ps.pkg.packageName; 20402 // Skip over if system app 20403 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20404 continue; 20405 } 20406 if (DEBUG_CLEAN_APKS) { 20407 Slog.i(TAG, "Checking package " + packageName); 20408 } 20409 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20410 if (keep) { 20411 if (DEBUG_CLEAN_APKS) { 20412 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20413 } 20414 } else { 20415 for (int i = 0; i < users.length; i++) { 20416 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20417 keep = true; 20418 if (DEBUG_CLEAN_APKS) { 20419 Slog.i(TAG, " Keeping package " + packageName + " for user " 20420 + users[i]); 20421 } 20422 break; 20423 } 20424 } 20425 } 20426 if (!keep) { 20427 if (DEBUG_CLEAN_APKS) { 20428 Slog.i(TAG, " Removing package " + packageName); 20429 } 20430 mHandler.post(new Runnable() { 20431 public void run() { 20432 deletePackageX(packageName, userHandle, 0); 20433 } //end run 20434 }); 20435 } 20436 } 20437 } 20438 20439 /** Called by UserManagerService */ 20440 void createNewUser(int userId) { 20441 synchronized (mInstallLock) { 20442 mSettings.createNewUserLI(this, mInstaller, userId); 20443 } 20444 synchronized (mPackages) { 20445 scheduleWritePackageRestrictionsLocked(userId); 20446 scheduleWritePackageListLocked(userId); 20447 applyFactoryDefaultBrowserLPw(userId); 20448 primeDomainVerificationsLPw(userId); 20449 } 20450 } 20451 20452 void onNewUserCreated(final int userId) { 20453 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20454 // If permission review for legacy apps is required, we represent 20455 // dagerous permissions for such apps as always granted runtime 20456 // permissions to keep per user flag state whether review is needed. 20457 // Hence, if a new user is added we have to propagate dangerous 20458 // permission grants for these legacy apps. 20459 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20460 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20461 | UPDATE_PERMISSIONS_REPLACE_ALL); 20462 } 20463 } 20464 20465 @Override 20466 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20467 mContext.enforceCallingOrSelfPermission( 20468 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20469 "Only package verification agents can read the verifier device identity"); 20470 20471 synchronized (mPackages) { 20472 return mSettings.getVerifierDeviceIdentityLPw(); 20473 } 20474 } 20475 20476 @Override 20477 public void setPermissionEnforced(String permission, boolean enforced) { 20478 // TODO: Now that we no longer change GID for storage, this should to away. 20479 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20480 "setPermissionEnforced"); 20481 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20482 synchronized (mPackages) { 20483 if (mSettings.mReadExternalStorageEnforced == null 20484 || mSettings.mReadExternalStorageEnforced != enforced) { 20485 mSettings.mReadExternalStorageEnforced = enforced; 20486 mSettings.writeLPr(); 20487 } 20488 } 20489 // kill any non-foreground processes so we restart them and 20490 // grant/revoke the GID. 20491 final IActivityManager am = ActivityManagerNative.getDefault(); 20492 if (am != null) { 20493 final long token = Binder.clearCallingIdentity(); 20494 try { 20495 am.killProcessesBelowForeground("setPermissionEnforcement"); 20496 } catch (RemoteException e) { 20497 } finally { 20498 Binder.restoreCallingIdentity(token); 20499 } 20500 } 20501 } else { 20502 throw new IllegalArgumentException("No selective enforcement for " + permission); 20503 } 20504 } 20505 20506 @Override 20507 @Deprecated 20508 public boolean isPermissionEnforced(String permission) { 20509 return true; 20510 } 20511 20512 @Override 20513 public boolean isStorageLow() { 20514 final long token = Binder.clearCallingIdentity(); 20515 try { 20516 final DeviceStorageMonitorInternal 20517 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20518 if (dsm != null) { 20519 return dsm.isMemoryLow(); 20520 } else { 20521 return false; 20522 } 20523 } finally { 20524 Binder.restoreCallingIdentity(token); 20525 } 20526 } 20527 20528 @Override 20529 public IPackageInstaller getPackageInstaller() { 20530 return mInstallerService; 20531 } 20532 20533 private boolean userNeedsBadging(int userId) { 20534 int index = mUserNeedsBadging.indexOfKey(userId); 20535 if (index < 0) { 20536 final UserInfo userInfo; 20537 final long token = Binder.clearCallingIdentity(); 20538 try { 20539 userInfo = sUserManager.getUserInfo(userId); 20540 } finally { 20541 Binder.restoreCallingIdentity(token); 20542 } 20543 final boolean b; 20544 if (userInfo != null && userInfo.isManagedProfile()) { 20545 b = true; 20546 } else { 20547 b = false; 20548 } 20549 mUserNeedsBadging.put(userId, b); 20550 return b; 20551 } 20552 return mUserNeedsBadging.valueAt(index); 20553 } 20554 20555 @Override 20556 public KeySet getKeySetByAlias(String packageName, String alias) { 20557 if (packageName == null || alias == null) { 20558 return null; 20559 } 20560 synchronized(mPackages) { 20561 final PackageParser.Package pkg = mPackages.get(packageName); 20562 if (pkg == null) { 20563 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20564 throw new IllegalArgumentException("Unknown package: " + packageName); 20565 } 20566 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20567 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20568 } 20569 } 20570 20571 @Override 20572 public KeySet getSigningKeySet(String packageName) { 20573 if (packageName == null) { 20574 return null; 20575 } 20576 synchronized(mPackages) { 20577 final PackageParser.Package pkg = mPackages.get(packageName); 20578 if (pkg == null) { 20579 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20580 throw new IllegalArgumentException("Unknown package: " + packageName); 20581 } 20582 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20583 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20584 throw new SecurityException("May not access signing KeySet of other apps."); 20585 } 20586 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20587 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20588 } 20589 } 20590 20591 @Override 20592 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20593 if (packageName == null || ks == null) { 20594 return false; 20595 } 20596 synchronized(mPackages) { 20597 final PackageParser.Package pkg = mPackages.get(packageName); 20598 if (pkg == null) { 20599 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20600 throw new IllegalArgumentException("Unknown package: " + packageName); 20601 } 20602 IBinder ksh = ks.getToken(); 20603 if (ksh instanceof KeySetHandle) { 20604 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20605 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20606 } 20607 return false; 20608 } 20609 } 20610 20611 @Override 20612 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20613 if (packageName == null || ks == null) { 20614 return false; 20615 } 20616 synchronized(mPackages) { 20617 final PackageParser.Package pkg = mPackages.get(packageName); 20618 if (pkg == null) { 20619 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20620 throw new IllegalArgumentException("Unknown package: " + packageName); 20621 } 20622 IBinder ksh = ks.getToken(); 20623 if (ksh instanceof KeySetHandle) { 20624 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20625 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20626 } 20627 return false; 20628 } 20629 } 20630 20631 private void deletePackageIfUnusedLPr(final String packageName) { 20632 PackageSetting ps = mSettings.mPackages.get(packageName); 20633 if (ps == null) { 20634 return; 20635 } 20636 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20637 // TODO Implement atomic delete if package is unused 20638 // It is currently possible that the package will be deleted even if it is installed 20639 // after this method returns. 20640 mHandler.post(new Runnable() { 20641 public void run() { 20642 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20643 } 20644 }); 20645 } 20646 } 20647 20648 /** 20649 * Check and throw if the given before/after packages would be considered a 20650 * downgrade. 20651 */ 20652 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20653 throws PackageManagerException { 20654 if (after.versionCode < before.mVersionCode) { 20655 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20656 "Update version code " + after.versionCode + " is older than current " 20657 + before.mVersionCode); 20658 } else if (after.versionCode == before.mVersionCode) { 20659 if (after.baseRevisionCode < before.baseRevisionCode) { 20660 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20661 "Update base revision code " + after.baseRevisionCode 20662 + " is older than current " + before.baseRevisionCode); 20663 } 20664 20665 if (!ArrayUtils.isEmpty(after.splitNames)) { 20666 for (int i = 0; i < after.splitNames.length; i++) { 20667 final String splitName = after.splitNames[i]; 20668 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20669 if (j != -1) { 20670 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20671 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20672 "Update split " + splitName + " revision code " 20673 + after.splitRevisionCodes[i] + " is older than current " 20674 + before.splitRevisionCodes[j]); 20675 } 20676 } 20677 } 20678 } 20679 } 20680 } 20681 20682 private static class MoveCallbacks extends Handler { 20683 private static final int MSG_CREATED = 1; 20684 private static final int MSG_STATUS_CHANGED = 2; 20685 20686 private final RemoteCallbackList<IPackageMoveObserver> 20687 mCallbacks = new RemoteCallbackList<>(); 20688 20689 private final SparseIntArray mLastStatus = new SparseIntArray(); 20690 20691 public MoveCallbacks(Looper looper) { 20692 super(looper); 20693 } 20694 20695 public void register(IPackageMoveObserver callback) { 20696 mCallbacks.register(callback); 20697 } 20698 20699 public void unregister(IPackageMoveObserver callback) { 20700 mCallbacks.unregister(callback); 20701 } 20702 20703 @Override 20704 public void handleMessage(Message msg) { 20705 final SomeArgs args = (SomeArgs) msg.obj; 20706 final int n = mCallbacks.beginBroadcast(); 20707 for (int i = 0; i < n; i++) { 20708 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20709 try { 20710 invokeCallback(callback, msg.what, args); 20711 } catch (RemoteException ignored) { 20712 } 20713 } 20714 mCallbacks.finishBroadcast(); 20715 args.recycle(); 20716 } 20717 20718 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20719 throws RemoteException { 20720 switch (what) { 20721 case MSG_CREATED: { 20722 callback.onCreated(args.argi1, (Bundle) args.arg2); 20723 break; 20724 } 20725 case MSG_STATUS_CHANGED: { 20726 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20727 break; 20728 } 20729 } 20730 } 20731 20732 private void notifyCreated(int moveId, Bundle extras) { 20733 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20734 20735 final SomeArgs args = SomeArgs.obtain(); 20736 args.argi1 = moveId; 20737 args.arg2 = extras; 20738 obtainMessage(MSG_CREATED, args).sendToTarget(); 20739 } 20740 20741 private void notifyStatusChanged(int moveId, int status) { 20742 notifyStatusChanged(moveId, status, -1); 20743 } 20744 20745 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20746 Slog.v(TAG, "Move " + moveId + " status " + status); 20747 20748 final SomeArgs args = SomeArgs.obtain(); 20749 args.argi1 = moveId; 20750 args.argi2 = status; 20751 args.arg3 = estMillis; 20752 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20753 20754 synchronized (mLastStatus) { 20755 mLastStatus.put(moveId, status); 20756 } 20757 } 20758 } 20759 20760 private final static class OnPermissionChangeListeners extends Handler { 20761 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20762 20763 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20764 new RemoteCallbackList<>(); 20765 20766 public OnPermissionChangeListeners(Looper looper) { 20767 super(looper); 20768 } 20769 20770 @Override 20771 public void handleMessage(Message msg) { 20772 switch (msg.what) { 20773 case MSG_ON_PERMISSIONS_CHANGED: { 20774 final int uid = msg.arg1; 20775 handleOnPermissionsChanged(uid); 20776 } break; 20777 } 20778 } 20779 20780 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20781 mPermissionListeners.register(listener); 20782 20783 } 20784 20785 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20786 mPermissionListeners.unregister(listener); 20787 } 20788 20789 public void onPermissionsChanged(int uid) { 20790 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20791 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20792 } 20793 } 20794 20795 private void handleOnPermissionsChanged(int uid) { 20796 final int count = mPermissionListeners.beginBroadcast(); 20797 try { 20798 for (int i = 0; i < count; i++) { 20799 IOnPermissionsChangeListener callback = mPermissionListeners 20800 .getBroadcastItem(i); 20801 try { 20802 callback.onPermissionsChanged(uid); 20803 } catch (RemoteException e) { 20804 Log.e(TAG, "Permission listener is dead", e); 20805 } 20806 } 20807 } finally { 20808 mPermissionListeners.finishBroadcast(); 20809 } 20810 } 20811 } 20812 20813 private class PackageManagerInternalImpl extends PackageManagerInternal { 20814 @Override 20815 public void setLocationPackagesProvider(PackagesProvider provider) { 20816 synchronized (mPackages) { 20817 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20818 } 20819 } 20820 20821 @Override 20822 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20823 synchronized (mPackages) { 20824 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20825 } 20826 } 20827 20828 @Override 20829 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20830 synchronized (mPackages) { 20831 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20832 } 20833 } 20834 20835 @Override 20836 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20837 synchronized (mPackages) { 20838 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20839 } 20840 } 20841 20842 @Override 20843 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20844 synchronized (mPackages) { 20845 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20846 } 20847 } 20848 20849 @Override 20850 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20851 synchronized (mPackages) { 20852 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20853 } 20854 } 20855 20856 @Override 20857 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20858 synchronized (mPackages) { 20859 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20860 packageName, userId); 20861 } 20862 } 20863 20864 @Override 20865 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20866 synchronized (mPackages) { 20867 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20868 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20869 packageName, userId); 20870 } 20871 } 20872 20873 @Override 20874 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20875 synchronized (mPackages) { 20876 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20877 packageName, userId); 20878 } 20879 } 20880 20881 @Override 20882 public void setKeepUninstalledPackages(final List<String> packageList) { 20883 Preconditions.checkNotNull(packageList); 20884 List<String> removedFromList = null; 20885 synchronized (mPackages) { 20886 if (mKeepUninstalledPackages != null) { 20887 final int packagesCount = mKeepUninstalledPackages.size(); 20888 for (int i = 0; i < packagesCount; i++) { 20889 String oldPackage = mKeepUninstalledPackages.get(i); 20890 if (packageList != null && packageList.contains(oldPackage)) { 20891 continue; 20892 } 20893 if (removedFromList == null) { 20894 removedFromList = new ArrayList<>(); 20895 } 20896 removedFromList.add(oldPackage); 20897 } 20898 } 20899 mKeepUninstalledPackages = new ArrayList<>(packageList); 20900 if (removedFromList != null) { 20901 final int removedCount = removedFromList.size(); 20902 for (int i = 0; i < removedCount; i++) { 20903 deletePackageIfUnusedLPr(removedFromList.get(i)); 20904 } 20905 } 20906 } 20907 } 20908 20909 @Override 20910 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20911 synchronized (mPackages) { 20912 // If we do not support permission review, done. 20913 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20914 return false; 20915 } 20916 20917 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20918 if (packageSetting == null) { 20919 return false; 20920 } 20921 20922 // Permission review applies only to apps not supporting the new permission model. 20923 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20924 return false; 20925 } 20926 20927 // Legacy apps have the permission and get user consent on launch. 20928 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20929 return permissionsState.isPermissionReviewRequired(userId); 20930 } 20931 } 20932 20933 @Override 20934 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20935 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20936 } 20937 20938 @Override 20939 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20940 int userId) { 20941 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20942 } 20943 20944 @Override 20945 public void setDeviceAndProfileOwnerPackages( 20946 int deviceOwnerUserId, String deviceOwnerPackage, 20947 SparseArray<String> profileOwnerPackages) { 20948 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20949 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20950 } 20951 20952 @Override 20953 public boolean isPackageDataProtected(int userId, String packageName) { 20954 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20955 } 20956 } 20957 20958 @Override 20959 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20960 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20961 synchronized (mPackages) { 20962 final long identity = Binder.clearCallingIdentity(); 20963 try { 20964 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20965 packageNames, userId); 20966 } finally { 20967 Binder.restoreCallingIdentity(identity); 20968 } 20969 } 20970 } 20971 20972 private static void enforceSystemOrPhoneCaller(String tag) { 20973 int callingUid = Binder.getCallingUid(); 20974 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20975 throw new SecurityException( 20976 "Cannot call " + tag + " from UID " + callingUid); 20977 } 20978 } 20979 20980 boolean isHistoricalPackageUsageAvailable() { 20981 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20982 } 20983 20984 /** 20985 * Return a <b>copy</b> of the collection of packages known to the package manager. 20986 * @return A copy of the values of mPackages. 20987 */ 20988 Collection<PackageParser.Package> getPackages() { 20989 synchronized (mPackages) { 20990 return new ArrayList<>(mPackages.values()); 20991 } 20992 } 20993 20994 /** 20995 * Logs process start information (including base APK hash) to the security log. 20996 * @hide 20997 */ 20998 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20999 String apkFile, int pid) { 21000 if (!SecurityLog.isLoggingEnabled()) { 21001 return; 21002 } 21003 Bundle data = new Bundle(); 21004 data.putLong("startTimestamp", System.currentTimeMillis()); 21005 data.putString("processName", processName); 21006 data.putInt("uid", uid); 21007 data.putString("seinfo", seinfo); 21008 data.putString("apkFile", apkFile); 21009 data.putInt("pid", pid); 21010 Message msg = mProcessLoggingHandler.obtainMessage( 21011 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21012 msg.setData(data); 21013 mProcessLoggingHandler.sendMessage(msg); 21014 } 21015} 21016