PackageManagerService.java revision 93729fea513f2674da2acc3e0c7324eda827d9df
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.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.MATCH_ALL; 60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 64import static android.content.pm.PackageManager.PERMISSION_DENIED; 65import static android.content.pm.PackageManager.PERMISSION_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 70import static android.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 85 86import android.Manifest; 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IOnPermissionsChangeListener; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.IntentFilterVerificationInfo; 118import android.content.pm.KeySet; 119import android.content.pm.ManifestDigest; 120import android.content.pm.PackageCleanItem; 121import android.content.pm.PackageInfo; 122import android.content.pm.PackageInfoLite; 123import android.content.pm.PackageInstaller; 124import android.content.pm.PackageManager; 125import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 126import android.content.pm.PackageManagerInternal; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageStats; 132import android.content.pm.PackageUserState; 133import android.content.pm.ParceledListSlice; 134import android.content.pm.PermissionGroupInfo; 135import android.content.pm.PermissionInfo; 136import android.content.pm.ProviderInfo; 137import android.content.pm.ResolveInfo; 138import android.content.pm.ServiceInfo; 139import android.content.pm.Signature; 140import android.content.pm.UserInfo; 141import android.content.pm.VerificationParams; 142import android.content.pm.VerifierDeviceIdentity; 143import android.content.pm.VerifierInfo; 144import android.content.res.Resources; 145import android.hardware.display.DisplayManager; 146import android.net.Uri; 147import android.os.Debug; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteCallbackList; 162import android.os.RemoteException; 163import android.os.SELinux; 164import android.os.ServiceManager; 165import android.os.SystemClock; 166import android.os.SystemProperties; 167import android.os.Trace; 168import android.os.UserHandle; 169import android.os.UserManager; 170import android.os.storage.IMountService; 171import android.os.storage.MountServiceInternal; 172import android.os.storage.StorageEventListener; 173import android.os.storage.StorageManager; 174import android.os.storage.VolumeInfo; 175import android.os.storage.VolumeRecord; 176import android.security.KeyStore; 177import android.security.SystemKeyStore; 178import android.system.ErrnoException; 179import android.system.Os; 180import android.system.StructStat; 181import android.text.TextUtils; 182import android.text.format.DateUtils; 183import android.util.ArrayMap; 184import android.util.ArraySet; 185import android.util.AtomicFile; 186import android.util.DisplayMetrics; 187import android.util.EventLog; 188import android.util.ExceptionUtils; 189import android.util.Log; 190import android.util.LogPrinter; 191import android.util.MathUtils; 192import android.util.PrintStreamPrinter; 193import android.util.Slog; 194import android.util.SparseArray; 195import android.util.SparseBooleanArray; 196import android.util.SparseIntArray; 197import android.util.Xml; 198import android.view.Display; 199 200import dalvik.system.DexFile; 201import dalvik.system.VMRuntime; 202 203import libcore.io.IoUtils; 204import libcore.util.EmptyArray; 205 206import com.android.internal.R; 207import com.android.internal.annotations.GuardedBy; 208import com.android.internal.app.IMediaContainerService; 209import com.android.internal.app.ResolverActivity; 210import com.android.internal.content.NativeLibraryHelper; 211import com.android.internal.content.PackageHelper; 212import com.android.internal.os.IParcelFileDescriptorFactory; 213import com.android.internal.os.SomeArgs; 214import com.android.internal.os.Zygote; 215import com.android.internal.util.ArrayUtils; 216import com.android.internal.util.FastPrintWriter; 217import com.android.internal.util.FastXmlSerializer; 218import com.android.internal.util.IndentingPrintWriter; 219import com.android.internal.util.Preconditions; 220import com.android.server.EventLogTags; 221import com.android.server.FgThread; 222import com.android.server.IntentResolver; 223import com.android.server.LocalServices; 224import com.android.server.ServiceThread; 225import com.android.server.SystemConfig; 226import com.android.server.Watchdog; 227import com.android.server.pm.PermissionsState.PermissionState; 228import com.android.server.pm.Settings.DatabaseVersion; 229import com.android.server.pm.Settings.VersionInfo; 230import com.android.server.storage.DeviceStorageMonitorInternal; 231 232import org.xmlpull.v1.XmlPullParser; 233import org.xmlpull.v1.XmlPullParserException; 234import org.xmlpull.v1.XmlSerializer; 235 236import java.io.BufferedInputStream; 237import java.io.BufferedOutputStream; 238import java.io.BufferedReader; 239import java.io.ByteArrayInputStream; 240import java.io.ByteArrayOutputStream; 241import java.io.File; 242import java.io.FileDescriptor; 243import java.io.FileNotFoundException; 244import java.io.FileOutputStream; 245import java.io.FileReader; 246import java.io.FilenameFilter; 247import java.io.IOException; 248import java.io.InputStream; 249import java.io.PrintWriter; 250import java.nio.charset.StandardCharsets; 251import java.security.NoSuchAlgorithmException; 252import java.security.PublicKey; 253import java.security.cert.CertificateEncodingException; 254import java.security.cert.CertificateException; 255import java.text.SimpleDateFormat; 256import java.util.ArrayList; 257import java.util.Arrays; 258import java.util.Collection; 259import java.util.Collections; 260import java.util.Comparator; 261import java.util.Date; 262import java.util.Iterator; 263import java.util.List; 264import java.util.Map; 265import java.util.Objects; 266import java.util.Set; 267import java.util.concurrent.CountDownLatch; 268import java.util.concurrent.TimeUnit; 269import java.util.concurrent.atomic.AtomicBoolean; 270import java.util.concurrent.atomic.AtomicInteger; 271import java.util.concurrent.atomic.AtomicLong; 272 273/** 274 * Keep track of all those .apks everywhere. 275 * 276 * This is very central to the platform's security; please run the unit 277 * tests whenever making modifications here: 278 * 279runtest -c android.content.pm.PackageManagerTests frameworks-core 280 * 281 * {@hide} 282 */ 283public class PackageManagerService extends IPackageManager.Stub { 284 static final String TAG = "PackageManager"; 285 static final boolean DEBUG_SETTINGS = false; 286 static final boolean DEBUG_PREFERRED = false; 287 static final boolean DEBUG_UPGRADE = false; 288 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 289 private static final boolean DEBUG_BACKUP = false; 290 private static final boolean DEBUG_INSTALL = false; 291 private static final boolean DEBUG_REMOVE = false; 292 private static final boolean DEBUG_BROADCASTS = false; 293 private static final boolean DEBUG_SHOW_INFO = false; 294 private static final boolean DEBUG_PACKAGE_INFO = false; 295 private static final boolean DEBUG_INTENT_MATCHING = false; 296 private static final boolean DEBUG_PACKAGE_SCANNING = false; 297 private static final boolean DEBUG_VERIFY = false; 298 private static final boolean DEBUG_DEXOPT = false; 299 private static final boolean DEBUG_ABI_SELECTION = false; 300 301 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 302 303 private static final int RADIO_UID = Process.PHONE_UID; 304 private static final int LOG_UID = Process.LOG_UID; 305 private static final int NFC_UID = Process.NFC_UID; 306 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 307 private static final int SHELL_UID = Process.SHELL_UID; 308 309 // Cap the size of permission trees that 3rd party apps can define 310 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 311 312 // Suffix used during package installation when copying/moving 313 // package apks to install directory. 314 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 315 316 static final int SCAN_NO_DEX = 1<<1; 317 static final int SCAN_FORCE_DEX = 1<<2; 318 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 319 static final int SCAN_NEW_INSTALL = 1<<4; 320 static final int SCAN_NO_PATHS = 1<<5; 321 static final int SCAN_UPDATE_TIME = 1<<6; 322 static final int SCAN_DEFER_DEX = 1<<7; 323 static final int SCAN_BOOTING = 1<<8; 324 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 325 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 326 static final int SCAN_REPLACING = 1<<11; 327 static final int SCAN_REQUIRE_KNOWN = 1<<12; 328 static final int SCAN_MOVE = 1<<13; 329 static final int SCAN_INITIAL = 1<<14; 330 331 static final int REMOVE_CHATTY = 1<<16; 332 333 private static final int[] EMPTY_INT_ARRAY = new int[0]; 334 335 /** 336 * Timeout (in milliseconds) after which the watchdog should declare that 337 * our handler thread is wedged. The usual default for such things is one 338 * minute but we sometimes do very lengthy I/O operations on this thread, 339 * such as installing multi-gigabyte applications, so ours needs to be longer. 340 */ 341 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 342 343 /** 344 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 345 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 346 * settings entry if available, otherwise we use the hardcoded default. If it's been 347 * more than this long since the last fstrim, we force one during the boot sequence. 348 * 349 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 350 * one gets run at the next available charging+idle time. This final mandatory 351 * no-fstrim check kicks in only of the other scheduling criteria is never met. 352 */ 353 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 354 355 /** 356 * Whether verification is enabled by default. 357 */ 358 private static final boolean DEFAULT_VERIFY_ENABLE = true; 359 360 /** 361 * The default maximum time to wait for the verification agent to return in 362 * milliseconds. 363 */ 364 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 365 366 /** 367 * The default response for package verification timeout. 368 * 369 * This can be either PackageManager.VERIFICATION_ALLOW or 370 * PackageManager.VERIFICATION_REJECT. 371 */ 372 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 373 374 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 375 376 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 377 DEFAULT_CONTAINER_PACKAGE, 378 "com.android.defcontainer.DefaultContainerService"); 379 380 private static final String KILL_APP_REASON_GIDS_CHANGED = 381 "permission grant or revoke changed gids"; 382 383 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 384 "permissions revoked"; 385 386 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 387 388 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 389 390 /** Permission grant: not grant the permission. */ 391 private static final int GRANT_DENIED = 1; 392 393 /** Permission grant: grant the permission as an install permission. */ 394 private static final int GRANT_INSTALL = 2; 395 396 /** Permission grant: grant the permission as an install permission for a legacy app. */ 397 private static final int GRANT_INSTALL_LEGACY = 3; 398 399 /** Permission grant: grant the permission as a runtime one. */ 400 private static final int GRANT_RUNTIME = 4; 401 402 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 403 private static final int GRANT_UPGRADE = 5; 404 405 /** Canonical intent used to identify what counts as a "web browser" app */ 406 private static final Intent sBrowserIntent; 407 static { 408 sBrowserIntent = new Intent(); 409 sBrowserIntent.setAction(Intent.ACTION_VIEW); 410 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 411 sBrowserIntent.setData(Uri.parse("http:")); 412 } 413 414 final ServiceThread mHandlerThread; 415 416 final PackageHandler mHandler; 417 418 /** 419 * Messages for {@link #mHandler} that need to wait for system ready before 420 * being dispatched. 421 */ 422 private ArrayList<Message> mPostSystemReadyMessages; 423 424 final int mSdkVersion = Build.VERSION.SDK_INT; 425 426 final Context mContext; 427 final boolean mFactoryTest; 428 final boolean mOnlyCore; 429 final boolean mLazyDexOpt; 430 final long mDexOptLRUThresholdInMills; 431 final DisplayMetrics mMetrics; 432 final int mDefParseFlags; 433 final String[] mSeparateProcesses; 434 final boolean mIsUpgrade; 435 436 // This is where all application persistent data goes. 437 final File mAppDataDir; 438 439 // This is where all application persistent data goes for secondary users. 440 final File mUserAppDataDir; 441 442 /** The location for ASEC container files on internal storage. */ 443 final String mAsecInternalPath; 444 445 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 446 // LOCK HELD. Can be called with mInstallLock held. 447 @GuardedBy("mInstallLock") 448 final Installer mInstaller; 449 450 /** Directory where installed third-party apps stored */ 451 final File mAppInstallDir; 452 453 /** 454 * Directory to which applications installed internally have their 455 * 32 bit native libraries copied. 456 */ 457 private File mAppLib32InstallDir; 458 459 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 460 // apps. 461 final File mDrmAppPrivateInstallDir; 462 463 // ---------------------------------------------------------------- 464 465 // Lock for state used when installing and doing other long running 466 // operations. Methods that must be called with this lock held have 467 // the suffix "LI". 468 final Object mInstallLock = new Object(); 469 470 // ---------------------------------------------------------------- 471 472 // Keys are String (package name), values are Package. This also serves 473 // as the lock for the global state. Methods that must be called with 474 // this lock held have the prefix "LP". 475 @GuardedBy("mPackages") 476 final ArrayMap<String, PackageParser.Package> mPackages = 477 new ArrayMap<String, PackageParser.Package>(); 478 479 // Tracks available target package names -> overlay package paths. 480 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 481 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 482 483 /** 484 * Tracks new system packages [received in an OTA] that we expect to 485 * find updated user-installed versions. Keys are package name, values 486 * are package location. 487 */ 488 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 489 490 /** 491 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 492 */ 493 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 494 /** 495 * Whether or not system app permissions should be promoted from install to runtime. 496 */ 497 boolean mPromoteSystemApps; 498 499 final Settings mSettings; 500 boolean mRestoredSettings; 501 502 // System configuration read by SystemConfig. 503 final int[] mGlobalGids; 504 final SparseArray<ArraySet<String>> mSystemPermissions; 505 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 506 507 // If mac_permissions.xml was found for seinfo labeling. 508 boolean mFoundPolicyFile; 509 510 // If a recursive restorecon of /data/data/<pkg> is needed. 511 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 512 513 public static final class SharedLibraryEntry { 514 public final String path; 515 public final String apk; 516 517 SharedLibraryEntry(String _path, String _apk) { 518 path = _path; 519 apk = _apk; 520 } 521 } 522 523 // Currently known shared libraries. 524 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 525 new ArrayMap<String, SharedLibraryEntry>(); 526 527 // All available activities, for your resolving pleasure. 528 final ActivityIntentResolver mActivities = 529 new ActivityIntentResolver(); 530 531 // All available receivers, for your resolving pleasure. 532 final ActivityIntentResolver mReceivers = 533 new ActivityIntentResolver(); 534 535 // All available services, for your resolving pleasure. 536 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 537 538 // All available providers, for your resolving pleasure. 539 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 540 541 // Mapping from provider base names (first directory in content URI codePath) 542 // to the provider information. 543 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 544 new ArrayMap<String, PackageParser.Provider>(); 545 546 // Mapping from instrumentation class names to info about them. 547 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 548 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 549 550 // Mapping from permission names to info about them. 551 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 552 new ArrayMap<String, PackageParser.PermissionGroup>(); 553 554 // Packages whose data we have transfered into another package, thus 555 // should no longer exist. 556 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 557 558 // Broadcast actions that are only available to the system. 559 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 560 561 /** List of packages waiting for verification. */ 562 final SparseArray<PackageVerificationState> mPendingVerification 563 = new SparseArray<PackageVerificationState>(); 564 565 /** Set of packages associated with each app op permission. */ 566 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 567 568 final PackageInstallerService mInstallerService; 569 570 private final PackageDexOptimizer mPackageDexOptimizer; 571 572 private AtomicInteger mNextMoveId = new AtomicInteger(); 573 private final MoveCallbacks mMoveCallbacks; 574 575 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 576 577 // Cache of users who need badging. 578 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 579 580 /** Token for keys in mPendingVerification. */ 581 private int mPendingVerificationToken = 0; 582 583 volatile boolean mSystemReady; 584 volatile boolean mSafeMode; 585 volatile boolean mHasSystemUidErrors; 586 587 ApplicationInfo mAndroidApplication; 588 final ActivityInfo mResolveActivity = new ActivityInfo(); 589 final ResolveInfo mResolveInfo = new ResolveInfo(); 590 ComponentName mResolveComponentName; 591 PackageParser.Package mPlatformPackage; 592 ComponentName mCustomResolverComponentName; 593 594 boolean mResolverReplaced = false; 595 596 private final ComponentName mIntentFilterVerifierComponent; 597 private int mIntentFilterVerificationToken = 0; 598 599 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 600 = new SparseArray<IntentFilterVerificationState>(); 601 602 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 603 new DefaultPermissionGrantPolicy(this); 604 605 private static class IFVerificationParams { 606 PackageParser.Package pkg; 607 boolean replacing; 608 int userId; 609 int verifierUid; 610 611 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 612 int _userId, int _verifierUid) { 613 pkg = _pkg; 614 replacing = _replacing; 615 userId = _userId; 616 replacing = _replacing; 617 verifierUid = _verifierUid; 618 } 619 } 620 621 private interface IntentFilterVerifier<T extends IntentFilter> { 622 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 623 T filter, String packageName); 624 void startVerifications(int userId); 625 void receiveVerificationResponse(int verificationId); 626 } 627 628 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 629 private Context mContext; 630 private ComponentName mIntentFilterVerifierComponent; 631 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 632 633 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 634 mContext = context; 635 mIntentFilterVerifierComponent = verifierComponent; 636 } 637 638 private String getDefaultScheme() { 639 return IntentFilter.SCHEME_HTTPS; 640 } 641 642 @Override 643 public void startVerifications(int userId) { 644 // Launch verifications requests 645 int count = mCurrentIntentFilterVerifications.size(); 646 for (int n=0; n<count; n++) { 647 int verificationId = mCurrentIntentFilterVerifications.get(n); 648 final IntentFilterVerificationState ivs = 649 mIntentFilterVerificationStates.get(verificationId); 650 651 String packageName = ivs.getPackageName(); 652 653 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 654 final int filterCount = filters.size(); 655 ArraySet<String> domainsSet = new ArraySet<>(); 656 for (int m=0; m<filterCount; m++) { 657 PackageParser.ActivityIntentInfo filter = filters.get(m); 658 domainsSet.addAll(filter.getHostsList()); 659 } 660 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 661 synchronized (mPackages) { 662 if (mSettings.createIntentFilterVerificationIfNeededLPw( 663 packageName, domainsList) != null) { 664 scheduleWriteSettingsLocked(); 665 } 666 } 667 sendVerificationRequest(userId, verificationId, ivs); 668 } 669 mCurrentIntentFilterVerifications.clear(); 670 } 671 672 private void sendVerificationRequest(int userId, int verificationId, 673 IntentFilterVerificationState ivs) { 674 675 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 676 verificationIntent.putExtra( 677 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 678 verificationId); 679 verificationIntent.putExtra( 680 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 681 getDefaultScheme()); 682 verificationIntent.putExtra( 683 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 684 ivs.getHostsString()); 685 verificationIntent.putExtra( 686 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 687 ivs.getPackageName()); 688 verificationIntent.setComponent(mIntentFilterVerifierComponent); 689 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 690 691 UserHandle user = new UserHandle(userId); 692 mContext.sendBroadcastAsUser(verificationIntent, user); 693 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 694 "Sending IntentFilter verification broadcast"); 695 } 696 697 public void receiveVerificationResponse(int verificationId) { 698 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 699 700 final boolean verified = ivs.isVerified(); 701 702 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 703 final int count = filters.size(); 704 if (DEBUG_DOMAIN_VERIFICATION) { 705 Slog.i(TAG, "Received verification response " + verificationId 706 + " for " + count + " filters, verified=" + verified); 707 } 708 for (int n=0; n<count; n++) { 709 PackageParser.ActivityIntentInfo filter = filters.get(n); 710 filter.setVerified(verified); 711 712 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 713 + " verified with result:" + verified + " and hosts:" 714 + ivs.getHostsString()); 715 } 716 717 mIntentFilterVerificationStates.remove(verificationId); 718 719 final String packageName = ivs.getPackageName(); 720 IntentFilterVerificationInfo ivi = null; 721 722 synchronized (mPackages) { 723 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 724 } 725 if (ivi == null) { 726 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 727 + verificationId + " packageName:" + packageName); 728 return; 729 } 730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 731 "Updating IntentFilterVerificationInfo for package " + packageName 732 +" verificationId:" + verificationId); 733 734 synchronized (mPackages) { 735 if (verified) { 736 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 737 } else { 738 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 739 } 740 scheduleWriteSettingsLocked(); 741 742 final int userId = ivs.getUserId(); 743 if (userId != UserHandle.USER_ALL) { 744 final int userStatus = 745 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 746 747 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 748 boolean needUpdate = false; 749 750 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 751 // already been set by the User thru the Disambiguation dialog 752 switch (userStatus) { 753 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 754 if (verified) { 755 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 756 } else { 757 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 758 } 759 needUpdate = true; 760 break; 761 762 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 763 if (verified) { 764 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 765 needUpdate = true; 766 } 767 break; 768 769 default: 770 // Nothing to do 771 } 772 773 if (needUpdate) { 774 mSettings.updateIntentFilterVerificationStatusLPw( 775 packageName, updatedStatus, userId); 776 scheduleWritePackageRestrictionsLocked(userId); 777 } 778 } 779 } 780 } 781 782 @Override 783 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 784 ActivityIntentInfo filter, String packageName) { 785 if (!hasValidDomains(filter)) { 786 return false; 787 } 788 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 789 if (ivs == null) { 790 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 791 packageName); 792 } 793 if (DEBUG_DOMAIN_VERIFICATION) { 794 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 795 } 796 ivs.addFilter(filter); 797 return true; 798 } 799 800 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 801 int userId, int verificationId, String packageName) { 802 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 803 verifierUid, userId, packageName); 804 ivs.setPendingState(); 805 synchronized (mPackages) { 806 mIntentFilterVerificationStates.append(verificationId, ivs); 807 mCurrentIntentFilterVerifications.add(verificationId); 808 } 809 return ivs; 810 } 811 } 812 813 private static boolean hasValidDomains(ActivityIntentInfo filter) { 814 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 815 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 816 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 817 } 818 819 private IntentFilterVerifier mIntentFilterVerifier; 820 821 // Set of pending broadcasts for aggregating enable/disable of components. 822 static class PendingPackageBroadcasts { 823 // for each user id, a map of <package name -> components within that package> 824 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 825 826 public PendingPackageBroadcasts() { 827 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 828 } 829 830 public ArrayList<String> get(int userId, String packageName) { 831 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 832 return packages.get(packageName); 833 } 834 835 public void put(int userId, String packageName, ArrayList<String> components) { 836 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 837 packages.put(packageName, components); 838 } 839 840 public void remove(int userId, String packageName) { 841 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 842 if (packages != null) { 843 packages.remove(packageName); 844 } 845 } 846 847 public void remove(int userId) { 848 mUidMap.remove(userId); 849 } 850 851 public int userIdCount() { 852 return mUidMap.size(); 853 } 854 855 public int userIdAt(int n) { 856 return mUidMap.keyAt(n); 857 } 858 859 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 860 return mUidMap.get(userId); 861 } 862 863 public int size() { 864 // total number of pending broadcast entries across all userIds 865 int num = 0; 866 for (int i = 0; i< mUidMap.size(); i++) { 867 num += mUidMap.valueAt(i).size(); 868 } 869 return num; 870 } 871 872 public void clear() { 873 mUidMap.clear(); 874 } 875 876 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 877 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 878 if (map == null) { 879 map = new ArrayMap<String, ArrayList<String>>(); 880 mUidMap.put(userId, map); 881 } 882 return map; 883 } 884 } 885 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 886 887 // Service Connection to remote media container service to copy 888 // package uri's from external media onto secure containers 889 // or internal storage. 890 private IMediaContainerService mContainerService = null; 891 892 static final int SEND_PENDING_BROADCAST = 1; 893 static final int MCS_BOUND = 3; 894 static final int END_COPY = 4; 895 static final int INIT_COPY = 5; 896 static final int MCS_UNBIND = 6; 897 static final int START_CLEANING_PACKAGE = 7; 898 static final int FIND_INSTALL_LOC = 8; 899 static final int POST_INSTALL = 9; 900 static final int MCS_RECONNECT = 10; 901 static final int MCS_GIVE_UP = 11; 902 static final int UPDATED_MEDIA_STATUS = 12; 903 static final int WRITE_SETTINGS = 13; 904 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 905 static final int PACKAGE_VERIFIED = 15; 906 static final int CHECK_PENDING_VERIFICATION = 16; 907 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 908 static final int INTENT_FILTER_VERIFIED = 18; 909 910 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 911 912 // Delay time in millisecs 913 static final int BROADCAST_DELAY = 10 * 1000; 914 915 static UserManagerService sUserManager; 916 917 // Stores a list of users whose package restrictions file needs to be updated 918 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 919 920 final private DefaultContainerConnection mDefContainerConn = 921 new DefaultContainerConnection(); 922 class DefaultContainerConnection implements ServiceConnection { 923 public void onServiceConnected(ComponentName name, IBinder service) { 924 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 925 IMediaContainerService imcs = 926 IMediaContainerService.Stub.asInterface(service); 927 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 928 } 929 930 public void onServiceDisconnected(ComponentName name) { 931 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 932 } 933 } 934 935 // Recordkeeping of restore-after-install operations that are currently in flight 936 // between the Package Manager and the Backup Manager 937 class PostInstallData { 938 public InstallArgs args; 939 public PackageInstalledInfo res; 940 941 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 942 args = _a; 943 res = _r; 944 } 945 } 946 947 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 948 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 949 950 // XML tags for backup/restore of various bits of state 951 private static final String TAG_PREFERRED_BACKUP = "pa"; 952 private static final String TAG_DEFAULT_APPS = "da"; 953 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 954 955 final String mRequiredVerifierPackage; 956 final String mRequiredInstallerPackage; 957 958 private final PackageUsage mPackageUsage = new PackageUsage(); 959 960 private class PackageUsage { 961 private static final int WRITE_INTERVAL 962 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 963 964 private final Object mFileLock = new Object(); 965 private final AtomicLong mLastWritten = new AtomicLong(0); 966 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 967 968 private boolean mIsHistoricalPackageUsageAvailable = true; 969 970 boolean isHistoricalPackageUsageAvailable() { 971 return mIsHistoricalPackageUsageAvailable; 972 } 973 974 void write(boolean force) { 975 if (force) { 976 writeInternal(); 977 return; 978 } 979 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 980 && !DEBUG_DEXOPT) { 981 return; 982 } 983 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 984 new Thread("PackageUsage_DiskWriter") { 985 @Override 986 public void run() { 987 try { 988 writeInternal(); 989 } finally { 990 mBackgroundWriteRunning.set(false); 991 } 992 } 993 }.start(); 994 } 995 } 996 997 private void writeInternal() { 998 synchronized (mPackages) { 999 synchronized (mFileLock) { 1000 AtomicFile file = getFile(); 1001 FileOutputStream f = null; 1002 try { 1003 f = file.startWrite(); 1004 BufferedOutputStream out = new BufferedOutputStream(f); 1005 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1006 StringBuilder sb = new StringBuilder(); 1007 for (PackageParser.Package pkg : mPackages.values()) { 1008 if (pkg.mLastPackageUsageTimeInMills == 0) { 1009 continue; 1010 } 1011 sb.setLength(0); 1012 sb.append(pkg.packageName); 1013 sb.append(' '); 1014 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1015 sb.append('\n'); 1016 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1017 } 1018 out.flush(); 1019 file.finishWrite(f); 1020 } catch (IOException e) { 1021 if (f != null) { 1022 file.failWrite(f); 1023 } 1024 Log.e(TAG, "Failed to write package usage times", e); 1025 } 1026 } 1027 } 1028 mLastWritten.set(SystemClock.elapsedRealtime()); 1029 } 1030 1031 void readLP() { 1032 synchronized (mFileLock) { 1033 AtomicFile file = getFile(); 1034 BufferedInputStream in = null; 1035 try { 1036 in = new BufferedInputStream(file.openRead()); 1037 StringBuffer sb = new StringBuffer(); 1038 while (true) { 1039 String packageName = readToken(in, sb, ' '); 1040 if (packageName == null) { 1041 break; 1042 } 1043 String timeInMillisString = readToken(in, sb, '\n'); 1044 if (timeInMillisString == null) { 1045 throw new IOException("Failed to find last usage time for package " 1046 + packageName); 1047 } 1048 PackageParser.Package pkg = mPackages.get(packageName); 1049 if (pkg == null) { 1050 continue; 1051 } 1052 long timeInMillis; 1053 try { 1054 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1055 } catch (NumberFormatException e) { 1056 throw new IOException("Failed to parse " + timeInMillisString 1057 + " as a long.", e); 1058 } 1059 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1060 } 1061 } catch (FileNotFoundException expected) { 1062 mIsHistoricalPackageUsageAvailable = false; 1063 } catch (IOException e) { 1064 Log.w(TAG, "Failed to read package usage times", e); 1065 } finally { 1066 IoUtils.closeQuietly(in); 1067 } 1068 } 1069 mLastWritten.set(SystemClock.elapsedRealtime()); 1070 } 1071 1072 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1073 throws IOException { 1074 sb.setLength(0); 1075 while (true) { 1076 int ch = in.read(); 1077 if (ch == -1) { 1078 if (sb.length() == 0) { 1079 return null; 1080 } 1081 throw new IOException("Unexpected EOF"); 1082 } 1083 if (ch == endOfToken) { 1084 return sb.toString(); 1085 } 1086 sb.append((char)ch); 1087 } 1088 } 1089 1090 private AtomicFile getFile() { 1091 File dataDir = Environment.getDataDirectory(); 1092 File systemDir = new File(dataDir, "system"); 1093 File fname = new File(systemDir, "package-usage.list"); 1094 return new AtomicFile(fname); 1095 } 1096 } 1097 1098 class PackageHandler extends Handler { 1099 private boolean mBound = false; 1100 final ArrayList<HandlerParams> mPendingInstalls = 1101 new ArrayList<HandlerParams>(); 1102 1103 private boolean connectToService() { 1104 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1105 " DefaultContainerService"); 1106 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1107 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1108 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1109 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1111 mBound = true; 1112 return true; 1113 } 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 return false; 1116 } 1117 1118 private void disconnectService() { 1119 mContainerService = null; 1120 mBound = false; 1121 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1122 mContext.unbindService(mDefContainerConn); 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1124 } 1125 1126 PackageHandler(Looper looper) { 1127 super(looper); 1128 } 1129 1130 public void handleMessage(Message msg) { 1131 try { 1132 doHandleMessage(msg); 1133 } finally { 1134 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1135 } 1136 } 1137 1138 void doHandleMessage(Message msg) { 1139 switch (msg.what) { 1140 case INIT_COPY: { 1141 HandlerParams params = (HandlerParams) msg.obj; 1142 int idx = mPendingInstalls.size(); 1143 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1144 // If a bind was already initiated we dont really 1145 // need to do anything. The pending install 1146 // will be processed later on. 1147 if (!mBound) { 1148 try { 1149 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1150 System.identityHashCode(params)); 1151 // If this is the only one pending we might 1152 // have to bind to the service again. 1153 if (!connectToService()) { 1154 Slog.e(TAG, "Failed to bind to media container service"); 1155 params.serviceError(); 1156 return; 1157 } else { 1158 // Once we bind to the service, the first 1159 // pending request will be processed. 1160 mPendingInstalls.add(idx, params); 1161 } 1162 } finally { 1163 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1164 System.identityHashCode(params)); 1165 } 1166 } else { 1167 mPendingInstalls.add(idx, params); 1168 // Already bound to the service. Just make 1169 // sure we trigger off processing the first request. 1170 if (idx == 0) { 1171 mHandler.sendEmptyMessage(MCS_BOUND); 1172 } 1173 } 1174 break; 1175 } 1176 case MCS_BOUND: { 1177 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1178 if (msg.obj != null) { 1179 mContainerService = (IMediaContainerService) msg.obj; 1180 } 1181 if (mContainerService == null) { 1182 if (!mBound) { 1183 // Something seriously wrong since we are not bound and we are not 1184 // waiting for connection. Bail out. 1185 Slog.e(TAG, "Cannot bind to media container service"); 1186 for (HandlerParams params : mPendingInstalls) { 1187 // Indicate service bind error 1188 params.serviceError(); 1189 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1190 System.identityHashCode(params)); 1191 } 1192 mPendingInstalls.clear(); 1193 } else { 1194 Slog.w(TAG, "Waiting to connect to media container service"); 1195 } 1196 } else if (mPendingInstalls.size() > 0) { 1197 HandlerParams params = mPendingInstalls.get(0); 1198 if (params != null) { 1199 if (params.startCopy()) { 1200 // We are done... look for more work or to 1201 // go idle. 1202 if (DEBUG_SD_INSTALL) Log.i(TAG, 1203 "Checking for more work or unbind..."); 1204 // Delete pending install 1205 if (mPendingInstalls.size() > 0) { 1206 mPendingInstalls.remove(0); 1207 } 1208 if (mPendingInstalls.size() == 0) { 1209 if (mBound) { 1210 if (DEBUG_SD_INSTALL) Log.i(TAG, 1211 "Posting delayed MCS_UNBIND"); 1212 removeMessages(MCS_UNBIND); 1213 Message ubmsg = obtainMessage(MCS_UNBIND); 1214 // Unbind after a little delay, to avoid 1215 // continual thrashing. 1216 sendMessageDelayed(ubmsg, 10000); 1217 } 1218 } else { 1219 // There are more pending requests in queue. 1220 // Just post MCS_BOUND message to trigger processing 1221 // of next pending install. 1222 if (DEBUG_SD_INSTALL) Log.i(TAG, 1223 "Posting MCS_BOUND for next work"); 1224 mHandler.sendEmptyMessage(MCS_BOUND); 1225 } 1226 } 1227 } 1228 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1229 System.identityHashCode(params)); 1230 } else { 1231 // Should never happen ideally. 1232 Slog.w(TAG, "Empty queue"); 1233 } 1234 break; 1235 } 1236 case MCS_RECONNECT: { 1237 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1238 if (mPendingInstalls.size() > 0) { 1239 if (mBound) { 1240 disconnectService(); 1241 } 1242 if (!connectToService()) { 1243 Slog.e(TAG, "Failed to bind to media container service"); 1244 for (HandlerParams params : mPendingInstalls) { 1245 // Indicate service bind error 1246 params.serviceError(); 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1248 System.identityHashCode(params)); 1249 } 1250 mPendingInstalls.clear(); 1251 } 1252 } 1253 break; 1254 } 1255 case MCS_UNBIND: { 1256 // If there is no actual work left, then time to unbind. 1257 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1258 1259 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1260 if (mBound) { 1261 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1262 1263 disconnectService(); 1264 } 1265 } else if (mPendingInstalls.size() > 0) { 1266 // There are more pending requests in queue. 1267 // Just post MCS_BOUND message to trigger processing 1268 // of next pending install. 1269 mHandler.sendEmptyMessage(MCS_BOUND); 1270 } 1271 1272 break; 1273 } 1274 case MCS_GIVE_UP: { 1275 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1276 HandlerParams params = mPendingInstalls.remove(0); 1277 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1278 System.identityHashCode(params)); 1279 break; 1280 } 1281 case SEND_PENDING_BROADCAST: { 1282 String packages[]; 1283 ArrayList<String> components[]; 1284 int size = 0; 1285 int uids[]; 1286 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1287 synchronized (mPackages) { 1288 if (mPendingBroadcasts == null) { 1289 return; 1290 } 1291 size = mPendingBroadcasts.size(); 1292 if (size <= 0) { 1293 // Nothing to be done. Just return 1294 return; 1295 } 1296 packages = new String[size]; 1297 components = new ArrayList[size]; 1298 uids = new int[size]; 1299 int i = 0; // filling out the above arrays 1300 1301 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1302 int packageUserId = mPendingBroadcasts.userIdAt(n); 1303 Iterator<Map.Entry<String, ArrayList<String>>> it 1304 = mPendingBroadcasts.packagesForUserId(packageUserId) 1305 .entrySet().iterator(); 1306 while (it.hasNext() && i < size) { 1307 Map.Entry<String, ArrayList<String>> ent = it.next(); 1308 packages[i] = ent.getKey(); 1309 components[i] = ent.getValue(); 1310 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1311 uids[i] = (ps != null) 1312 ? UserHandle.getUid(packageUserId, ps.appId) 1313 : -1; 1314 i++; 1315 } 1316 } 1317 size = i; 1318 mPendingBroadcasts.clear(); 1319 } 1320 // Send broadcasts 1321 for (int i = 0; i < size; i++) { 1322 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1323 } 1324 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1325 break; 1326 } 1327 case START_CLEANING_PACKAGE: { 1328 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1329 final String packageName = (String)msg.obj; 1330 final int userId = msg.arg1; 1331 final boolean andCode = msg.arg2 != 0; 1332 synchronized (mPackages) { 1333 if (userId == UserHandle.USER_ALL) { 1334 int[] users = sUserManager.getUserIds(); 1335 for (int user : users) { 1336 mSettings.addPackageToCleanLPw( 1337 new PackageCleanItem(user, packageName, andCode)); 1338 } 1339 } else { 1340 mSettings.addPackageToCleanLPw( 1341 new PackageCleanItem(userId, packageName, andCode)); 1342 } 1343 } 1344 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1345 startCleaningPackages(); 1346 } break; 1347 case POST_INSTALL: { 1348 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1349 PostInstallData data = mRunningInstalls.get(msg.arg1); 1350 mRunningInstalls.delete(msg.arg1); 1351 boolean deleteOld = false; 1352 1353 if (data != null) { 1354 InstallArgs args = data.args; 1355 PackageInstalledInfo res = data.res; 1356 1357 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1358 final String packageName = res.pkg.applicationInfo.packageName; 1359 res.removedInfo.sendBroadcast(false, true, false); 1360 Bundle extras = new Bundle(1); 1361 extras.putInt(Intent.EXTRA_UID, res.uid); 1362 1363 // Now that we successfully installed the package, grant runtime 1364 // permissions if requested before broadcasting the install. 1365 if ((args.installFlags 1366 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1367 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1368 args.installGrantPermissions); 1369 } 1370 1371 // Determine the set of users who are adding this 1372 // package for the first time vs. those who are seeing 1373 // an update. 1374 int[] firstUsers; 1375 int[] updateUsers = new int[0]; 1376 if (res.origUsers == null || res.origUsers.length == 0) { 1377 firstUsers = res.newUsers; 1378 } else { 1379 firstUsers = new int[0]; 1380 for (int i=0; i<res.newUsers.length; i++) { 1381 int user = res.newUsers[i]; 1382 boolean isNew = true; 1383 for (int j=0; j<res.origUsers.length; j++) { 1384 if (res.origUsers[j] == user) { 1385 isNew = false; 1386 break; 1387 } 1388 } 1389 if (isNew) { 1390 int[] newFirst = new int[firstUsers.length+1]; 1391 System.arraycopy(firstUsers, 0, newFirst, 0, 1392 firstUsers.length); 1393 newFirst[firstUsers.length] = user; 1394 firstUsers = newFirst; 1395 } else { 1396 int[] newUpdate = new int[updateUsers.length+1]; 1397 System.arraycopy(updateUsers, 0, newUpdate, 0, 1398 updateUsers.length); 1399 newUpdate[updateUsers.length] = user; 1400 updateUsers = newUpdate; 1401 } 1402 } 1403 } 1404 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1405 packageName, extras, null, null, firstUsers); 1406 final boolean update = res.removedInfo.removedPackage != null; 1407 if (update) { 1408 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1409 } 1410 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1411 packageName, extras, null, null, updateUsers); 1412 if (update) { 1413 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1414 packageName, extras, null, null, updateUsers); 1415 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1416 null, null, packageName, null, updateUsers); 1417 1418 // treat asec-hosted packages like removable media on upgrade 1419 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1420 if (DEBUG_INSTALL) { 1421 Slog.i(TAG, "upgrading pkg " + res.pkg 1422 + " is ASEC-hosted -> AVAILABLE"); 1423 } 1424 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1425 ArrayList<String> pkgList = new ArrayList<String>(1); 1426 pkgList.add(packageName); 1427 sendResourcesChangedBroadcast(true, true, 1428 pkgList,uidArray, null); 1429 } 1430 } 1431 if (res.removedInfo.args != null) { 1432 // Remove the replaced package's older resources safely now 1433 deleteOld = true; 1434 } 1435 1436 // If this app is a browser and it's newly-installed for some 1437 // users, clear any default-browser state in those users 1438 if (firstUsers.length > 0) { 1439 // the app's nature doesn't depend on the user, so we can just 1440 // check its browser nature in any user and generalize. 1441 if (packageIsBrowser(packageName, firstUsers[0])) { 1442 synchronized (mPackages) { 1443 for (int userId : firstUsers) { 1444 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1445 } 1446 } 1447 } 1448 } 1449 // Log current value of "unknown sources" setting 1450 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1451 getUnknownSourcesSettings()); 1452 } 1453 // Force a gc to clear up things 1454 Runtime.getRuntime().gc(); 1455 // We delete after a gc for applications on sdcard. 1456 if (deleteOld) { 1457 synchronized (mInstallLock) { 1458 res.removedInfo.args.doPostDeleteLI(true); 1459 } 1460 } 1461 if (args.observer != null) { 1462 try { 1463 Bundle extras = extrasForInstallResult(res); 1464 args.observer.onPackageInstalled(res.name, res.returnCode, 1465 res.returnMsg, extras); 1466 } catch (RemoteException e) { 1467 Slog.i(TAG, "Observer no longer exists."); 1468 } 1469 } 1470 } else { 1471 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1472 } 1473 1474 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1475 } break; 1476 case UPDATED_MEDIA_STATUS: { 1477 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1478 boolean reportStatus = msg.arg1 == 1; 1479 boolean doGc = msg.arg2 == 1; 1480 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1481 if (doGc) { 1482 // Force a gc to clear up stale containers. 1483 Runtime.getRuntime().gc(); 1484 } 1485 if (msg.obj != null) { 1486 @SuppressWarnings("unchecked") 1487 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1488 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1489 // Unload containers 1490 unloadAllContainers(args); 1491 } 1492 if (reportStatus) { 1493 try { 1494 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1495 PackageHelper.getMountService().finishMediaUpdate(); 1496 } catch (RemoteException e) { 1497 Log.e(TAG, "MountService not running?"); 1498 } 1499 } 1500 } break; 1501 case WRITE_SETTINGS: { 1502 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1503 synchronized (mPackages) { 1504 removeMessages(WRITE_SETTINGS); 1505 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1506 mSettings.writeLPr(); 1507 mDirtyUsers.clear(); 1508 } 1509 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1510 } break; 1511 case WRITE_PACKAGE_RESTRICTIONS: { 1512 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1513 synchronized (mPackages) { 1514 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1515 for (int userId : mDirtyUsers) { 1516 mSettings.writePackageRestrictionsLPr(userId); 1517 } 1518 mDirtyUsers.clear(); 1519 } 1520 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1521 } break; 1522 case CHECK_PENDING_VERIFICATION: { 1523 final int verificationId = msg.arg1; 1524 final PackageVerificationState state = mPendingVerification.get(verificationId); 1525 1526 if ((state != null) && !state.timeoutExtended()) { 1527 final InstallArgs args = state.getInstallArgs(); 1528 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1529 1530 Slog.i(TAG, "Verification timed out for " + originUri); 1531 mPendingVerification.remove(verificationId); 1532 1533 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1534 1535 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1536 Slog.i(TAG, "Continuing with installation of " + originUri); 1537 state.setVerifierResponse(Binder.getCallingUid(), 1538 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1539 broadcastPackageVerified(verificationId, originUri, 1540 PackageManager.VERIFICATION_ALLOW, 1541 state.getInstallArgs().getUser()); 1542 try { 1543 ret = args.copyApk(mContainerService, true); 1544 } catch (RemoteException e) { 1545 Slog.e(TAG, "Could not contact the ContainerService"); 1546 } 1547 } else { 1548 broadcastPackageVerified(verificationId, originUri, 1549 PackageManager.VERIFICATION_REJECT, 1550 state.getInstallArgs().getUser()); 1551 } 1552 1553 processPendingInstall(args, ret); 1554 mHandler.sendEmptyMessage(MCS_UNBIND); 1555 } 1556 Trace.asyncTraceEnd( 1557 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 1558 break; 1559 } 1560 case PACKAGE_VERIFIED: { 1561 final int verificationId = msg.arg1; 1562 1563 final PackageVerificationState state = mPendingVerification.get(verificationId); 1564 if (state == null) { 1565 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1566 break; 1567 } 1568 1569 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1570 1571 state.setVerifierResponse(response.callerUid, response.code); 1572 1573 if (state.isVerificationComplete()) { 1574 mPendingVerification.remove(verificationId); 1575 1576 final InstallArgs args = state.getInstallArgs(); 1577 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1578 1579 int ret; 1580 if (state.isInstallAllowed()) { 1581 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1582 broadcastPackageVerified(verificationId, originUri, 1583 response.code, state.getInstallArgs().getUser()); 1584 try { 1585 ret = args.copyApk(mContainerService, true); 1586 } catch (RemoteException e) { 1587 Slog.e(TAG, "Could not contact the ContainerService"); 1588 } 1589 } else { 1590 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1591 } 1592 1593 processPendingInstall(args, ret); 1594 1595 mHandler.sendEmptyMessage(MCS_UNBIND); 1596 } 1597 1598 break; 1599 } 1600 case START_INTENT_FILTER_VERIFICATIONS: { 1601 IFVerificationParams params = (IFVerificationParams) msg.obj; 1602 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1603 params.replacing, params.pkg); 1604 break; 1605 } 1606 case INTENT_FILTER_VERIFIED: { 1607 final int verificationId = msg.arg1; 1608 1609 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1610 verificationId); 1611 if (state == null) { 1612 Slog.w(TAG, "Invalid IntentFilter verification token " 1613 + verificationId + " received"); 1614 break; 1615 } 1616 1617 final int userId = state.getUserId(); 1618 1619 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1620 "Processing IntentFilter verification with token:" 1621 + verificationId + " and userId:" + userId); 1622 1623 final IntentFilterVerificationResponse response = 1624 (IntentFilterVerificationResponse) msg.obj; 1625 1626 state.setVerifierResponse(response.callerUid, response.code); 1627 1628 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1629 "IntentFilter verification with token:" + verificationId 1630 + " and userId:" + userId 1631 + " is settings verifier response with response code:" 1632 + response.code); 1633 1634 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1635 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1636 + response.getFailedDomainsString()); 1637 } 1638 1639 if (state.isVerificationComplete()) { 1640 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1641 } else { 1642 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1643 "IntentFilter verification with token:" + verificationId 1644 + " was not said to be complete"); 1645 } 1646 1647 break; 1648 } 1649 } 1650 } 1651 } 1652 1653 private StorageEventListener mStorageListener = new StorageEventListener() { 1654 @Override 1655 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1656 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1657 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1658 final String volumeUuid = vol.getFsUuid(); 1659 1660 // Clean up any users or apps that were removed or recreated 1661 // while this volume was missing 1662 reconcileUsers(volumeUuid); 1663 reconcileApps(volumeUuid); 1664 1665 // Clean up any install sessions that expired or were 1666 // cancelled while this volume was missing 1667 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1668 1669 loadPrivatePackages(vol); 1670 1671 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1672 unloadPrivatePackages(vol); 1673 } 1674 } 1675 1676 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1677 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1678 updateExternalMediaStatus(true, false); 1679 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1680 updateExternalMediaStatus(false, false); 1681 } 1682 } 1683 } 1684 1685 @Override 1686 public void onVolumeForgotten(String fsUuid) { 1687 if (TextUtils.isEmpty(fsUuid)) { 1688 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1689 return; 1690 } 1691 1692 // Remove any apps installed on the forgotten volume 1693 synchronized (mPackages) { 1694 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1695 for (PackageSetting ps : packages) { 1696 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1697 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1698 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1699 } 1700 1701 mSettings.onVolumeForgotten(fsUuid); 1702 mSettings.writeLPr(); 1703 } 1704 } 1705 }; 1706 1707 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1708 String[] grantedPermissions) { 1709 if (userId >= UserHandle.USER_OWNER) { 1710 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1711 } else if (userId == UserHandle.USER_ALL) { 1712 final int[] userIds; 1713 synchronized (mPackages) { 1714 userIds = UserManagerService.getInstance().getUserIds(); 1715 } 1716 for (int someUserId : userIds) { 1717 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1718 } 1719 } 1720 1721 // We could have touched GID membership, so flush out packages.list 1722 synchronized (mPackages) { 1723 mSettings.writePackageListLPr(); 1724 } 1725 } 1726 1727 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1728 String[] grantedPermissions) { 1729 SettingBase sb = (SettingBase) pkg.mExtras; 1730 if (sb == null) { 1731 return; 1732 } 1733 1734 PermissionsState permissionsState = sb.getPermissionsState(); 1735 1736 for (String permission : pkg.requestedPermissions) { 1737 BasePermission bp = mSettings.mPermissions.get(permission); 1738 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1739 || ArrayUtils.contains(grantedPermissions, permission))) { 1740 permissionsState.grantRuntimePermission(bp, userId); 1741 } 1742 } 1743 } 1744 1745 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1746 Bundle extras = null; 1747 switch (res.returnCode) { 1748 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1749 extras = new Bundle(); 1750 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1751 res.origPermission); 1752 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1753 res.origPackage); 1754 break; 1755 } 1756 case PackageManager.INSTALL_SUCCEEDED: { 1757 extras = new Bundle(); 1758 extras.putBoolean(Intent.EXTRA_REPLACING, 1759 res.removedInfo != null && res.removedInfo.removedPackage != null); 1760 break; 1761 } 1762 } 1763 return extras; 1764 } 1765 1766 void scheduleWriteSettingsLocked() { 1767 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1768 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1769 } 1770 } 1771 1772 void scheduleWritePackageRestrictionsLocked(int userId) { 1773 if (!sUserManager.exists(userId)) return; 1774 mDirtyUsers.add(userId); 1775 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1776 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1777 } 1778 } 1779 1780 public static PackageManagerService main(Context context, Installer installer, 1781 boolean factoryTest, boolean onlyCore) { 1782 PackageManagerService m = new PackageManagerService(context, installer, 1783 factoryTest, onlyCore); 1784 ServiceManager.addService("package", m); 1785 return m; 1786 } 1787 1788 static String[] splitString(String str, char sep) { 1789 int count = 1; 1790 int i = 0; 1791 while ((i=str.indexOf(sep, i)) >= 0) { 1792 count++; 1793 i++; 1794 } 1795 1796 String[] res = new String[count]; 1797 i=0; 1798 count = 0; 1799 int lastI=0; 1800 while ((i=str.indexOf(sep, i)) >= 0) { 1801 res[count] = str.substring(lastI, i); 1802 count++; 1803 i++; 1804 lastI = i; 1805 } 1806 res[count] = str.substring(lastI, str.length()); 1807 return res; 1808 } 1809 1810 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1811 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1812 Context.DISPLAY_SERVICE); 1813 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1814 } 1815 1816 public PackageManagerService(Context context, Installer installer, 1817 boolean factoryTest, boolean onlyCore) { 1818 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1819 SystemClock.uptimeMillis()); 1820 1821 if (mSdkVersion <= 0) { 1822 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1823 } 1824 1825 mContext = context; 1826 mFactoryTest = factoryTest; 1827 mOnlyCore = onlyCore; 1828 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1829 mMetrics = new DisplayMetrics(); 1830 mSettings = new Settings(mPackages); 1831 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1832 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1833 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1834 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1835 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1836 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1837 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1838 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1839 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1840 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1841 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1842 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1843 1844 // TODO: add a property to control this? 1845 long dexOptLRUThresholdInMinutes; 1846 if (mLazyDexOpt) { 1847 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1848 } else { 1849 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1850 } 1851 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1852 1853 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1854 if (separateProcesses != null && separateProcesses.length() > 0) { 1855 if ("*".equals(separateProcesses)) { 1856 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1857 mSeparateProcesses = null; 1858 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1859 } else { 1860 mDefParseFlags = 0; 1861 mSeparateProcesses = separateProcesses.split(","); 1862 Slog.w(TAG, "Running with debug.separate_processes: " 1863 + separateProcesses); 1864 } 1865 } else { 1866 mDefParseFlags = 0; 1867 mSeparateProcesses = null; 1868 } 1869 1870 mInstaller = installer; 1871 mPackageDexOptimizer = new PackageDexOptimizer(this); 1872 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1873 1874 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1875 FgThread.get().getLooper()); 1876 1877 getDefaultDisplayMetrics(context, mMetrics); 1878 1879 SystemConfig systemConfig = SystemConfig.getInstance(); 1880 mGlobalGids = systemConfig.getGlobalGids(); 1881 mSystemPermissions = systemConfig.getSystemPermissions(); 1882 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1883 1884 synchronized (mInstallLock) { 1885 // writer 1886 synchronized (mPackages) { 1887 mHandlerThread = new ServiceThread(TAG, 1888 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1889 mHandlerThread.start(); 1890 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1891 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1892 1893 File dataDir = Environment.getDataDirectory(); 1894 mAppDataDir = new File(dataDir, "data"); 1895 mAppInstallDir = new File(dataDir, "app"); 1896 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1897 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1898 mUserAppDataDir = new File(dataDir, "user"); 1899 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1900 1901 sUserManager = new UserManagerService(context, this, 1902 mInstallLock, mPackages); 1903 1904 // Propagate permission configuration in to package manager. 1905 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1906 = systemConfig.getPermissions(); 1907 for (int i=0; i<permConfig.size(); i++) { 1908 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1909 BasePermission bp = mSettings.mPermissions.get(perm.name); 1910 if (bp == null) { 1911 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1912 mSettings.mPermissions.put(perm.name, bp); 1913 } 1914 if (perm.gids != null) { 1915 bp.setGids(perm.gids, perm.perUser); 1916 } 1917 } 1918 1919 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1920 for (int i=0; i<libConfig.size(); i++) { 1921 mSharedLibraries.put(libConfig.keyAt(i), 1922 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1923 } 1924 1925 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1926 1927 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1928 mSdkVersion, mOnlyCore); 1929 1930 String customResolverActivity = Resources.getSystem().getString( 1931 R.string.config_customResolverActivity); 1932 if (TextUtils.isEmpty(customResolverActivity)) { 1933 customResolverActivity = null; 1934 } else { 1935 mCustomResolverComponentName = ComponentName.unflattenFromString( 1936 customResolverActivity); 1937 } 1938 1939 long startTime = SystemClock.uptimeMillis(); 1940 1941 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1942 startTime); 1943 1944 // Set flag to monitor and not change apk file paths when 1945 // scanning install directories. 1946 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1947 1948 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1949 1950 /** 1951 * Add everything in the in the boot class path to the 1952 * list of process files because dexopt will have been run 1953 * if necessary during zygote startup. 1954 */ 1955 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1956 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1957 1958 if (bootClassPath != null) { 1959 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1960 for (String element : bootClassPathElements) { 1961 alreadyDexOpted.add(element); 1962 } 1963 } else { 1964 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1965 } 1966 1967 if (systemServerClassPath != null) { 1968 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1969 for (String element : systemServerClassPathElements) { 1970 alreadyDexOpted.add(element); 1971 } 1972 } else { 1973 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1974 } 1975 1976 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1977 final String[] dexCodeInstructionSets = 1978 getDexCodeInstructionSets( 1979 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1980 1981 /** 1982 * Ensure all external libraries have had dexopt run on them. 1983 */ 1984 if (mSharedLibraries.size() > 0) { 1985 // NOTE: For now, we're compiling these system "shared libraries" 1986 // (and framework jars) into all available architectures. It's possible 1987 // to compile them only when we come across an app that uses them (there's 1988 // already logic for that in scanPackageLI) but that adds some complexity. 1989 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1990 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1991 final String lib = libEntry.path; 1992 if (lib == null) { 1993 continue; 1994 } 1995 1996 try { 1997 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1998 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1999 alreadyDexOpted.add(lib); 2000 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2001 } 2002 } catch (FileNotFoundException e) { 2003 Slog.w(TAG, "Library not found: " + lib); 2004 } catch (IOException e) { 2005 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2006 + e.getMessage()); 2007 } 2008 } 2009 } 2010 } 2011 2012 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2013 2014 // Gross hack for now: we know this file doesn't contain any 2015 // code, so don't dexopt it to avoid the resulting log spew. 2016 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2017 2018 // Gross hack for now: we know this file is only part of 2019 // the boot class path for art, so don't dexopt it to 2020 // avoid the resulting log spew. 2021 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2022 2023 /** 2024 * There are a number of commands implemented in Java, which 2025 * we currently need to do the dexopt on so that they can be 2026 * run from a non-root shell. 2027 */ 2028 String[] frameworkFiles = frameworkDir.list(); 2029 if (frameworkFiles != null) { 2030 // TODO: We could compile these only for the most preferred ABI. We should 2031 // first double check that the dex files for these commands are not referenced 2032 // by other system apps. 2033 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2034 for (int i=0; i<frameworkFiles.length; i++) { 2035 File libPath = new File(frameworkDir, frameworkFiles[i]); 2036 String path = libPath.getPath(); 2037 // Skip the file if we already did it. 2038 if (alreadyDexOpted.contains(path)) { 2039 continue; 2040 } 2041 // Skip the file if it is not a type we want to dexopt. 2042 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2043 continue; 2044 } 2045 try { 2046 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2047 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2048 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2049 } 2050 } catch (FileNotFoundException e) { 2051 Slog.w(TAG, "Jar not found: " + path); 2052 } catch (IOException e) { 2053 Slog.w(TAG, "Exception reading jar: " + path, e); 2054 } 2055 } 2056 } 2057 } 2058 2059 final VersionInfo ver = mSettings.getInternalVersion(); 2060 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2061 // when upgrading from pre-M, promote system app permissions from install to runtime 2062 mPromoteSystemApps = 2063 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2064 2065 // save off the names of pre-existing system packages prior to scanning; we don't 2066 // want to automatically grant runtime permissions for new system apps 2067 if (mPromoteSystemApps) { 2068 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2069 while (pkgSettingIter.hasNext()) { 2070 PackageSetting ps = pkgSettingIter.next(); 2071 if (isSystemApp(ps)) { 2072 mExistingSystemPackages.add(ps.name); 2073 } 2074 } 2075 } 2076 2077 // Collect vendor overlay packages. 2078 // (Do this before scanning any apps.) 2079 // For security and version matching reason, only consider 2080 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2081 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2082 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2083 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2084 2085 // Find base frameworks (resource packages without code). 2086 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2087 | PackageParser.PARSE_IS_SYSTEM_DIR 2088 | PackageParser.PARSE_IS_PRIVILEGED, 2089 scanFlags | SCAN_NO_DEX, 0); 2090 2091 // Collected privileged system packages. 2092 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2093 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2094 | PackageParser.PARSE_IS_SYSTEM_DIR 2095 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2096 2097 // Collect ordinary system packages. 2098 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2099 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2100 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2101 2102 // Collect all vendor packages. 2103 File vendorAppDir = new File("/vendor/app"); 2104 try { 2105 vendorAppDir = vendorAppDir.getCanonicalFile(); 2106 } catch (IOException e) { 2107 // failed to look up canonical path, continue with original one 2108 } 2109 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2110 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2111 2112 // Collect all OEM packages. 2113 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2114 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2116 2117 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2118 mInstaller.moveFiles(); 2119 2120 // Prune any system packages that no longer exist. 2121 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2122 if (!mOnlyCore) { 2123 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2124 while (psit.hasNext()) { 2125 PackageSetting ps = psit.next(); 2126 2127 /* 2128 * If this is not a system app, it can't be a 2129 * disable system app. 2130 */ 2131 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2132 continue; 2133 } 2134 2135 /* 2136 * If the package is scanned, it's not erased. 2137 */ 2138 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2139 if (scannedPkg != null) { 2140 /* 2141 * If the system app is both scanned and in the 2142 * disabled packages list, then it must have been 2143 * added via OTA. Remove it from the currently 2144 * scanned package so the previously user-installed 2145 * application can be scanned. 2146 */ 2147 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2148 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2149 + ps.name + "; removing system app. Last known codePath=" 2150 + ps.codePathString + ", installStatus=" + ps.installStatus 2151 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2152 + scannedPkg.mVersionCode); 2153 removePackageLI(ps, true); 2154 mExpectingBetter.put(ps.name, ps.codePath); 2155 } 2156 2157 continue; 2158 } 2159 2160 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2161 psit.remove(); 2162 logCriticalInfo(Log.WARN, "System package " + ps.name 2163 + " no longer exists; wiping its data"); 2164 removeDataDirsLI(null, ps.name); 2165 } else { 2166 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2167 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2168 possiblyDeletedUpdatedSystemApps.add(ps.name); 2169 } 2170 } 2171 } 2172 } 2173 2174 //look for any incomplete package installations 2175 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2176 //clean up list 2177 for(int i = 0; i < deletePkgsList.size(); i++) { 2178 //clean up here 2179 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2180 } 2181 //delete tmp files 2182 deleteTempPackageFiles(); 2183 2184 // Remove any shared userIDs that have no associated packages 2185 mSettings.pruneSharedUsersLPw(); 2186 2187 if (!mOnlyCore) { 2188 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2189 SystemClock.uptimeMillis()); 2190 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2191 2192 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2193 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2194 2195 /** 2196 * Remove disable package settings for any updated system 2197 * apps that were removed via an OTA. If they're not a 2198 * previously-updated app, remove them completely. 2199 * Otherwise, just revoke their system-level permissions. 2200 */ 2201 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2202 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2203 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2204 2205 String msg; 2206 if (deletedPkg == null) { 2207 msg = "Updated system package " + deletedAppName 2208 + " no longer exists; wiping its data"; 2209 removeDataDirsLI(null, deletedAppName); 2210 } else { 2211 msg = "Updated system app + " + deletedAppName 2212 + " no longer present; removing system privileges for " 2213 + deletedAppName; 2214 2215 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2216 2217 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2218 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2219 } 2220 logCriticalInfo(Log.WARN, msg); 2221 } 2222 2223 /** 2224 * Make sure all system apps that we expected to appear on 2225 * the userdata partition actually showed up. If they never 2226 * appeared, crawl back and revive the system version. 2227 */ 2228 for (int i = 0; i < mExpectingBetter.size(); i++) { 2229 final String packageName = mExpectingBetter.keyAt(i); 2230 if (!mPackages.containsKey(packageName)) { 2231 final File scanFile = mExpectingBetter.valueAt(i); 2232 2233 logCriticalInfo(Log.WARN, "Expected better " + packageName 2234 + " but never showed up; reverting to system"); 2235 2236 final int reparseFlags; 2237 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2238 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2239 | PackageParser.PARSE_IS_SYSTEM_DIR 2240 | PackageParser.PARSE_IS_PRIVILEGED; 2241 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2242 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2243 | PackageParser.PARSE_IS_SYSTEM_DIR; 2244 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2245 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2246 | PackageParser.PARSE_IS_SYSTEM_DIR; 2247 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2248 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2249 | PackageParser.PARSE_IS_SYSTEM_DIR; 2250 } else { 2251 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2252 continue; 2253 } 2254 2255 mSettings.enableSystemPackageLPw(packageName); 2256 2257 try { 2258 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2259 } catch (PackageManagerException e) { 2260 Slog.e(TAG, "Failed to parse original system package: " 2261 + e.getMessage()); 2262 } 2263 } 2264 } 2265 } 2266 mExpectingBetter.clear(); 2267 2268 // Now that we know all of the shared libraries, update all clients to have 2269 // the correct library paths. 2270 updateAllSharedLibrariesLPw(); 2271 2272 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2273 // NOTE: We ignore potential failures here during a system scan (like 2274 // the rest of the commands above) because there's precious little we 2275 // can do about it. A settings error is reported, though. 2276 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2277 false /* force dexopt */, false /* defer dexopt */); 2278 } 2279 2280 // Now that we know all the packages we are keeping, 2281 // read and update their last usage times. 2282 mPackageUsage.readLP(); 2283 2284 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2285 SystemClock.uptimeMillis()); 2286 Slog.i(TAG, "Time to scan packages: " 2287 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2288 + " seconds"); 2289 2290 // If the platform SDK has changed since the last time we booted, 2291 // we need to re-grant app permission to catch any new ones that 2292 // appear. This is really a hack, and means that apps can in some 2293 // cases get permissions that the user didn't initially explicitly 2294 // allow... it would be nice to have some better way to handle 2295 // this situation. 2296 int updateFlags = UPDATE_PERMISSIONS_ALL; 2297 if (ver.sdkVersion != mSdkVersion) { 2298 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2299 + mSdkVersion + "; regranting permissions for internal storage"); 2300 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2301 } 2302 updatePermissionsLPw(null, null, updateFlags); 2303 ver.sdkVersion = mSdkVersion; 2304 // clear only after permissions have been updated 2305 mExistingSystemPackages.clear(); 2306 mPromoteSystemApps = false; 2307 2308 // If this is the first boot, and it is a normal boot, then 2309 // we need to initialize the default preferred apps. 2310 if (!mRestoredSettings && !onlyCore) { 2311 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2312 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2313 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2314 } 2315 2316 // If this is first boot after an OTA, and a normal boot, then 2317 // we need to clear code cache directories. 2318 if (mIsUpgrade && !onlyCore) { 2319 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2320 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2321 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2322 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2323 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2324 } 2325 } 2326 ver.fingerprint = Build.FINGERPRINT; 2327 } 2328 2329 checkDefaultBrowser(); 2330 2331 // All the changes are done during package scanning. 2332 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2333 2334 // can downgrade to reader 2335 mSettings.writeLPr(); 2336 2337 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2338 SystemClock.uptimeMillis()); 2339 2340 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2341 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2342 2343 mInstallerService = new PackageInstallerService(context, this); 2344 2345 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2346 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2347 mIntentFilterVerifierComponent); 2348 2349 } // synchronized (mPackages) 2350 } // synchronized (mInstallLock) 2351 2352 // Now after opening every single application zip, make sure they 2353 // are all flushed. Not really needed, but keeps things nice and 2354 // tidy. 2355 Runtime.getRuntime().gc(); 2356 2357 // Expose private service for system components to use. 2358 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2359 } 2360 2361 @Override 2362 public boolean isFirstBoot() { 2363 return !mRestoredSettings; 2364 } 2365 2366 @Override 2367 public boolean isOnlyCoreApps() { 2368 return mOnlyCore; 2369 } 2370 2371 @Override 2372 public boolean isUpgrade() { 2373 return mIsUpgrade; 2374 } 2375 2376 private String getRequiredVerifierLPr() { 2377 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2378 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2379 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2380 2381 String requiredVerifier = null; 2382 2383 final int N = receivers.size(); 2384 for (int i = 0; i < N; i++) { 2385 final ResolveInfo info = receivers.get(i); 2386 2387 if (info.activityInfo == null) { 2388 continue; 2389 } 2390 2391 final String packageName = info.activityInfo.packageName; 2392 2393 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2394 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2395 continue; 2396 } 2397 2398 if (requiredVerifier != null) { 2399 throw new RuntimeException("There can be only one required verifier"); 2400 } 2401 2402 requiredVerifier = packageName; 2403 } 2404 2405 return requiredVerifier; 2406 } 2407 2408 private String getRequiredInstallerLPr() { 2409 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2410 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2411 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2412 2413 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2414 PACKAGE_MIME_TYPE, 0, 0); 2415 2416 String requiredInstaller = null; 2417 2418 final int N = installers.size(); 2419 for (int i = 0; i < N; i++) { 2420 final ResolveInfo info = installers.get(i); 2421 final String packageName = info.activityInfo.packageName; 2422 2423 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2424 continue; 2425 } 2426 2427 if (requiredInstaller != null) { 2428 throw new RuntimeException("There must be one required installer"); 2429 } 2430 2431 requiredInstaller = packageName; 2432 } 2433 2434 if (requiredInstaller == null) { 2435 throw new RuntimeException("There must be one required installer"); 2436 } 2437 2438 return requiredInstaller; 2439 } 2440 2441 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2442 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2443 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2444 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2445 2446 ComponentName verifierComponentName = null; 2447 2448 int priority = -1000; 2449 final int N = receivers.size(); 2450 for (int i = 0; i < N; i++) { 2451 final ResolveInfo info = receivers.get(i); 2452 2453 if (info.activityInfo == null) { 2454 continue; 2455 } 2456 2457 final String packageName = info.activityInfo.packageName; 2458 2459 final PackageSetting ps = mSettings.mPackages.get(packageName); 2460 if (ps == null) { 2461 continue; 2462 } 2463 2464 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2465 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2466 continue; 2467 } 2468 2469 // Select the IntentFilterVerifier with the highest priority 2470 if (priority < info.priority) { 2471 priority = info.priority; 2472 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2473 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2474 + verifierComponentName + " with priority: " + info.priority); 2475 } 2476 } 2477 2478 return verifierComponentName; 2479 } 2480 2481 private void primeDomainVerificationsLPw(int userId) { 2482 if (DEBUG_DOMAIN_VERIFICATION) { 2483 Slog.d(TAG, "Priming domain verifications in user " + userId); 2484 } 2485 2486 SystemConfig systemConfig = SystemConfig.getInstance(); 2487 ArraySet<String> packages = systemConfig.getLinkedApps(); 2488 ArraySet<String> domains = new ArraySet<String>(); 2489 2490 for (String packageName : packages) { 2491 PackageParser.Package pkg = mPackages.get(packageName); 2492 if (pkg != null) { 2493 if (!pkg.isSystemApp()) { 2494 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2495 continue; 2496 } 2497 2498 domains.clear(); 2499 for (PackageParser.Activity a : pkg.activities) { 2500 for (ActivityIntentInfo filter : a.intents) { 2501 if (hasValidDomains(filter)) { 2502 domains.addAll(filter.getHostsList()); 2503 } 2504 } 2505 } 2506 2507 if (domains.size() > 0) { 2508 if (DEBUG_DOMAIN_VERIFICATION) { 2509 Slog.v(TAG, " + " + packageName); 2510 } 2511 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2512 // state w.r.t. the formal app-linkage "no verification attempted" state; 2513 // and then 'always' in the per-user state actually used for intent resolution. 2514 final IntentFilterVerificationInfo ivi; 2515 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2516 new ArrayList<String>(domains)); 2517 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2518 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2519 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2520 } else { 2521 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2522 + "' does not handle web links"); 2523 } 2524 } else { 2525 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2526 } 2527 } 2528 2529 scheduleWritePackageRestrictionsLocked(userId); 2530 scheduleWriteSettingsLocked(); 2531 } 2532 2533 private void applyFactoryDefaultBrowserLPw(int userId) { 2534 // The default browser app's package name is stored in a string resource, 2535 // with a product-specific overlay used for vendor customization. 2536 String browserPkg = mContext.getResources().getString( 2537 com.android.internal.R.string.default_browser); 2538 if (!TextUtils.isEmpty(browserPkg)) { 2539 // non-empty string => required to be a known package 2540 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2541 if (ps == null) { 2542 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2543 browserPkg = null; 2544 } else { 2545 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2546 } 2547 } 2548 2549 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2550 // default. If there's more than one, just leave everything alone. 2551 if (browserPkg == null) { 2552 calculateDefaultBrowserLPw(userId); 2553 } 2554 } 2555 2556 private void calculateDefaultBrowserLPw(int userId) { 2557 List<String> allBrowsers = resolveAllBrowserApps(userId); 2558 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2559 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2560 } 2561 2562 private List<String> resolveAllBrowserApps(int userId) { 2563 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2564 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2565 PackageManager.MATCH_ALL, userId); 2566 2567 final int count = list.size(); 2568 List<String> result = new ArrayList<String>(count); 2569 for (int i=0; i<count; i++) { 2570 ResolveInfo info = list.get(i); 2571 if (info.activityInfo == null 2572 || !info.handleAllWebDataURI 2573 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2574 || result.contains(info.activityInfo.packageName)) { 2575 continue; 2576 } 2577 result.add(info.activityInfo.packageName); 2578 } 2579 2580 return result; 2581 } 2582 2583 private boolean packageIsBrowser(String packageName, int userId) { 2584 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2585 PackageManager.MATCH_ALL, userId); 2586 final int N = list.size(); 2587 for (int i = 0; i < N; i++) { 2588 ResolveInfo info = list.get(i); 2589 if (packageName.equals(info.activityInfo.packageName)) { 2590 return true; 2591 } 2592 } 2593 return false; 2594 } 2595 2596 private void checkDefaultBrowser() { 2597 final int myUserId = UserHandle.myUserId(); 2598 final String packageName = getDefaultBrowserPackageName(myUserId); 2599 if (packageName != null) { 2600 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2601 if (info == null) { 2602 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2603 synchronized (mPackages) { 2604 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2605 } 2606 } 2607 } 2608 } 2609 2610 @Override 2611 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2612 throws RemoteException { 2613 try { 2614 return super.onTransact(code, data, reply, flags); 2615 } catch (RuntimeException e) { 2616 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2617 Slog.wtf(TAG, "Package Manager Crash", e); 2618 } 2619 throw e; 2620 } 2621 } 2622 2623 void cleanupInstallFailedPackage(PackageSetting ps) { 2624 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2625 2626 removeDataDirsLI(ps.volumeUuid, ps.name); 2627 if (ps.codePath != null) { 2628 if (ps.codePath.isDirectory()) { 2629 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2630 } else { 2631 ps.codePath.delete(); 2632 } 2633 } 2634 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2635 if (ps.resourcePath.isDirectory()) { 2636 FileUtils.deleteContents(ps.resourcePath); 2637 } 2638 ps.resourcePath.delete(); 2639 } 2640 mSettings.removePackageLPw(ps.name); 2641 } 2642 2643 static int[] appendInts(int[] cur, int[] add) { 2644 if (add == null) return cur; 2645 if (cur == null) return add; 2646 final int N = add.length; 2647 for (int i=0; i<N; i++) { 2648 cur = appendInt(cur, add[i]); 2649 } 2650 return cur; 2651 } 2652 2653 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2654 if (!sUserManager.exists(userId)) return null; 2655 final PackageSetting ps = (PackageSetting) p.mExtras; 2656 if (ps == null) { 2657 return null; 2658 } 2659 2660 final PermissionsState permissionsState = ps.getPermissionsState(); 2661 2662 final int[] gids = permissionsState.computeGids(userId); 2663 final Set<String> permissions = permissionsState.getPermissions(userId); 2664 final PackageUserState state = ps.readUserState(userId); 2665 2666 return PackageParser.generatePackageInfo(p, gids, flags, 2667 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2668 } 2669 2670 @Override 2671 public boolean isPackageFrozen(String packageName) { 2672 synchronized (mPackages) { 2673 final PackageSetting ps = mSettings.mPackages.get(packageName); 2674 if (ps != null) { 2675 return ps.frozen; 2676 } 2677 } 2678 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2679 return true; 2680 } 2681 2682 @Override 2683 public boolean isPackageAvailable(String packageName, int userId) { 2684 if (!sUserManager.exists(userId)) return false; 2685 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2686 synchronized (mPackages) { 2687 PackageParser.Package p = mPackages.get(packageName); 2688 if (p != null) { 2689 final PackageSetting ps = (PackageSetting) p.mExtras; 2690 if (ps != null) { 2691 final PackageUserState state = ps.readUserState(userId); 2692 if (state != null) { 2693 return PackageParser.isAvailable(state); 2694 } 2695 } 2696 } 2697 } 2698 return false; 2699 } 2700 2701 @Override 2702 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2703 if (!sUserManager.exists(userId)) return null; 2704 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2705 // reader 2706 synchronized (mPackages) { 2707 PackageParser.Package p = mPackages.get(packageName); 2708 if (DEBUG_PACKAGE_INFO) 2709 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2710 if (p != null) { 2711 return generatePackageInfo(p, flags, userId); 2712 } 2713 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2714 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2715 } 2716 } 2717 return null; 2718 } 2719 2720 @Override 2721 public String[] currentToCanonicalPackageNames(String[] names) { 2722 String[] out = new String[names.length]; 2723 // reader 2724 synchronized (mPackages) { 2725 for (int i=names.length-1; i>=0; i--) { 2726 PackageSetting ps = mSettings.mPackages.get(names[i]); 2727 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2728 } 2729 } 2730 return out; 2731 } 2732 2733 @Override 2734 public String[] canonicalToCurrentPackageNames(String[] names) { 2735 String[] out = new String[names.length]; 2736 // reader 2737 synchronized (mPackages) { 2738 for (int i=names.length-1; i>=0; i--) { 2739 String cur = mSettings.mRenamedPackages.get(names[i]); 2740 out[i] = cur != null ? cur : names[i]; 2741 } 2742 } 2743 return out; 2744 } 2745 2746 @Override 2747 public int getPackageUid(String packageName, int userId) { 2748 if (!sUserManager.exists(userId)) return -1; 2749 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2750 2751 // reader 2752 synchronized (mPackages) { 2753 PackageParser.Package p = mPackages.get(packageName); 2754 if(p != null) { 2755 return UserHandle.getUid(userId, p.applicationInfo.uid); 2756 } 2757 PackageSetting ps = mSettings.mPackages.get(packageName); 2758 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2759 return -1; 2760 } 2761 p = ps.pkg; 2762 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2763 } 2764 } 2765 2766 @Override 2767 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2768 if (!sUserManager.exists(userId)) { 2769 return null; 2770 } 2771 2772 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2773 "getPackageGids"); 2774 2775 // reader 2776 synchronized (mPackages) { 2777 PackageParser.Package p = mPackages.get(packageName); 2778 if (DEBUG_PACKAGE_INFO) { 2779 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2780 } 2781 if (p != null) { 2782 PackageSetting ps = (PackageSetting) p.mExtras; 2783 return ps.getPermissionsState().computeGids(userId); 2784 } 2785 } 2786 2787 return null; 2788 } 2789 2790 static PermissionInfo generatePermissionInfo( 2791 BasePermission bp, int flags) { 2792 if (bp.perm != null) { 2793 return PackageParser.generatePermissionInfo(bp.perm, flags); 2794 } 2795 PermissionInfo pi = new PermissionInfo(); 2796 pi.name = bp.name; 2797 pi.packageName = bp.sourcePackage; 2798 pi.nonLocalizedLabel = bp.name; 2799 pi.protectionLevel = bp.protectionLevel; 2800 return pi; 2801 } 2802 2803 @Override 2804 public PermissionInfo getPermissionInfo(String name, int flags) { 2805 // reader 2806 synchronized (mPackages) { 2807 final BasePermission p = mSettings.mPermissions.get(name); 2808 if (p != null) { 2809 return generatePermissionInfo(p, flags); 2810 } 2811 return null; 2812 } 2813 } 2814 2815 @Override 2816 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2817 // reader 2818 synchronized (mPackages) { 2819 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2820 for (BasePermission p : mSettings.mPermissions.values()) { 2821 if (group == null) { 2822 if (p.perm == null || p.perm.info.group == null) { 2823 out.add(generatePermissionInfo(p, flags)); 2824 } 2825 } else { 2826 if (p.perm != null && group.equals(p.perm.info.group)) { 2827 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2828 } 2829 } 2830 } 2831 2832 if (out.size() > 0) { 2833 return out; 2834 } 2835 return mPermissionGroups.containsKey(group) ? out : null; 2836 } 2837 } 2838 2839 @Override 2840 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2841 // reader 2842 synchronized (mPackages) { 2843 return PackageParser.generatePermissionGroupInfo( 2844 mPermissionGroups.get(name), flags); 2845 } 2846 } 2847 2848 @Override 2849 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2850 // reader 2851 synchronized (mPackages) { 2852 final int N = mPermissionGroups.size(); 2853 ArrayList<PermissionGroupInfo> out 2854 = new ArrayList<PermissionGroupInfo>(N); 2855 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2856 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2857 } 2858 return out; 2859 } 2860 } 2861 2862 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2863 int userId) { 2864 if (!sUserManager.exists(userId)) return null; 2865 PackageSetting ps = mSettings.mPackages.get(packageName); 2866 if (ps != null) { 2867 if (ps.pkg == null) { 2868 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2869 flags, userId); 2870 if (pInfo != null) { 2871 return pInfo.applicationInfo; 2872 } 2873 return null; 2874 } 2875 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2876 ps.readUserState(userId), userId); 2877 } 2878 return null; 2879 } 2880 2881 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2882 int userId) { 2883 if (!sUserManager.exists(userId)) return null; 2884 PackageSetting ps = mSettings.mPackages.get(packageName); 2885 if (ps != null) { 2886 PackageParser.Package pkg = ps.pkg; 2887 if (pkg == null) { 2888 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2889 return null; 2890 } 2891 // Only data remains, so we aren't worried about code paths 2892 pkg = new PackageParser.Package(packageName); 2893 pkg.applicationInfo.packageName = packageName; 2894 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2895 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2896 pkg.applicationInfo.dataDir = Environment 2897 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2898 .getAbsolutePath(); 2899 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2900 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2901 } 2902 return generatePackageInfo(pkg, flags, userId); 2903 } 2904 return null; 2905 } 2906 2907 @Override 2908 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2911 // writer 2912 synchronized (mPackages) { 2913 PackageParser.Package p = mPackages.get(packageName); 2914 if (DEBUG_PACKAGE_INFO) Log.v( 2915 TAG, "getApplicationInfo " + packageName 2916 + ": " + p); 2917 if (p != null) { 2918 PackageSetting ps = mSettings.mPackages.get(packageName); 2919 if (ps == null) return null; 2920 // Note: isEnabledLP() does not apply here - always return info 2921 return PackageParser.generateApplicationInfo( 2922 p, flags, ps.readUserState(userId), userId); 2923 } 2924 if ("android".equals(packageName)||"system".equals(packageName)) { 2925 return mAndroidApplication; 2926 } 2927 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2928 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2929 } 2930 } 2931 return null; 2932 } 2933 2934 @Override 2935 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2936 final IPackageDataObserver observer) { 2937 mContext.enforceCallingOrSelfPermission( 2938 android.Manifest.permission.CLEAR_APP_CACHE, null); 2939 // Queue up an async operation since clearing cache may take a little while. 2940 mHandler.post(new Runnable() { 2941 public void run() { 2942 mHandler.removeCallbacks(this); 2943 int retCode = -1; 2944 synchronized (mInstallLock) { 2945 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2946 if (retCode < 0) { 2947 Slog.w(TAG, "Couldn't clear application caches"); 2948 } 2949 } 2950 if (observer != null) { 2951 try { 2952 observer.onRemoveCompleted(null, (retCode >= 0)); 2953 } catch (RemoteException e) { 2954 Slog.w(TAG, "RemoveException when invoking call back"); 2955 } 2956 } 2957 } 2958 }); 2959 } 2960 2961 @Override 2962 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2963 final IntentSender pi) { 2964 mContext.enforceCallingOrSelfPermission( 2965 android.Manifest.permission.CLEAR_APP_CACHE, null); 2966 // Queue up an async operation since clearing cache may take a little while. 2967 mHandler.post(new Runnable() { 2968 public void run() { 2969 mHandler.removeCallbacks(this); 2970 int retCode = -1; 2971 synchronized (mInstallLock) { 2972 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2973 if (retCode < 0) { 2974 Slog.w(TAG, "Couldn't clear application caches"); 2975 } 2976 } 2977 if(pi != null) { 2978 try { 2979 // Callback via pending intent 2980 int code = (retCode >= 0) ? 1 : 0; 2981 pi.sendIntent(null, code, null, 2982 null, null); 2983 } catch (SendIntentException e1) { 2984 Slog.i(TAG, "Failed to send pending intent"); 2985 } 2986 } 2987 } 2988 }); 2989 } 2990 2991 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2992 synchronized (mInstallLock) { 2993 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2994 throw new IOException("Failed to free enough space"); 2995 } 2996 } 2997 } 2998 2999 @Override 3000 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3001 if (!sUserManager.exists(userId)) return null; 3002 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3003 synchronized (mPackages) { 3004 PackageParser.Activity a = mActivities.mActivities.get(component); 3005 3006 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3007 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3008 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3009 if (ps == null) return null; 3010 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3011 userId); 3012 } 3013 if (mResolveComponentName.equals(component)) { 3014 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3015 new PackageUserState(), userId); 3016 } 3017 } 3018 return null; 3019 } 3020 3021 @Override 3022 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3023 String resolvedType) { 3024 synchronized (mPackages) { 3025 if (component.equals(mResolveComponentName)) { 3026 // The resolver supports EVERYTHING! 3027 return true; 3028 } 3029 PackageParser.Activity a = mActivities.mActivities.get(component); 3030 if (a == null) { 3031 return false; 3032 } 3033 for (int i=0; i<a.intents.size(); i++) { 3034 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3035 intent.getData(), intent.getCategories(), TAG) >= 0) { 3036 return true; 3037 } 3038 } 3039 return false; 3040 } 3041 } 3042 3043 @Override 3044 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3045 if (!sUserManager.exists(userId)) return null; 3046 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3047 synchronized (mPackages) { 3048 PackageParser.Activity a = mReceivers.mActivities.get(component); 3049 if (DEBUG_PACKAGE_INFO) Log.v( 3050 TAG, "getReceiverInfo " + component + ": " + a); 3051 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3052 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3053 if (ps == null) return null; 3054 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3055 userId); 3056 } 3057 } 3058 return null; 3059 } 3060 3061 @Override 3062 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3063 if (!sUserManager.exists(userId)) return null; 3064 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3065 synchronized (mPackages) { 3066 PackageParser.Service s = mServices.mServices.get(component); 3067 if (DEBUG_PACKAGE_INFO) Log.v( 3068 TAG, "getServiceInfo " + component + ": " + s); 3069 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3070 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3071 if (ps == null) return null; 3072 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3073 userId); 3074 } 3075 } 3076 return null; 3077 } 3078 3079 @Override 3080 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3081 if (!sUserManager.exists(userId)) return null; 3082 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3083 synchronized (mPackages) { 3084 PackageParser.Provider p = mProviders.mProviders.get(component); 3085 if (DEBUG_PACKAGE_INFO) Log.v( 3086 TAG, "getProviderInfo " + component + ": " + p); 3087 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3088 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3089 if (ps == null) return null; 3090 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3091 userId); 3092 } 3093 } 3094 return null; 3095 } 3096 3097 @Override 3098 public String[] getSystemSharedLibraryNames() { 3099 Set<String> libSet; 3100 synchronized (mPackages) { 3101 libSet = mSharedLibraries.keySet(); 3102 int size = libSet.size(); 3103 if (size > 0) { 3104 String[] libs = new String[size]; 3105 libSet.toArray(libs); 3106 return libs; 3107 } 3108 } 3109 return null; 3110 } 3111 3112 /** 3113 * @hide 3114 */ 3115 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3116 synchronized (mPackages) { 3117 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3118 if (lib != null && lib.apk != null) { 3119 return mPackages.get(lib.apk); 3120 } 3121 } 3122 return null; 3123 } 3124 3125 @Override 3126 public FeatureInfo[] getSystemAvailableFeatures() { 3127 Collection<FeatureInfo> featSet; 3128 synchronized (mPackages) { 3129 featSet = mAvailableFeatures.values(); 3130 int size = featSet.size(); 3131 if (size > 0) { 3132 FeatureInfo[] features = new FeatureInfo[size+1]; 3133 featSet.toArray(features); 3134 FeatureInfo fi = new FeatureInfo(); 3135 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3136 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3137 features[size] = fi; 3138 return features; 3139 } 3140 } 3141 return null; 3142 } 3143 3144 @Override 3145 public boolean hasSystemFeature(String name) { 3146 synchronized (mPackages) { 3147 return mAvailableFeatures.containsKey(name); 3148 } 3149 } 3150 3151 private void checkValidCaller(int uid, int userId) { 3152 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3153 return; 3154 3155 throw new SecurityException("Caller uid=" + uid 3156 + " is not privileged to communicate with user=" + userId); 3157 } 3158 3159 @Override 3160 public int checkPermission(String permName, String pkgName, int userId) { 3161 if (!sUserManager.exists(userId)) { 3162 return PackageManager.PERMISSION_DENIED; 3163 } 3164 3165 synchronized (mPackages) { 3166 final PackageParser.Package p = mPackages.get(pkgName); 3167 if (p != null && p.mExtras != null) { 3168 final PackageSetting ps = (PackageSetting) p.mExtras; 3169 final PermissionsState permissionsState = ps.getPermissionsState(); 3170 if (permissionsState.hasPermission(permName, userId)) { 3171 return PackageManager.PERMISSION_GRANTED; 3172 } 3173 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3174 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3175 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3176 return PackageManager.PERMISSION_GRANTED; 3177 } 3178 } 3179 } 3180 3181 return PackageManager.PERMISSION_DENIED; 3182 } 3183 3184 @Override 3185 public int checkUidPermission(String permName, int uid) { 3186 final int userId = UserHandle.getUserId(uid); 3187 3188 if (!sUserManager.exists(userId)) { 3189 return PackageManager.PERMISSION_DENIED; 3190 } 3191 3192 synchronized (mPackages) { 3193 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3194 if (obj != null) { 3195 final SettingBase ps = (SettingBase) obj; 3196 final PermissionsState permissionsState = ps.getPermissionsState(); 3197 if (permissionsState.hasPermission(permName, userId)) { 3198 return PackageManager.PERMISSION_GRANTED; 3199 } 3200 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3201 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3202 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3203 return PackageManager.PERMISSION_GRANTED; 3204 } 3205 } else { 3206 ArraySet<String> perms = mSystemPermissions.get(uid); 3207 if (perms != null) { 3208 if (perms.contains(permName)) { 3209 return PackageManager.PERMISSION_GRANTED; 3210 } 3211 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3212 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3213 return PackageManager.PERMISSION_GRANTED; 3214 } 3215 } 3216 } 3217 } 3218 3219 return PackageManager.PERMISSION_DENIED; 3220 } 3221 3222 @Override 3223 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3224 if (UserHandle.getCallingUserId() != userId) { 3225 mContext.enforceCallingPermission( 3226 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3227 "isPermissionRevokedByPolicy for user " + userId); 3228 } 3229 3230 if (checkPermission(permission, packageName, userId) 3231 == PackageManager.PERMISSION_GRANTED) { 3232 return false; 3233 } 3234 3235 final long identity = Binder.clearCallingIdentity(); 3236 try { 3237 final int flags = getPermissionFlags(permission, packageName, userId); 3238 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3239 } finally { 3240 Binder.restoreCallingIdentity(identity); 3241 } 3242 } 3243 3244 @Override 3245 public String getPermissionControllerPackageName() { 3246 synchronized (mPackages) { 3247 return mRequiredInstallerPackage; 3248 } 3249 } 3250 3251 /** 3252 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3253 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3254 * @param checkShell TODO(yamasani): 3255 * @param message the message to log on security exception 3256 */ 3257 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3258 boolean checkShell, String message) { 3259 if (userId < 0) { 3260 throw new IllegalArgumentException("Invalid userId " + userId); 3261 } 3262 if (checkShell) { 3263 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3264 } 3265 if (userId == UserHandle.getUserId(callingUid)) return; 3266 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3267 if (requireFullPermission) { 3268 mContext.enforceCallingOrSelfPermission( 3269 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3270 } else { 3271 try { 3272 mContext.enforceCallingOrSelfPermission( 3273 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3274 } catch (SecurityException se) { 3275 mContext.enforceCallingOrSelfPermission( 3276 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3277 } 3278 } 3279 } 3280 } 3281 3282 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3283 if (callingUid == Process.SHELL_UID) { 3284 if (userHandle >= 0 3285 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3286 throw new SecurityException("Shell does not have permission to access user " 3287 + userHandle); 3288 } else if (userHandle < 0) { 3289 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3290 + Debug.getCallers(3)); 3291 } 3292 } 3293 } 3294 3295 private BasePermission findPermissionTreeLP(String permName) { 3296 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3297 if (permName.startsWith(bp.name) && 3298 permName.length() > bp.name.length() && 3299 permName.charAt(bp.name.length()) == '.') { 3300 return bp; 3301 } 3302 } 3303 return null; 3304 } 3305 3306 private BasePermission checkPermissionTreeLP(String permName) { 3307 if (permName != null) { 3308 BasePermission bp = findPermissionTreeLP(permName); 3309 if (bp != null) { 3310 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3311 return bp; 3312 } 3313 throw new SecurityException("Calling uid " 3314 + Binder.getCallingUid() 3315 + " is not allowed to add to permission tree " 3316 + bp.name + " owned by uid " + bp.uid); 3317 } 3318 } 3319 throw new SecurityException("No permission tree found for " + permName); 3320 } 3321 3322 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3323 if (s1 == null) { 3324 return s2 == null; 3325 } 3326 if (s2 == null) { 3327 return false; 3328 } 3329 if (s1.getClass() != s2.getClass()) { 3330 return false; 3331 } 3332 return s1.equals(s2); 3333 } 3334 3335 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3336 if (pi1.icon != pi2.icon) return false; 3337 if (pi1.logo != pi2.logo) return false; 3338 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3339 if (!compareStrings(pi1.name, pi2.name)) return false; 3340 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3341 // We'll take care of setting this one. 3342 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3343 // These are not currently stored in settings. 3344 //if (!compareStrings(pi1.group, pi2.group)) return false; 3345 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3346 //if (pi1.labelRes != pi2.labelRes) return false; 3347 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3348 return true; 3349 } 3350 3351 int permissionInfoFootprint(PermissionInfo info) { 3352 int size = info.name.length(); 3353 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3354 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3355 return size; 3356 } 3357 3358 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3359 int size = 0; 3360 for (BasePermission perm : mSettings.mPermissions.values()) { 3361 if (perm.uid == tree.uid) { 3362 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3363 } 3364 } 3365 return size; 3366 } 3367 3368 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3369 // We calculate the max size of permissions defined by this uid and throw 3370 // if that plus the size of 'info' would exceed our stated maximum. 3371 if (tree.uid != Process.SYSTEM_UID) { 3372 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3373 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3374 throw new SecurityException("Permission tree size cap exceeded"); 3375 } 3376 } 3377 } 3378 3379 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3380 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3381 throw new SecurityException("Label must be specified in permission"); 3382 } 3383 BasePermission tree = checkPermissionTreeLP(info.name); 3384 BasePermission bp = mSettings.mPermissions.get(info.name); 3385 boolean added = bp == null; 3386 boolean changed = true; 3387 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3388 if (added) { 3389 enforcePermissionCapLocked(info, tree); 3390 bp = new BasePermission(info.name, tree.sourcePackage, 3391 BasePermission.TYPE_DYNAMIC); 3392 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3393 throw new SecurityException( 3394 "Not allowed to modify non-dynamic permission " 3395 + info.name); 3396 } else { 3397 if (bp.protectionLevel == fixedLevel 3398 && bp.perm.owner.equals(tree.perm.owner) 3399 && bp.uid == tree.uid 3400 && comparePermissionInfos(bp.perm.info, info)) { 3401 changed = false; 3402 } 3403 } 3404 bp.protectionLevel = fixedLevel; 3405 info = new PermissionInfo(info); 3406 info.protectionLevel = fixedLevel; 3407 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3408 bp.perm.info.packageName = tree.perm.info.packageName; 3409 bp.uid = tree.uid; 3410 if (added) { 3411 mSettings.mPermissions.put(info.name, bp); 3412 } 3413 if (changed) { 3414 if (!async) { 3415 mSettings.writeLPr(); 3416 } else { 3417 scheduleWriteSettingsLocked(); 3418 } 3419 } 3420 return added; 3421 } 3422 3423 @Override 3424 public boolean addPermission(PermissionInfo info) { 3425 synchronized (mPackages) { 3426 return addPermissionLocked(info, false); 3427 } 3428 } 3429 3430 @Override 3431 public boolean addPermissionAsync(PermissionInfo info) { 3432 synchronized (mPackages) { 3433 return addPermissionLocked(info, true); 3434 } 3435 } 3436 3437 @Override 3438 public void removePermission(String name) { 3439 synchronized (mPackages) { 3440 checkPermissionTreeLP(name); 3441 BasePermission bp = mSettings.mPermissions.get(name); 3442 if (bp != null) { 3443 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3444 throw new SecurityException( 3445 "Not allowed to modify non-dynamic permission " 3446 + name); 3447 } 3448 mSettings.mPermissions.remove(name); 3449 mSettings.writeLPr(); 3450 } 3451 } 3452 } 3453 3454 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3455 BasePermission bp) { 3456 int index = pkg.requestedPermissions.indexOf(bp.name); 3457 if (index == -1) { 3458 throw new SecurityException("Package " + pkg.packageName 3459 + " has not requested permission " + bp.name); 3460 } 3461 if (!bp.isRuntime() && !bp.isDevelopment()) { 3462 throw new SecurityException("Permission " + bp.name 3463 + " is not a changeable permission type"); 3464 } 3465 } 3466 3467 @Override 3468 public void grantRuntimePermission(String packageName, String name, final int userId) { 3469 if (!sUserManager.exists(userId)) { 3470 Log.e(TAG, "No such user:" + userId); 3471 return; 3472 } 3473 3474 mContext.enforceCallingOrSelfPermission( 3475 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3476 "grantRuntimePermission"); 3477 3478 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3479 "grantRuntimePermission"); 3480 3481 final int uid; 3482 final SettingBase sb; 3483 3484 synchronized (mPackages) { 3485 final PackageParser.Package pkg = mPackages.get(packageName); 3486 if (pkg == null) { 3487 throw new IllegalArgumentException("Unknown package: " + packageName); 3488 } 3489 3490 final BasePermission bp = mSettings.mPermissions.get(name); 3491 if (bp == null) { 3492 throw new IllegalArgumentException("Unknown permission: " + name); 3493 } 3494 3495 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3496 3497 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3498 sb = (SettingBase) pkg.mExtras; 3499 if (sb == null) { 3500 throw new IllegalArgumentException("Unknown package: " + packageName); 3501 } 3502 3503 final PermissionsState permissionsState = sb.getPermissionsState(); 3504 3505 final int flags = permissionsState.getPermissionFlags(name, userId); 3506 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3507 throw new SecurityException("Cannot grant system fixed permission: " 3508 + name + " for package: " + packageName); 3509 } 3510 3511 if (bp.isDevelopment()) { 3512 // Development permissions must be handled specially, since they are not 3513 // normal runtime permissions. For now they apply to all users. 3514 if (permissionsState.grantInstallPermission(bp) != 3515 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3516 scheduleWriteSettingsLocked(); 3517 } 3518 return; 3519 } 3520 3521 final int result = permissionsState.grantRuntimePermission(bp, userId); 3522 switch (result) { 3523 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3524 return; 3525 } 3526 3527 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3528 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3529 mHandler.post(new Runnable() { 3530 @Override 3531 public void run() { 3532 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3533 } 3534 }); 3535 } break; 3536 } 3537 3538 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3539 3540 // Not critical if that is lost - app has to request again. 3541 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3542 } 3543 3544 // Only need to do this if user is initialized. Otherwise it's a new user 3545 // and there are no processes running as the user yet and there's no need 3546 // to make an expensive call to remount processes for the changed permissions. 3547 if (READ_EXTERNAL_STORAGE.equals(name) 3548 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3549 final long token = Binder.clearCallingIdentity(); 3550 try { 3551 if (sUserManager.isInitialized(userId)) { 3552 MountServiceInternal mountServiceInternal = LocalServices.getService( 3553 MountServiceInternal.class); 3554 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3555 } 3556 } finally { 3557 Binder.restoreCallingIdentity(token); 3558 } 3559 } 3560 } 3561 3562 @Override 3563 public void revokeRuntimePermission(String packageName, String name, int userId) { 3564 if (!sUserManager.exists(userId)) { 3565 Log.e(TAG, "No such user:" + userId); 3566 return; 3567 } 3568 3569 mContext.enforceCallingOrSelfPermission( 3570 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3571 "revokeRuntimePermission"); 3572 3573 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3574 "revokeRuntimePermission"); 3575 3576 final int appId; 3577 3578 synchronized (mPackages) { 3579 final PackageParser.Package pkg = mPackages.get(packageName); 3580 if (pkg == null) { 3581 throw new IllegalArgumentException("Unknown package: " + packageName); 3582 } 3583 3584 final BasePermission bp = mSettings.mPermissions.get(name); 3585 if (bp == null) { 3586 throw new IllegalArgumentException("Unknown permission: " + name); 3587 } 3588 3589 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3590 3591 SettingBase sb = (SettingBase) pkg.mExtras; 3592 if (sb == null) { 3593 throw new IllegalArgumentException("Unknown package: " + packageName); 3594 } 3595 3596 final PermissionsState permissionsState = sb.getPermissionsState(); 3597 3598 final int flags = permissionsState.getPermissionFlags(name, userId); 3599 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3600 throw new SecurityException("Cannot revoke system fixed permission: " 3601 + name + " for package: " + packageName); 3602 } 3603 3604 if (bp.isDevelopment()) { 3605 // Development permissions must be handled specially, since they are not 3606 // normal runtime permissions. For now they apply to all users. 3607 if (permissionsState.revokeInstallPermission(bp) != 3608 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3609 scheduleWriteSettingsLocked(); 3610 } 3611 return; 3612 } 3613 3614 if (permissionsState.revokeRuntimePermission(bp, userId) == 3615 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3616 return; 3617 } 3618 3619 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3620 3621 // Critical, after this call app should never have the permission. 3622 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3623 3624 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3625 } 3626 3627 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3628 } 3629 3630 @Override 3631 public void resetRuntimePermissions() { 3632 mContext.enforceCallingOrSelfPermission( 3633 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3634 "revokeRuntimePermission"); 3635 3636 int callingUid = Binder.getCallingUid(); 3637 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3638 mContext.enforceCallingOrSelfPermission( 3639 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3640 "resetRuntimePermissions"); 3641 } 3642 3643 synchronized (mPackages) { 3644 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3645 for (int userId : UserManagerService.getInstance().getUserIds()) { 3646 final int packageCount = mPackages.size(); 3647 for (int i = 0; i < packageCount; i++) { 3648 PackageParser.Package pkg = mPackages.valueAt(i); 3649 if (!(pkg.mExtras instanceof PackageSetting)) { 3650 continue; 3651 } 3652 PackageSetting ps = (PackageSetting) pkg.mExtras; 3653 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3654 } 3655 } 3656 } 3657 } 3658 3659 @Override 3660 public int getPermissionFlags(String name, String packageName, int userId) { 3661 if (!sUserManager.exists(userId)) { 3662 return 0; 3663 } 3664 3665 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3666 3667 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3668 "getPermissionFlags"); 3669 3670 synchronized (mPackages) { 3671 final PackageParser.Package pkg = mPackages.get(packageName); 3672 if (pkg == null) { 3673 throw new IllegalArgumentException("Unknown package: " + packageName); 3674 } 3675 3676 final BasePermission bp = mSettings.mPermissions.get(name); 3677 if (bp == null) { 3678 throw new IllegalArgumentException("Unknown permission: " + name); 3679 } 3680 3681 SettingBase sb = (SettingBase) pkg.mExtras; 3682 if (sb == null) { 3683 throw new IllegalArgumentException("Unknown package: " + packageName); 3684 } 3685 3686 PermissionsState permissionsState = sb.getPermissionsState(); 3687 return permissionsState.getPermissionFlags(name, userId); 3688 } 3689 } 3690 3691 @Override 3692 public void updatePermissionFlags(String name, String packageName, int flagMask, 3693 int flagValues, int userId) { 3694 if (!sUserManager.exists(userId)) { 3695 return; 3696 } 3697 3698 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3699 3700 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3701 "updatePermissionFlags"); 3702 3703 // Only the system can change these flags and nothing else. 3704 if (getCallingUid() != Process.SYSTEM_UID) { 3705 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3706 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3707 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3708 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3709 } 3710 3711 synchronized (mPackages) { 3712 final PackageParser.Package pkg = mPackages.get(packageName); 3713 if (pkg == null) { 3714 throw new IllegalArgumentException("Unknown package: " + packageName); 3715 } 3716 3717 final BasePermission bp = mSettings.mPermissions.get(name); 3718 if (bp == null) { 3719 throw new IllegalArgumentException("Unknown permission: " + name); 3720 } 3721 3722 SettingBase sb = (SettingBase) pkg.mExtras; 3723 if (sb == null) { 3724 throw new IllegalArgumentException("Unknown package: " + packageName); 3725 } 3726 3727 PermissionsState permissionsState = sb.getPermissionsState(); 3728 3729 // Only the package manager can change flags for system component permissions. 3730 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3731 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3732 return; 3733 } 3734 3735 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3736 3737 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3738 // Install and runtime permissions are stored in different places, 3739 // so figure out what permission changed and persist the change. 3740 if (permissionsState.getInstallPermissionState(name) != null) { 3741 scheduleWriteSettingsLocked(); 3742 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3743 || hadState) { 3744 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3745 } 3746 } 3747 } 3748 } 3749 3750 /** 3751 * Update the permission flags for all packages and runtime permissions of a user in order 3752 * to allow device or profile owner to remove POLICY_FIXED. 3753 */ 3754 @Override 3755 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3756 if (!sUserManager.exists(userId)) { 3757 return; 3758 } 3759 3760 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3761 3762 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3763 "updatePermissionFlagsForAllApps"); 3764 3765 // Only the system can change system fixed flags. 3766 if (getCallingUid() != Process.SYSTEM_UID) { 3767 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3768 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3769 } 3770 3771 synchronized (mPackages) { 3772 boolean changed = false; 3773 final int packageCount = mPackages.size(); 3774 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3775 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3776 SettingBase sb = (SettingBase) pkg.mExtras; 3777 if (sb == null) { 3778 continue; 3779 } 3780 PermissionsState permissionsState = sb.getPermissionsState(); 3781 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3782 userId, flagMask, flagValues); 3783 } 3784 if (changed) { 3785 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3786 } 3787 } 3788 } 3789 3790 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3791 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3792 != PackageManager.PERMISSION_GRANTED 3793 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3794 != PackageManager.PERMISSION_GRANTED) { 3795 throw new SecurityException(message + " requires " 3796 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3797 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3798 } 3799 } 3800 3801 @Override 3802 public boolean shouldShowRequestPermissionRationale(String permissionName, 3803 String packageName, int userId) { 3804 if (UserHandle.getCallingUserId() != userId) { 3805 mContext.enforceCallingPermission( 3806 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3807 "canShowRequestPermissionRationale for user " + userId); 3808 } 3809 3810 final int uid = getPackageUid(packageName, userId); 3811 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3812 return false; 3813 } 3814 3815 if (checkPermission(permissionName, packageName, userId) 3816 == PackageManager.PERMISSION_GRANTED) { 3817 return false; 3818 } 3819 3820 final int flags; 3821 3822 final long identity = Binder.clearCallingIdentity(); 3823 try { 3824 flags = getPermissionFlags(permissionName, 3825 packageName, userId); 3826 } finally { 3827 Binder.restoreCallingIdentity(identity); 3828 } 3829 3830 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3831 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3832 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3833 3834 if ((flags & fixedFlags) != 0) { 3835 return false; 3836 } 3837 3838 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3839 } 3840 3841 @Override 3842 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3843 mContext.enforceCallingOrSelfPermission( 3844 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3845 "addOnPermissionsChangeListener"); 3846 3847 synchronized (mPackages) { 3848 mOnPermissionChangeListeners.addListenerLocked(listener); 3849 } 3850 } 3851 3852 @Override 3853 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3854 synchronized (mPackages) { 3855 mOnPermissionChangeListeners.removeListenerLocked(listener); 3856 } 3857 } 3858 3859 @Override 3860 public boolean isProtectedBroadcast(String actionName) { 3861 synchronized (mPackages) { 3862 return mProtectedBroadcasts.contains(actionName); 3863 } 3864 } 3865 3866 @Override 3867 public int checkSignatures(String pkg1, String pkg2) { 3868 synchronized (mPackages) { 3869 final PackageParser.Package p1 = mPackages.get(pkg1); 3870 final PackageParser.Package p2 = mPackages.get(pkg2); 3871 if (p1 == null || p1.mExtras == null 3872 || p2 == null || p2.mExtras == null) { 3873 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3874 } 3875 return compareSignatures(p1.mSignatures, p2.mSignatures); 3876 } 3877 } 3878 3879 @Override 3880 public int checkUidSignatures(int uid1, int uid2) { 3881 // Map to base uids. 3882 uid1 = UserHandle.getAppId(uid1); 3883 uid2 = UserHandle.getAppId(uid2); 3884 // reader 3885 synchronized (mPackages) { 3886 Signature[] s1; 3887 Signature[] s2; 3888 Object obj = mSettings.getUserIdLPr(uid1); 3889 if (obj != null) { 3890 if (obj instanceof SharedUserSetting) { 3891 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3892 } else if (obj instanceof PackageSetting) { 3893 s1 = ((PackageSetting)obj).signatures.mSignatures; 3894 } else { 3895 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3896 } 3897 } else { 3898 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3899 } 3900 obj = mSettings.getUserIdLPr(uid2); 3901 if (obj != null) { 3902 if (obj instanceof SharedUserSetting) { 3903 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3904 } else if (obj instanceof PackageSetting) { 3905 s2 = ((PackageSetting)obj).signatures.mSignatures; 3906 } else { 3907 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3908 } 3909 } else { 3910 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3911 } 3912 return compareSignatures(s1, s2); 3913 } 3914 } 3915 3916 private void killUid(int appId, int userId, String reason) { 3917 final long identity = Binder.clearCallingIdentity(); 3918 try { 3919 IActivityManager am = ActivityManagerNative.getDefault(); 3920 if (am != null) { 3921 try { 3922 am.killUid(appId, userId, reason); 3923 } catch (RemoteException e) { 3924 /* ignore - same process */ 3925 } 3926 } 3927 } finally { 3928 Binder.restoreCallingIdentity(identity); 3929 } 3930 } 3931 3932 /** 3933 * Compares two sets of signatures. Returns: 3934 * <br /> 3935 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3936 * <br /> 3937 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3938 * <br /> 3939 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3940 * <br /> 3941 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3942 * <br /> 3943 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3944 */ 3945 static int compareSignatures(Signature[] s1, Signature[] s2) { 3946 if (s1 == null) { 3947 return s2 == null 3948 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3949 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3950 } 3951 3952 if (s2 == null) { 3953 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3954 } 3955 3956 if (s1.length != s2.length) { 3957 return PackageManager.SIGNATURE_NO_MATCH; 3958 } 3959 3960 // Since both signature sets are of size 1, we can compare without HashSets. 3961 if (s1.length == 1) { 3962 return s1[0].equals(s2[0]) ? 3963 PackageManager.SIGNATURE_MATCH : 3964 PackageManager.SIGNATURE_NO_MATCH; 3965 } 3966 3967 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3968 for (Signature sig : s1) { 3969 set1.add(sig); 3970 } 3971 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3972 for (Signature sig : s2) { 3973 set2.add(sig); 3974 } 3975 // Make sure s2 contains all signatures in s1. 3976 if (set1.equals(set2)) { 3977 return PackageManager.SIGNATURE_MATCH; 3978 } 3979 return PackageManager.SIGNATURE_NO_MATCH; 3980 } 3981 3982 /** 3983 * If the database version for this type of package (internal storage or 3984 * external storage) is less than the version where package signatures 3985 * were updated, return true. 3986 */ 3987 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3988 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3989 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3990 } 3991 3992 /** 3993 * Used for backward compatibility to make sure any packages with 3994 * certificate chains get upgraded to the new style. {@code existingSigs} 3995 * will be in the old format (since they were stored on disk from before the 3996 * system upgrade) and {@code scannedSigs} will be in the newer format. 3997 */ 3998 private int compareSignaturesCompat(PackageSignatures existingSigs, 3999 PackageParser.Package scannedPkg) { 4000 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4001 return PackageManager.SIGNATURE_NO_MATCH; 4002 } 4003 4004 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4005 for (Signature sig : existingSigs.mSignatures) { 4006 existingSet.add(sig); 4007 } 4008 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4009 for (Signature sig : scannedPkg.mSignatures) { 4010 try { 4011 Signature[] chainSignatures = sig.getChainSignatures(); 4012 for (Signature chainSig : chainSignatures) { 4013 scannedCompatSet.add(chainSig); 4014 } 4015 } catch (CertificateEncodingException e) { 4016 scannedCompatSet.add(sig); 4017 } 4018 } 4019 /* 4020 * Make sure the expanded scanned set contains all signatures in the 4021 * existing one. 4022 */ 4023 if (scannedCompatSet.equals(existingSet)) { 4024 // Migrate the old signatures to the new scheme. 4025 existingSigs.assignSignatures(scannedPkg.mSignatures); 4026 // The new KeySets will be re-added later in the scanning process. 4027 synchronized (mPackages) { 4028 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4029 } 4030 return PackageManager.SIGNATURE_MATCH; 4031 } 4032 return PackageManager.SIGNATURE_NO_MATCH; 4033 } 4034 4035 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4036 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4037 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4038 } 4039 4040 private int compareSignaturesRecover(PackageSignatures existingSigs, 4041 PackageParser.Package scannedPkg) { 4042 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4043 return PackageManager.SIGNATURE_NO_MATCH; 4044 } 4045 4046 String msg = null; 4047 try { 4048 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4049 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4050 + scannedPkg.packageName); 4051 return PackageManager.SIGNATURE_MATCH; 4052 } 4053 } catch (CertificateException e) { 4054 msg = e.getMessage(); 4055 } 4056 4057 logCriticalInfo(Log.INFO, 4058 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4059 return PackageManager.SIGNATURE_NO_MATCH; 4060 } 4061 4062 @Override 4063 public String[] getPackagesForUid(int uid) { 4064 uid = UserHandle.getAppId(uid); 4065 // reader 4066 synchronized (mPackages) { 4067 Object obj = mSettings.getUserIdLPr(uid); 4068 if (obj instanceof SharedUserSetting) { 4069 final SharedUserSetting sus = (SharedUserSetting) obj; 4070 final int N = sus.packages.size(); 4071 final String[] res = new String[N]; 4072 final Iterator<PackageSetting> it = sus.packages.iterator(); 4073 int i = 0; 4074 while (it.hasNext()) { 4075 res[i++] = it.next().name; 4076 } 4077 return res; 4078 } else if (obj instanceof PackageSetting) { 4079 final PackageSetting ps = (PackageSetting) obj; 4080 return new String[] { ps.name }; 4081 } 4082 } 4083 return null; 4084 } 4085 4086 @Override 4087 public String getNameForUid(int uid) { 4088 // reader 4089 synchronized (mPackages) { 4090 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4091 if (obj instanceof SharedUserSetting) { 4092 final SharedUserSetting sus = (SharedUserSetting) obj; 4093 return sus.name + ":" + sus.userId; 4094 } else if (obj instanceof PackageSetting) { 4095 final PackageSetting ps = (PackageSetting) obj; 4096 return ps.name; 4097 } 4098 } 4099 return null; 4100 } 4101 4102 @Override 4103 public int getUidForSharedUser(String sharedUserName) { 4104 if(sharedUserName == null) { 4105 return -1; 4106 } 4107 // reader 4108 synchronized (mPackages) { 4109 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4110 if (suid == null) { 4111 return -1; 4112 } 4113 return suid.userId; 4114 } 4115 } 4116 4117 @Override 4118 public int getFlagsForUid(int uid) { 4119 synchronized (mPackages) { 4120 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4121 if (obj instanceof SharedUserSetting) { 4122 final SharedUserSetting sus = (SharedUserSetting) obj; 4123 return sus.pkgFlags; 4124 } else if (obj instanceof PackageSetting) { 4125 final PackageSetting ps = (PackageSetting) obj; 4126 return ps.pkgFlags; 4127 } 4128 } 4129 return 0; 4130 } 4131 4132 @Override 4133 public int getPrivateFlagsForUid(int uid) { 4134 synchronized (mPackages) { 4135 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4136 if (obj instanceof SharedUserSetting) { 4137 final SharedUserSetting sus = (SharedUserSetting) obj; 4138 return sus.pkgPrivateFlags; 4139 } else if (obj instanceof PackageSetting) { 4140 final PackageSetting ps = (PackageSetting) obj; 4141 return ps.pkgPrivateFlags; 4142 } 4143 } 4144 return 0; 4145 } 4146 4147 @Override 4148 public boolean isUidPrivileged(int uid) { 4149 uid = UserHandle.getAppId(uid); 4150 // reader 4151 synchronized (mPackages) { 4152 Object obj = mSettings.getUserIdLPr(uid); 4153 if (obj instanceof SharedUserSetting) { 4154 final SharedUserSetting sus = (SharedUserSetting) obj; 4155 final Iterator<PackageSetting> it = sus.packages.iterator(); 4156 while (it.hasNext()) { 4157 if (it.next().isPrivileged()) { 4158 return true; 4159 } 4160 } 4161 } else if (obj instanceof PackageSetting) { 4162 final PackageSetting ps = (PackageSetting) obj; 4163 return ps.isPrivileged(); 4164 } 4165 } 4166 return false; 4167 } 4168 4169 @Override 4170 public String[] getAppOpPermissionPackages(String permissionName) { 4171 synchronized (mPackages) { 4172 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4173 if (pkgs == null) { 4174 return null; 4175 } 4176 return pkgs.toArray(new String[pkgs.size()]); 4177 } 4178 } 4179 4180 @Override 4181 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4182 int flags, int userId) { 4183 if (!sUserManager.exists(userId)) return null; 4184 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4185 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4186 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4187 } 4188 4189 @Override 4190 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4191 IntentFilter filter, int match, ComponentName activity) { 4192 final int userId = UserHandle.getCallingUserId(); 4193 if (DEBUG_PREFERRED) { 4194 Log.v(TAG, "setLastChosenActivity intent=" + intent 4195 + " resolvedType=" + resolvedType 4196 + " flags=" + flags 4197 + " filter=" + filter 4198 + " match=" + match 4199 + " activity=" + activity); 4200 filter.dump(new PrintStreamPrinter(System.out), " "); 4201 } 4202 intent.setComponent(null); 4203 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4204 // Find any earlier preferred or last chosen entries and nuke them 4205 findPreferredActivity(intent, resolvedType, 4206 flags, query, 0, false, true, false, userId); 4207 // Add the new activity as the last chosen for this filter 4208 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4209 "Setting last chosen"); 4210 } 4211 4212 @Override 4213 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4214 final int userId = UserHandle.getCallingUserId(); 4215 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4216 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4217 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4218 false, false, false, userId); 4219 } 4220 4221 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4222 int flags, List<ResolveInfo> query, int userId) { 4223 if (query != null) { 4224 final int N = query.size(); 4225 if (N == 1) { 4226 return query.get(0); 4227 } else if (N > 1) { 4228 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4229 // If there is more than one activity with the same priority, 4230 // then let the user decide between them. 4231 ResolveInfo r0 = query.get(0); 4232 ResolveInfo r1 = query.get(1); 4233 if (DEBUG_INTENT_MATCHING || debug) { 4234 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4235 + r1.activityInfo.name + "=" + r1.priority); 4236 } 4237 // If the first activity has a higher priority, or a different 4238 // default, then it is always desireable to pick it. 4239 if (r0.priority != r1.priority 4240 || r0.preferredOrder != r1.preferredOrder 4241 || r0.isDefault != r1.isDefault) { 4242 return query.get(0); 4243 } 4244 // If we have saved a preference for a preferred activity for 4245 // this Intent, use that. 4246 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4247 flags, query, r0.priority, true, false, debug, userId); 4248 if (ri != null) { 4249 return ri; 4250 } 4251 if (userId != 0) { 4252 ri = new ResolveInfo(mResolveInfo); 4253 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4254 ri.activityInfo.applicationInfo = new ApplicationInfo( 4255 ri.activityInfo.applicationInfo); 4256 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4257 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4258 return ri; 4259 } 4260 return mResolveInfo; 4261 } 4262 } 4263 return null; 4264 } 4265 4266 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4267 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4268 final int N = query.size(); 4269 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4270 .get(userId); 4271 // Get the list of persistent preferred activities that handle the intent 4272 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4273 List<PersistentPreferredActivity> pprefs = ppir != null 4274 ? ppir.queryIntent(intent, resolvedType, 4275 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4276 : null; 4277 if (pprefs != null && pprefs.size() > 0) { 4278 final int M = pprefs.size(); 4279 for (int i=0; i<M; i++) { 4280 final PersistentPreferredActivity ppa = pprefs.get(i); 4281 if (DEBUG_PREFERRED || debug) { 4282 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4283 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4284 + "\n component=" + ppa.mComponent); 4285 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4286 } 4287 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4288 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4289 if (DEBUG_PREFERRED || debug) { 4290 Slog.v(TAG, "Found persistent preferred activity:"); 4291 if (ai != null) { 4292 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4293 } else { 4294 Slog.v(TAG, " null"); 4295 } 4296 } 4297 if (ai == null) { 4298 // This previously registered persistent preferred activity 4299 // component is no longer known. Ignore it and do NOT remove it. 4300 continue; 4301 } 4302 for (int j=0; j<N; j++) { 4303 final ResolveInfo ri = query.get(j); 4304 if (!ri.activityInfo.applicationInfo.packageName 4305 .equals(ai.applicationInfo.packageName)) { 4306 continue; 4307 } 4308 if (!ri.activityInfo.name.equals(ai.name)) { 4309 continue; 4310 } 4311 // Found a persistent preference that can handle the intent. 4312 if (DEBUG_PREFERRED || debug) { 4313 Slog.v(TAG, "Returning persistent preferred activity: " + 4314 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4315 } 4316 return ri; 4317 } 4318 } 4319 } 4320 return null; 4321 } 4322 4323 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4324 List<ResolveInfo> query, int priority, boolean always, 4325 boolean removeMatches, boolean debug, int userId) { 4326 if (!sUserManager.exists(userId)) return null; 4327 // writer 4328 synchronized (mPackages) { 4329 if (intent.getSelector() != null) { 4330 intent = intent.getSelector(); 4331 } 4332 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4333 4334 // Try to find a matching persistent preferred activity. 4335 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4336 debug, userId); 4337 4338 // If a persistent preferred activity matched, use it. 4339 if (pri != null) { 4340 return pri; 4341 } 4342 4343 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4344 // Get the list of preferred activities that handle the intent 4345 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4346 List<PreferredActivity> prefs = pir != null 4347 ? pir.queryIntent(intent, resolvedType, 4348 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4349 : null; 4350 if (prefs != null && prefs.size() > 0) { 4351 boolean changed = false; 4352 try { 4353 // First figure out how good the original match set is. 4354 // We will only allow preferred activities that came 4355 // from the same match quality. 4356 int match = 0; 4357 4358 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4359 4360 final int N = query.size(); 4361 for (int j=0; j<N; j++) { 4362 final ResolveInfo ri = query.get(j); 4363 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4364 + ": 0x" + Integer.toHexString(match)); 4365 if (ri.match > match) { 4366 match = ri.match; 4367 } 4368 } 4369 4370 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4371 + Integer.toHexString(match)); 4372 4373 match &= IntentFilter.MATCH_CATEGORY_MASK; 4374 final int M = prefs.size(); 4375 for (int i=0; i<M; i++) { 4376 final PreferredActivity pa = prefs.get(i); 4377 if (DEBUG_PREFERRED || debug) { 4378 Slog.v(TAG, "Checking PreferredActivity ds=" 4379 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4380 + "\n component=" + pa.mPref.mComponent); 4381 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4382 } 4383 if (pa.mPref.mMatch != match) { 4384 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4385 + Integer.toHexString(pa.mPref.mMatch)); 4386 continue; 4387 } 4388 // If it's not an "always" type preferred activity and that's what we're 4389 // looking for, skip it. 4390 if (always && !pa.mPref.mAlways) { 4391 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4392 continue; 4393 } 4394 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4395 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4396 if (DEBUG_PREFERRED || debug) { 4397 Slog.v(TAG, "Found preferred activity:"); 4398 if (ai != null) { 4399 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4400 } else { 4401 Slog.v(TAG, " null"); 4402 } 4403 } 4404 if (ai == null) { 4405 // This previously registered preferred activity 4406 // component is no longer known. Most likely an update 4407 // to the app was installed and in the new version this 4408 // component no longer exists. Clean it up by removing 4409 // it from the preferred activities list, and skip it. 4410 Slog.w(TAG, "Removing dangling preferred activity: " 4411 + pa.mPref.mComponent); 4412 pir.removeFilter(pa); 4413 changed = true; 4414 continue; 4415 } 4416 for (int j=0; j<N; j++) { 4417 final ResolveInfo ri = query.get(j); 4418 if (!ri.activityInfo.applicationInfo.packageName 4419 .equals(ai.applicationInfo.packageName)) { 4420 continue; 4421 } 4422 if (!ri.activityInfo.name.equals(ai.name)) { 4423 continue; 4424 } 4425 4426 if (removeMatches) { 4427 pir.removeFilter(pa); 4428 changed = true; 4429 if (DEBUG_PREFERRED) { 4430 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4431 } 4432 break; 4433 } 4434 4435 // Okay we found a previously set preferred or last chosen app. 4436 // If the result set is different from when this 4437 // was created, we need to clear it and re-ask the 4438 // user their preference, if we're looking for an "always" type entry. 4439 if (always && !pa.mPref.sameSet(query)) { 4440 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4441 + intent + " type " + resolvedType); 4442 if (DEBUG_PREFERRED) { 4443 Slog.v(TAG, "Removing preferred activity since set changed " 4444 + pa.mPref.mComponent); 4445 } 4446 pir.removeFilter(pa); 4447 // Re-add the filter as a "last chosen" entry (!always) 4448 PreferredActivity lastChosen = new PreferredActivity( 4449 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4450 pir.addFilter(lastChosen); 4451 changed = true; 4452 return null; 4453 } 4454 4455 // Yay! Either the set matched or we're looking for the last chosen 4456 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4457 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4458 return ri; 4459 } 4460 } 4461 } finally { 4462 if (changed) { 4463 if (DEBUG_PREFERRED) { 4464 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4465 } 4466 scheduleWritePackageRestrictionsLocked(userId); 4467 } 4468 } 4469 } 4470 } 4471 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4472 return null; 4473 } 4474 4475 /* 4476 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4477 */ 4478 @Override 4479 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4480 int targetUserId) { 4481 mContext.enforceCallingOrSelfPermission( 4482 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4483 List<CrossProfileIntentFilter> matches = 4484 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4485 if (matches != null) { 4486 int size = matches.size(); 4487 for (int i = 0; i < size; i++) { 4488 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4489 } 4490 } 4491 if (hasWebURI(intent)) { 4492 // cross-profile app linking works only towards the parent. 4493 final UserInfo parent = getProfileParent(sourceUserId); 4494 synchronized(mPackages) { 4495 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4496 intent, resolvedType, 0, sourceUserId, parent.id); 4497 return xpDomainInfo != null; 4498 } 4499 } 4500 return false; 4501 } 4502 4503 private UserInfo getProfileParent(int userId) { 4504 final long identity = Binder.clearCallingIdentity(); 4505 try { 4506 return sUserManager.getProfileParent(userId); 4507 } finally { 4508 Binder.restoreCallingIdentity(identity); 4509 } 4510 } 4511 4512 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4513 String resolvedType, int userId) { 4514 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4515 if (resolver != null) { 4516 return resolver.queryIntent(intent, resolvedType, false, userId); 4517 } 4518 return null; 4519 } 4520 4521 @Override 4522 public List<ResolveInfo> queryIntentActivities(Intent intent, 4523 String resolvedType, int flags, int userId) { 4524 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4525 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4526 ComponentName comp = intent.getComponent(); 4527 if (comp == null) { 4528 if (intent.getSelector() != null) { 4529 intent = intent.getSelector(); 4530 comp = intent.getComponent(); 4531 } 4532 } 4533 4534 if (comp != null) { 4535 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4536 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4537 if (ai != null) { 4538 final ResolveInfo ri = new ResolveInfo(); 4539 ri.activityInfo = ai; 4540 list.add(ri); 4541 } 4542 return list; 4543 } 4544 4545 // reader 4546 synchronized (mPackages) { 4547 final String pkgName = intent.getPackage(); 4548 if (pkgName == null) { 4549 List<CrossProfileIntentFilter> matchingFilters = 4550 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4551 // Check for results that need to skip the current profile. 4552 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4553 resolvedType, flags, userId); 4554 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4555 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4556 result.add(xpResolveInfo); 4557 return filterIfNotPrimaryUser(result, userId); 4558 } 4559 4560 // Check for results in the current profile. 4561 List<ResolveInfo> result = mActivities.queryIntent( 4562 intent, resolvedType, flags, userId); 4563 4564 // Check for cross profile results. 4565 xpResolveInfo = queryCrossProfileIntents( 4566 matchingFilters, intent, resolvedType, flags, userId); 4567 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4568 result.add(xpResolveInfo); 4569 Collections.sort(result, mResolvePrioritySorter); 4570 } 4571 result = filterIfNotPrimaryUser(result, userId); 4572 if (hasWebURI(intent)) { 4573 CrossProfileDomainInfo xpDomainInfo = null; 4574 final UserInfo parent = getProfileParent(userId); 4575 if (parent != null) { 4576 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4577 flags, userId, parent.id); 4578 } 4579 if (xpDomainInfo != null) { 4580 if (xpResolveInfo != null) { 4581 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4582 // in the result. 4583 result.remove(xpResolveInfo); 4584 } 4585 if (result.size() == 0) { 4586 result.add(xpDomainInfo.resolveInfo); 4587 return result; 4588 } 4589 } else if (result.size() <= 1) { 4590 return result; 4591 } 4592 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4593 xpDomainInfo, userId); 4594 Collections.sort(result, mResolvePrioritySorter); 4595 } 4596 return result; 4597 } 4598 final PackageParser.Package pkg = mPackages.get(pkgName); 4599 if (pkg != null) { 4600 return filterIfNotPrimaryUser( 4601 mActivities.queryIntentForPackage( 4602 intent, resolvedType, flags, pkg.activities, userId), 4603 userId); 4604 } 4605 return new ArrayList<ResolveInfo>(); 4606 } 4607 } 4608 4609 private static class CrossProfileDomainInfo { 4610 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4611 ResolveInfo resolveInfo; 4612 /* Best domain verification status of the activities found in the other profile */ 4613 int bestDomainVerificationStatus; 4614 } 4615 4616 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4617 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4618 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4619 sourceUserId)) { 4620 return null; 4621 } 4622 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4623 resolvedType, flags, parentUserId); 4624 4625 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4626 return null; 4627 } 4628 CrossProfileDomainInfo result = null; 4629 int size = resultTargetUser.size(); 4630 for (int i = 0; i < size; i++) { 4631 ResolveInfo riTargetUser = resultTargetUser.get(i); 4632 // Intent filter verification is only for filters that specify a host. So don't return 4633 // those that handle all web uris. 4634 if (riTargetUser.handleAllWebDataURI) { 4635 continue; 4636 } 4637 String packageName = riTargetUser.activityInfo.packageName; 4638 PackageSetting ps = mSettings.mPackages.get(packageName); 4639 if (ps == null) { 4640 continue; 4641 } 4642 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4643 int status = (int)(verificationState >> 32); 4644 if (result == null) { 4645 result = new CrossProfileDomainInfo(); 4646 result.resolveInfo = 4647 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4648 result.bestDomainVerificationStatus = status; 4649 } else { 4650 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4651 result.bestDomainVerificationStatus); 4652 } 4653 } 4654 // Don't consider matches with status NEVER across profiles. 4655 if (result != null && result.bestDomainVerificationStatus 4656 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4657 return null; 4658 } 4659 return result; 4660 } 4661 4662 /** 4663 * Verification statuses are ordered from the worse to the best, except for 4664 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4665 */ 4666 private int bestDomainVerificationStatus(int status1, int status2) { 4667 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4668 return status2; 4669 } 4670 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4671 return status1; 4672 } 4673 return (int) MathUtils.max(status1, status2); 4674 } 4675 4676 private boolean isUserEnabled(int userId) { 4677 long callingId = Binder.clearCallingIdentity(); 4678 try { 4679 UserInfo userInfo = sUserManager.getUserInfo(userId); 4680 return userInfo != null && userInfo.isEnabled(); 4681 } finally { 4682 Binder.restoreCallingIdentity(callingId); 4683 } 4684 } 4685 4686 /** 4687 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4688 * 4689 * @return filtered list 4690 */ 4691 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4692 if (userId == UserHandle.USER_OWNER) { 4693 return resolveInfos; 4694 } 4695 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4696 ResolveInfo info = resolveInfos.get(i); 4697 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4698 resolveInfos.remove(i); 4699 } 4700 } 4701 return resolveInfos; 4702 } 4703 4704 private static boolean hasWebURI(Intent intent) { 4705 if (intent.getData() == null) { 4706 return false; 4707 } 4708 final String scheme = intent.getScheme(); 4709 if (TextUtils.isEmpty(scheme)) { 4710 return false; 4711 } 4712 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4713 } 4714 4715 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4716 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4717 int userId) { 4718 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4719 4720 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4721 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4722 candidates.size()); 4723 } 4724 4725 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4726 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4727 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4728 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4729 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4730 4731 synchronized (mPackages) { 4732 final int count = candidates.size(); 4733 // First, try to use linked apps. Partition the candidates into four lists: 4734 // one for the final results, one for the "do not use ever", one for "undefined status" 4735 // and finally one for "browser app type". 4736 for (int n=0; n<count; n++) { 4737 ResolveInfo info = candidates.get(n); 4738 String packageName = info.activityInfo.packageName; 4739 PackageSetting ps = mSettings.mPackages.get(packageName); 4740 if (ps != null) { 4741 // Add to the special match all list (Browser use case) 4742 if (info.handleAllWebDataURI) { 4743 matchAllList.add(info); 4744 continue; 4745 } 4746 // Try to get the status from User settings first 4747 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4748 int status = (int)(packedStatus >> 32); 4749 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4750 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4751 if (DEBUG_DOMAIN_VERIFICATION) { 4752 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4753 + " : linkgen=" + linkGeneration); 4754 } 4755 // Use link-enabled generation as preferredOrder, i.e. 4756 // prefer newly-enabled over earlier-enabled. 4757 info.preferredOrder = linkGeneration; 4758 alwaysList.add(info); 4759 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4760 if (DEBUG_DOMAIN_VERIFICATION) { 4761 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4762 } 4763 neverList.add(info); 4764 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4765 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4766 if (DEBUG_DOMAIN_VERIFICATION) { 4767 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4768 } 4769 undefinedList.add(info); 4770 } 4771 } 4772 } 4773 // First try to add the "always" resolution(s) for the current user, if any 4774 if (alwaysList.size() > 0) { 4775 result.addAll(alwaysList); 4776 // if there is an "always" for the parent user, add it. 4777 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4778 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4779 result.add(xpDomainInfo.resolveInfo); 4780 } else { 4781 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4782 result.addAll(undefinedList); 4783 if (xpDomainInfo != null && ( 4784 xpDomainInfo.bestDomainVerificationStatus 4785 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4786 || xpDomainInfo.bestDomainVerificationStatus 4787 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4788 result.add(xpDomainInfo.resolveInfo); 4789 } 4790 // Also add Browsers (all of them or only the default one) 4791 if ((matchFlags & MATCH_ALL) != 0) { 4792 result.addAll(matchAllList); 4793 } else { 4794 // Browser/generic handling case. If there's a default browser, go straight 4795 // to that (but only if there is no other higher-priority match). 4796 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4797 int maxMatchPrio = 0; 4798 ResolveInfo defaultBrowserMatch = null; 4799 final int numCandidates = matchAllList.size(); 4800 for (int n = 0; n < numCandidates; n++) { 4801 ResolveInfo info = matchAllList.get(n); 4802 // track the highest overall match priority... 4803 if (info.priority > maxMatchPrio) { 4804 maxMatchPrio = info.priority; 4805 } 4806 // ...and the highest-priority default browser match 4807 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4808 if (defaultBrowserMatch == null 4809 || (defaultBrowserMatch.priority < info.priority)) { 4810 if (debug) { 4811 Slog.v(TAG, "Considering default browser match " + info); 4812 } 4813 defaultBrowserMatch = info; 4814 } 4815 } 4816 } 4817 if (defaultBrowserMatch != null 4818 && defaultBrowserMatch.priority >= maxMatchPrio 4819 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4820 { 4821 if (debug) { 4822 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4823 } 4824 result.add(defaultBrowserMatch); 4825 } else { 4826 result.addAll(matchAllList); 4827 } 4828 } 4829 4830 // If there is nothing selected, add all candidates and remove the ones that the user 4831 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4832 if (result.size() == 0) { 4833 result.addAll(candidates); 4834 result.removeAll(neverList); 4835 } 4836 } 4837 } 4838 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4839 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4840 result.size()); 4841 for (ResolveInfo info : result) { 4842 Slog.v(TAG, " + " + info.activityInfo); 4843 } 4844 } 4845 return result; 4846 } 4847 4848 // Returns a packed value as a long: 4849 // 4850 // high 'int'-sized word: link status: undefined/ask/never/always. 4851 // low 'int'-sized word: relative priority among 'always' results. 4852 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4853 long result = ps.getDomainVerificationStatusForUser(userId); 4854 // if none available, get the master status 4855 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4856 if (ps.getIntentFilterVerificationInfo() != null) { 4857 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4858 } 4859 } 4860 return result; 4861 } 4862 4863 private ResolveInfo querySkipCurrentProfileIntents( 4864 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4865 int flags, int sourceUserId) { 4866 if (matchingFilters != null) { 4867 int size = matchingFilters.size(); 4868 for (int i = 0; i < size; i ++) { 4869 CrossProfileIntentFilter filter = matchingFilters.get(i); 4870 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4871 // Checking if there are activities in the target user that can handle the 4872 // intent. 4873 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4874 flags, sourceUserId); 4875 if (resolveInfo != null) { 4876 return resolveInfo; 4877 } 4878 } 4879 } 4880 } 4881 return null; 4882 } 4883 4884 // Return matching ResolveInfo if any for skip current profile intent filters. 4885 private ResolveInfo queryCrossProfileIntents( 4886 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4887 int flags, int sourceUserId) { 4888 if (matchingFilters != null) { 4889 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4890 // match the same intent. For performance reasons, it is better not to 4891 // run queryIntent twice for the same userId 4892 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4893 int size = matchingFilters.size(); 4894 for (int i = 0; i < size; i++) { 4895 CrossProfileIntentFilter filter = matchingFilters.get(i); 4896 int targetUserId = filter.getTargetUserId(); 4897 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4898 && !alreadyTriedUserIds.get(targetUserId)) { 4899 // Checking if there are activities in the target user that can handle the 4900 // intent. 4901 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4902 flags, sourceUserId); 4903 if (resolveInfo != null) return resolveInfo; 4904 alreadyTriedUserIds.put(targetUserId, true); 4905 } 4906 } 4907 } 4908 return null; 4909 } 4910 4911 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4912 String resolvedType, int flags, int sourceUserId) { 4913 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4914 resolvedType, flags, filter.getTargetUserId()); 4915 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4916 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4917 } 4918 return null; 4919 } 4920 4921 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4922 int sourceUserId, int targetUserId) { 4923 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4924 String className; 4925 if (targetUserId == UserHandle.USER_OWNER) { 4926 className = FORWARD_INTENT_TO_USER_OWNER; 4927 } else { 4928 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4929 } 4930 ComponentName forwardingActivityComponentName = new ComponentName( 4931 mAndroidApplication.packageName, className); 4932 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4933 sourceUserId); 4934 if (targetUserId == UserHandle.USER_OWNER) { 4935 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4936 forwardingResolveInfo.noResourceId = true; 4937 } 4938 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4939 forwardingResolveInfo.priority = 0; 4940 forwardingResolveInfo.preferredOrder = 0; 4941 forwardingResolveInfo.match = 0; 4942 forwardingResolveInfo.isDefault = true; 4943 forwardingResolveInfo.filter = filter; 4944 forwardingResolveInfo.targetUserId = targetUserId; 4945 return forwardingResolveInfo; 4946 } 4947 4948 @Override 4949 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4950 Intent[] specifics, String[] specificTypes, Intent intent, 4951 String resolvedType, int flags, int userId) { 4952 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4953 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4954 false, "query intent activity options"); 4955 final String resultsAction = intent.getAction(); 4956 4957 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4958 | PackageManager.GET_RESOLVED_FILTER, userId); 4959 4960 if (DEBUG_INTENT_MATCHING) { 4961 Log.v(TAG, "Query " + intent + ": " + results); 4962 } 4963 4964 int specificsPos = 0; 4965 int N; 4966 4967 // todo: note that the algorithm used here is O(N^2). This 4968 // isn't a problem in our current environment, but if we start running 4969 // into situations where we have more than 5 or 10 matches then this 4970 // should probably be changed to something smarter... 4971 4972 // First we go through and resolve each of the specific items 4973 // that were supplied, taking care of removing any corresponding 4974 // duplicate items in the generic resolve list. 4975 if (specifics != null) { 4976 for (int i=0; i<specifics.length; i++) { 4977 final Intent sintent = specifics[i]; 4978 if (sintent == null) { 4979 continue; 4980 } 4981 4982 if (DEBUG_INTENT_MATCHING) { 4983 Log.v(TAG, "Specific #" + i + ": " + sintent); 4984 } 4985 4986 String action = sintent.getAction(); 4987 if (resultsAction != null && resultsAction.equals(action)) { 4988 // If this action was explicitly requested, then don't 4989 // remove things that have it. 4990 action = null; 4991 } 4992 4993 ResolveInfo ri = null; 4994 ActivityInfo ai = null; 4995 4996 ComponentName comp = sintent.getComponent(); 4997 if (comp == null) { 4998 ri = resolveIntent( 4999 sintent, 5000 specificTypes != null ? specificTypes[i] : null, 5001 flags, userId); 5002 if (ri == null) { 5003 continue; 5004 } 5005 if (ri == mResolveInfo) { 5006 // ACK! Must do something better with this. 5007 } 5008 ai = ri.activityInfo; 5009 comp = new ComponentName(ai.applicationInfo.packageName, 5010 ai.name); 5011 } else { 5012 ai = getActivityInfo(comp, flags, userId); 5013 if (ai == null) { 5014 continue; 5015 } 5016 } 5017 5018 // Look for any generic query activities that are duplicates 5019 // of this specific one, and remove them from the results. 5020 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5021 N = results.size(); 5022 int j; 5023 for (j=specificsPos; j<N; j++) { 5024 ResolveInfo sri = results.get(j); 5025 if ((sri.activityInfo.name.equals(comp.getClassName()) 5026 && sri.activityInfo.applicationInfo.packageName.equals( 5027 comp.getPackageName())) 5028 || (action != null && sri.filter.matchAction(action))) { 5029 results.remove(j); 5030 if (DEBUG_INTENT_MATCHING) Log.v( 5031 TAG, "Removing duplicate item from " + j 5032 + " due to specific " + specificsPos); 5033 if (ri == null) { 5034 ri = sri; 5035 } 5036 j--; 5037 N--; 5038 } 5039 } 5040 5041 // Add this specific item to its proper place. 5042 if (ri == null) { 5043 ri = new ResolveInfo(); 5044 ri.activityInfo = ai; 5045 } 5046 results.add(specificsPos, ri); 5047 ri.specificIndex = i; 5048 specificsPos++; 5049 } 5050 } 5051 5052 // Now we go through the remaining generic results and remove any 5053 // duplicate actions that are found here. 5054 N = results.size(); 5055 for (int i=specificsPos; i<N-1; i++) { 5056 final ResolveInfo rii = results.get(i); 5057 if (rii.filter == null) { 5058 continue; 5059 } 5060 5061 // Iterate over all of the actions of this result's intent 5062 // filter... typically this should be just one. 5063 final Iterator<String> it = rii.filter.actionsIterator(); 5064 if (it == null) { 5065 continue; 5066 } 5067 while (it.hasNext()) { 5068 final String action = it.next(); 5069 if (resultsAction != null && resultsAction.equals(action)) { 5070 // If this action was explicitly requested, then don't 5071 // remove things that have it. 5072 continue; 5073 } 5074 for (int j=i+1; j<N; j++) { 5075 final ResolveInfo rij = results.get(j); 5076 if (rij.filter != null && rij.filter.hasAction(action)) { 5077 results.remove(j); 5078 if (DEBUG_INTENT_MATCHING) Log.v( 5079 TAG, "Removing duplicate item from " + j 5080 + " due to action " + action + " at " + i); 5081 j--; 5082 N--; 5083 } 5084 } 5085 } 5086 5087 // If the caller didn't request filter information, drop it now 5088 // so we don't have to marshall/unmarshall it. 5089 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5090 rii.filter = null; 5091 } 5092 } 5093 5094 // Filter out the caller activity if so requested. 5095 if (caller != null) { 5096 N = results.size(); 5097 for (int i=0; i<N; i++) { 5098 ActivityInfo ainfo = results.get(i).activityInfo; 5099 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5100 && caller.getClassName().equals(ainfo.name)) { 5101 results.remove(i); 5102 break; 5103 } 5104 } 5105 } 5106 5107 // If the caller didn't request filter information, 5108 // drop them now so we don't have to 5109 // marshall/unmarshall it. 5110 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5111 N = results.size(); 5112 for (int i=0; i<N; i++) { 5113 results.get(i).filter = null; 5114 } 5115 } 5116 5117 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5118 return results; 5119 } 5120 5121 @Override 5122 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5123 int userId) { 5124 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5125 ComponentName comp = intent.getComponent(); 5126 if (comp == null) { 5127 if (intent.getSelector() != null) { 5128 intent = intent.getSelector(); 5129 comp = intent.getComponent(); 5130 } 5131 } 5132 if (comp != null) { 5133 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5134 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5135 if (ai != null) { 5136 ResolveInfo ri = new ResolveInfo(); 5137 ri.activityInfo = ai; 5138 list.add(ri); 5139 } 5140 return list; 5141 } 5142 5143 // reader 5144 synchronized (mPackages) { 5145 String pkgName = intent.getPackage(); 5146 if (pkgName == null) { 5147 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5148 } 5149 final PackageParser.Package pkg = mPackages.get(pkgName); 5150 if (pkg != null) { 5151 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5152 userId); 5153 } 5154 return null; 5155 } 5156 } 5157 5158 @Override 5159 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5160 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5161 if (!sUserManager.exists(userId)) return null; 5162 if (query != null) { 5163 if (query.size() >= 1) { 5164 // If there is more than one service with the same priority, 5165 // just arbitrarily pick the first one. 5166 return query.get(0); 5167 } 5168 } 5169 return null; 5170 } 5171 5172 @Override 5173 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5174 int userId) { 5175 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5176 ComponentName comp = intent.getComponent(); 5177 if (comp == null) { 5178 if (intent.getSelector() != null) { 5179 intent = intent.getSelector(); 5180 comp = intent.getComponent(); 5181 } 5182 } 5183 if (comp != null) { 5184 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5185 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5186 if (si != null) { 5187 final ResolveInfo ri = new ResolveInfo(); 5188 ri.serviceInfo = si; 5189 list.add(ri); 5190 } 5191 return list; 5192 } 5193 5194 // reader 5195 synchronized (mPackages) { 5196 String pkgName = intent.getPackage(); 5197 if (pkgName == null) { 5198 return mServices.queryIntent(intent, resolvedType, flags, userId); 5199 } 5200 final PackageParser.Package pkg = mPackages.get(pkgName); 5201 if (pkg != null) { 5202 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5203 userId); 5204 } 5205 return null; 5206 } 5207 } 5208 5209 @Override 5210 public List<ResolveInfo> queryIntentContentProviders( 5211 Intent intent, String resolvedType, int flags, int userId) { 5212 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5213 ComponentName comp = intent.getComponent(); 5214 if (comp == null) { 5215 if (intent.getSelector() != null) { 5216 intent = intent.getSelector(); 5217 comp = intent.getComponent(); 5218 } 5219 } 5220 if (comp != null) { 5221 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5222 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5223 if (pi != null) { 5224 final ResolveInfo ri = new ResolveInfo(); 5225 ri.providerInfo = pi; 5226 list.add(ri); 5227 } 5228 return list; 5229 } 5230 5231 // reader 5232 synchronized (mPackages) { 5233 String pkgName = intent.getPackage(); 5234 if (pkgName == null) { 5235 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5236 } 5237 final PackageParser.Package pkg = mPackages.get(pkgName); 5238 if (pkg != null) { 5239 return mProviders.queryIntentForPackage( 5240 intent, resolvedType, flags, pkg.providers, userId); 5241 } 5242 return null; 5243 } 5244 } 5245 5246 @Override 5247 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5248 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5249 5250 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5251 5252 // writer 5253 synchronized (mPackages) { 5254 ArrayList<PackageInfo> list; 5255 if (listUninstalled) { 5256 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5257 for (PackageSetting ps : mSettings.mPackages.values()) { 5258 PackageInfo pi; 5259 if (ps.pkg != null) { 5260 pi = generatePackageInfo(ps.pkg, flags, userId); 5261 } else { 5262 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5263 } 5264 if (pi != null) { 5265 list.add(pi); 5266 } 5267 } 5268 } else { 5269 list = new ArrayList<PackageInfo>(mPackages.size()); 5270 for (PackageParser.Package p : mPackages.values()) { 5271 PackageInfo pi = generatePackageInfo(p, flags, userId); 5272 if (pi != null) { 5273 list.add(pi); 5274 } 5275 } 5276 } 5277 5278 return new ParceledListSlice<PackageInfo>(list); 5279 } 5280 } 5281 5282 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5283 String[] permissions, boolean[] tmp, int flags, int userId) { 5284 int numMatch = 0; 5285 final PermissionsState permissionsState = ps.getPermissionsState(); 5286 for (int i=0; i<permissions.length; i++) { 5287 final String permission = permissions[i]; 5288 if (permissionsState.hasPermission(permission, userId)) { 5289 tmp[i] = true; 5290 numMatch++; 5291 } else { 5292 tmp[i] = false; 5293 } 5294 } 5295 if (numMatch == 0) { 5296 return; 5297 } 5298 PackageInfo pi; 5299 if (ps.pkg != null) { 5300 pi = generatePackageInfo(ps.pkg, flags, userId); 5301 } else { 5302 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5303 } 5304 // The above might return null in cases of uninstalled apps or install-state 5305 // skew across users/profiles. 5306 if (pi != null) { 5307 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5308 if (numMatch == permissions.length) { 5309 pi.requestedPermissions = permissions; 5310 } else { 5311 pi.requestedPermissions = new String[numMatch]; 5312 numMatch = 0; 5313 for (int i=0; i<permissions.length; i++) { 5314 if (tmp[i]) { 5315 pi.requestedPermissions[numMatch] = permissions[i]; 5316 numMatch++; 5317 } 5318 } 5319 } 5320 } 5321 list.add(pi); 5322 } 5323 } 5324 5325 @Override 5326 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5327 String[] permissions, int flags, int userId) { 5328 if (!sUserManager.exists(userId)) return null; 5329 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5330 5331 // writer 5332 synchronized (mPackages) { 5333 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5334 boolean[] tmpBools = new boolean[permissions.length]; 5335 if (listUninstalled) { 5336 for (PackageSetting ps : mSettings.mPackages.values()) { 5337 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5338 } 5339 } else { 5340 for (PackageParser.Package pkg : mPackages.values()) { 5341 PackageSetting ps = (PackageSetting)pkg.mExtras; 5342 if (ps != null) { 5343 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5344 userId); 5345 } 5346 } 5347 } 5348 5349 return new ParceledListSlice<PackageInfo>(list); 5350 } 5351 } 5352 5353 @Override 5354 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5355 if (!sUserManager.exists(userId)) return null; 5356 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5357 5358 // writer 5359 synchronized (mPackages) { 5360 ArrayList<ApplicationInfo> list; 5361 if (listUninstalled) { 5362 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5363 for (PackageSetting ps : mSettings.mPackages.values()) { 5364 ApplicationInfo ai; 5365 if (ps.pkg != null) { 5366 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5367 ps.readUserState(userId), userId); 5368 } else { 5369 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5370 } 5371 if (ai != null) { 5372 list.add(ai); 5373 } 5374 } 5375 } else { 5376 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5377 for (PackageParser.Package p : mPackages.values()) { 5378 if (p.mExtras != null) { 5379 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5380 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5381 if (ai != null) { 5382 list.add(ai); 5383 } 5384 } 5385 } 5386 } 5387 5388 return new ParceledListSlice<ApplicationInfo>(list); 5389 } 5390 } 5391 5392 public List<ApplicationInfo> getPersistentApplications(int flags) { 5393 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5394 5395 // reader 5396 synchronized (mPackages) { 5397 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5398 final int userId = UserHandle.getCallingUserId(); 5399 while (i.hasNext()) { 5400 final PackageParser.Package p = i.next(); 5401 if (p.applicationInfo != null 5402 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5403 && (!mSafeMode || isSystemApp(p))) { 5404 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5405 if (ps != null) { 5406 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5407 ps.readUserState(userId), userId); 5408 if (ai != null) { 5409 finalList.add(ai); 5410 } 5411 } 5412 } 5413 } 5414 } 5415 5416 return finalList; 5417 } 5418 5419 @Override 5420 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5421 if (!sUserManager.exists(userId)) return null; 5422 // reader 5423 synchronized (mPackages) { 5424 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5425 PackageSetting ps = provider != null 5426 ? mSettings.mPackages.get(provider.owner.packageName) 5427 : null; 5428 return ps != null 5429 && mSettings.isEnabledLPr(provider.info, flags, userId) 5430 && (!mSafeMode || (provider.info.applicationInfo.flags 5431 &ApplicationInfo.FLAG_SYSTEM) != 0) 5432 ? PackageParser.generateProviderInfo(provider, flags, 5433 ps.readUserState(userId), userId) 5434 : null; 5435 } 5436 } 5437 5438 /** 5439 * @deprecated 5440 */ 5441 @Deprecated 5442 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5443 // reader 5444 synchronized (mPackages) { 5445 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5446 .entrySet().iterator(); 5447 final int userId = UserHandle.getCallingUserId(); 5448 while (i.hasNext()) { 5449 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5450 PackageParser.Provider p = entry.getValue(); 5451 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5452 5453 if (ps != null && p.syncable 5454 && (!mSafeMode || (p.info.applicationInfo.flags 5455 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5456 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5457 ps.readUserState(userId), userId); 5458 if (info != null) { 5459 outNames.add(entry.getKey()); 5460 outInfo.add(info); 5461 } 5462 } 5463 } 5464 } 5465 } 5466 5467 @Override 5468 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5469 int uid, int flags) { 5470 ArrayList<ProviderInfo> finalList = null; 5471 // reader 5472 synchronized (mPackages) { 5473 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5474 final int userId = processName != null ? 5475 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5476 while (i.hasNext()) { 5477 final PackageParser.Provider p = i.next(); 5478 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5479 if (ps != null && p.info.authority != null 5480 && (processName == null 5481 || (p.info.processName.equals(processName) 5482 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5483 && mSettings.isEnabledLPr(p.info, flags, userId) 5484 && (!mSafeMode 5485 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5486 if (finalList == null) { 5487 finalList = new ArrayList<ProviderInfo>(3); 5488 } 5489 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5490 ps.readUserState(userId), userId); 5491 if (info != null) { 5492 finalList.add(info); 5493 } 5494 } 5495 } 5496 } 5497 5498 if (finalList != null) { 5499 Collections.sort(finalList, mProviderInitOrderSorter); 5500 return new ParceledListSlice<ProviderInfo>(finalList); 5501 } 5502 5503 return null; 5504 } 5505 5506 @Override 5507 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5508 int flags) { 5509 // reader 5510 synchronized (mPackages) { 5511 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5512 return PackageParser.generateInstrumentationInfo(i, flags); 5513 } 5514 } 5515 5516 @Override 5517 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5518 int flags) { 5519 ArrayList<InstrumentationInfo> finalList = 5520 new ArrayList<InstrumentationInfo>(); 5521 5522 // reader 5523 synchronized (mPackages) { 5524 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5525 while (i.hasNext()) { 5526 final PackageParser.Instrumentation p = i.next(); 5527 if (targetPackage == null 5528 || targetPackage.equals(p.info.targetPackage)) { 5529 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5530 flags); 5531 if (ii != null) { 5532 finalList.add(ii); 5533 } 5534 } 5535 } 5536 } 5537 5538 return finalList; 5539 } 5540 5541 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5542 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5543 if (overlays == null) { 5544 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5545 return; 5546 } 5547 for (PackageParser.Package opkg : overlays.values()) { 5548 // Not much to do if idmap fails: we already logged the error 5549 // and we certainly don't want to abort installation of pkg simply 5550 // because an overlay didn't fit properly. For these reasons, 5551 // ignore the return value of createIdmapForPackagePairLI. 5552 createIdmapForPackagePairLI(pkg, opkg); 5553 } 5554 } 5555 5556 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5557 PackageParser.Package opkg) { 5558 if (!opkg.mTrustedOverlay) { 5559 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5560 opkg.baseCodePath + ": overlay not trusted"); 5561 return false; 5562 } 5563 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5564 if (overlaySet == null) { 5565 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5566 opkg.baseCodePath + " but target package has no known overlays"); 5567 return false; 5568 } 5569 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5570 // TODO: generate idmap for split APKs 5571 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5572 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5573 + opkg.baseCodePath); 5574 return false; 5575 } 5576 PackageParser.Package[] overlayArray = 5577 overlaySet.values().toArray(new PackageParser.Package[0]); 5578 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5579 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5580 return p1.mOverlayPriority - p2.mOverlayPriority; 5581 } 5582 }; 5583 Arrays.sort(overlayArray, cmp); 5584 5585 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5586 int i = 0; 5587 for (PackageParser.Package p : overlayArray) { 5588 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5589 } 5590 return true; 5591 } 5592 5593 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5594 final File[] files = dir.listFiles(); 5595 if (ArrayUtils.isEmpty(files)) { 5596 Log.d(TAG, "No files in app dir " + dir); 5597 return; 5598 } 5599 5600 if (DEBUG_PACKAGE_SCANNING) { 5601 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5602 + " flags=0x" + Integer.toHexString(parseFlags)); 5603 } 5604 5605 for (File file : files) { 5606 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5607 && !PackageInstallerService.isStageName(file.getName()); 5608 if (!isPackage) { 5609 // Ignore entries which are not packages 5610 continue; 5611 } 5612 try { 5613 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5614 scanFlags, currentTime, null); 5615 } catch (PackageManagerException e) { 5616 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5617 5618 // Delete invalid userdata apps 5619 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5620 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5621 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5622 if (file.isDirectory()) { 5623 mInstaller.rmPackageDir(file.getAbsolutePath()); 5624 } else { 5625 file.delete(); 5626 } 5627 } 5628 } 5629 } 5630 } 5631 5632 private static File getSettingsProblemFile() { 5633 File dataDir = Environment.getDataDirectory(); 5634 File systemDir = new File(dataDir, "system"); 5635 File fname = new File(systemDir, "uiderrors.txt"); 5636 return fname; 5637 } 5638 5639 static void reportSettingsProblem(int priority, String msg) { 5640 logCriticalInfo(priority, msg); 5641 } 5642 5643 static void logCriticalInfo(int priority, String msg) { 5644 Slog.println(priority, TAG, msg); 5645 EventLogTags.writePmCriticalInfo(msg); 5646 try { 5647 File fname = getSettingsProblemFile(); 5648 FileOutputStream out = new FileOutputStream(fname, true); 5649 PrintWriter pw = new FastPrintWriter(out); 5650 SimpleDateFormat formatter = new SimpleDateFormat(); 5651 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5652 pw.println(dateString + ": " + msg); 5653 pw.close(); 5654 FileUtils.setPermissions( 5655 fname.toString(), 5656 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5657 -1, -1); 5658 } catch (java.io.IOException e) { 5659 } 5660 } 5661 5662 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5663 PackageParser.Package pkg, File srcFile, int parseFlags) 5664 throws PackageManagerException { 5665 if (ps != null 5666 && ps.codePath.equals(srcFile) 5667 && ps.timeStamp == srcFile.lastModified() 5668 && !isCompatSignatureUpdateNeeded(pkg) 5669 && !isRecoverSignatureUpdateNeeded(pkg)) { 5670 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5671 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5672 ArraySet<PublicKey> signingKs; 5673 synchronized (mPackages) { 5674 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5675 } 5676 if (ps.signatures.mSignatures != null 5677 && ps.signatures.mSignatures.length != 0 5678 && signingKs != null) { 5679 // Optimization: reuse the existing cached certificates 5680 // if the package appears to be unchanged. 5681 pkg.mSignatures = ps.signatures.mSignatures; 5682 pkg.mSigningKeys = signingKs; 5683 return; 5684 } 5685 5686 Slog.w(TAG, "PackageSetting for " + ps.name 5687 + " is missing signatures. Collecting certs again to recover them."); 5688 } else { 5689 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5690 } 5691 5692 try { 5693 pp.collectCertificates(pkg, parseFlags); 5694 pp.collectManifestDigest(pkg); 5695 } catch (PackageParserException e) { 5696 throw PackageManagerException.from(e); 5697 } 5698 } 5699 5700 /** 5701 * Traces a package scan. 5702 * @see #scanPackageLI(File, int, int, long, UserHandle) 5703 */ 5704 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5705 long currentTime, UserHandle user) throws PackageManagerException { 5706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5707 try { 5708 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5709 } finally { 5710 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5711 } 5712 } 5713 5714 /** 5715 * Scans a package and returns the newly parsed package. 5716 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5717 */ 5718 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5719 long currentTime, UserHandle user) throws PackageManagerException { 5720 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5721 parseFlags |= mDefParseFlags; 5722 PackageParser pp = new PackageParser(); 5723 pp.setSeparateProcesses(mSeparateProcesses); 5724 pp.setOnlyCoreApps(mOnlyCore); 5725 pp.setDisplayMetrics(mMetrics); 5726 5727 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5728 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5729 } 5730 5731 final PackageParser.Package pkg; 5732 try { 5733 pkg = pp.parsePackage(scanFile, parseFlags); 5734 } catch (PackageParserException e) { 5735 throw PackageManagerException.from(e); 5736 } 5737 5738 PackageSetting ps = null; 5739 PackageSetting updatedPkg; 5740 // reader 5741 synchronized (mPackages) { 5742 // Look to see if we already know about this package. 5743 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5744 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5745 // This package has been renamed to its original name. Let's 5746 // use that. 5747 ps = mSettings.peekPackageLPr(oldName); 5748 } 5749 // If there was no original package, see one for the real package name. 5750 if (ps == null) { 5751 ps = mSettings.peekPackageLPr(pkg.packageName); 5752 } 5753 // Check to see if this package could be hiding/updating a system 5754 // package. Must look for it either under the original or real 5755 // package name depending on our state. 5756 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5757 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5758 } 5759 boolean updatedPkgBetter = false; 5760 // First check if this is a system package that may involve an update 5761 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5762 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5763 // it needs to drop FLAG_PRIVILEGED. 5764 if (locationIsPrivileged(scanFile)) { 5765 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5766 } else { 5767 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5768 } 5769 5770 if (ps != null && !ps.codePath.equals(scanFile)) { 5771 // The path has changed from what was last scanned... check the 5772 // version of the new path against what we have stored to determine 5773 // what to do. 5774 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5775 if (pkg.mVersionCode <= ps.versionCode) { 5776 // The system package has been updated and the code path does not match 5777 // Ignore entry. Skip it. 5778 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5779 + " ignored: updated version " + ps.versionCode 5780 + " better than this " + pkg.mVersionCode); 5781 if (!updatedPkg.codePath.equals(scanFile)) { 5782 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5783 + ps.name + " changing from " + updatedPkg.codePathString 5784 + " to " + scanFile); 5785 updatedPkg.codePath = scanFile; 5786 updatedPkg.codePathString = scanFile.toString(); 5787 updatedPkg.resourcePath = scanFile; 5788 updatedPkg.resourcePathString = scanFile.toString(); 5789 } 5790 updatedPkg.pkg = pkg; 5791 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5792 "Package " + ps.name + " at " + scanFile 5793 + " ignored: updated version " + ps.versionCode 5794 + " better than this " + pkg.mVersionCode); 5795 } else { 5796 // The current app on the system partition is better than 5797 // what we have updated to on the data partition; switch 5798 // back to the system partition version. 5799 // At this point, its safely assumed that package installation for 5800 // apps in system partition will go through. If not there won't be a working 5801 // version of the app 5802 // writer 5803 synchronized (mPackages) { 5804 // Just remove the loaded entries from package lists. 5805 mPackages.remove(ps.name); 5806 } 5807 5808 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5809 + " reverting from " + ps.codePathString 5810 + ": new version " + pkg.mVersionCode 5811 + " better than installed " + ps.versionCode); 5812 5813 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5814 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5815 synchronized (mInstallLock) { 5816 args.cleanUpResourcesLI(); 5817 } 5818 synchronized (mPackages) { 5819 mSettings.enableSystemPackageLPw(ps.name); 5820 } 5821 updatedPkgBetter = true; 5822 } 5823 } 5824 } 5825 5826 if (updatedPkg != null) { 5827 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5828 // initially 5829 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5830 5831 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5832 // flag set initially 5833 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5834 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5835 } 5836 } 5837 5838 // Verify certificates against what was last scanned 5839 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5840 5841 /* 5842 * A new system app appeared, but we already had a non-system one of the 5843 * same name installed earlier. 5844 */ 5845 boolean shouldHideSystemApp = false; 5846 if (updatedPkg == null && ps != null 5847 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5848 /* 5849 * Check to make sure the signatures match first. If they don't, 5850 * wipe the installed application and its data. 5851 */ 5852 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5853 != PackageManager.SIGNATURE_MATCH) { 5854 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5855 + " signatures don't match existing userdata copy; removing"); 5856 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5857 ps = null; 5858 } else { 5859 /* 5860 * If the newly-added system app is an older version than the 5861 * already installed version, hide it. It will be scanned later 5862 * and re-added like an update. 5863 */ 5864 if (pkg.mVersionCode <= ps.versionCode) { 5865 shouldHideSystemApp = true; 5866 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5867 + " but new version " + pkg.mVersionCode + " better than installed " 5868 + ps.versionCode + "; hiding system"); 5869 } else { 5870 /* 5871 * The newly found system app is a newer version that the 5872 * one previously installed. Simply remove the 5873 * already-installed application and replace it with our own 5874 * while keeping the application data. 5875 */ 5876 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5877 + " reverting from " + ps.codePathString + ": new version " 5878 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5879 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5880 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5881 synchronized (mInstallLock) { 5882 args.cleanUpResourcesLI(); 5883 } 5884 } 5885 } 5886 } 5887 5888 // The apk is forward locked (not public) if its code and resources 5889 // are kept in different files. (except for app in either system or 5890 // vendor path). 5891 // TODO grab this value from PackageSettings 5892 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5893 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5894 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5895 } 5896 } 5897 5898 // TODO: extend to support forward-locked splits 5899 String resourcePath = null; 5900 String baseResourcePath = null; 5901 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5902 if (ps != null && ps.resourcePathString != null) { 5903 resourcePath = ps.resourcePathString; 5904 baseResourcePath = ps.resourcePathString; 5905 } else { 5906 // Should not happen at all. Just log an error. 5907 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5908 } 5909 } else { 5910 resourcePath = pkg.codePath; 5911 baseResourcePath = pkg.baseCodePath; 5912 } 5913 5914 // Set application objects path explicitly. 5915 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5916 pkg.applicationInfo.setCodePath(pkg.codePath); 5917 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5918 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5919 pkg.applicationInfo.setResourcePath(resourcePath); 5920 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5921 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5922 5923 // Note that we invoke the following method only if we are about to unpack an application 5924 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5925 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5926 5927 /* 5928 * If the system app should be overridden by a previously installed 5929 * data, hide the system app now and let the /data/app scan pick it up 5930 * again. 5931 */ 5932 if (shouldHideSystemApp) { 5933 synchronized (mPackages) { 5934 /* 5935 * We have to grant systems permissions before we hide, because 5936 * grantPermissions will assume the package update is trying to 5937 * expand its permissions. 5938 */ 5939 grantPermissionsLPw(pkg, true, pkg.packageName); 5940 mSettings.disableSystemPackageLPw(pkg.packageName); 5941 } 5942 } 5943 5944 return scannedPkg; 5945 } 5946 5947 private static String fixProcessName(String defProcessName, 5948 String processName, int uid) { 5949 if (processName == null) { 5950 return defProcessName; 5951 } 5952 return processName; 5953 } 5954 5955 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5956 throws PackageManagerException { 5957 if (pkgSetting.signatures.mSignatures != null) { 5958 // Already existing package. Make sure signatures match 5959 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5960 == PackageManager.SIGNATURE_MATCH; 5961 if (!match) { 5962 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5963 == PackageManager.SIGNATURE_MATCH; 5964 } 5965 if (!match) { 5966 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5967 == PackageManager.SIGNATURE_MATCH; 5968 } 5969 if (!match) { 5970 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5971 + pkg.packageName + " signatures do not match the " 5972 + "previously installed version; ignoring!"); 5973 } 5974 } 5975 5976 // Check for shared user signatures 5977 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5978 // Already existing package. Make sure signatures match 5979 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5980 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5981 if (!match) { 5982 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5983 == PackageManager.SIGNATURE_MATCH; 5984 } 5985 if (!match) { 5986 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5987 == PackageManager.SIGNATURE_MATCH; 5988 } 5989 if (!match) { 5990 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5991 "Package " + pkg.packageName 5992 + " has no signatures that match those in shared user " 5993 + pkgSetting.sharedUser.name + "; ignoring!"); 5994 } 5995 } 5996 } 5997 5998 /** 5999 * Enforces that only the system UID or root's UID can call a method exposed 6000 * via Binder. 6001 * 6002 * @param message used as message if SecurityException is thrown 6003 * @throws SecurityException if the caller is not system or root 6004 */ 6005 private static final void enforceSystemOrRoot(String message) { 6006 final int uid = Binder.getCallingUid(); 6007 if (uid != Process.SYSTEM_UID && uid != 0) { 6008 throw new SecurityException(message); 6009 } 6010 } 6011 6012 @Override 6013 public void performBootDexOpt() { 6014 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6015 6016 // Before everything else, see whether we need to fstrim. 6017 try { 6018 IMountService ms = PackageHelper.getMountService(); 6019 if (ms != null) { 6020 final boolean isUpgrade = isUpgrade(); 6021 boolean doTrim = isUpgrade; 6022 if (doTrim) { 6023 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6024 } else { 6025 final long interval = android.provider.Settings.Global.getLong( 6026 mContext.getContentResolver(), 6027 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6028 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6029 if (interval > 0) { 6030 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6031 if (timeSinceLast > interval) { 6032 doTrim = true; 6033 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6034 + "; running immediately"); 6035 } 6036 } 6037 } 6038 if (doTrim) { 6039 if (!isFirstBoot()) { 6040 try { 6041 ActivityManagerNative.getDefault().showBootMessage( 6042 mContext.getResources().getString( 6043 R.string.android_upgrading_fstrim), true); 6044 } catch (RemoteException e) { 6045 } 6046 } 6047 ms.runMaintenance(); 6048 } 6049 } else { 6050 Slog.e(TAG, "Mount service unavailable!"); 6051 } 6052 } catch (RemoteException e) { 6053 // Can't happen; MountService is local 6054 } 6055 6056 final ArraySet<PackageParser.Package> pkgs; 6057 synchronized (mPackages) { 6058 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6059 } 6060 6061 if (pkgs != null) { 6062 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6063 // in case the device runs out of space. 6064 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6065 // Give priority to core apps. 6066 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6067 PackageParser.Package pkg = it.next(); 6068 if (pkg.coreApp) { 6069 if (DEBUG_DEXOPT) { 6070 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6071 } 6072 sortedPkgs.add(pkg); 6073 it.remove(); 6074 } 6075 } 6076 // Give priority to system apps that listen for pre boot complete. 6077 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6078 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6079 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6080 PackageParser.Package pkg = it.next(); 6081 if (pkgNames.contains(pkg.packageName)) { 6082 if (DEBUG_DEXOPT) { 6083 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6084 } 6085 sortedPkgs.add(pkg); 6086 it.remove(); 6087 } 6088 } 6089 // Give priority to system apps. 6090 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6091 PackageParser.Package pkg = it.next(); 6092 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6093 if (DEBUG_DEXOPT) { 6094 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6095 } 6096 sortedPkgs.add(pkg); 6097 it.remove(); 6098 } 6099 } 6100 // Give priority to updated system apps. 6101 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6102 PackageParser.Package pkg = it.next(); 6103 if (pkg.isUpdatedSystemApp()) { 6104 if (DEBUG_DEXOPT) { 6105 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6106 } 6107 sortedPkgs.add(pkg); 6108 it.remove(); 6109 } 6110 } 6111 // Give priority to apps that listen for boot complete. 6112 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6113 pkgNames = getPackageNamesForIntent(intent); 6114 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6115 PackageParser.Package pkg = it.next(); 6116 if (pkgNames.contains(pkg.packageName)) { 6117 if (DEBUG_DEXOPT) { 6118 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6119 } 6120 sortedPkgs.add(pkg); 6121 it.remove(); 6122 } 6123 } 6124 // Filter out packages that aren't recently used. 6125 filterRecentlyUsedApps(pkgs); 6126 // Add all remaining apps. 6127 for (PackageParser.Package pkg : pkgs) { 6128 if (DEBUG_DEXOPT) { 6129 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6130 } 6131 sortedPkgs.add(pkg); 6132 } 6133 6134 // If we want to be lazy, filter everything that wasn't recently used. 6135 if (mLazyDexOpt) { 6136 filterRecentlyUsedApps(sortedPkgs); 6137 } 6138 6139 int i = 0; 6140 int total = sortedPkgs.size(); 6141 File dataDir = Environment.getDataDirectory(); 6142 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6143 if (lowThreshold == 0) { 6144 throw new IllegalStateException("Invalid low memory threshold"); 6145 } 6146 for (PackageParser.Package pkg : sortedPkgs) { 6147 long usableSpace = dataDir.getUsableSpace(); 6148 if (usableSpace < lowThreshold) { 6149 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6150 break; 6151 } 6152 performBootDexOpt(pkg, ++i, total); 6153 } 6154 } 6155 } 6156 6157 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6158 // Filter out packages that aren't recently used. 6159 // 6160 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6161 // should do a full dexopt. 6162 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6163 int total = pkgs.size(); 6164 int skipped = 0; 6165 long now = System.currentTimeMillis(); 6166 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6167 PackageParser.Package pkg = i.next(); 6168 long then = pkg.mLastPackageUsageTimeInMills; 6169 if (then + mDexOptLRUThresholdInMills < now) { 6170 if (DEBUG_DEXOPT) { 6171 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6172 ((then == 0) ? "never" : new Date(then))); 6173 } 6174 i.remove(); 6175 skipped++; 6176 } 6177 } 6178 if (DEBUG_DEXOPT) { 6179 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6180 } 6181 } 6182 } 6183 6184 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6185 List<ResolveInfo> ris = null; 6186 try { 6187 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6188 intent, null, 0, UserHandle.USER_OWNER); 6189 } catch (RemoteException e) { 6190 } 6191 ArraySet<String> pkgNames = new ArraySet<String>(); 6192 if (ris != null) { 6193 for (ResolveInfo ri : ris) { 6194 pkgNames.add(ri.activityInfo.packageName); 6195 } 6196 } 6197 return pkgNames; 6198 } 6199 6200 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6201 if (DEBUG_DEXOPT) { 6202 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6203 } 6204 if (!isFirstBoot()) { 6205 try { 6206 ActivityManagerNative.getDefault().showBootMessage( 6207 mContext.getResources().getString(R.string.android_upgrading_apk, 6208 curr, total), true); 6209 } catch (RemoteException e) { 6210 } 6211 } 6212 PackageParser.Package p = pkg; 6213 synchronized (mInstallLock) { 6214 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6215 false /* force dex */, false /* defer */, true /* include dependencies */); 6216 } 6217 } 6218 6219 @Override 6220 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6221 return performDexOpt(packageName, instructionSet, false); 6222 } 6223 6224 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6225 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6226 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6227 if (!dexopt && !updateUsage) { 6228 // We aren't going to dexopt or update usage, so bail early. 6229 return false; 6230 } 6231 PackageParser.Package p; 6232 final String targetInstructionSet; 6233 synchronized (mPackages) { 6234 p = mPackages.get(packageName); 6235 if (p == null) { 6236 return false; 6237 } 6238 if (updateUsage) { 6239 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6240 } 6241 mPackageUsage.write(false); 6242 if (!dexopt) { 6243 // We aren't going to dexopt, so bail early. 6244 return false; 6245 } 6246 6247 targetInstructionSet = instructionSet != null ? instructionSet : 6248 getPrimaryInstructionSet(p.applicationInfo); 6249 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6250 return false; 6251 } 6252 } 6253 long callingId = Binder.clearCallingIdentity(); 6254 try { 6255 synchronized (mInstallLock) { 6256 final String[] instructionSets = new String[] { targetInstructionSet }; 6257 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6258 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6259 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6260 } 6261 } finally { 6262 Binder.restoreCallingIdentity(callingId); 6263 } 6264 } 6265 6266 public ArraySet<String> getPackagesThatNeedDexOpt() { 6267 ArraySet<String> pkgs = null; 6268 synchronized (mPackages) { 6269 for (PackageParser.Package p : mPackages.values()) { 6270 if (DEBUG_DEXOPT) { 6271 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6272 } 6273 if (!p.mDexOptPerformed.isEmpty()) { 6274 continue; 6275 } 6276 if (pkgs == null) { 6277 pkgs = new ArraySet<String>(); 6278 } 6279 pkgs.add(p.packageName); 6280 } 6281 } 6282 return pkgs; 6283 } 6284 6285 public void shutdown() { 6286 mPackageUsage.write(true); 6287 } 6288 6289 @Override 6290 public void forceDexOpt(String packageName) { 6291 enforceSystemOrRoot("forceDexOpt"); 6292 6293 PackageParser.Package pkg; 6294 synchronized (mPackages) { 6295 pkg = mPackages.get(packageName); 6296 if (pkg == null) { 6297 throw new IllegalArgumentException("Missing package: " + packageName); 6298 } 6299 } 6300 6301 synchronized (mInstallLock) { 6302 final String[] instructionSets = new String[] { 6303 getPrimaryInstructionSet(pkg.applicationInfo) }; 6304 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6305 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6306 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6307 throw new IllegalStateException("Failed to dexopt: " + res); 6308 } 6309 } 6310 } 6311 6312 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6313 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6314 Slog.w(TAG, "Unable to update from " + oldPkg.name 6315 + " to " + newPkg.packageName 6316 + ": old package not in system partition"); 6317 return false; 6318 } else if (mPackages.get(oldPkg.name) != null) { 6319 Slog.w(TAG, "Unable to update from " + oldPkg.name 6320 + " to " + newPkg.packageName 6321 + ": old package still exists"); 6322 return false; 6323 } 6324 return true; 6325 } 6326 6327 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6328 int[] users = sUserManager.getUserIds(); 6329 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6330 if (res < 0) { 6331 return res; 6332 } 6333 for (int user : users) { 6334 if (user != 0) { 6335 res = mInstaller.createUserData(volumeUuid, packageName, 6336 UserHandle.getUid(user, uid), user, seinfo); 6337 if (res < 0) { 6338 return res; 6339 } 6340 } 6341 } 6342 return res; 6343 } 6344 6345 private int removeDataDirsLI(String volumeUuid, String packageName) { 6346 int[] users = sUserManager.getUserIds(); 6347 int res = 0; 6348 for (int user : users) { 6349 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6350 if (resInner < 0) { 6351 res = resInner; 6352 } 6353 } 6354 6355 return res; 6356 } 6357 6358 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6359 int[] users = sUserManager.getUserIds(); 6360 int res = 0; 6361 for (int user : users) { 6362 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6363 if (resInner < 0) { 6364 res = resInner; 6365 } 6366 } 6367 return res; 6368 } 6369 6370 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6371 PackageParser.Package changingLib) { 6372 if (file.path != null) { 6373 usesLibraryFiles.add(file.path); 6374 return; 6375 } 6376 PackageParser.Package p = mPackages.get(file.apk); 6377 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6378 // If we are doing this while in the middle of updating a library apk, 6379 // then we need to make sure to use that new apk for determining the 6380 // dependencies here. (We haven't yet finished committing the new apk 6381 // to the package manager state.) 6382 if (p == null || p.packageName.equals(changingLib.packageName)) { 6383 p = changingLib; 6384 } 6385 } 6386 if (p != null) { 6387 usesLibraryFiles.addAll(p.getAllCodePaths()); 6388 } 6389 } 6390 6391 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6392 PackageParser.Package changingLib) throws PackageManagerException { 6393 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6394 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6395 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6396 for (int i=0; i<N; i++) { 6397 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6398 if (file == null) { 6399 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6400 "Package " + pkg.packageName + " requires unavailable shared library " 6401 + pkg.usesLibraries.get(i) + "; failing!"); 6402 } 6403 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6404 } 6405 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6406 for (int i=0; i<N; i++) { 6407 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6408 if (file == null) { 6409 Slog.w(TAG, "Package " + pkg.packageName 6410 + " desires unavailable shared library " 6411 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6412 } else { 6413 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6414 } 6415 } 6416 N = usesLibraryFiles.size(); 6417 if (N > 0) { 6418 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6419 } else { 6420 pkg.usesLibraryFiles = null; 6421 } 6422 } 6423 } 6424 6425 private static boolean hasString(List<String> list, List<String> which) { 6426 if (list == null) { 6427 return false; 6428 } 6429 for (int i=list.size()-1; i>=0; i--) { 6430 for (int j=which.size()-1; j>=0; j--) { 6431 if (which.get(j).equals(list.get(i))) { 6432 return true; 6433 } 6434 } 6435 } 6436 return false; 6437 } 6438 6439 private void updateAllSharedLibrariesLPw() { 6440 for (PackageParser.Package pkg : mPackages.values()) { 6441 try { 6442 updateSharedLibrariesLPw(pkg, null); 6443 } catch (PackageManagerException e) { 6444 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6445 } 6446 } 6447 } 6448 6449 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6450 PackageParser.Package changingPkg) { 6451 ArrayList<PackageParser.Package> res = null; 6452 for (PackageParser.Package pkg : mPackages.values()) { 6453 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6454 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6455 if (res == null) { 6456 res = new ArrayList<PackageParser.Package>(); 6457 } 6458 res.add(pkg); 6459 try { 6460 updateSharedLibrariesLPw(pkg, changingPkg); 6461 } catch (PackageManagerException e) { 6462 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6463 } 6464 } 6465 } 6466 return res; 6467 } 6468 6469 /** 6470 * Derive the value of the {@code cpuAbiOverride} based on the provided 6471 * value and an optional stored value from the package settings. 6472 */ 6473 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6474 String cpuAbiOverride = null; 6475 6476 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6477 cpuAbiOverride = null; 6478 } else if (abiOverride != null) { 6479 cpuAbiOverride = abiOverride; 6480 } else if (settings != null) { 6481 cpuAbiOverride = settings.cpuAbiOverrideString; 6482 } 6483 6484 return cpuAbiOverride; 6485 } 6486 6487 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6488 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6489 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6490 try { 6491 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6492 } finally { 6493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6494 } 6495 } 6496 6497 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6498 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6499 boolean success = false; 6500 try { 6501 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6502 currentTime, user); 6503 success = true; 6504 return res; 6505 } finally { 6506 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6507 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6508 } 6509 } 6510 } 6511 6512 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6513 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6514 final File scanFile = new File(pkg.codePath); 6515 if (pkg.applicationInfo.getCodePath() == null || 6516 pkg.applicationInfo.getResourcePath() == null) { 6517 // Bail out. The resource and code paths haven't been set. 6518 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6519 "Code and resource paths haven't been set correctly"); 6520 } 6521 6522 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6523 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6524 } else { 6525 // Only allow system apps to be flagged as core apps. 6526 pkg.coreApp = false; 6527 } 6528 6529 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6530 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6531 } 6532 6533 if (mCustomResolverComponentName != null && 6534 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6535 setUpCustomResolverActivity(pkg); 6536 } 6537 6538 if (pkg.packageName.equals("android")) { 6539 synchronized (mPackages) { 6540 if (mAndroidApplication != null) { 6541 Slog.w(TAG, "*************************************************"); 6542 Slog.w(TAG, "Core android package being redefined. Skipping."); 6543 Slog.w(TAG, " file=" + scanFile); 6544 Slog.w(TAG, "*************************************************"); 6545 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6546 "Core android package being redefined. Skipping."); 6547 } 6548 6549 // Set up information for our fall-back user intent resolution activity. 6550 mPlatformPackage = pkg; 6551 pkg.mVersionCode = mSdkVersion; 6552 mAndroidApplication = pkg.applicationInfo; 6553 6554 if (!mResolverReplaced) { 6555 mResolveActivity.applicationInfo = mAndroidApplication; 6556 mResolveActivity.name = ResolverActivity.class.getName(); 6557 mResolveActivity.packageName = mAndroidApplication.packageName; 6558 mResolveActivity.processName = "system:ui"; 6559 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6560 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6561 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6562 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6563 mResolveActivity.exported = true; 6564 mResolveActivity.enabled = true; 6565 mResolveInfo.activityInfo = mResolveActivity; 6566 mResolveInfo.priority = 0; 6567 mResolveInfo.preferredOrder = 0; 6568 mResolveInfo.match = 0; 6569 mResolveComponentName = new ComponentName( 6570 mAndroidApplication.packageName, mResolveActivity.name); 6571 } 6572 } 6573 } 6574 6575 if (DEBUG_PACKAGE_SCANNING) { 6576 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6577 Log.d(TAG, "Scanning package " + pkg.packageName); 6578 } 6579 6580 if (mPackages.containsKey(pkg.packageName) 6581 || mSharedLibraries.containsKey(pkg.packageName)) { 6582 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6583 "Application package " + pkg.packageName 6584 + " already installed. Skipping duplicate."); 6585 } 6586 6587 // If we're only installing presumed-existing packages, require that the 6588 // scanned APK is both already known and at the path previously established 6589 // for it. Previously unknown packages we pick up normally, but if we have an 6590 // a priori expectation about this package's install presence, enforce it. 6591 // With a singular exception for new system packages. When an OTA contains 6592 // a new system package, we allow the codepath to change from a system location 6593 // to the user-installed location. If we don't allow this change, any newer, 6594 // user-installed version of the application will be ignored. 6595 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6596 if (mExpectingBetter.containsKey(pkg.packageName)) { 6597 logCriticalInfo(Log.WARN, 6598 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6599 } else { 6600 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6601 if (known != null) { 6602 if (DEBUG_PACKAGE_SCANNING) { 6603 Log.d(TAG, "Examining " + pkg.codePath 6604 + " and requiring known paths " + known.codePathString 6605 + " & " + known.resourcePathString); 6606 } 6607 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6608 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6609 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6610 "Application package " + pkg.packageName 6611 + " found at " + pkg.applicationInfo.getCodePath() 6612 + " but expected at " + known.codePathString + "; ignoring."); 6613 } 6614 } 6615 } 6616 } 6617 6618 // Initialize package source and resource directories 6619 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6620 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6621 6622 SharedUserSetting suid = null; 6623 PackageSetting pkgSetting = null; 6624 6625 if (!isSystemApp(pkg)) { 6626 // Only system apps can use these features. 6627 pkg.mOriginalPackages = null; 6628 pkg.mRealPackage = null; 6629 pkg.mAdoptPermissions = null; 6630 } 6631 6632 // writer 6633 synchronized (mPackages) { 6634 if (pkg.mSharedUserId != null) { 6635 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6636 if (suid == null) { 6637 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6638 "Creating application package " + pkg.packageName 6639 + " for shared user failed"); 6640 } 6641 if (DEBUG_PACKAGE_SCANNING) { 6642 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6643 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6644 + "): packages=" + suid.packages); 6645 } 6646 } 6647 6648 // Check if we are renaming from an original package name. 6649 PackageSetting origPackage = null; 6650 String realName = null; 6651 if (pkg.mOriginalPackages != null) { 6652 // This package may need to be renamed to a previously 6653 // installed name. Let's check on that... 6654 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6655 if (pkg.mOriginalPackages.contains(renamed)) { 6656 // This package had originally been installed as the 6657 // original name, and we have already taken care of 6658 // transitioning to the new one. Just update the new 6659 // one to continue using the old name. 6660 realName = pkg.mRealPackage; 6661 if (!pkg.packageName.equals(renamed)) { 6662 // Callers into this function may have already taken 6663 // care of renaming the package; only do it here if 6664 // it is not already done. 6665 pkg.setPackageName(renamed); 6666 } 6667 6668 } else { 6669 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6670 if ((origPackage = mSettings.peekPackageLPr( 6671 pkg.mOriginalPackages.get(i))) != null) { 6672 // We do have the package already installed under its 6673 // original name... should we use it? 6674 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6675 // New package is not compatible with original. 6676 origPackage = null; 6677 continue; 6678 } else if (origPackage.sharedUser != null) { 6679 // Make sure uid is compatible between packages. 6680 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6681 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6682 + " to " + pkg.packageName + ": old uid " 6683 + origPackage.sharedUser.name 6684 + " differs from " + pkg.mSharedUserId); 6685 origPackage = null; 6686 continue; 6687 } 6688 } else { 6689 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6690 + pkg.packageName + " to old name " + origPackage.name); 6691 } 6692 break; 6693 } 6694 } 6695 } 6696 } 6697 6698 if (mTransferedPackages.contains(pkg.packageName)) { 6699 Slog.w(TAG, "Package " + pkg.packageName 6700 + " was transferred to another, but its .apk remains"); 6701 } 6702 6703 // Just create the setting, don't add it yet. For already existing packages 6704 // the PkgSetting exists already and doesn't have to be created. 6705 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6706 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6707 pkg.applicationInfo.primaryCpuAbi, 6708 pkg.applicationInfo.secondaryCpuAbi, 6709 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6710 user, false); 6711 if (pkgSetting == null) { 6712 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6713 "Creating application package " + pkg.packageName + " failed"); 6714 } 6715 6716 if (pkgSetting.origPackage != null) { 6717 // If we are first transitioning from an original package, 6718 // fix up the new package's name now. We need to do this after 6719 // looking up the package under its new name, so getPackageLP 6720 // can take care of fiddling things correctly. 6721 pkg.setPackageName(origPackage.name); 6722 6723 // File a report about this. 6724 String msg = "New package " + pkgSetting.realName 6725 + " renamed to replace old package " + pkgSetting.name; 6726 reportSettingsProblem(Log.WARN, msg); 6727 6728 // Make a note of it. 6729 mTransferedPackages.add(origPackage.name); 6730 6731 // No longer need to retain this. 6732 pkgSetting.origPackage = null; 6733 } 6734 6735 if (realName != null) { 6736 // Make a note of it. 6737 mTransferedPackages.add(pkg.packageName); 6738 } 6739 6740 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6741 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6742 } 6743 6744 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6745 // Check all shared libraries and map to their actual file path. 6746 // We only do this here for apps not on a system dir, because those 6747 // are the only ones that can fail an install due to this. We 6748 // will take care of the system apps by updating all of their 6749 // library paths after the scan is done. 6750 updateSharedLibrariesLPw(pkg, null); 6751 } 6752 6753 if (mFoundPolicyFile) { 6754 SELinuxMMAC.assignSeinfoValue(pkg); 6755 } 6756 6757 pkg.applicationInfo.uid = pkgSetting.appId; 6758 pkg.mExtras = pkgSetting; 6759 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6760 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6761 // We just determined the app is signed correctly, so bring 6762 // over the latest parsed certs. 6763 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6764 } else { 6765 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6766 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6767 "Package " + pkg.packageName + " upgrade keys do not match the " 6768 + "previously installed version"); 6769 } else { 6770 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6771 String msg = "System package " + pkg.packageName 6772 + " signature changed; retaining data."; 6773 reportSettingsProblem(Log.WARN, msg); 6774 } 6775 } 6776 } else { 6777 try { 6778 verifySignaturesLP(pkgSetting, pkg); 6779 // We just determined the app is signed correctly, so bring 6780 // over the latest parsed certs. 6781 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6782 } catch (PackageManagerException e) { 6783 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6784 throw e; 6785 } 6786 // The signature has changed, but this package is in the system 6787 // image... let's recover! 6788 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6789 // However... if this package is part of a shared user, but it 6790 // doesn't match the signature of the shared user, let's fail. 6791 // What this means is that you can't change the signatures 6792 // associated with an overall shared user, which doesn't seem all 6793 // that unreasonable. 6794 if (pkgSetting.sharedUser != null) { 6795 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6796 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6797 throw new PackageManagerException( 6798 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6799 "Signature mismatch for shared user : " 6800 + pkgSetting.sharedUser); 6801 } 6802 } 6803 // File a report about this. 6804 String msg = "System package " + pkg.packageName 6805 + " signature changed; retaining data."; 6806 reportSettingsProblem(Log.WARN, msg); 6807 } 6808 } 6809 // Verify that this new package doesn't have any content providers 6810 // that conflict with existing packages. Only do this if the 6811 // package isn't already installed, since we don't want to break 6812 // things that are installed. 6813 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6814 final int N = pkg.providers.size(); 6815 int i; 6816 for (i=0; i<N; i++) { 6817 PackageParser.Provider p = pkg.providers.get(i); 6818 if (p.info.authority != null) { 6819 String names[] = p.info.authority.split(";"); 6820 for (int j = 0; j < names.length; j++) { 6821 if (mProvidersByAuthority.containsKey(names[j])) { 6822 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6823 final String otherPackageName = 6824 ((other != null && other.getComponentName() != null) ? 6825 other.getComponentName().getPackageName() : "?"); 6826 throw new PackageManagerException( 6827 INSTALL_FAILED_CONFLICTING_PROVIDER, 6828 "Can't install because provider name " + names[j] 6829 + " (in package " + pkg.applicationInfo.packageName 6830 + ") is already used by " + otherPackageName); 6831 } 6832 } 6833 } 6834 } 6835 } 6836 6837 if (pkg.mAdoptPermissions != null) { 6838 // This package wants to adopt ownership of permissions from 6839 // another package. 6840 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6841 final String origName = pkg.mAdoptPermissions.get(i); 6842 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6843 if (orig != null) { 6844 if (verifyPackageUpdateLPr(orig, pkg)) { 6845 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6846 + pkg.packageName); 6847 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6848 } 6849 } 6850 } 6851 } 6852 } 6853 6854 final String pkgName = pkg.packageName; 6855 6856 final long scanFileTime = scanFile.lastModified(); 6857 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6858 pkg.applicationInfo.processName = fixProcessName( 6859 pkg.applicationInfo.packageName, 6860 pkg.applicationInfo.processName, 6861 pkg.applicationInfo.uid); 6862 6863 File dataPath; 6864 if (mPlatformPackage == pkg) { 6865 // The system package is special. 6866 dataPath = new File(Environment.getDataDirectory(), "system"); 6867 6868 pkg.applicationInfo.dataDir = dataPath.getPath(); 6869 6870 } else { 6871 // This is a normal package, need to make its data directory. 6872 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6873 UserHandle.USER_OWNER, pkg.packageName); 6874 6875 boolean uidError = false; 6876 if (dataPath.exists()) { 6877 int currentUid = 0; 6878 try { 6879 StructStat stat = Os.stat(dataPath.getPath()); 6880 currentUid = stat.st_uid; 6881 } catch (ErrnoException e) { 6882 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6883 } 6884 6885 // If we have mismatched owners for the data path, we have a problem. 6886 if (currentUid != pkg.applicationInfo.uid) { 6887 boolean recovered = false; 6888 if (currentUid == 0) { 6889 // The directory somehow became owned by root. Wow. 6890 // This is probably because the system was stopped while 6891 // installd was in the middle of messing with its libs 6892 // directory. Ask installd to fix that. 6893 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6894 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6895 if (ret >= 0) { 6896 recovered = true; 6897 String msg = "Package " + pkg.packageName 6898 + " unexpectedly changed to uid 0; recovered to " + 6899 + pkg.applicationInfo.uid; 6900 reportSettingsProblem(Log.WARN, msg); 6901 } 6902 } 6903 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6904 || (scanFlags&SCAN_BOOTING) != 0)) { 6905 // If this is a system app, we can at least delete its 6906 // current data so the application will still work. 6907 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6908 if (ret >= 0) { 6909 // TODO: Kill the processes first 6910 // Old data gone! 6911 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6912 ? "System package " : "Third party package "; 6913 String msg = prefix + pkg.packageName 6914 + " has changed from uid: " 6915 + currentUid + " to " 6916 + pkg.applicationInfo.uid + "; old data erased"; 6917 reportSettingsProblem(Log.WARN, msg); 6918 recovered = true; 6919 6920 // And now re-install the app. 6921 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6922 pkg.applicationInfo.seinfo); 6923 if (ret == -1) { 6924 // Ack should not happen! 6925 msg = prefix + pkg.packageName 6926 + " could not have data directory re-created after delete."; 6927 reportSettingsProblem(Log.WARN, msg); 6928 throw new PackageManagerException( 6929 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6930 } 6931 } 6932 if (!recovered) { 6933 mHasSystemUidErrors = true; 6934 } 6935 } else if (!recovered) { 6936 // If we allow this install to proceed, we will be broken. 6937 // Abort, abort! 6938 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6939 "scanPackageLI"); 6940 } 6941 if (!recovered) { 6942 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6943 + pkg.applicationInfo.uid + "/fs_" 6944 + currentUid; 6945 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6946 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6947 String msg = "Package " + pkg.packageName 6948 + " has mismatched uid: " 6949 + currentUid + " on disk, " 6950 + pkg.applicationInfo.uid + " in settings"; 6951 // writer 6952 synchronized (mPackages) { 6953 mSettings.mReadMessages.append(msg); 6954 mSettings.mReadMessages.append('\n'); 6955 uidError = true; 6956 if (!pkgSetting.uidError) { 6957 reportSettingsProblem(Log.ERROR, msg); 6958 } 6959 } 6960 } 6961 } 6962 pkg.applicationInfo.dataDir = dataPath.getPath(); 6963 if (mShouldRestoreconData) { 6964 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6965 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6966 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6967 } 6968 } else { 6969 if (DEBUG_PACKAGE_SCANNING) { 6970 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6971 Log.v(TAG, "Want this data dir: " + dataPath); 6972 } 6973 //invoke installer to do the actual installation 6974 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6975 pkg.applicationInfo.seinfo); 6976 if (ret < 0) { 6977 // Error from installer 6978 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6979 "Unable to create data dirs [errorCode=" + ret + "]"); 6980 } 6981 6982 if (dataPath.exists()) { 6983 pkg.applicationInfo.dataDir = dataPath.getPath(); 6984 } else { 6985 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6986 pkg.applicationInfo.dataDir = null; 6987 } 6988 } 6989 6990 pkgSetting.uidError = uidError; 6991 } 6992 6993 final String path = scanFile.getPath(); 6994 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6995 6996 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6997 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6998 6999 // Some system apps still use directory structure for native libraries 7000 // in which case we might end up not detecting abi solely based on apk 7001 // structure. Try to detect abi based on directory structure. 7002 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7003 pkg.applicationInfo.primaryCpuAbi == null) { 7004 setBundledAppAbisAndRoots(pkg, pkgSetting); 7005 setNativeLibraryPaths(pkg); 7006 } 7007 7008 } else { 7009 if ((scanFlags & SCAN_MOVE) != 0) { 7010 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7011 // but we already have this packages package info in the PackageSetting. We just 7012 // use that and derive the native library path based on the new codepath. 7013 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7014 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7015 } 7016 7017 // Set native library paths again. For moves, the path will be updated based on the 7018 // ABIs we've determined above. For non-moves, the path will be updated based on the 7019 // ABIs we determined during compilation, but the path will depend on the final 7020 // package path (after the rename away from the stage path). 7021 setNativeLibraryPaths(pkg); 7022 } 7023 7024 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7025 final int[] userIds = sUserManager.getUserIds(); 7026 synchronized (mInstallLock) { 7027 // Make sure all user data directories are ready to roll; we're okay 7028 // if they already exist 7029 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7030 for (int userId : userIds) { 7031 if (userId != 0) { 7032 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7033 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7034 pkg.applicationInfo.seinfo); 7035 } 7036 } 7037 } 7038 7039 // Create a native library symlink only if we have native libraries 7040 // and if the native libraries are 32 bit libraries. We do not provide 7041 // this symlink for 64 bit libraries. 7042 if (pkg.applicationInfo.primaryCpuAbi != null && 7043 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7044 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7045 try { 7046 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7047 for (int userId : userIds) { 7048 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7049 nativeLibPath, userId) < 0) { 7050 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7051 "Failed linking native library dir (user=" + userId + ")"); 7052 } 7053 } 7054 } finally { 7055 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7056 } 7057 } 7058 } 7059 7060 // This is a special case for the "system" package, where the ABI is 7061 // dictated by the zygote configuration (and init.rc). We should keep track 7062 // of this ABI so that we can deal with "normal" applications that run under 7063 // the same UID correctly. 7064 if (mPlatformPackage == pkg) { 7065 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7066 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7067 } 7068 7069 // If there's a mismatch between the abi-override in the package setting 7070 // and the abiOverride specified for the install. Warn about this because we 7071 // would've already compiled the app without taking the package setting into 7072 // account. 7073 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7074 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7075 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7076 " for package: " + pkg.packageName); 7077 } 7078 } 7079 7080 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7081 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7082 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7083 7084 // Copy the derived override back to the parsed package, so that we can 7085 // update the package settings accordingly. 7086 pkg.cpuAbiOverride = cpuAbiOverride; 7087 7088 if (DEBUG_ABI_SELECTION) { 7089 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7090 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7091 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7092 } 7093 7094 // Push the derived path down into PackageSettings so we know what to 7095 // clean up at uninstall time. 7096 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7097 7098 if (DEBUG_ABI_SELECTION) { 7099 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7100 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7101 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7102 } 7103 7104 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7105 // We don't do this here during boot because we can do it all 7106 // at once after scanning all existing packages. 7107 // 7108 // We also do this *before* we perform dexopt on this package, so that 7109 // we can avoid redundant dexopts, and also to make sure we've got the 7110 // code and package path correct. 7111 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7112 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7113 } 7114 7115 if ((scanFlags & SCAN_NO_DEX) == 0) { 7116 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7117 7118 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7119 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7120 7121 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7122 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7123 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7124 } 7125 } 7126 if (mFactoryTest && pkg.requestedPermissions.contains( 7127 android.Manifest.permission.FACTORY_TEST)) { 7128 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7129 } 7130 7131 ArrayList<PackageParser.Package> clientLibPkgs = null; 7132 7133 // writer 7134 synchronized (mPackages) { 7135 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7136 // Only system apps can add new shared libraries. 7137 if (pkg.libraryNames != null) { 7138 for (int i=0; i<pkg.libraryNames.size(); i++) { 7139 String name = pkg.libraryNames.get(i); 7140 boolean allowed = false; 7141 if (pkg.isUpdatedSystemApp()) { 7142 // New library entries can only be added through the 7143 // system image. This is important to get rid of a lot 7144 // of nasty edge cases: for example if we allowed a non- 7145 // system update of the app to add a library, then uninstalling 7146 // the update would make the library go away, and assumptions 7147 // we made such as through app install filtering would now 7148 // have allowed apps on the device which aren't compatible 7149 // with it. Better to just have the restriction here, be 7150 // conservative, and create many fewer cases that can negatively 7151 // impact the user experience. 7152 final PackageSetting sysPs = mSettings 7153 .getDisabledSystemPkgLPr(pkg.packageName); 7154 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7155 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7156 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7157 allowed = true; 7158 allowed = true; 7159 break; 7160 } 7161 } 7162 } 7163 } else { 7164 allowed = true; 7165 } 7166 if (allowed) { 7167 if (!mSharedLibraries.containsKey(name)) { 7168 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7169 } else if (!name.equals(pkg.packageName)) { 7170 Slog.w(TAG, "Package " + pkg.packageName + " library " 7171 + name + " already exists; skipping"); 7172 } 7173 } else { 7174 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7175 + name + " that is not declared on system image; skipping"); 7176 } 7177 } 7178 if ((scanFlags&SCAN_BOOTING) == 0) { 7179 // If we are not booting, we need to update any applications 7180 // that are clients of our shared library. If we are booting, 7181 // this will all be done once the scan is complete. 7182 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7183 } 7184 } 7185 } 7186 } 7187 7188 // We also need to dexopt any apps that are dependent on this library. Note that 7189 // if these fail, we should abort the install since installing the library will 7190 // result in some apps being broken. 7191 if (clientLibPkgs != null) { 7192 if ((scanFlags & SCAN_NO_DEX) == 0) { 7193 for (int i = 0; i < clientLibPkgs.size(); i++) { 7194 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7195 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7196 null /* instruction sets */, forceDex, 7197 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7198 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7199 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7200 "scanPackageLI failed to dexopt clientLibPkgs"); 7201 } 7202 } 7203 } 7204 } 7205 7206 // Request the ActivityManager to kill the process(only for existing packages) 7207 // so that we do not end up in a confused state while the user is still using the older 7208 // version of the application while the new one gets installed. 7209 if ((scanFlags & SCAN_REPLACING) != 0) { 7210 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7211 7212 killApplication(pkg.applicationInfo.packageName, 7213 pkg.applicationInfo.uid, "replace pkg"); 7214 7215 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7216 } 7217 7218 // Also need to kill any apps that are dependent on the library. 7219 if (clientLibPkgs != null) { 7220 for (int i=0; i<clientLibPkgs.size(); i++) { 7221 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7222 killApplication(clientPkg.applicationInfo.packageName, 7223 clientPkg.applicationInfo.uid, "update lib"); 7224 } 7225 } 7226 7227 // Make sure we're not adding any bogus keyset info 7228 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7229 ksms.assertScannedPackageValid(pkg); 7230 7231 // writer 7232 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7233 7234 boolean createIdmapFailed = false; 7235 synchronized (mPackages) { 7236 // We don't expect installation to fail beyond this point 7237 7238 // Add the new setting to mSettings 7239 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7240 // Add the new setting to mPackages 7241 mPackages.put(pkg.applicationInfo.packageName, pkg); 7242 // Make sure we don't accidentally delete its data. 7243 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7244 while (iter.hasNext()) { 7245 PackageCleanItem item = iter.next(); 7246 if (pkgName.equals(item.packageName)) { 7247 iter.remove(); 7248 } 7249 } 7250 7251 // Take care of first install / last update times. 7252 if (currentTime != 0) { 7253 if (pkgSetting.firstInstallTime == 0) { 7254 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7255 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7256 pkgSetting.lastUpdateTime = currentTime; 7257 } 7258 } else if (pkgSetting.firstInstallTime == 0) { 7259 // We need *something*. Take time time stamp of the file. 7260 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7261 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7262 if (scanFileTime != pkgSetting.timeStamp) { 7263 // A package on the system image has changed; consider this 7264 // to be an update. 7265 pkgSetting.lastUpdateTime = scanFileTime; 7266 } 7267 } 7268 7269 // Add the package's KeySets to the global KeySetManagerService 7270 ksms.addScannedPackageLPw(pkg); 7271 7272 int N = pkg.providers.size(); 7273 StringBuilder r = null; 7274 int i; 7275 for (i=0; i<N; i++) { 7276 PackageParser.Provider p = pkg.providers.get(i); 7277 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7278 p.info.processName, pkg.applicationInfo.uid); 7279 mProviders.addProvider(p); 7280 p.syncable = p.info.isSyncable; 7281 if (p.info.authority != null) { 7282 String names[] = p.info.authority.split(";"); 7283 p.info.authority = null; 7284 for (int j = 0; j < names.length; j++) { 7285 if (j == 1 && p.syncable) { 7286 // We only want the first authority for a provider to possibly be 7287 // syncable, so if we already added this provider using a different 7288 // authority clear the syncable flag. We copy the provider before 7289 // changing it because the mProviders object contains a reference 7290 // to a provider that we don't want to change. 7291 // Only do this for the second authority since the resulting provider 7292 // object can be the same for all future authorities for this provider. 7293 p = new PackageParser.Provider(p); 7294 p.syncable = false; 7295 } 7296 if (!mProvidersByAuthority.containsKey(names[j])) { 7297 mProvidersByAuthority.put(names[j], p); 7298 if (p.info.authority == null) { 7299 p.info.authority = names[j]; 7300 } else { 7301 p.info.authority = p.info.authority + ";" + names[j]; 7302 } 7303 if (DEBUG_PACKAGE_SCANNING) { 7304 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7305 Log.d(TAG, "Registered content provider: " + names[j] 7306 + ", className = " + p.info.name + ", isSyncable = " 7307 + p.info.isSyncable); 7308 } 7309 } else { 7310 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7311 Slog.w(TAG, "Skipping provider name " + names[j] + 7312 " (in package " + pkg.applicationInfo.packageName + 7313 "): name already used by " 7314 + ((other != null && other.getComponentName() != null) 7315 ? other.getComponentName().getPackageName() : "?")); 7316 } 7317 } 7318 } 7319 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7320 if (r == null) { 7321 r = new StringBuilder(256); 7322 } else { 7323 r.append(' '); 7324 } 7325 r.append(p.info.name); 7326 } 7327 } 7328 if (r != null) { 7329 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7330 } 7331 7332 N = pkg.services.size(); 7333 r = null; 7334 for (i=0; i<N; i++) { 7335 PackageParser.Service s = pkg.services.get(i); 7336 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7337 s.info.processName, pkg.applicationInfo.uid); 7338 mServices.addService(s); 7339 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7340 if (r == null) { 7341 r = new StringBuilder(256); 7342 } else { 7343 r.append(' '); 7344 } 7345 r.append(s.info.name); 7346 } 7347 } 7348 if (r != null) { 7349 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7350 } 7351 7352 N = pkg.receivers.size(); 7353 r = null; 7354 for (i=0; i<N; i++) { 7355 PackageParser.Activity a = pkg.receivers.get(i); 7356 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7357 a.info.processName, pkg.applicationInfo.uid); 7358 mReceivers.addActivity(a, "receiver"); 7359 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7360 if (r == null) { 7361 r = new StringBuilder(256); 7362 } else { 7363 r.append(' '); 7364 } 7365 r.append(a.info.name); 7366 } 7367 } 7368 if (r != null) { 7369 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7370 } 7371 7372 N = pkg.activities.size(); 7373 r = null; 7374 for (i=0; i<N; i++) { 7375 PackageParser.Activity a = pkg.activities.get(i); 7376 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7377 a.info.processName, pkg.applicationInfo.uid); 7378 mActivities.addActivity(a, "activity"); 7379 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7380 if (r == null) { 7381 r = new StringBuilder(256); 7382 } else { 7383 r.append(' '); 7384 } 7385 r.append(a.info.name); 7386 } 7387 } 7388 if (r != null) { 7389 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7390 } 7391 7392 N = pkg.permissionGroups.size(); 7393 r = null; 7394 for (i=0; i<N; i++) { 7395 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7396 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7397 if (cur == null) { 7398 mPermissionGroups.put(pg.info.name, pg); 7399 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7400 if (r == null) { 7401 r = new StringBuilder(256); 7402 } else { 7403 r.append(' '); 7404 } 7405 r.append(pg.info.name); 7406 } 7407 } else { 7408 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7409 + pg.info.packageName + " ignored: original from " 7410 + cur.info.packageName); 7411 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7412 if (r == null) { 7413 r = new StringBuilder(256); 7414 } else { 7415 r.append(' '); 7416 } 7417 r.append("DUP:"); 7418 r.append(pg.info.name); 7419 } 7420 } 7421 } 7422 if (r != null) { 7423 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7424 } 7425 7426 N = pkg.permissions.size(); 7427 r = null; 7428 for (i=0; i<N; i++) { 7429 PackageParser.Permission p = pkg.permissions.get(i); 7430 7431 // Assume by default that we did not install this permission into the system. 7432 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7433 7434 // Now that permission groups have a special meaning, we ignore permission 7435 // groups for legacy apps to prevent unexpected behavior. In particular, 7436 // permissions for one app being granted to someone just becuase they happen 7437 // to be in a group defined by another app (before this had no implications). 7438 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7439 p.group = mPermissionGroups.get(p.info.group); 7440 // Warn for a permission in an unknown group. 7441 if (p.info.group != null && p.group == null) { 7442 Slog.w(TAG, "Permission " + p.info.name + " from package " 7443 + p.info.packageName + " in an unknown group " + p.info.group); 7444 } 7445 } 7446 7447 ArrayMap<String, BasePermission> permissionMap = 7448 p.tree ? mSettings.mPermissionTrees 7449 : mSettings.mPermissions; 7450 BasePermission bp = permissionMap.get(p.info.name); 7451 7452 // Allow system apps to redefine non-system permissions 7453 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7454 final boolean currentOwnerIsSystem = (bp.perm != null 7455 && isSystemApp(bp.perm.owner)); 7456 if (isSystemApp(p.owner)) { 7457 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7458 // It's a built-in permission and no owner, take ownership now 7459 bp.packageSetting = pkgSetting; 7460 bp.perm = p; 7461 bp.uid = pkg.applicationInfo.uid; 7462 bp.sourcePackage = p.info.packageName; 7463 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7464 } else if (!currentOwnerIsSystem) { 7465 String msg = "New decl " + p.owner + " of permission " 7466 + p.info.name + " is system; overriding " + bp.sourcePackage; 7467 reportSettingsProblem(Log.WARN, msg); 7468 bp = null; 7469 } 7470 } 7471 } 7472 7473 if (bp == null) { 7474 bp = new BasePermission(p.info.name, p.info.packageName, 7475 BasePermission.TYPE_NORMAL); 7476 permissionMap.put(p.info.name, bp); 7477 } 7478 7479 if (bp.perm == null) { 7480 if (bp.sourcePackage == null 7481 || bp.sourcePackage.equals(p.info.packageName)) { 7482 BasePermission tree = findPermissionTreeLP(p.info.name); 7483 if (tree == null 7484 || tree.sourcePackage.equals(p.info.packageName)) { 7485 bp.packageSetting = pkgSetting; 7486 bp.perm = p; 7487 bp.uid = pkg.applicationInfo.uid; 7488 bp.sourcePackage = p.info.packageName; 7489 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7490 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7491 if (r == null) { 7492 r = new StringBuilder(256); 7493 } else { 7494 r.append(' '); 7495 } 7496 r.append(p.info.name); 7497 } 7498 } else { 7499 Slog.w(TAG, "Permission " + p.info.name + " from package " 7500 + p.info.packageName + " ignored: base tree " 7501 + tree.name + " is from package " 7502 + tree.sourcePackage); 7503 } 7504 } else { 7505 Slog.w(TAG, "Permission " + p.info.name + " from package " 7506 + p.info.packageName + " ignored: original from " 7507 + bp.sourcePackage); 7508 } 7509 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7510 if (r == null) { 7511 r = new StringBuilder(256); 7512 } else { 7513 r.append(' '); 7514 } 7515 r.append("DUP:"); 7516 r.append(p.info.name); 7517 } 7518 if (bp.perm == p) { 7519 bp.protectionLevel = p.info.protectionLevel; 7520 } 7521 } 7522 7523 if (r != null) { 7524 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7525 } 7526 7527 N = pkg.instrumentation.size(); 7528 r = null; 7529 for (i=0; i<N; i++) { 7530 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7531 a.info.packageName = pkg.applicationInfo.packageName; 7532 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7533 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7534 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7535 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7536 a.info.dataDir = pkg.applicationInfo.dataDir; 7537 7538 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7539 // need other information about the application, like the ABI and what not ? 7540 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7541 mInstrumentation.put(a.getComponentName(), a); 7542 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7543 if (r == null) { 7544 r = new StringBuilder(256); 7545 } else { 7546 r.append(' '); 7547 } 7548 r.append(a.info.name); 7549 } 7550 } 7551 if (r != null) { 7552 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7553 } 7554 7555 if (pkg.protectedBroadcasts != null) { 7556 N = pkg.protectedBroadcasts.size(); 7557 for (i=0; i<N; i++) { 7558 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7559 } 7560 } 7561 7562 pkgSetting.setTimeStamp(scanFileTime); 7563 7564 // Create idmap files for pairs of (packages, overlay packages). 7565 // Note: "android", ie framework-res.apk, is handled by native layers. 7566 if (pkg.mOverlayTarget != null) { 7567 // This is an overlay package. 7568 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7569 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7570 mOverlays.put(pkg.mOverlayTarget, 7571 new ArrayMap<String, PackageParser.Package>()); 7572 } 7573 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7574 map.put(pkg.packageName, pkg); 7575 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7576 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7577 createIdmapFailed = true; 7578 } 7579 } 7580 } else if (mOverlays.containsKey(pkg.packageName) && 7581 !pkg.packageName.equals("android")) { 7582 // This is a regular package, with one or more known overlay packages. 7583 createIdmapsForPackageLI(pkg); 7584 } 7585 } 7586 7587 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7588 7589 if (createIdmapFailed) { 7590 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7591 "scanPackageLI failed to createIdmap"); 7592 } 7593 return pkg; 7594 } 7595 7596 /** 7597 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7598 * is derived purely on the basis of the contents of {@code scanFile} and 7599 * {@code cpuAbiOverride}. 7600 * 7601 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7602 */ 7603 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7604 String cpuAbiOverride, boolean extractLibs) 7605 throws PackageManagerException { 7606 // TODO: We can probably be smarter about this stuff. For installed apps, 7607 // we can calculate this information at install time once and for all. For 7608 // system apps, we can probably assume that this information doesn't change 7609 // after the first boot scan. As things stand, we do lots of unnecessary work. 7610 7611 // Give ourselves some initial paths; we'll come back for another 7612 // pass once we've determined ABI below. 7613 setNativeLibraryPaths(pkg); 7614 7615 // We would never need to extract libs for forward-locked and external packages, 7616 // since the container service will do it for us. We shouldn't attempt to 7617 // extract libs from system app when it was not updated. 7618 if (pkg.isForwardLocked() || isExternal(pkg) || 7619 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7620 extractLibs = false; 7621 } 7622 7623 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7624 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7625 7626 NativeLibraryHelper.Handle handle = null; 7627 try { 7628 handle = NativeLibraryHelper.Handle.create(pkg); 7629 // TODO(multiArch): This can be null for apps that didn't go through the 7630 // usual installation process. We can calculate it again, like we 7631 // do during install time. 7632 // 7633 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7634 // unnecessary. 7635 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7636 7637 // Null out the abis so that they can be recalculated. 7638 pkg.applicationInfo.primaryCpuAbi = null; 7639 pkg.applicationInfo.secondaryCpuAbi = null; 7640 if (isMultiArch(pkg.applicationInfo)) { 7641 // Warn if we've set an abiOverride for multi-lib packages.. 7642 // By definition, we need to copy both 32 and 64 bit libraries for 7643 // such packages. 7644 if (pkg.cpuAbiOverride != null 7645 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7646 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7647 } 7648 7649 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7650 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7651 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7652 if (extractLibs) { 7653 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7654 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7655 useIsaSpecificSubdirs); 7656 } else { 7657 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7658 } 7659 } 7660 7661 maybeThrowExceptionForMultiArchCopy( 7662 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7663 7664 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7665 if (extractLibs) { 7666 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7667 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7668 useIsaSpecificSubdirs); 7669 } else { 7670 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7671 } 7672 } 7673 7674 maybeThrowExceptionForMultiArchCopy( 7675 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7676 7677 if (abi64 >= 0) { 7678 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7679 } 7680 7681 if (abi32 >= 0) { 7682 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7683 if (abi64 >= 0) { 7684 pkg.applicationInfo.secondaryCpuAbi = abi; 7685 } else { 7686 pkg.applicationInfo.primaryCpuAbi = abi; 7687 } 7688 } 7689 } else { 7690 String[] abiList = (cpuAbiOverride != null) ? 7691 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7692 7693 // Enable gross and lame hacks for apps that are built with old 7694 // SDK tools. We must scan their APKs for renderscript bitcode and 7695 // not launch them if it's present. Don't bother checking on devices 7696 // that don't have 64 bit support. 7697 boolean needsRenderScriptOverride = false; 7698 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7699 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7700 abiList = Build.SUPPORTED_32_BIT_ABIS; 7701 needsRenderScriptOverride = true; 7702 } 7703 7704 final int copyRet; 7705 if (extractLibs) { 7706 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7707 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7708 } else { 7709 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7710 } 7711 7712 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7713 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7714 "Error unpackaging native libs for app, errorCode=" + copyRet); 7715 } 7716 7717 if (copyRet >= 0) { 7718 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7719 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7720 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7721 } else if (needsRenderScriptOverride) { 7722 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7723 } 7724 } 7725 } catch (IOException ioe) { 7726 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7727 } finally { 7728 IoUtils.closeQuietly(handle); 7729 } 7730 7731 // Now that we've calculated the ABIs and determined if it's an internal app, 7732 // we will go ahead and populate the nativeLibraryPath. 7733 setNativeLibraryPaths(pkg); 7734 } 7735 7736 /** 7737 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7738 * i.e, so that all packages can be run inside a single process if required. 7739 * 7740 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7741 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7742 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7743 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7744 * updating a package that belongs to a shared user. 7745 * 7746 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7747 * adds unnecessary complexity. 7748 */ 7749 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7750 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7751 String requiredInstructionSet = null; 7752 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7753 requiredInstructionSet = VMRuntime.getInstructionSet( 7754 scannedPackage.applicationInfo.primaryCpuAbi); 7755 } 7756 7757 PackageSetting requirer = null; 7758 for (PackageSetting ps : packagesForUser) { 7759 // If packagesForUser contains scannedPackage, we skip it. This will happen 7760 // when scannedPackage is an update of an existing package. Without this check, 7761 // we will never be able to change the ABI of any package belonging to a shared 7762 // user, even if it's compatible with other packages. 7763 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7764 if (ps.primaryCpuAbiString == null) { 7765 continue; 7766 } 7767 7768 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7769 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7770 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7771 // this but there's not much we can do. 7772 String errorMessage = "Instruction set mismatch, " 7773 + ((requirer == null) ? "[caller]" : requirer) 7774 + " requires " + requiredInstructionSet + " whereas " + ps 7775 + " requires " + instructionSet; 7776 Slog.w(TAG, errorMessage); 7777 } 7778 7779 if (requiredInstructionSet == null) { 7780 requiredInstructionSet = instructionSet; 7781 requirer = ps; 7782 } 7783 } 7784 } 7785 7786 if (requiredInstructionSet != null) { 7787 String adjustedAbi; 7788 if (requirer != null) { 7789 // requirer != null implies that either scannedPackage was null or that scannedPackage 7790 // did not require an ABI, in which case we have to adjust scannedPackage to match 7791 // the ABI of the set (which is the same as requirer's ABI) 7792 adjustedAbi = requirer.primaryCpuAbiString; 7793 if (scannedPackage != null) { 7794 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7795 } 7796 } else { 7797 // requirer == null implies that we're updating all ABIs in the set to 7798 // match scannedPackage. 7799 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7800 } 7801 7802 for (PackageSetting ps : packagesForUser) { 7803 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7804 if (ps.primaryCpuAbiString != null) { 7805 continue; 7806 } 7807 7808 ps.primaryCpuAbiString = adjustedAbi; 7809 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7810 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7811 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7812 7813 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7814 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7815 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7816 ps.primaryCpuAbiString = null; 7817 ps.pkg.applicationInfo.primaryCpuAbi = null; 7818 return; 7819 } else { 7820 mInstaller.rmdex(ps.codePathString, 7821 getDexCodeInstructionSet(getPreferredInstructionSet())); 7822 } 7823 } 7824 } 7825 } 7826 } 7827 } 7828 7829 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7830 synchronized (mPackages) { 7831 mResolverReplaced = true; 7832 // Set up information for custom user intent resolution activity. 7833 mResolveActivity.applicationInfo = pkg.applicationInfo; 7834 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7835 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7836 mResolveActivity.processName = pkg.applicationInfo.packageName; 7837 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7838 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7839 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7840 mResolveActivity.theme = 0; 7841 mResolveActivity.exported = true; 7842 mResolveActivity.enabled = true; 7843 mResolveInfo.activityInfo = mResolveActivity; 7844 mResolveInfo.priority = 0; 7845 mResolveInfo.preferredOrder = 0; 7846 mResolveInfo.match = 0; 7847 mResolveComponentName = mCustomResolverComponentName; 7848 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7849 mResolveComponentName); 7850 } 7851 } 7852 7853 private static String calculateBundledApkRoot(final String codePathString) { 7854 final File codePath = new File(codePathString); 7855 final File codeRoot; 7856 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7857 codeRoot = Environment.getRootDirectory(); 7858 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7859 codeRoot = Environment.getOemDirectory(); 7860 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7861 codeRoot = Environment.getVendorDirectory(); 7862 } else { 7863 // Unrecognized code path; take its top real segment as the apk root: 7864 // e.g. /something/app/blah.apk => /something 7865 try { 7866 File f = codePath.getCanonicalFile(); 7867 File parent = f.getParentFile(); // non-null because codePath is a file 7868 File tmp; 7869 while ((tmp = parent.getParentFile()) != null) { 7870 f = parent; 7871 parent = tmp; 7872 } 7873 codeRoot = f; 7874 Slog.w(TAG, "Unrecognized code path " 7875 + codePath + " - using " + codeRoot); 7876 } catch (IOException e) { 7877 // Can't canonicalize the code path -- shenanigans? 7878 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7879 return Environment.getRootDirectory().getPath(); 7880 } 7881 } 7882 return codeRoot.getPath(); 7883 } 7884 7885 /** 7886 * Derive and set the location of native libraries for the given package, 7887 * which varies depending on where and how the package was installed. 7888 */ 7889 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7890 final ApplicationInfo info = pkg.applicationInfo; 7891 final String codePath = pkg.codePath; 7892 final File codeFile = new File(codePath); 7893 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7894 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7895 7896 info.nativeLibraryRootDir = null; 7897 info.nativeLibraryRootRequiresIsa = false; 7898 info.nativeLibraryDir = null; 7899 info.secondaryNativeLibraryDir = null; 7900 7901 if (isApkFile(codeFile)) { 7902 // Monolithic install 7903 if (bundledApp) { 7904 // If "/system/lib64/apkname" exists, assume that is the per-package 7905 // native library directory to use; otherwise use "/system/lib/apkname". 7906 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7907 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7908 getPrimaryInstructionSet(info)); 7909 7910 // This is a bundled system app so choose the path based on the ABI. 7911 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7912 // is just the default path. 7913 final String apkName = deriveCodePathName(codePath); 7914 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7915 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7916 apkName).getAbsolutePath(); 7917 7918 if (info.secondaryCpuAbi != null) { 7919 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7920 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7921 secondaryLibDir, apkName).getAbsolutePath(); 7922 } 7923 } else if (asecApp) { 7924 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7925 .getAbsolutePath(); 7926 } else { 7927 final String apkName = deriveCodePathName(codePath); 7928 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7929 .getAbsolutePath(); 7930 } 7931 7932 info.nativeLibraryRootRequiresIsa = false; 7933 info.nativeLibraryDir = info.nativeLibraryRootDir; 7934 } else { 7935 // Cluster install 7936 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7937 info.nativeLibraryRootRequiresIsa = true; 7938 7939 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7940 getPrimaryInstructionSet(info)).getAbsolutePath(); 7941 7942 if (info.secondaryCpuAbi != null) { 7943 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7944 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7945 } 7946 } 7947 } 7948 7949 /** 7950 * Calculate the abis and roots for a bundled app. These can uniquely 7951 * be determined from the contents of the system partition, i.e whether 7952 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7953 * of this information, and instead assume that the system was built 7954 * sensibly. 7955 */ 7956 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7957 PackageSetting pkgSetting) { 7958 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7959 7960 // If "/system/lib64/apkname" exists, assume that is the per-package 7961 // native library directory to use; otherwise use "/system/lib/apkname". 7962 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7963 setBundledAppAbi(pkg, apkRoot, apkName); 7964 // pkgSetting might be null during rescan following uninstall of updates 7965 // to a bundled app, so accommodate that possibility. The settings in 7966 // that case will be established later from the parsed package. 7967 // 7968 // If the settings aren't null, sync them up with what we've just derived. 7969 // note that apkRoot isn't stored in the package settings. 7970 if (pkgSetting != null) { 7971 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7972 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7973 } 7974 } 7975 7976 /** 7977 * Deduces the ABI of a bundled app and sets the relevant fields on the 7978 * parsed pkg object. 7979 * 7980 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7981 * under which system libraries are installed. 7982 * @param apkName the name of the installed package. 7983 */ 7984 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7985 final File codeFile = new File(pkg.codePath); 7986 7987 final boolean has64BitLibs; 7988 final boolean has32BitLibs; 7989 if (isApkFile(codeFile)) { 7990 // Monolithic install 7991 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7992 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7993 } else { 7994 // Cluster install 7995 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7996 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7997 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7998 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7999 has64BitLibs = (new File(rootDir, isa)).exists(); 8000 } else { 8001 has64BitLibs = false; 8002 } 8003 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8004 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8005 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8006 has32BitLibs = (new File(rootDir, isa)).exists(); 8007 } else { 8008 has32BitLibs = false; 8009 } 8010 } 8011 8012 if (has64BitLibs && !has32BitLibs) { 8013 // The package has 64 bit libs, but not 32 bit libs. Its primary 8014 // ABI should be 64 bit. We can safely assume here that the bundled 8015 // native libraries correspond to the most preferred ABI in the list. 8016 8017 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8018 pkg.applicationInfo.secondaryCpuAbi = null; 8019 } else if (has32BitLibs && !has64BitLibs) { 8020 // The package has 32 bit libs but not 64 bit libs. Its primary 8021 // ABI should be 32 bit. 8022 8023 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8024 pkg.applicationInfo.secondaryCpuAbi = null; 8025 } else if (has32BitLibs && has64BitLibs) { 8026 // The application has both 64 and 32 bit bundled libraries. We check 8027 // here that the app declares multiArch support, and warn if it doesn't. 8028 // 8029 // We will be lenient here and record both ABIs. The primary will be the 8030 // ABI that's higher on the list, i.e, a device that's configured to prefer 8031 // 64 bit apps will see a 64 bit primary ABI, 8032 8033 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8034 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8035 } 8036 8037 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8038 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8039 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8040 } else { 8041 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8042 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8043 } 8044 } else { 8045 pkg.applicationInfo.primaryCpuAbi = null; 8046 pkg.applicationInfo.secondaryCpuAbi = null; 8047 } 8048 } 8049 8050 private void killApplication(String pkgName, int appId, String reason) { 8051 // Request the ActivityManager to kill the process(only for existing packages) 8052 // so that we do not end up in a confused state while the user is still using the older 8053 // version of the application while the new one gets installed. 8054 IActivityManager am = ActivityManagerNative.getDefault(); 8055 if (am != null) { 8056 try { 8057 am.killApplicationWithAppId(pkgName, appId, reason); 8058 } catch (RemoteException e) { 8059 } 8060 } 8061 } 8062 8063 void removePackageLI(PackageSetting ps, boolean chatty) { 8064 if (DEBUG_INSTALL) { 8065 if (chatty) 8066 Log.d(TAG, "Removing package " + ps.name); 8067 } 8068 8069 // writer 8070 synchronized (mPackages) { 8071 mPackages.remove(ps.name); 8072 final PackageParser.Package pkg = ps.pkg; 8073 if (pkg != null) { 8074 cleanPackageDataStructuresLILPw(pkg, chatty); 8075 } 8076 } 8077 } 8078 8079 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8080 if (DEBUG_INSTALL) { 8081 if (chatty) 8082 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8083 } 8084 8085 // writer 8086 synchronized (mPackages) { 8087 mPackages.remove(pkg.applicationInfo.packageName); 8088 cleanPackageDataStructuresLILPw(pkg, chatty); 8089 } 8090 } 8091 8092 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8093 int N = pkg.providers.size(); 8094 StringBuilder r = null; 8095 int i; 8096 for (i=0; i<N; i++) { 8097 PackageParser.Provider p = pkg.providers.get(i); 8098 mProviders.removeProvider(p); 8099 if (p.info.authority == null) { 8100 8101 /* There was another ContentProvider with this authority when 8102 * this app was installed so this authority is null, 8103 * Ignore it as we don't have to unregister the provider. 8104 */ 8105 continue; 8106 } 8107 String names[] = p.info.authority.split(";"); 8108 for (int j = 0; j < names.length; j++) { 8109 if (mProvidersByAuthority.get(names[j]) == p) { 8110 mProvidersByAuthority.remove(names[j]); 8111 if (DEBUG_REMOVE) { 8112 if (chatty) 8113 Log.d(TAG, "Unregistered content provider: " + names[j] 8114 + ", className = " + p.info.name + ", isSyncable = " 8115 + p.info.isSyncable); 8116 } 8117 } 8118 } 8119 if (DEBUG_REMOVE && chatty) { 8120 if (r == null) { 8121 r = new StringBuilder(256); 8122 } else { 8123 r.append(' '); 8124 } 8125 r.append(p.info.name); 8126 } 8127 } 8128 if (r != null) { 8129 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8130 } 8131 8132 N = pkg.services.size(); 8133 r = null; 8134 for (i=0; i<N; i++) { 8135 PackageParser.Service s = pkg.services.get(i); 8136 mServices.removeService(s); 8137 if (chatty) { 8138 if (r == null) { 8139 r = new StringBuilder(256); 8140 } else { 8141 r.append(' '); 8142 } 8143 r.append(s.info.name); 8144 } 8145 } 8146 if (r != null) { 8147 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8148 } 8149 8150 N = pkg.receivers.size(); 8151 r = null; 8152 for (i=0; i<N; i++) { 8153 PackageParser.Activity a = pkg.receivers.get(i); 8154 mReceivers.removeActivity(a, "receiver"); 8155 if (DEBUG_REMOVE && chatty) { 8156 if (r == null) { 8157 r = new StringBuilder(256); 8158 } else { 8159 r.append(' '); 8160 } 8161 r.append(a.info.name); 8162 } 8163 } 8164 if (r != null) { 8165 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8166 } 8167 8168 N = pkg.activities.size(); 8169 r = null; 8170 for (i=0; i<N; i++) { 8171 PackageParser.Activity a = pkg.activities.get(i); 8172 mActivities.removeActivity(a, "activity"); 8173 if (DEBUG_REMOVE && chatty) { 8174 if (r == null) { 8175 r = new StringBuilder(256); 8176 } else { 8177 r.append(' '); 8178 } 8179 r.append(a.info.name); 8180 } 8181 } 8182 if (r != null) { 8183 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8184 } 8185 8186 N = pkg.permissions.size(); 8187 r = null; 8188 for (i=0; i<N; i++) { 8189 PackageParser.Permission p = pkg.permissions.get(i); 8190 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8191 if (bp == null) { 8192 bp = mSettings.mPermissionTrees.get(p.info.name); 8193 } 8194 if (bp != null && bp.perm == p) { 8195 bp.perm = null; 8196 if (DEBUG_REMOVE && chatty) { 8197 if (r == null) { 8198 r = new StringBuilder(256); 8199 } else { 8200 r.append(' '); 8201 } 8202 r.append(p.info.name); 8203 } 8204 } 8205 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8206 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8207 if (appOpPerms != null) { 8208 appOpPerms.remove(pkg.packageName); 8209 } 8210 } 8211 } 8212 if (r != null) { 8213 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8214 } 8215 8216 N = pkg.requestedPermissions.size(); 8217 r = null; 8218 for (i=0; i<N; i++) { 8219 String perm = pkg.requestedPermissions.get(i); 8220 BasePermission bp = mSettings.mPermissions.get(perm); 8221 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8222 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8223 if (appOpPerms != null) { 8224 appOpPerms.remove(pkg.packageName); 8225 if (appOpPerms.isEmpty()) { 8226 mAppOpPermissionPackages.remove(perm); 8227 } 8228 } 8229 } 8230 } 8231 if (r != null) { 8232 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8233 } 8234 8235 N = pkg.instrumentation.size(); 8236 r = null; 8237 for (i=0; i<N; i++) { 8238 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8239 mInstrumentation.remove(a.getComponentName()); 8240 if (DEBUG_REMOVE && chatty) { 8241 if (r == null) { 8242 r = new StringBuilder(256); 8243 } else { 8244 r.append(' '); 8245 } 8246 r.append(a.info.name); 8247 } 8248 } 8249 if (r != null) { 8250 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8251 } 8252 8253 r = null; 8254 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8255 // Only system apps can hold shared libraries. 8256 if (pkg.libraryNames != null) { 8257 for (i=0; i<pkg.libraryNames.size(); i++) { 8258 String name = pkg.libraryNames.get(i); 8259 SharedLibraryEntry cur = mSharedLibraries.get(name); 8260 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8261 mSharedLibraries.remove(name); 8262 if (DEBUG_REMOVE && chatty) { 8263 if (r == null) { 8264 r = new StringBuilder(256); 8265 } else { 8266 r.append(' '); 8267 } 8268 r.append(name); 8269 } 8270 } 8271 } 8272 } 8273 } 8274 if (r != null) { 8275 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8276 } 8277 } 8278 8279 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8280 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8281 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8282 return true; 8283 } 8284 } 8285 return false; 8286 } 8287 8288 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8289 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8290 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8291 8292 private void updatePermissionsLPw(String changingPkg, 8293 PackageParser.Package pkgInfo, int flags) { 8294 // Make sure there are no dangling permission trees. 8295 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8296 while (it.hasNext()) { 8297 final BasePermission bp = it.next(); 8298 if (bp.packageSetting == null) { 8299 // We may not yet have parsed the package, so just see if 8300 // we still know about its settings. 8301 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8302 } 8303 if (bp.packageSetting == null) { 8304 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8305 + " from package " + bp.sourcePackage); 8306 it.remove(); 8307 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8308 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8309 Slog.i(TAG, "Removing old permission tree: " + bp.name 8310 + " from package " + bp.sourcePackage); 8311 flags |= UPDATE_PERMISSIONS_ALL; 8312 it.remove(); 8313 } 8314 } 8315 } 8316 8317 // Make sure all dynamic permissions have been assigned to a package, 8318 // and make sure there are no dangling permissions. 8319 it = mSettings.mPermissions.values().iterator(); 8320 while (it.hasNext()) { 8321 final BasePermission bp = it.next(); 8322 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8323 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8324 + bp.name + " pkg=" + bp.sourcePackage 8325 + " info=" + bp.pendingInfo); 8326 if (bp.packageSetting == null && bp.pendingInfo != null) { 8327 final BasePermission tree = findPermissionTreeLP(bp.name); 8328 if (tree != null && tree.perm != null) { 8329 bp.packageSetting = tree.packageSetting; 8330 bp.perm = new PackageParser.Permission(tree.perm.owner, 8331 new PermissionInfo(bp.pendingInfo)); 8332 bp.perm.info.packageName = tree.perm.info.packageName; 8333 bp.perm.info.name = bp.name; 8334 bp.uid = tree.uid; 8335 } 8336 } 8337 } 8338 if (bp.packageSetting == null) { 8339 // We may not yet have parsed the package, so just see if 8340 // we still know about its settings. 8341 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8342 } 8343 if (bp.packageSetting == null) { 8344 Slog.w(TAG, "Removing dangling permission: " + bp.name 8345 + " from package " + bp.sourcePackage); 8346 it.remove(); 8347 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8348 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8349 Slog.i(TAG, "Removing old permission: " + bp.name 8350 + " from package " + bp.sourcePackage); 8351 flags |= UPDATE_PERMISSIONS_ALL; 8352 it.remove(); 8353 } 8354 } 8355 } 8356 8357 // Now update the permissions for all packages, in particular 8358 // replace the granted permissions of the system packages. 8359 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8360 for (PackageParser.Package pkg : mPackages.values()) { 8361 if (pkg != pkgInfo) { 8362 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8363 changingPkg); 8364 } 8365 } 8366 } 8367 8368 if (pkgInfo != null) { 8369 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8370 } 8371 } 8372 8373 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8374 String packageOfInterest) { 8375 // IMPORTANT: There are two types of permissions: install and runtime. 8376 // Install time permissions are granted when the app is installed to 8377 // all device users and users added in the future. Runtime permissions 8378 // are granted at runtime explicitly to specific users. Normal and signature 8379 // protected permissions are install time permissions. Dangerous permissions 8380 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8381 // otherwise they are runtime permissions. This function does not manage 8382 // runtime permissions except for the case an app targeting Lollipop MR1 8383 // being upgraded to target a newer SDK, in which case dangerous permissions 8384 // are transformed from install time to runtime ones. 8385 8386 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8387 if (ps == null) { 8388 return; 8389 } 8390 8391 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8392 8393 PermissionsState permissionsState = ps.getPermissionsState(); 8394 PermissionsState origPermissions = permissionsState; 8395 8396 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8397 8398 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8399 8400 boolean changedInstallPermission = false; 8401 8402 if (replace) { 8403 ps.installPermissionsFixed = false; 8404 if (!ps.isSharedUser()) { 8405 origPermissions = new PermissionsState(permissionsState); 8406 permissionsState.reset(); 8407 } 8408 } 8409 8410 permissionsState.setGlobalGids(mGlobalGids); 8411 8412 final int N = pkg.requestedPermissions.size(); 8413 for (int i=0; i<N; i++) { 8414 final String name = pkg.requestedPermissions.get(i); 8415 final BasePermission bp = mSettings.mPermissions.get(name); 8416 8417 if (DEBUG_INSTALL) { 8418 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8419 } 8420 8421 if (bp == null || bp.packageSetting == null) { 8422 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8423 Slog.w(TAG, "Unknown permission " + name 8424 + " in package " + pkg.packageName); 8425 } 8426 continue; 8427 } 8428 8429 final String perm = bp.name; 8430 boolean allowedSig = false; 8431 int grant = GRANT_DENIED; 8432 8433 // Keep track of app op permissions. 8434 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8435 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8436 if (pkgs == null) { 8437 pkgs = new ArraySet<>(); 8438 mAppOpPermissionPackages.put(bp.name, pkgs); 8439 } 8440 pkgs.add(pkg.packageName); 8441 } 8442 8443 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8444 switch (level) { 8445 case PermissionInfo.PROTECTION_NORMAL: { 8446 // For all apps normal permissions are install time ones. 8447 grant = GRANT_INSTALL; 8448 } break; 8449 8450 case PermissionInfo.PROTECTION_DANGEROUS: { 8451 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8452 // For legacy apps dangerous permissions are install time ones. 8453 grant = GRANT_INSTALL_LEGACY; 8454 } else if (origPermissions.hasInstallPermission(bp.name)) { 8455 // For legacy apps that became modern, install becomes runtime. 8456 grant = GRANT_UPGRADE; 8457 } else if (mPromoteSystemApps 8458 && isSystemApp(ps) 8459 && mExistingSystemPackages.contains(ps.name)) { 8460 // For legacy system apps, install becomes runtime. 8461 // We cannot check hasInstallPermission() for system apps since those 8462 // permissions were granted implicitly and not persisted pre-M. 8463 grant = GRANT_UPGRADE; 8464 } else { 8465 // For modern apps keep runtime permissions unchanged. 8466 grant = GRANT_RUNTIME; 8467 } 8468 } break; 8469 8470 case PermissionInfo.PROTECTION_SIGNATURE: { 8471 // For all apps signature permissions are install time ones. 8472 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8473 if (allowedSig) { 8474 grant = GRANT_INSTALL; 8475 } 8476 } break; 8477 } 8478 8479 if (DEBUG_INSTALL) { 8480 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8481 } 8482 8483 if (grant != GRANT_DENIED) { 8484 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8485 // If this is an existing, non-system package, then 8486 // we can't add any new permissions to it. 8487 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8488 // Except... if this is a permission that was added 8489 // to the platform (note: need to only do this when 8490 // updating the platform). 8491 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8492 grant = GRANT_DENIED; 8493 } 8494 } 8495 } 8496 8497 switch (grant) { 8498 case GRANT_INSTALL: { 8499 // Revoke this as runtime permission to handle the case of 8500 // a runtime permission being downgraded to an install one. 8501 for (int userId : UserManagerService.getInstance().getUserIds()) { 8502 if (origPermissions.getRuntimePermissionState( 8503 bp.name, userId) != null) { 8504 // Revoke the runtime permission and clear the flags. 8505 origPermissions.revokeRuntimePermission(bp, userId); 8506 origPermissions.updatePermissionFlags(bp, userId, 8507 PackageManager.MASK_PERMISSION_FLAGS, 0); 8508 // If we revoked a permission permission, we have to write. 8509 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8510 changedRuntimePermissionUserIds, userId); 8511 } 8512 } 8513 // Grant an install permission. 8514 if (permissionsState.grantInstallPermission(bp) != 8515 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8516 changedInstallPermission = true; 8517 } 8518 } break; 8519 8520 case GRANT_INSTALL_LEGACY: { 8521 // Grant an install permission. 8522 if (permissionsState.grantInstallPermission(bp) != 8523 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8524 changedInstallPermission = true; 8525 } 8526 } break; 8527 8528 case GRANT_RUNTIME: { 8529 // Grant previously granted runtime permissions. 8530 for (int userId : UserManagerService.getInstance().getUserIds()) { 8531 PermissionState permissionState = origPermissions 8532 .getRuntimePermissionState(bp.name, userId); 8533 final int flags = permissionState != null 8534 ? permissionState.getFlags() : 0; 8535 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8536 if (permissionsState.grantRuntimePermission(bp, userId) == 8537 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8538 // If we cannot put the permission as it was, we have to write. 8539 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8540 changedRuntimePermissionUserIds, userId); 8541 } 8542 } 8543 // Propagate the permission flags. 8544 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8545 } 8546 } break; 8547 8548 case GRANT_UPGRADE: { 8549 // Grant runtime permissions for a previously held install permission. 8550 PermissionState permissionState = origPermissions 8551 .getInstallPermissionState(bp.name); 8552 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8553 8554 if (origPermissions.revokeInstallPermission(bp) 8555 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8556 // We will be transferring the permission flags, so clear them. 8557 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8558 PackageManager.MASK_PERMISSION_FLAGS, 0); 8559 changedInstallPermission = true; 8560 } 8561 8562 // If the permission is not to be promoted to runtime we ignore it and 8563 // also its other flags as they are not applicable to install permissions. 8564 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8565 for (int userId : currentUserIds) { 8566 if (permissionsState.grantRuntimePermission(bp, userId) != 8567 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8568 // Transfer the permission flags. 8569 permissionsState.updatePermissionFlags(bp, userId, 8570 flags, flags); 8571 // If we granted the permission, we have to write. 8572 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8573 changedRuntimePermissionUserIds, userId); 8574 } 8575 } 8576 } 8577 } break; 8578 8579 default: { 8580 if (packageOfInterest == null 8581 || packageOfInterest.equals(pkg.packageName)) { 8582 Slog.w(TAG, "Not granting permission " + perm 8583 + " to package " + pkg.packageName 8584 + " because it was previously installed without"); 8585 } 8586 } break; 8587 } 8588 } else { 8589 if (permissionsState.revokeInstallPermission(bp) != 8590 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8591 // Also drop the permission flags. 8592 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8593 PackageManager.MASK_PERMISSION_FLAGS, 0); 8594 changedInstallPermission = true; 8595 Slog.i(TAG, "Un-granting permission " + perm 8596 + " from package " + pkg.packageName 8597 + " (protectionLevel=" + bp.protectionLevel 8598 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8599 + ")"); 8600 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8601 // Don't print warning for app op permissions, since it is fine for them 8602 // not to be granted, there is a UI for the user to decide. 8603 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8604 Slog.w(TAG, "Not granting permission " + perm 8605 + " to package " + pkg.packageName 8606 + " (protectionLevel=" + bp.protectionLevel 8607 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8608 + ")"); 8609 } 8610 } 8611 } 8612 } 8613 8614 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8615 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8616 // This is the first that we have heard about this package, so the 8617 // permissions we have now selected are fixed until explicitly 8618 // changed. 8619 ps.installPermissionsFixed = true; 8620 } 8621 8622 // Persist the runtime permissions state for users with changes. 8623 for (int userId : changedRuntimePermissionUserIds) { 8624 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8625 } 8626 8627 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8628 } 8629 8630 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8631 boolean allowed = false; 8632 final int NP = PackageParser.NEW_PERMISSIONS.length; 8633 for (int ip=0; ip<NP; ip++) { 8634 final PackageParser.NewPermissionInfo npi 8635 = PackageParser.NEW_PERMISSIONS[ip]; 8636 if (npi.name.equals(perm) 8637 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8638 allowed = true; 8639 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8640 + pkg.packageName); 8641 break; 8642 } 8643 } 8644 return allowed; 8645 } 8646 8647 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8648 BasePermission bp, PermissionsState origPermissions) { 8649 boolean allowed; 8650 allowed = (compareSignatures( 8651 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8652 == PackageManager.SIGNATURE_MATCH) 8653 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8654 == PackageManager.SIGNATURE_MATCH); 8655 if (!allowed && (bp.protectionLevel 8656 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8657 if (isSystemApp(pkg)) { 8658 // For updated system applications, a system permission 8659 // is granted only if it had been defined by the original application. 8660 if (pkg.isUpdatedSystemApp()) { 8661 final PackageSetting sysPs = mSettings 8662 .getDisabledSystemPkgLPr(pkg.packageName); 8663 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8664 // If the original was granted this permission, we take 8665 // that grant decision as read and propagate it to the 8666 // update. 8667 if (sysPs.isPrivileged()) { 8668 allowed = true; 8669 } 8670 } else { 8671 // The system apk may have been updated with an older 8672 // version of the one on the data partition, but which 8673 // granted a new system permission that it didn't have 8674 // before. In this case we do want to allow the app to 8675 // now get the new permission if the ancestral apk is 8676 // privileged to get it. 8677 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8678 for (int j=0; 8679 j<sysPs.pkg.requestedPermissions.size(); j++) { 8680 if (perm.equals( 8681 sysPs.pkg.requestedPermissions.get(j))) { 8682 allowed = true; 8683 break; 8684 } 8685 } 8686 } 8687 } 8688 } else { 8689 allowed = isPrivilegedApp(pkg); 8690 } 8691 } 8692 } 8693 if (!allowed) { 8694 if (!allowed && (bp.protectionLevel 8695 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8696 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8697 // If this was a previously normal/dangerous permission that got moved 8698 // to a system permission as part of the runtime permission redesign, then 8699 // we still want to blindly grant it to old apps. 8700 allowed = true; 8701 } 8702 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8703 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8704 // If this permission is to be granted to the system installer and 8705 // this app is an installer, then it gets the permission. 8706 allowed = true; 8707 } 8708 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8709 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8710 // If this permission is to be granted to the system verifier and 8711 // this app is a verifier, then it gets the permission. 8712 allowed = true; 8713 } 8714 if (!allowed && (bp.protectionLevel 8715 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8716 && isSystemApp(pkg)) { 8717 // Any pre-installed system app is allowed to get this permission. 8718 allowed = true; 8719 } 8720 if (!allowed && (bp.protectionLevel 8721 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8722 // For development permissions, a development permission 8723 // is granted only if it was already granted. 8724 allowed = origPermissions.hasInstallPermission(perm); 8725 } 8726 } 8727 return allowed; 8728 } 8729 8730 final class ActivityIntentResolver 8731 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8732 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8733 boolean defaultOnly, int userId) { 8734 if (!sUserManager.exists(userId)) return null; 8735 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8736 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8737 } 8738 8739 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8740 int userId) { 8741 if (!sUserManager.exists(userId)) return null; 8742 mFlags = flags; 8743 return super.queryIntent(intent, resolvedType, 8744 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8745 } 8746 8747 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8748 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8749 if (!sUserManager.exists(userId)) return null; 8750 if (packageActivities == null) { 8751 return null; 8752 } 8753 mFlags = flags; 8754 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8755 final int N = packageActivities.size(); 8756 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8757 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8758 8759 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8760 for (int i = 0; i < N; ++i) { 8761 intentFilters = packageActivities.get(i).intents; 8762 if (intentFilters != null && intentFilters.size() > 0) { 8763 PackageParser.ActivityIntentInfo[] array = 8764 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8765 intentFilters.toArray(array); 8766 listCut.add(array); 8767 } 8768 } 8769 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8770 } 8771 8772 public final void addActivity(PackageParser.Activity a, String type) { 8773 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8774 mActivities.put(a.getComponentName(), a); 8775 if (DEBUG_SHOW_INFO) 8776 Log.v( 8777 TAG, " " + type + " " + 8778 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8779 if (DEBUG_SHOW_INFO) 8780 Log.v(TAG, " Class=" + a.info.name); 8781 final int NI = a.intents.size(); 8782 for (int j=0; j<NI; j++) { 8783 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8784 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8785 intent.setPriority(0); 8786 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8787 + a.className + " with priority > 0, forcing to 0"); 8788 } 8789 if (DEBUG_SHOW_INFO) { 8790 Log.v(TAG, " IntentFilter:"); 8791 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8792 } 8793 if (!intent.debugCheck()) { 8794 Log.w(TAG, "==> For Activity " + a.info.name); 8795 } 8796 addFilter(intent); 8797 } 8798 } 8799 8800 public final void removeActivity(PackageParser.Activity a, String type) { 8801 mActivities.remove(a.getComponentName()); 8802 if (DEBUG_SHOW_INFO) { 8803 Log.v(TAG, " " + type + " " 8804 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8805 : a.info.name) + ":"); 8806 Log.v(TAG, " Class=" + a.info.name); 8807 } 8808 final int NI = a.intents.size(); 8809 for (int j=0; j<NI; j++) { 8810 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8811 if (DEBUG_SHOW_INFO) { 8812 Log.v(TAG, " IntentFilter:"); 8813 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8814 } 8815 removeFilter(intent); 8816 } 8817 } 8818 8819 @Override 8820 protected boolean allowFilterResult( 8821 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8822 ActivityInfo filterAi = filter.activity.info; 8823 for (int i=dest.size()-1; i>=0; i--) { 8824 ActivityInfo destAi = dest.get(i).activityInfo; 8825 if (destAi.name == filterAi.name 8826 && destAi.packageName == filterAi.packageName) { 8827 return false; 8828 } 8829 } 8830 return true; 8831 } 8832 8833 @Override 8834 protected ActivityIntentInfo[] newArray(int size) { 8835 return new ActivityIntentInfo[size]; 8836 } 8837 8838 @Override 8839 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8840 if (!sUserManager.exists(userId)) return true; 8841 PackageParser.Package p = filter.activity.owner; 8842 if (p != null) { 8843 PackageSetting ps = (PackageSetting)p.mExtras; 8844 if (ps != null) { 8845 // System apps are never considered stopped for purposes of 8846 // filtering, because there may be no way for the user to 8847 // actually re-launch them. 8848 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8849 && ps.getStopped(userId); 8850 } 8851 } 8852 return false; 8853 } 8854 8855 @Override 8856 protected boolean isPackageForFilter(String packageName, 8857 PackageParser.ActivityIntentInfo info) { 8858 return packageName.equals(info.activity.owner.packageName); 8859 } 8860 8861 @Override 8862 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8863 int match, int userId) { 8864 if (!sUserManager.exists(userId)) return null; 8865 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8866 return null; 8867 } 8868 final PackageParser.Activity activity = info.activity; 8869 if (mSafeMode && (activity.info.applicationInfo.flags 8870 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8871 return null; 8872 } 8873 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8874 if (ps == null) { 8875 return null; 8876 } 8877 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8878 ps.readUserState(userId), userId); 8879 if (ai == null) { 8880 return null; 8881 } 8882 final ResolveInfo res = new ResolveInfo(); 8883 res.activityInfo = ai; 8884 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8885 res.filter = info; 8886 } 8887 if (info != null) { 8888 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8889 } 8890 res.priority = info.getPriority(); 8891 res.preferredOrder = activity.owner.mPreferredOrder; 8892 //System.out.println("Result: " + res.activityInfo.className + 8893 // " = " + res.priority); 8894 res.match = match; 8895 res.isDefault = info.hasDefault; 8896 res.labelRes = info.labelRes; 8897 res.nonLocalizedLabel = info.nonLocalizedLabel; 8898 if (userNeedsBadging(userId)) { 8899 res.noResourceId = true; 8900 } else { 8901 res.icon = info.icon; 8902 } 8903 res.iconResourceId = info.icon; 8904 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8905 return res; 8906 } 8907 8908 @Override 8909 protected void sortResults(List<ResolveInfo> results) { 8910 Collections.sort(results, mResolvePrioritySorter); 8911 } 8912 8913 @Override 8914 protected void dumpFilter(PrintWriter out, String prefix, 8915 PackageParser.ActivityIntentInfo filter) { 8916 out.print(prefix); out.print( 8917 Integer.toHexString(System.identityHashCode(filter.activity))); 8918 out.print(' '); 8919 filter.activity.printComponentShortName(out); 8920 out.print(" filter "); 8921 out.println(Integer.toHexString(System.identityHashCode(filter))); 8922 } 8923 8924 @Override 8925 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8926 return filter.activity; 8927 } 8928 8929 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8930 PackageParser.Activity activity = (PackageParser.Activity)label; 8931 out.print(prefix); out.print( 8932 Integer.toHexString(System.identityHashCode(activity))); 8933 out.print(' '); 8934 activity.printComponentShortName(out); 8935 if (count > 1) { 8936 out.print(" ("); out.print(count); out.print(" filters)"); 8937 } 8938 out.println(); 8939 } 8940 8941// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8942// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8943// final List<ResolveInfo> retList = Lists.newArrayList(); 8944// while (i.hasNext()) { 8945// final ResolveInfo resolveInfo = i.next(); 8946// if (isEnabledLP(resolveInfo.activityInfo)) { 8947// retList.add(resolveInfo); 8948// } 8949// } 8950// return retList; 8951// } 8952 8953 // Keys are String (activity class name), values are Activity. 8954 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8955 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8956 private int mFlags; 8957 } 8958 8959 private final class ServiceIntentResolver 8960 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8961 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8962 boolean defaultOnly, int userId) { 8963 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8964 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8965 } 8966 8967 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8968 int userId) { 8969 if (!sUserManager.exists(userId)) return null; 8970 mFlags = flags; 8971 return super.queryIntent(intent, resolvedType, 8972 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8973 } 8974 8975 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8976 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8977 if (!sUserManager.exists(userId)) return null; 8978 if (packageServices == null) { 8979 return null; 8980 } 8981 mFlags = flags; 8982 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8983 final int N = packageServices.size(); 8984 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8985 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8986 8987 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8988 for (int i = 0; i < N; ++i) { 8989 intentFilters = packageServices.get(i).intents; 8990 if (intentFilters != null && intentFilters.size() > 0) { 8991 PackageParser.ServiceIntentInfo[] array = 8992 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8993 intentFilters.toArray(array); 8994 listCut.add(array); 8995 } 8996 } 8997 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8998 } 8999 9000 public final void addService(PackageParser.Service s) { 9001 mServices.put(s.getComponentName(), s); 9002 if (DEBUG_SHOW_INFO) { 9003 Log.v(TAG, " " 9004 + (s.info.nonLocalizedLabel != null 9005 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9006 Log.v(TAG, " Class=" + s.info.name); 9007 } 9008 final int NI = s.intents.size(); 9009 int j; 9010 for (j=0; j<NI; j++) { 9011 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9012 if (DEBUG_SHOW_INFO) { 9013 Log.v(TAG, " IntentFilter:"); 9014 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9015 } 9016 if (!intent.debugCheck()) { 9017 Log.w(TAG, "==> For Service " + s.info.name); 9018 } 9019 addFilter(intent); 9020 } 9021 } 9022 9023 public final void removeService(PackageParser.Service s) { 9024 mServices.remove(s.getComponentName()); 9025 if (DEBUG_SHOW_INFO) { 9026 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9027 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9028 Log.v(TAG, " Class=" + s.info.name); 9029 } 9030 final int NI = s.intents.size(); 9031 int j; 9032 for (j=0; j<NI; j++) { 9033 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9034 if (DEBUG_SHOW_INFO) { 9035 Log.v(TAG, " IntentFilter:"); 9036 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9037 } 9038 removeFilter(intent); 9039 } 9040 } 9041 9042 @Override 9043 protected boolean allowFilterResult( 9044 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9045 ServiceInfo filterSi = filter.service.info; 9046 for (int i=dest.size()-1; i>=0; i--) { 9047 ServiceInfo destAi = dest.get(i).serviceInfo; 9048 if (destAi.name == filterSi.name 9049 && destAi.packageName == filterSi.packageName) { 9050 return false; 9051 } 9052 } 9053 return true; 9054 } 9055 9056 @Override 9057 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9058 return new PackageParser.ServiceIntentInfo[size]; 9059 } 9060 9061 @Override 9062 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9063 if (!sUserManager.exists(userId)) return true; 9064 PackageParser.Package p = filter.service.owner; 9065 if (p != null) { 9066 PackageSetting ps = (PackageSetting)p.mExtras; 9067 if (ps != null) { 9068 // System apps are never considered stopped for purposes of 9069 // filtering, because there may be no way for the user to 9070 // actually re-launch them. 9071 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9072 && ps.getStopped(userId); 9073 } 9074 } 9075 return false; 9076 } 9077 9078 @Override 9079 protected boolean isPackageForFilter(String packageName, 9080 PackageParser.ServiceIntentInfo info) { 9081 return packageName.equals(info.service.owner.packageName); 9082 } 9083 9084 @Override 9085 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9086 int match, int userId) { 9087 if (!sUserManager.exists(userId)) return null; 9088 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9089 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9090 return null; 9091 } 9092 final PackageParser.Service service = info.service; 9093 if (mSafeMode && (service.info.applicationInfo.flags 9094 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9095 return null; 9096 } 9097 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9098 if (ps == null) { 9099 return null; 9100 } 9101 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9102 ps.readUserState(userId), userId); 9103 if (si == null) { 9104 return null; 9105 } 9106 final ResolveInfo res = new ResolveInfo(); 9107 res.serviceInfo = si; 9108 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9109 res.filter = filter; 9110 } 9111 res.priority = info.getPriority(); 9112 res.preferredOrder = service.owner.mPreferredOrder; 9113 res.match = match; 9114 res.isDefault = info.hasDefault; 9115 res.labelRes = info.labelRes; 9116 res.nonLocalizedLabel = info.nonLocalizedLabel; 9117 res.icon = info.icon; 9118 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9119 return res; 9120 } 9121 9122 @Override 9123 protected void sortResults(List<ResolveInfo> results) { 9124 Collections.sort(results, mResolvePrioritySorter); 9125 } 9126 9127 @Override 9128 protected void dumpFilter(PrintWriter out, String prefix, 9129 PackageParser.ServiceIntentInfo filter) { 9130 out.print(prefix); out.print( 9131 Integer.toHexString(System.identityHashCode(filter.service))); 9132 out.print(' '); 9133 filter.service.printComponentShortName(out); 9134 out.print(" filter "); 9135 out.println(Integer.toHexString(System.identityHashCode(filter))); 9136 } 9137 9138 @Override 9139 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9140 return filter.service; 9141 } 9142 9143 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9144 PackageParser.Service service = (PackageParser.Service)label; 9145 out.print(prefix); out.print( 9146 Integer.toHexString(System.identityHashCode(service))); 9147 out.print(' '); 9148 service.printComponentShortName(out); 9149 if (count > 1) { 9150 out.print(" ("); out.print(count); out.print(" filters)"); 9151 } 9152 out.println(); 9153 } 9154 9155// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9156// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9157// final List<ResolveInfo> retList = Lists.newArrayList(); 9158// while (i.hasNext()) { 9159// final ResolveInfo resolveInfo = (ResolveInfo) i; 9160// if (isEnabledLP(resolveInfo.serviceInfo)) { 9161// retList.add(resolveInfo); 9162// } 9163// } 9164// return retList; 9165// } 9166 9167 // Keys are String (activity class name), values are Activity. 9168 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9169 = new ArrayMap<ComponentName, PackageParser.Service>(); 9170 private int mFlags; 9171 }; 9172 9173 private final class ProviderIntentResolver 9174 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9175 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9176 boolean defaultOnly, int userId) { 9177 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9178 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9179 } 9180 9181 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9182 int userId) { 9183 if (!sUserManager.exists(userId)) 9184 return null; 9185 mFlags = flags; 9186 return super.queryIntent(intent, resolvedType, 9187 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9188 } 9189 9190 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9191 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9192 if (!sUserManager.exists(userId)) 9193 return null; 9194 if (packageProviders == null) { 9195 return null; 9196 } 9197 mFlags = flags; 9198 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9199 final int N = packageProviders.size(); 9200 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9201 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9202 9203 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9204 for (int i = 0; i < N; ++i) { 9205 intentFilters = packageProviders.get(i).intents; 9206 if (intentFilters != null && intentFilters.size() > 0) { 9207 PackageParser.ProviderIntentInfo[] array = 9208 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9209 intentFilters.toArray(array); 9210 listCut.add(array); 9211 } 9212 } 9213 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9214 } 9215 9216 public final void addProvider(PackageParser.Provider p) { 9217 if (mProviders.containsKey(p.getComponentName())) { 9218 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9219 return; 9220 } 9221 9222 mProviders.put(p.getComponentName(), p); 9223 if (DEBUG_SHOW_INFO) { 9224 Log.v(TAG, " " 9225 + (p.info.nonLocalizedLabel != null 9226 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9227 Log.v(TAG, " Class=" + p.info.name); 9228 } 9229 final int NI = p.intents.size(); 9230 int j; 9231 for (j = 0; j < NI; j++) { 9232 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9233 if (DEBUG_SHOW_INFO) { 9234 Log.v(TAG, " IntentFilter:"); 9235 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9236 } 9237 if (!intent.debugCheck()) { 9238 Log.w(TAG, "==> For Provider " + p.info.name); 9239 } 9240 addFilter(intent); 9241 } 9242 } 9243 9244 public final void removeProvider(PackageParser.Provider p) { 9245 mProviders.remove(p.getComponentName()); 9246 if (DEBUG_SHOW_INFO) { 9247 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9248 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9249 Log.v(TAG, " Class=" + p.info.name); 9250 } 9251 final int NI = p.intents.size(); 9252 int j; 9253 for (j = 0; j < NI; j++) { 9254 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9255 if (DEBUG_SHOW_INFO) { 9256 Log.v(TAG, " IntentFilter:"); 9257 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9258 } 9259 removeFilter(intent); 9260 } 9261 } 9262 9263 @Override 9264 protected boolean allowFilterResult( 9265 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9266 ProviderInfo filterPi = filter.provider.info; 9267 for (int i = dest.size() - 1; i >= 0; i--) { 9268 ProviderInfo destPi = dest.get(i).providerInfo; 9269 if (destPi.name == filterPi.name 9270 && destPi.packageName == filterPi.packageName) { 9271 return false; 9272 } 9273 } 9274 return true; 9275 } 9276 9277 @Override 9278 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9279 return new PackageParser.ProviderIntentInfo[size]; 9280 } 9281 9282 @Override 9283 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9284 if (!sUserManager.exists(userId)) 9285 return true; 9286 PackageParser.Package p = filter.provider.owner; 9287 if (p != null) { 9288 PackageSetting ps = (PackageSetting) p.mExtras; 9289 if (ps != null) { 9290 // System apps are never considered stopped for purposes of 9291 // filtering, because there may be no way for the user to 9292 // actually re-launch them. 9293 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9294 && ps.getStopped(userId); 9295 } 9296 } 9297 return false; 9298 } 9299 9300 @Override 9301 protected boolean isPackageForFilter(String packageName, 9302 PackageParser.ProviderIntentInfo info) { 9303 return packageName.equals(info.provider.owner.packageName); 9304 } 9305 9306 @Override 9307 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9308 int match, int userId) { 9309 if (!sUserManager.exists(userId)) 9310 return null; 9311 final PackageParser.ProviderIntentInfo info = filter; 9312 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9313 return null; 9314 } 9315 final PackageParser.Provider provider = info.provider; 9316 if (mSafeMode && (provider.info.applicationInfo.flags 9317 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9318 return null; 9319 } 9320 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9321 if (ps == null) { 9322 return null; 9323 } 9324 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9325 ps.readUserState(userId), userId); 9326 if (pi == null) { 9327 return null; 9328 } 9329 final ResolveInfo res = new ResolveInfo(); 9330 res.providerInfo = pi; 9331 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9332 res.filter = filter; 9333 } 9334 res.priority = info.getPriority(); 9335 res.preferredOrder = provider.owner.mPreferredOrder; 9336 res.match = match; 9337 res.isDefault = info.hasDefault; 9338 res.labelRes = info.labelRes; 9339 res.nonLocalizedLabel = info.nonLocalizedLabel; 9340 res.icon = info.icon; 9341 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9342 return res; 9343 } 9344 9345 @Override 9346 protected void sortResults(List<ResolveInfo> results) { 9347 Collections.sort(results, mResolvePrioritySorter); 9348 } 9349 9350 @Override 9351 protected void dumpFilter(PrintWriter out, String prefix, 9352 PackageParser.ProviderIntentInfo filter) { 9353 out.print(prefix); 9354 out.print( 9355 Integer.toHexString(System.identityHashCode(filter.provider))); 9356 out.print(' '); 9357 filter.provider.printComponentShortName(out); 9358 out.print(" filter "); 9359 out.println(Integer.toHexString(System.identityHashCode(filter))); 9360 } 9361 9362 @Override 9363 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9364 return filter.provider; 9365 } 9366 9367 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9368 PackageParser.Provider provider = (PackageParser.Provider)label; 9369 out.print(prefix); out.print( 9370 Integer.toHexString(System.identityHashCode(provider))); 9371 out.print(' '); 9372 provider.printComponentShortName(out); 9373 if (count > 1) { 9374 out.print(" ("); out.print(count); out.print(" filters)"); 9375 } 9376 out.println(); 9377 } 9378 9379 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9380 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9381 private int mFlags; 9382 }; 9383 9384 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9385 new Comparator<ResolveInfo>() { 9386 public int compare(ResolveInfo r1, ResolveInfo r2) { 9387 int v1 = r1.priority; 9388 int v2 = r2.priority; 9389 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9390 if (v1 != v2) { 9391 return (v1 > v2) ? -1 : 1; 9392 } 9393 v1 = r1.preferredOrder; 9394 v2 = r2.preferredOrder; 9395 if (v1 != v2) { 9396 return (v1 > v2) ? -1 : 1; 9397 } 9398 if (r1.isDefault != r2.isDefault) { 9399 return r1.isDefault ? -1 : 1; 9400 } 9401 v1 = r1.match; 9402 v2 = r2.match; 9403 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9404 if (v1 != v2) { 9405 return (v1 > v2) ? -1 : 1; 9406 } 9407 if (r1.system != r2.system) { 9408 return r1.system ? -1 : 1; 9409 } 9410 return 0; 9411 } 9412 }; 9413 9414 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9415 new Comparator<ProviderInfo>() { 9416 public int compare(ProviderInfo p1, ProviderInfo p2) { 9417 final int v1 = p1.initOrder; 9418 final int v2 = p2.initOrder; 9419 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9420 } 9421 }; 9422 9423 final void sendPackageBroadcast(final String action, final String pkg, 9424 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9425 final int[] userIds) { 9426 mHandler.post(new Runnable() { 9427 @Override 9428 public void run() { 9429 try { 9430 final IActivityManager am = ActivityManagerNative.getDefault(); 9431 if (am == null) return; 9432 final int[] resolvedUserIds; 9433 if (userIds == null) { 9434 resolvedUserIds = am.getRunningUserIds(); 9435 } else { 9436 resolvedUserIds = userIds; 9437 } 9438 for (int id : resolvedUserIds) { 9439 final Intent intent = new Intent(action, 9440 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9441 if (extras != null) { 9442 intent.putExtras(extras); 9443 } 9444 if (targetPkg != null) { 9445 intent.setPackage(targetPkg); 9446 } 9447 // Modify the UID when posting to other users 9448 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9449 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9450 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9451 intent.putExtra(Intent.EXTRA_UID, uid); 9452 } 9453 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9454 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9455 if (DEBUG_BROADCASTS) { 9456 RuntimeException here = new RuntimeException("here"); 9457 here.fillInStackTrace(); 9458 Slog.d(TAG, "Sending to user " + id + ": " 9459 + intent.toShortString(false, true, false, false) 9460 + " " + intent.getExtras(), here); 9461 } 9462 am.broadcastIntent(null, intent, null, finishedReceiver, 9463 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9464 null, finishedReceiver != null, false, id); 9465 } 9466 } catch (RemoteException ex) { 9467 } 9468 } 9469 }); 9470 } 9471 9472 /** 9473 * Check if the external storage media is available. This is true if there 9474 * is a mounted external storage medium or if the external storage is 9475 * emulated. 9476 */ 9477 private boolean isExternalMediaAvailable() { 9478 return mMediaMounted || Environment.isExternalStorageEmulated(); 9479 } 9480 9481 @Override 9482 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9483 // writer 9484 synchronized (mPackages) { 9485 if (!isExternalMediaAvailable()) { 9486 // If the external storage is no longer mounted at this point, 9487 // the caller may not have been able to delete all of this 9488 // packages files and can not delete any more. Bail. 9489 return null; 9490 } 9491 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9492 if (lastPackage != null) { 9493 pkgs.remove(lastPackage); 9494 } 9495 if (pkgs.size() > 0) { 9496 return pkgs.get(0); 9497 } 9498 } 9499 return null; 9500 } 9501 9502 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9503 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9504 userId, andCode ? 1 : 0, packageName); 9505 if (mSystemReady) { 9506 msg.sendToTarget(); 9507 } else { 9508 if (mPostSystemReadyMessages == null) { 9509 mPostSystemReadyMessages = new ArrayList<>(); 9510 } 9511 mPostSystemReadyMessages.add(msg); 9512 } 9513 } 9514 9515 void startCleaningPackages() { 9516 // reader 9517 synchronized (mPackages) { 9518 if (!isExternalMediaAvailable()) { 9519 return; 9520 } 9521 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9522 return; 9523 } 9524 } 9525 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9526 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9527 IActivityManager am = ActivityManagerNative.getDefault(); 9528 if (am != null) { 9529 try { 9530 am.startService(null, intent, null, mContext.getOpPackageName(), 9531 UserHandle.USER_OWNER); 9532 } catch (RemoteException e) { 9533 } 9534 } 9535 } 9536 9537 @Override 9538 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9539 int installFlags, String installerPackageName, VerificationParams verificationParams, 9540 String packageAbiOverride) { 9541 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9542 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9543 } 9544 9545 @Override 9546 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9547 int installFlags, String installerPackageName, VerificationParams verificationParams, 9548 String packageAbiOverride, int userId) { 9549 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9550 9551 final int callingUid = Binder.getCallingUid(); 9552 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9553 9554 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9555 try { 9556 if (observer != null) { 9557 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9558 } 9559 } catch (RemoteException re) { 9560 } 9561 return; 9562 } 9563 9564 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9565 installFlags |= PackageManager.INSTALL_FROM_ADB; 9566 9567 } else { 9568 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9569 // about installerPackageName. 9570 9571 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9572 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9573 } 9574 9575 UserHandle user; 9576 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9577 user = UserHandle.ALL; 9578 } else { 9579 user = new UserHandle(userId); 9580 } 9581 9582 // Only system components can circumvent runtime permissions when installing. 9583 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9584 && mContext.checkCallingOrSelfPermission(Manifest.permission 9585 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9586 throw new SecurityException("You need the " 9587 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9588 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9589 } 9590 9591 verificationParams.setInstallerUid(callingUid); 9592 9593 final File originFile = new File(originPath); 9594 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9595 9596 final Message msg = mHandler.obtainMessage(INIT_COPY); 9597 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9598 null, verificationParams, user, packageAbiOverride, null); 9599 mHandler.sendMessage(msg); 9600 } 9601 9602 void installStage(String packageName, File stagedDir, String stagedCid, 9603 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9604 String installerPackageName, int installerUid, UserHandle user) { 9605 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9606 params.referrerUri, installerUid, null); 9607 verifParams.setInstallerUid(installerUid); 9608 9609 final OriginInfo origin; 9610 if (stagedDir != null) { 9611 origin = OriginInfo.fromStagedFile(stagedDir); 9612 } else { 9613 origin = OriginInfo.fromStagedContainer(stagedCid); 9614 } 9615 9616 final Message msg = mHandler.obtainMessage(INIT_COPY); 9617 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9618 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9619 params.grantedRuntimePermissions); 9620 9621 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9622 System.identityHashCode(msg.obj)); 9623 9624 mHandler.sendMessage(msg); 9625 } 9626 9627 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9628 Bundle extras = new Bundle(1); 9629 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9630 9631 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9632 packageName, extras, null, null, new int[] {userId}); 9633 try { 9634 IActivityManager am = ActivityManagerNative.getDefault(); 9635 final boolean isSystem = 9636 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9637 if (isSystem && am.isUserRunning(userId, false)) { 9638 // The just-installed/enabled app is bundled on the system, so presumed 9639 // to be able to run automatically without needing an explicit launch. 9640 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9641 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9642 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9643 .setPackage(packageName); 9644 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9645 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9646 } 9647 } catch (RemoteException e) { 9648 // shouldn't happen 9649 Slog.w(TAG, "Unable to bootstrap installed package", e); 9650 } 9651 } 9652 9653 @Override 9654 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9655 int userId) { 9656 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9657 PackageSetting pkgSetting; 9658 final int uid = Binder.getCallingUid(); 9659 enforceCrossUserPermission(uid, userId, true, true, 9660 "setApplicationHiddenSetting for user " + userId); 9661 9662 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9663 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9664 return false; 9665 } 9666 9667 long callingId = Binder.clearCallingIdentity(); 9668 try { 9669 boolean sendAdded = false; 9670 boolean sendRemoved = false; 9671 // writer 9672 synchronized (mPackages) { 9673 pkgSetting = mSettings.mPackages.get(packageName); 9674 if (pkgSetting == null) { 9675 return false; 9676 } 9677 if (pkgSetting.getHidden(userId) != hidden) { 9678 pkgSetting.setHidden(hidden, userId); 9679 mSettings.writePackageRestrictionsLPr(userId); 9680 if (hidden) { 9681 sendRemoved = true; 9682 } else { 9683 sendAdded = true; 9684 } 9685 } 9686 } 9687 if (sendAdded) { 9688 sendPackageAddedForUser(packageName, pkgSetting, userId); 9689 return true; 9690 } 9691 if (sendRemoved) { 9692 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9693 "hiding pkg"); 9694 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9695 return true; 9696 } 9697 } finally { 9698 Binder.restoreCallingIdentity(callingId); 9699 } 9700 return false; 9701 } 9702 9703 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9704 int userId) { 9705 final PackageRemovedInfo info = new PackageRemovedInfo(); 9706 info.removedPackage = packageName; 9707 info.removedUsers = new int[] {userId}; 9708 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9709 info.sendBroadcast(false, false, false); 9710 } 9711 9712 /** 9713 * Returns true if application is not found or there was an error. Otherwise it returns 9714 * the hidden state of the package for the given user. 9715 */ 9716 @Override 9717 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9718 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9719 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9720 false, "getApplicationHidden for user " + userId); 9721 PackageSetting pkgSetting; 9722 long callingId = Binder.clearCallingIdentity(); 9723 try { 9724 // writer 9725 synchronized (mPackages) { 9726 pkgSetting = mSettings.mPackages.get(packageName); 9727 if (pkgSetting == null) { 9728 return true; 9729 } 9730 return pkgSetting.getHidden(userId); 9731 } 9732 } finally { 9733 Binder.restoreCallingIdentity(callingId); 9734 } 9735 } 9736 9737 /** 9738 * @hide 9739 */ 9740 @Override 9741 public int installExistingPackageAsUser(String packageName, int userId) { 9742 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9743 null); 9744 PackageSetting pkgSetting; 9745 final int uid = Binder.getCallingUid(); 9746 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9747 + userId); 9748 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9749 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9750 } 9751 9752 long callingId = Binder.clearCallingIdentity(); 9753 try { 9754 boolean sendAdded = false; 9755 9756 // writer 9757 synchronized (mPackages) { 9758 pkgSetting = mSettings.mPackages.get(packageName); 9759 if (pkgSetting == null) { 9760 return PackageManager.INSTALL_FAILED_INVALID_URI; 9761 } 9762 if (!pkgSetting.getInstalled(userId)) { 9763 pkgSetting.setInstalled(true, userId); 9764 pkgSetting.setHidden(false, userId); 9765 mSettings.writePackageRestrictionsLPr(userId); 9766 sendAdded = true; 9767 } 9768 } 9769 9770 if (sendAdded) { 9771 sendPackageAddedForUser(packageName, pkgSetting, userId); 9772 } 9773 } finally { 9774 Binder.restoreCallingIdentity(callingId); 9775 } 9776 9777 return PackageManager.INSTALL_SUCCEEDED; 9778 } 9779 9780 boolean isUserRestricted(int userId, String restrictionKey) { 9781 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9782 if (restrictions.getBoolean(restrictionKey, false)) { 9783 Log.w(TAG, "User is restricted: " + restrictionKey); 9784 return true; 9785 } 9786 return false; 9787 } 9788 9789 @Override 9790 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9791 mContext.enforceCallingOrSelfPermission( 9792 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9793 "Only package verification agents can verify applications"); 9794 9795 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9796 final PackageVerificationResponse response = new PackageVerificationResponse( 9797 verificationCode, Binder.getCallingUid()); 9798 msg.arg1 = id; 9799 msg.obj = response; 9800 mHandler.sendMessage(msg); 9801 } 9802 9803 @Override 9804 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9805 long millisecondsToDelay) { 9806 mContext.enforceCallingOrSelfPermission( 9807 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9808 "Only package verification agents can extend verification timeouts"); 9809 9810 final PackageVerificationState state = mPendingVerification.get(id); 9811 final PackageVerificationResponse response = new PackageVerificationResponse( 9812 verificationCodeAtTimeout, Binder.getCallingUid()); 9813 9814 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9815 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9816 } 9817 if (millisecondsToDelay < 0) { 9818 millisecondsToDelay = 0; 9819 } 9820 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9821 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9822 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9823 } 9824 9825 if ((state != null) && !state.timeoutExtended()) { 9826 state.extendTimeout(); 9827 9828 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9829 msg.arg1 = id; 9830 msg.obj = response; 9831 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9832 } 9833 } 9834 9835 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9836 int verificationCode, UserHandle user) { 9837 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9838 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9839 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9840 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9841 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9842 9843 mContext.sendBroadcastAsUser(intent, user, 9844 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9845 } 9846 9847 private ComponentName matchComponentForVerifier(String packageName, 9848 List<ResolveInfo> receivers) { 9849 ActivityInfo targetReceiver = null; 9850 9851 final int NR = receivers.size(); 9852 for (int i = 0; i < NR; i++) { 9853 final ResolveInfo info = receivers.get(i); 9854 if (info.activityInfo == null) { 9855 continue; 9856 } 9857 9858 if (packageName.equals(info.activityInfo.packageName)) { 9859 targetReceiver = info.activityInfo; 9860 break; 9861 } 9862 } 9863 9864 if (targetReceiver == null) { 9865 return null; 9866 } 9867 9868 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9869 } 9870 9871 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9872 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9873 if (pkgInfo.verifiers.length == 0) { 9874 return null; 9875 } 9876 9877 final int N = pkgInfo.verifiers.length; 9878 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9879 for (int i = 0; i < N; i++) { 9880 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9881 9882 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9883 receivers); 9884 if (comp == null) { 9885 continue; 9886 } 9887 9888 final int verifierUid = getUidForVerifier(verifierInfo); 9889 if (verifierUid == -1) { 9890 continue; 9891 } 9892 9893 if (DEBUG_VERIFY) { 9894 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9895 + " with the correct signature"); 9896 } 9897 sufficientVerifiers.add(comp); 9898 verificationState.addSufficientVerifier(verifierUid); 9899 } 9900 9901 return sufficientVerifiers; 9902 } 9903 9904 private int getUidForVerifier(VerifierInfo verifierInfo) { 9905 synchronized (mPackages) { 9906 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9907 if (pkg == null) { 9908 return -1; 9909 } else if (pkg.mSignatures.length != 1) { 9910 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9911 + " has more than one signature; ignoring"); 9912 return -1; 9913 } 9914 9915 /* 9916 * If the public key of the package's signature does not match 9917 * our expected public key, then this is a different package and 9918 * we should skip. 9919 */ 9920 9921 final byte[] expectedPublicKey; 9922 try { 9923 final Signature verifierSig = pkg.mSignatures[0]; 9924 final PublicKey publicKey = verifierSig.getPublicKey(); 9925 expectedPublicKey = publicKey.getEncoded(); 9926 } catch (CertificateException e) { 9927 return -1; 9928 } 9929 9930 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9931 9932 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9933 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9934 + " does not have the expected public key; ignoring"); 9935 return -1; 9936 } 9937 9938 return pkg.applicationInfo.uid; 9939 } 9940 } 9941 9942 @Override 9943 public void finishPackageInstall(int token) { 9944 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9945 9946 if (DEBUG_INSTALL) { 9947 Slog.v(TAG, "BM finishing package install for " + token); 9948 } 9949 9950 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9951 mHandler.sendMessage(msg); 9952 } 9953 9954 /** 9955 * Get the verification agent timeout. 9956 * 9957 * @return verification timeout in milliseconds 9958 */ 9959 private long getVerificationTimeout() { 9960 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9961 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9962 DEFAULT_VERIFICATION_TIMEOUT); 9963 } 9964 9965 /** 9966 * Get the default verification agent response code. 9967 * 9968 * @return default verification response code 9969 */ 9970 private int getDefaultVerificationResponse() { 9971 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9972 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9973 DEFAULT_VERIFICATION_RESPONSE); 9974 } 9975 9976 /** 9977 * Check whether or not package verification has been enabled. 9978 * 9979 * @return true if verification should be performed 9980 */ 9981 private boolean isVerificationEnabled(int userId, int installFlags) { 9982 if (!DEFAULT_VERIFY_ENABLE) { 9983 return false; 9984 } 9985 9986 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9987 9988 // Check if installing from ADB 9989 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9990 // Do not run verification in a test harness environment 9991 if (ActivityManager.isRunningInTestHarness()) { 9992 return false; 9993 } 9994 if (ensureVerifyAppsEnabled) { 9995 return true; 9996 } 9997 // Check if the developer does not want package verification for ADB installs 9998 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9999 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10000 return false; 10001 } 10002 } 10003 10004 if (ensureVerifyAppsEnabled) { 10005 return true; 10006 } 10007 10008 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10009 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10010 } 10011 10012 @Override 10013 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10014 throws RemoteException { 10015 mContext.enforceCallingOrSelfPermission( 10016 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10017 "Only intentfilter verification agents can verify applications"); 10018 10019 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10020 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10021 Binder.getCallingUid(), verificationCode, failedDomains); 10022 msg.arg1 = id; 10023 msg.obj = response; 10024 mHandler.sendMessage(msg); 10025 } 10026 10027 @Override 10028 public int getIntentVerificationStatus(String packageName, int userId) { 10029 synchronized (mPackages) { 10030 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10031 } 10032 } 10033 10034 @Override 10035 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10036 mContext.enforceCallingOrSelfPermission( 10037 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10038 10039 boolean result = false; 10040 synchronized (mPackages) { 10041 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10042 } 10043 if (result) { 10044 scheduleWritePackageRestrictionsLocked(userId); 10045 } 10046 return result; 10047 } 10048 10049 @Override 10050 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10051 synchronized (mPackages) { 10052 return mSettings.getIntentFilterVerificationsLPr(packageName); 10053 } 10054 } 10055 10056 @Override 10057 public List<IntentFilter> getAllIntentFilters(String packageName) { 10058 if (TextUtils.isEmpty(packageName)) { 10059 return Collections.<IntentFilter>emptyList(); 10060 } 10061 synchronized (mPackages) { 10062 PackageParser.Package pkg = mPackages.get(packageName); 10063 if (pkg == null || pkg.activities == null) { 10064 return Collections.<IntentFilter>emptyList(); 10065 } 10066 final int count = pkg.activities.size(); 10067 ArrayList<IntentFilter> result = new ArrayList<>(); 10068 for (int n=0; n<count; n++) { 10069 PackageParser.Activity activity = pkg.activities.get(n); 10070 if (activity.intents != null || activity.intents.size() > 0) { 10071 result.addAll(activity.intents); 10072 } 10073 } 10074 return result; 10075 } 10076 } 10077 10078 @Override 10079 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10080 mContext.enforceCallingOrSelfPermission( 10081 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10082 10083 synchronized (mPackages) { 10084 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10085 if (packageName != null) { 10086 result |= updateIntentVerificationStatus(packageName, 10087 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10088 userId); 10089 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10090 packageName, userId); 10091 } 10092 return result; 10093 } 10094 } 10095 10096 @Override 10097 public String getDefaultBrowserPackageName(int userId) { 10098 synchronized (mPackages) { 10099 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10100 } 10101 } 10102 10103 /** 10104 * Get the "allow unknown sources" setting. 10105 * 10106 * @return the current "allow unknown sources" setting 10107 */ 10108 private int getUnknownSourcesSettings() { 10109 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10110 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10111 -1); 10112 } 10113 10114 @Override 10115 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10116 final int uid = Binder.getCallingUid(); 10117 // writer 10118 synchronized (mPackages) { 10119 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10120 if (targetPackageSetting == null) { 10121 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10122 } 10123 10124 PackageSetting installerPackageSetting; 10125 if (installerPackageName != null) { 10126 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10127 if (installerPackageSetting == null) { 10128 throw new IllegalArgumentException("Unknown installer package: " 10129 + installerPackageName); 10130 } 10131 } else { 10132 installerPackageSetting = null; 10133 } 10134 10135 Signature[] callerSignature; 10136 Object obj = mSettings.getUserIdLPr(uid); 10137 if (obj != null) { 10138 if (obj instanceof SharedUserSetting) { 10139 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10140 } else if (obj instanceof PackageSetting) { 10141 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10142 } else { 10143 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10144 } 10145 } else { 10146 throw new SecurityException("Unknown calling uid " + uid); 10147 } 10148 10149 // Verify: can't set installerPackageName to a package that is 10150 // not signed with the same cert as the caller. 10151 if (installerPackageSetting != null) { 10152 if (compareSignatures(callerSignature, 10153 installerPackageSetting.signatures.mSignatures) 10154 != PackageManager.SIGNATURE_MATCH) { 10155 throw new SecurityException( 10156 "Caller does not have same cert as new installer package " 10157 + installerPackageName); 10158 } 10159 } 10160 10161 // Verify: if target already has an installer package, it must 10162 // be signed with the same cert as the caller. 10163 if (targetPackageSetting.installerPackageName != null) { 10164 PackageSetting setting = mSettings.mPackages.get( 10165 targetPackageSetting.installerPackageName); 10166 // If the currently set package isn't valid, then it's always 10167 // okay to change it. 10168 if (setting != null) { 10169 if (compareSignatures(callerSignature, 10170 setting.signatures.mSignatures) 10171 != PackageManager.SIGNATURE_MATCH) { 10172 throw new SecurityException( 10173 "Caller does not have same cert as old installer package " 10174 + targetPackageSetting.installerPackageName); 10175 } 10176 } 10177 } 10178 10179 // Okay! 10180 targetPackageSetting.installerPackageName = installerPackageName; 10181 scheduleWriteSettingsLocked(); 10182 } 10183 } 10184 10185 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10186 // Queue up an async operation since the package installation may take a little while. 10187 mHandler.post(new Runnable() { 10188 public void run() { 10189 mHandler.removeCallbacks(this); 10190 // Result object to be returned 10191 PackageInstalledInfo res = new PackageInstalledInfo(); 10192 res.returnCode = currentStatus; 10193 res.uid = -1; 10194 res.pkg = null; 10195 res.removedInfo = new PackageRemovedInfo(); 10196 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10197 args.doPreInstall(res.returnCode); 10198 synchronized (mInstallLock) { 10199 installPackageTracedLI(args, res); 10200 } 10201 args.doPostInstall(res.returnCode, res.uid); 10202 } 10203 10204 // A restore should be performed at this point if (a) the install 10205 // succeeded, (b) the operation is not an update, and (c) the new 10206 // package has not opted out of backup participation. 10207 final boolean update = res.removedInfo.removedPackage != null; 10208 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10209 boolean doRestore = !update 10210 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10211 10212 // Set up the post-install work request bookkeeping. This will be used 10213 // and cleaned up by the post-install event handling regardless of whether 10214 // there's a restore pass performed. Token values are >= 1. 10215 int token; 10216 if (mNextInstallToken < 0) mNextInstallToken = 1; 10217 token = mNextInstallToken++; 10218 10219 PostInstallData data = new PostInstallData(args, res); 10220 mRunningInstalls.put(token, data); 10221 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10222 10223 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10224 // Pass responsibility to the Backup Manager. It will perform a 10225 // restore if appropriate, then pass responsibility back to the 10226 // Package Manager to run the post-install observer callbacks 10227 // and broadcasts. 10228 IBackupManager bm = IBackupManager.Stub.asInterface( 10229 ServiceManager.getService(Context.BACKUP_SERVICE)); 10230 if (bm != null) { 10231 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10232 + " to BM for possible restore"); 10233 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10234 try { 10235 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10236 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10237 } else { 10238 doRestore = false; 10239 } 10240 } catch (RemoteException e) { 10241 // can't happen; the backup manager is local 10242 } catch (Exception e) { 10243 Slog.e(TAG, "Exception trying to enqueue restore", e); 10244 doRestore = false; 10245 } finally { 10246 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10247 } 10248 } else { 10249 Slog.e(TAG, "Backup Manager not found!"); 10250 doRestore = false; 10251 } 10252 } 10253 10254 if (!doRestore) { 10255 // No restore possible, or the Backup Manager was mysteriously not 10256 // available -- just fire the post-install work request directly. 10257 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10258 10259 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10260 10261 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10262 mHandler.sendMessage(msg); 10263 } 10264 } 10265 }); 10266 } 10267 10268 private abstract class HandlerParams { 10269 private static final int MAX_RETRIES = 4; 10270 10271 /** 10272 * Number of times startCopy() has been attempted and had a non-fatal 10273 * error. 10274 */ 10275 private int mRetries = 0; 10276 10277 /** User handle for the user requesting the information or installation. */ 10278 private final UserHandle mUser; 10279 10280 HandlerParams(UserHandle user) { 10281 mUser = user; 10282 } 10283 10284 UserHandle getUser() { 10285 return mUser; 10286 } 10287 10288 final boolean startCopy() { 10289 boolean res; 10290 try { 10291 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10292 10293 if (++mRetries > MAX_RETRIES) { 10294 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10295 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10296 handleServiceError(); 10297 return false; 10298 } else { 10299 handleStartCopy(); 10300 res = true; 10301 } 10302 } catch (RemoteException e) { 10303 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10304 mHandler.sendEmptyMessage(MCS_RECONNECT); 10305 res = false; 10306 } 10307 handleReturnCode(); 10308 return res; 10309 } 10310 10311 final void serviceError() { 10312 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10313 handleServiceError(); 10314 handleReturnCode(); 10315 } 10316 10317 abstract void handleStartCopy() throws RemoteException; 10318 abstract void handleServiceError(); 10319 abstract void handleReturnCode(); 10320 } 10321 10322 class MeasureParams extends HandlerParams { 10323 private final PackageStats mStats; 10324 private boolean mSuccess; 10325 10326 private final IPackageStatsObserver mObserver; 10327 10328 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10329 super(new UserHandle(stats.userHandle)); 10330 mObserver = observer; 10331 mStats = stats; 10332 } 10333 10334 @Override 10335 public String toString() { 10336 return "MeasureParams{" 10337 + Integer.toHexString(System.identityHashCode(this)) 10338 + " " + mStats.packageName + "}"; 10339 } 10340 10341 @Override 10342 void handleStartCopy() throws RemoteException { 10343 synchronized (mInstallLock) { 10344 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10345 } 10346 10347 if (mSuccess) { 10348 final boolean mounted; 10349 if (Environment.isExternalStorageEmulated()) { 10350 mounted = true; 10351 } else { 10352 final String status = Environment.getExternalStorageState(); 10353 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10354 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10355 } 10356 10357 if (mounted) { 10358 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10359 10360 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10361 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10362 10363 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10364 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10365 10366 // Always subtract cache size, since it's a subdirectory 10367 mStats.externalDataSize -= mStats.externalCacheSize; 10368 10369 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10370 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10371 10372 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10373 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10374 } 10375 } 10376 } 10377 10378 @Override 10379 void handleReturnCode() { 10380 if (mObserver != null) { 10381 try { 10382 mObserver.onGetStatsCompleted(mStats, mSuccess); 10383 } catch (RemoteException e) { 10384 Slog.i(TAG, "Observer no longer exists."); 10385 } 10386 } 10387 } 10388 10389 @Override 10390 void handleServiceError() { 10391 Slog.e(TAG, "Could not measure application " + mStats.packageName 10392 + " external storage"); 10393 } 10394 } 10395 10396 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10397 throws RemoteException { 10398 long result = 0; 10399 for (File path : paths) { 10400 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10401 } 10402 return result; 10403 } 10404 10405 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10406 for (File path : paths) { 10407 try { 10408 mcs.clearDirectory(path.getAbsolutePath()); 10409 } catch (RemoteException e) { 10410 } 10411 } 10412 } 10413 10414 static class OriginInfo { 10415 /** 10416 * Location where install is coming from, before it has been 10417 * copied/renamed into place. This could be a single monolithic APK 10418 * file, or a cluster directory. This location may be untrusted. 10419 */ 10420 final File file; 10421 final String cid; 10422 10423 /** 10424 * Flag indicating that {@link #file} or {@link #cid} has already been 10425 * staged, meaning downstream users don't need to defensively copy the 10426 * contents. 10427 */ 10428 final boolean staged; 10429 10430 /** 10431 * Flag indicating that {@link #file} or {@link #cid} is an already 10432 * installed app that is being moved. 10433 */ 10434 final boolean existing; 10435 10436 final String resolvedPath; 10437 final File resolvedFile; 10438 10439 static OriginInfo fromNothing() { 10440 return new OriginInfo(null, null, false, false); 10441 } 10442 10443 static OriginInfo fromUntrustedFile(File file) { 10444 return new OriginInfo(file, null, false, false); 10445 } 10446 10447 static OriginInfo fromExistingFile(File file) { 10448 return new OriginInfo(file, null, false, true); 10449 } 10450 10451 static OriginInfo fromStagedFile(File file) { 10452 return new OriginInfo(file, null, true, false); 10453 } 10454 10455 static OriginInfo fromStagedContainer(String cid) { 10456 return new OriginInfo(null, cid, true, false); 10457 } 10458 10459 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10460 this.file = file; 10461 this.cid = cid; 10462 this.staged = staged; 10463 this.existing = existing; 10464 10465 if (cid != null) { 10466 resolvedPath = PackageHelper.getSdDir(cid); 10467 resolvedFile = new File(resolvedPath); 10468 } else if (file != null) { 10469 resolvedPath = file.getAbsolutePath(); 10470 resolvedFile = file; 10471 } else { 10472 resolvedPath = null; 10473 resolvedFile = null; 10474 } 10475 } 10476 } 10477 10478 class MoveInfo { 10479 final int moveId; 10480 final String fromUuid; 10481 final String toUuid; 10482 final String packageName; 10483 final String dataAppName; 10484 final int appId; 10485 final String seinfo; 10486 10487 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10488 String dataAppName, int appId, String seinfo) { 10489 this.moveId = moveId; 10490 this.fromUuid = fromUuid; 10491 this.toUuid = toUuid; 10492 this.packageName = packageName; 10493 this.dataAppName = dataAppName; 10494 this.appId = appId; 10495 this.seinfo = seinfo; 10496 } 10497 } 10498 10499 class InstallParams extends HandlerParams { 10500 final OriginInfo origin; 10501 final MoveInfo move; 10502 final IPackageInstallObserver2 observer; 10503 int installFlags; 10504 final String installerPackageName; 10505 final String volumeUuid; 10506 final VerificationParams verificationParams; 10507 private InstallArgs mArgs; 10508 private int mRet; 10509 final String packageAbiOverride; 10510 final String[] grantedRuntimePermissions; 10511 10512 10513 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10514 int installFlags, String installerPackageName, String volumeUuid, 10515 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10516 String[] grantedPermissions) { 10517 super(user); 10518 this.origin = origin; 10519 this.move = move; 10520 this.observer = observer; 10521 this.installFlags = installFlags; 10522 this.installerPackageName = installerPackageName; 10523 this.volumeUuid = volumeUuid; 10524 this.verificationParams = verificationParams; 10525 this.packageAbiOverride = packageAbiOverride; 10526 this.grantedRuntimePermissions = grantedPermissions; 10527 } 10528 10529 @Override 10530 public String toString() { 10531 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10532 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10533 } 10534 10535 public ManifestDigest getManifestDigest() { 10536 if (verificationParams == null) { 10537 return null; 10538 } 10539 return verificationParams.getManifestDigest(); 10540 } 10541 10542 private int installLocationPolicy(PackageInfoLite pkgLite) { 10543 String packageName = pkgLite.packageName; 10544 int installLocation = pkgLite.installLocation; 10545 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10546 // reader 10547 synchronized (mPackages) { 10548 PackageParser.Package pkg = mPackages.get(packageName); 10549 if (pkg != null) { 10550 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10551 // Check for downgrading. 10552 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10553 try { 10554 checkDowngrade(pkg, pkgLite); 10555 } catch (PackageManagerException e) { 10556 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10557 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10558 } 10559 } 10560 // Check for updated system application. 10561 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10562 if (onSd) { 10563 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10564 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10565 } 10566 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10567 } else { 10568 if (onSd) { 10569 // Install flag overrides everything. 10570 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10571 } 10572 // If current upgrade specifies particular preference 10573 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10574 // Application explicitly specified internal. 10575 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10576 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10577 // App explictly prefers external. Let policy decide 10578 } else { 10579 // Prefer previous location 10580 if (isExternal(pkg)) { 10581 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10582 } 10583 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10584 } 10585 } 10586 } else { 10587 // Invalid install. Return error code 10588 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10589 } 10590 } 10591 } 10592 // All the special cases have been taken care of. 10593 // Return result based on recommended install location. 10594 if (onSd) { 10595 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10596 } 10597 return pkgLite.recommendedInstallLocation; 10598 } 10599 10600 /* 10601 * Invoke remote method to get package information and install 10602 * location values. Override install location based on default 10603 * policy if needed and then create install arguments based 10604 * on the install location. 10605 */ 10606 public void handleStartCopy() throws RemoteException { 10607 int ret = PackageManager.INSTALL_SUCCEEDED; 10608 10609 // If we're already staged, we've firmly committed to an install location 10610 if (origin.staged) { 10611 if (origin.file != null) { 10612 installFlags |= PackageManager.INSTALL_INTERNAL; 10613 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10614 } else if (origin.cid != null) { 10615 installFlags |= PackageManager.INSTALL_EXTERNAL; 10616 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10617 } else { 10618 throw new IllegalStateException("Invalid stage location"); 10619 } 10620 } 10621 10622 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10623 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10624 PackageInfoLite pkgLite = null; 10625 10626 if (onInt && onSd) { 10627 // Check if both bits are set. 10628 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10629 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10630 } else { 10631 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10632 packageAbiOverride); 10633 10634 /* 10635 * If we have too little free space, try to free cache 10636 * before giving up. 10637 */ 10638 if (!origin.staged && pkgLite.recommendedInstallLocation 10639 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10640 // TODO: focus freeing disk space on the target device 10641 final StorageManager storage = StorageManager.from(mContext); 10642 final long lowThreshold = storage.getStorageLowBytes( 10643 Environment.getDataDirectory()); 10644 10645 final long sizeBytes = mContainerService.calculateInstalledSize( 10646 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10647 10648 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10649 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10650 installFlags, packageAbiOverride); 10651 } 10652 10653 /* 10654 * The cache free must have deleted the file we 10655 * downloaded to install. 10656 * 10657 * TODO: fix the "freeCache" call to not delete 10658 * the file we care about. 10659 */ 10660 if (pkgLite.recommendedInstallLocation 10661 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10662 pkgLite.recommendedInstallLocation 10663 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10664 } 10665 } 10666 } 10667 10668 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10669 int loc = pkgLite.recommendedInstallLocation; 10670 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10671 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10672 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10673 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10674 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10675 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10676 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10677 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10678 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10679 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10680 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10681 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10682 } else { 10683 // Override with defaults if needed. 10684 loc = installLocationPolicy(pkgLite); 10685 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10686 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10687 } else if (!onSd && !onInt) { 10688 // Override install location with flags 10689 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10690 // Set the flag to install on external media. 10691 installFlags |= PackageManager.INSTALL_EXTERNAL; 10692 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10693 } else { 10694 // Make sure the flag for installing on external 10695 // media is unset 10696 installFlags |= PackageManager.INSTALL_INTERNAL; 10697 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10698 } 10699 } 10700 } 10701 } 10702 10703 final InstallArgs args = createInstallArgs(this); 10704 mArgs = args; 10705 10706 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10707 /* 10708 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10709 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10710 */ 10711 int userIdentifier = getUser().getIdentifier(); 10712 if (userIdentifier == UserHandle.USER_ALL 10713 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10714 userIdentifier = UserHandle.USER_OWNER; 10715 } 10716 10717 /* 10718 * Determine if we have any installed package verifiers. If we 10719 * do, then we'll defer to them to verify the packages. 10720 */ 10721 final int requiredUid = mRequiredVerifierPackage == null ? -1 10722 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10723 if (!origin.existing && requiredUid != -1 10724 && isVerificationEnabled(userIdentifier, installFlags)) { 10725 final Intent verification = new Intent( 10726 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10727 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10728 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10729 PACKAGE_MIME_TYPE); 10730 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10731 10732 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10733 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10734 0 /* TODO: Which userId? */); 10735 10736 if (DEBUG_VERIFY) { 10737 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10738 + verification.toString() + " with " + pkgLite.verifiers.length 10739 + " optional verifiers"); 10740 } 10741 10742 final int verificationId = mPendingVerificationToken++; 10743 10744 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10745 10746 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10747 installerPackageName); 10748 10749 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10750 installFlags); 10751 10752 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10753 pkgLite.packageName); 10754 10755 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10756 pkgLite.versionCode); 10757 10758 if (verificationParams != null) { 10759 if (verificationParams.getVerificationURI() != null) { 10760 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10761 verificationParams.getVerificationURI()); 10762 } 10763 if (verificationParams.getOriginatingURI() != null) { 10764 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10765 verificationParams.getOriginatingURI()); 10766 } 10767 if (verificationParams.getReferrer() != null) { 10768 verification.putExtra(Intent.EXTRA_REFERRER, 10769 verificationParams.getReferrer()); 10770 } 10771 if (verificationParams.getOriginatingUid() >= 0) { 10772 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10773 verificationParams.getOriginatingUid()); 10774 } 10775 if (verificationParams.getInstallerUid() >= 0) { 10776 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10777 verificationParams.getInstallerUid()); 10778 } 10779 } 10780 10781 final PackageVerificationState verificationState = new PackageVerificationState( 10782 requiredUid, args); 10783 10784 mPendingVerification.append(verificationId, verificationState); 10785 10786 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10787 receivers, verificationState); 10788 10789 // Apps installed for "all" users use the device owner to verify the app 10790 UserHandle verifierUser = getUser(); 10791 if (verifierUser == UserHandle.ALL) { 10792 verifierUser = UserHandle.OWNER; 10793 } 10794 10795 /* 10796 * If any sufficient verifiers were listed in the package 10797 * manifest, attempt to ask them. 10798 */ 10799 if (sufficientVerifiers != null) { 10800 final int N = sufficientVerifiers.size(); 10801 if (N == 0) { 10802 Slog.i(TAG, "Additional verifiers required, but none installed."); 10803 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10804 } else { 10805 for (int i = 0; i < N; i++) { 10806 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10807 10808 final Intent sufficientIntent = new Intent(verification); 10809 sufficientIntent.setComponent(verifierComponent); 10810 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10811 } 10812 } 10813 } 10814 10815 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10816 mRequiredVerifierPackage, receivers); 10817 if (ret == PackageManager.INSTALL_SUCCEEDED 10818 && mRequiredVerifierPackage != null) { 10819 Trace.asyncTraceBegin( 10820 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 10821 /* 10822 * Send the intent to the required verification agent, 10823 * but only start the verification timeout after the 10824 * target BroadcastReceivers have run. 10825 */ 10826 verification.setComponent(requiredVerifierComponent); 10827 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10828 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10829 new BroadcastReceiver() { 10830 @Override 10831 public void onReceive(Context context, Intent intent) { 10832 final Message msg = mHandler 10833 .obtainMessage(CHECK_PENDING_VERIFICATION); 10834 msg.arg1 = verificationId; 10835 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10836 } 10837 }, null, 0, null, null); 10838 10839 /* 10840 * We don't want the copy to proceed until verification 10841 * succeeds, so null out this field. 10842 */ 10843 mArgs = null; 10844 } 10845 } else { 10846 /* 10847 * No package verification is enabled, so immediately start 10848 * the remote call to initiate copy using temporary file. 10849 */ 10850 ret = args.copyApk(mContainerService, true); 10851 } 10852 } 10853 10854 mRet = ret; 10855 } 10856 10857 @Override 10858 void handleReturnCode() { 10859 // If mArgs is null, then MCS couldn't be reached. When it 10860 // reconnects, it will try again to install. At that point, this 10861 // will succeed. 10862 if (mArgs != null) { 10863 processPendingInstall(mArgs, mRet); 10864 } 10865 } 10866 10867 @Override 10868 void handleServiceError() { 10869 mArgs = createInstallArgs(this); 10870 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10871 } 10872 10873 public boolean isForwardLocked() { 10874 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10875 } 10876 } 10877 10878 /** 10879 * Used during creation of InstallArgs 10880 * 10881 * @param installFlags package installation flags 10882 * @return true if should be installed on external storage 10883 */ 10884 private static boolean installOnExternalAsec(int installFlags) { 10885 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10886 return false; 10887 } 10888 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10889 return true; 10890 } 10891 return false; 10892 } 10893 10894 /** 10895 * Used during creation of InstallArgs 10896 * 10897 * @param installFlags package installation flags 10898 * @return true if should be installed as forward locked 10899 */ 10900 private static boolean installForwardLocked(int installFlags) { 10901 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10902 } 10903 10904 private InstallArgs createInstallArgs(InstallParams params) { 10905 if (params.move != null) { 10906 return new MoveInstallArgs(params); 10907 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10908 return new AsecInstallArgs(params); 10909 } else { 10910 return new FileInstallArgs(params); 10911 } 10912 } 10913 10914 /** 10915 * Create args that describe an existing installed package. Typically used 10916 * when cleaning up old installs, or used as a move source. 10917 */ 10918 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10919 String resourcePath, String[] instructionSets) { 10920 final boolean isInAsec; 10921 if (installOnExternalAsec(installFlags)) { 10922 /* Apps on SD card are always in ASEC containers. */ 10923 isInAsec = true; 10924 } else if (installForwardLocked(installFlags) 10925 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10926 /* 10927 * Forward-locked apps are only in ASEC containers if they're the 10928 * new style 10929 */ 10930 isInAsec = true; 10931 } else { 10932 isInAsec = false; 10933 } 10934 10935 if (isInAsec) { 10936 return new AsecInstallArgs(codePath, instructionSets, 10937 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10938 } else { 10939 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10940 } 10941 } 10942 10943 static abstract class InstallArgs { 10944 /** @see InstallParams#origin */ 10945 final OriginInfo origin; 10946 /** @see InstallParams#move */ 10947 final MoveInfo move; 10948 10949 final IPackageInstallObserver2 observer; 10950 // Always refers to PackageManager flags only 10951 final int installFlags; 10952 final String installerPackageName; 10953 final String volumeUuid; 10954 final ManifestDigest manifestDigest; 10955 final UserHandle user; 10956 final String abiOverride; 10957 final String[] installGrantPermissions; 10958 10959 // The list of instruction sets supported by this app. This is currently 10960 // only used during the rmdex() phase to clean up resources. We can get rid of this 10961 // if we move dex files under the common app path. 10962 /* nullable */ String[] instructionSets; 10963 10964 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10965 int installFlags, String installerPackageName, String volumeUuid, 10966 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10967 String abiOverride, String[] installGrantPermissions) { 10968 this.origin = origin; 10969 this.move = move; 10970 this.installFlags = installFlags; 10971 this.observer = observer; 10972 this.installerPackageName = installerPackageName; 10973 this.volumeUuid = volumeUuid; 10974 this.manifestDigest = manifestDigest; 10975 this.user = user; 10976 this.instructionSets = instructionSets; 10977 this.abiOverride = abiOverride; 10978 this.installGrantPermissions = installGrantPermissions; 10979 } 10980 10981 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10982 abstract int doPreInstall(int status); 10983 10984 /** 10985 * Rename package into final resting place. All paths on the given 10986 * scanned package should be updated to reflect the rename. 10987 */ 10988 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10989 abstract int doPostInstall(int status, int uid); 10990 10991 /** @see PackageSettingBase#codePathString */ 10992 abstract String getCodePath(); 10993 /** @see PackageSettingBase#resourcePathString */ 10994 abstract String getResourcePath(); 10995 10996 // Need installer lock especially for dex file removal. 10997 abstract void cleanUpResourcesLI(); 10998 abstract boolean doPostDeleteLI(boolean delete); 10999 11000 /** 11001 * Called before the source arguments are copied. This is used mostly 11002 * for MoveParams when it needs to read the source file to put it in the 11003 * destination. 11004 */ 11005 int doPreCopy() { 11006 return PackageManager.INSTALL_SUCCEEDED; 11007 } 11008 11009 /** 11010 * Called after the source arguments are copied. This is used mostly for 11011 * MoveParams when it needs to read the source file to put it in the 11012 * destination. 11013 * 11014 * @return 11015 */ 11016 int doPostCopy(int uid) { 11017 return PackageManager.INSTALL_SUCCEEDED; 11018 } 11019 11020 protected boolean isFwdLocked() { 11021 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11022 } 11023 11024 protected boolean isExternalAsec() { 11025 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11026 } 11027 11028 UserHandle getUser() { 11029 return user; 11030 } 11031 } 11032 11033 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11034 if (!allCodePaths.isEmpty()) { 11035 if (instructionSets == null) { 11036 throw new IllegalStateException("instructionSet == null"); 11037 } 11038 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11039 for (String codePath : allCodePaths) { 11040 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11041 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11042 if (retCode < 0) { 11043 Slog.w(TAG, "Couldn't remove dex file for package: " 11044 + " at location " + codePath + ", retcode=" + retCode); 11045 // we don't consider this to be a failure of the core package deletion 11046 } 11047 } 11048 } 11049 } 11050 } 11051 11052 /** 11053 * Logic to handle installation of non-ASEC applications, including copying 11054 * and renaming logic. 11055 */ 11056 class FileInstallArgs extends InstallArgs { 11057 private File codeFile; 11058 private File resourceFile; 11059 11060 // Example topology: 11061 // /data/app/com.example/base.apk 11062 // /data/app/com.example/split_foo.apk 11063 // /data/app/com.example/lib/arm/libfoo.so 11064 // /data/app/com.example/lib/arm64/libfoo.so 11065 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11066 11067 /** New install */ 11068 FileInstallArgs(InstallParams params) { 11069 super(params.origin, params.move, params.observer, params.installFlags, 11070 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11071 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11072 params.grantedRuntimePermissions); 11073 if (isFwdLocked()) { 11074 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11075 } 11076 } 11077 11078 /** Existing install */ 11079 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11080 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11081 null, null); 11082 this.codeFile = (codePath != null) ? new File(codePath) : null; 11083 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11084 } 11085 11086 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11087 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11088 try { 11089 return doCopyApk(imcs, temp); 11090 } finally { 11091 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11092 } 11093 } 11094 11095 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11096 if (origin.staged) { 11097 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11098 codeFile = origin.file; 11099 resourceFile = origin.file; 11100 return PackageManager.INSTALL_SUCCEEDED; 11101 } 11102 11103 try { 11104 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11105 codeFile = tempDir; 11106 resourceFile = tempDir; 11107 } catch (IOException e) { 11108 Slog.w(TAG, "Failed to create copy file: " + e); 11109 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11110 } 11111 11112 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11113 @Override 11114 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11115 if (!FileUtils.isValidExtFilename(name)) { 11116 throw new IllegalArgumentException("Invalid filename: " + name); 11117 } 11118 try { 11119 final File file = new File(codeFile, name); 11120 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11121 O_RDWR | O_CREAT, 0644); 11122 Os.chmod(file.getAbsolutePath(), 0644); 11123 return new ParcelFileDescriptor(fd); 11124 } catch (ErrnoException e) { 11125 throw new RemoteException("Failed to open: " + e.getMessage()); 11126 } 11127 } 11128 }; 11129 11130 int ret = PackageManager.INSTALL_SUCCEEDED; 11131 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11132 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11133 Slog.e(TAG, "Failed to copy package"); 11134 return ret; 11135 } 11136 11137 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11138 NativeLibraryHelper.Handle handle = null; 11139 try { 11140 handle = NativeLibraryHelper.Handle.create(codeFile); 11141 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11142 abiOverride); 11143 } catch (IOException e) { 11144 Slog.e(TAG, "Copying native libraries failed", e); 11145 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11146 } finally { 11147 IoUtils.closeQuietly(handle); 11148 } 11149 11150 return ret; 11151 } 11152 11153 int doPreInstall(int status) { 11154 if (status != PackageManager.INSTALL_SUCCEEDED) { 11155 cleanUp(); 11156 } 11157 return status; 11158 } 11159 11160 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11161 if (status != PackageManager.INSTALL_SUCCEEDED) { 11162 cleanUp(); 11163 return false; 11164 } 11165 11166 final File targetDir = codeFile.getParentFile(); 11167 final File beforeCodeFile = codeFile; 11168 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11169 11170 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11171 try { 11172 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11173 } catch (ErrnoException e) { 11174 Slog.w(TAG, "Failed to rename", e); 11175 return false; 11176 } 11177 11178 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11179 Slog.w(TAG, "Failed to restorecon"); 11180 return false; 11181 } 11182 11183 // Reflect the rename internally 11184 codeFile = afterCodeFile; 11185 resourceFile = afterCodeFile; 11186 11187 // Reflect the rename in scanned details 11188 pkg.codePath = afterCodeFile.getAbsolutePath(); 11189 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11190 pkg.baseCodePath); 11191 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11192 pkg.splitCodePaths); 11193 11194 // Reflect the rename in app info 11195 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11196 pkg.applicationInfo.setCodePath(pkg.codePath); 11197 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11198 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11199 pkg.applicationInfo.setResourcePath(pkg.codePath); 11200 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11201 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11202 11203 return true; 11204 } 11205 11206 int doPostInstall(int status, int uid) { 11207 if (status != PackageManager.INSTALL_SUCCEEDED) { 11208 cleanUp(); 11209 } 11210 return status; 11211 } 11212 11213 @Override 11214 String getCodePath() { 11215 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11216 } 11217 11218 @Override 11219 String getResourcePath() { 11220 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11221 } 11222 11223 private boolean cleanUp() { 11224 if (codeFile == null || !codeFile.exists()) { 11225 return false; 11226 } 11227 11228 if (codeFile.isDirectory()) { 11229 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11230 } else { 11231 codeFile.delete(); 11232 } 11233 11234 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11235 resourceFile.delete(); 11236 } 11237 11238 return true; 11239 } 11240 11241 void cleanUpResourcesLI() { 11242 // Try enumerating all code paths before deleting 11243 List<String> allCodePaths = Collections.EMPTY_LIST; 11244 if (codeFile != null && codeFile.exists()) { 11245 try { 11246 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11247 allCodePaths = pkg.getAllCodePaths(); 11248 } catch (PackageParserException e) { 11249 // Ignored; we tried our best 11250 } 11251 } 11252 11253 cleanUp(); 11254 removeDexFiles(allCodePaths, instructionSets); 11255 } 11256 11257 boolean doPostDeleteLI(boolean delete) { 11258 // XXX err, shouldn't we respect the delete flag? 11259 cleanUpResourcesLI(); 11260 return true; 11261 } 11262 } 11263 11264 private boolean isAsecExternal(String cid) { 11265 final String asecPath = PackageHelper.getSdFilesystem(cid); 11266 return !asecPath.startsWith(mAsecInternalPath); 11267 } 11268 11269 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11270 PackageManagerException { 11271 if (copyRet < 0) { 11272 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11273 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11274 throw new PackageManagerException(copyRet, message); 11275 } 11276 } 11277 } 11278 11279 /** 11280 * Extract the MountService "container ID" from the full code path of an 11281 * .apk. 11282 */ 11283 static String cidFromCodePath(String fullCodePath) { 11284 int eidx = fullCodePath.lastIndexOf("/"); 11285 String subStr1 = fullCodePath.substring(0, eidx); 11286 int sidx = subStr1.lastIndexOf("/"); 11287 return subStr1.substring(sidx+1, eidx); 11288 } 11289 11290 /** 11291 * Logic to handle installation of ASEC applications, including copying and 11292 * renaming logic. 11293 */ 11294 class AsecInstallArgs extends InstallArgs { 11295 static final String RES_FILE_NAME = "pkg.apk"; 11296 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11297 11298 String cid; 11299 String packagePath; 11300 String resourcePath; 11301 11302 /** New install */ 11303 AsecInstallArgs(InstallParams params) { 11304 super(params.origin, params.move, params.observer, params.installFlags, 11305 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11306 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11307 params.grantedRuntimePermissions); 11308 } 11309 11310 /** Existing install */ 11311 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11312 boolean isExternal, boolean isForwardLocked) { 11313 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11314 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11315 instructionSets, null, null); 11316 // Hackily pretend we're still looking at a full code path 11317 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11318 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11319 } 11320 11321 // Extract cid from fullCodePath 11322 int eidx = fullCodePath.lastIndexOf("/"); 11323 String subStr1 = fullCodePath.substring(0, eidx); 11324 int sidx = subStr1.lastIndexOf("/"); 11325 cid = subStr1.substring(sidx+1, eidx); 11326 setMountPath(subStr1); 11327 } 11328 11329 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11330 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11331 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11332 instructionSets, null, null); 11333 this.cid = cid; 11334 setMountPath(PackageHelper.getSdDir(cid)); 11335 } 11336 11337 void createCopyFile() { 11338 cid = mInstallerService.allocateExternalStageCidLegacy(); 11339 } 11340 11341 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11342 if (origin.staged) { 11343 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11344 cid = origin.cid; 11345 setMountPath(PackageHelper.getSdDir(cid)); 11346 return PackageManager.INSTALL_SUCCEEDED; 11347 } 11348 11349 if (temp) { 11350 createCopyFile(); 11351 } else { 11352 /* 11353 * Pre-emptively destroy the container since it's destroyed if 11354 * copying fails due to it existing anyway. 11355 */ 11356 PackageHelper.destroySdDir(cid); 11357 } 11358 11359 final String newMountPath = imcs.copyPackageToContainer( 11360 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11361 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11362 11363 if (newMountPath != null) { 11364 setMountPath(newMountPath); 11365 return PackageManager.INSTALL_SUCCEEDED; 11366 } else { 11367 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11368 } 11369 } 11370 11371 @Override 11372 String getCodePath() { 11373 return packagePath; 11374 } 11375 11376 @Override 11377 String getResourcePath() { 11378 return resourcePath; 11379 } 11380 11381 int doPreInstall(int status) { 11382 if (status != PackageManager.INSTALL_SUCCEEDED) { 11383 // Destroy container 11384 PackageHelper.destroySdDir(cid); 11385 } else { 11386 boolean mounted = PackageHelper.isContainerMounted(cid); 11387 if (!mounted) { 11388 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11389 Process.SYSTEM_UID); 11390 if (newMountPath != null) { 11391 setMountPath(newMountPath); 11392 } else { 11393 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11394 } 11395 } 11396 } 11397 return status; 11398 } 11399 11400 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11401 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11402 String newMountPath = null; 11403 if (PackageHelper.isContainerMounted(cid)) { 11404 // Unmount the container 11405 if (!PackageHelper.unMountSdDir(cid)) { 11406 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11407 return false; 11408 } 11409 } 11410 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11411 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11412 " which might be stale. Will try to clean up."); 11413 // Clean up the stale container and proceed to recreate. 11414 if (!PackageHelper.destroySdDir(newCacheId)) { 11415 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11416 return false; 11417 } 11418 // Successfully cleaned up stale container. Try to rename again. 11419 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11420 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11421 + " inspite of cleaning it up."); 11422 return false; 11423 } 11424 } 11425 if (!PackageHelper.isContainerMounted(newCacheId)) { 11426 Slog.w(TAG, "Mounting container " + newCacheId); 11427 newMountPath = PackageHelper.mountSdDir(newCacheId, 11428 getEncryptKey(), Process.SYSTEM_UID); 11429 } else { 11430 newMountPath = PackageHelper.getSdDir(newCacheId); 11431 } 11432 if (newMountPath == null) { 11433 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11434 return false; 11435 } 11436 Log.i(TAG, "Succesfully renamed " + cid + 11437 " to " + newCacheId + 11438 " at new path: " + newMountPath); 11439 cid = newCacheId; 11440 11441 final File beforeCodeFile = new File(packagePath); 11442 setMountPath(newMountPath); 11443 final File afterCodeFile = new File(packagePath); 11444 11445 // Reflect the rename in scanned details 11446 pkg.codePath = afterCodeFile.getAbsolutePath(); 11447 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11448 pkg.baseCodePath); 11449 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11450 pkg.splitCodePaths); 11451 11452 // Reflect the rename in app info 11453 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11454 pkg.applicationInfo.setCodePath(pkg.codePath); 11455 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11456 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11457 pkg.applicationInfo.setResourcePath(pkg.codePath); 11458 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11459 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11460 11461 return true; 11462 } 11463 11464 private void setMountPath(String mountPath) { 11465 final File mountFile = new File(mountPath); 11466 11467 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11468 if (monolithicFile.exists()) { 11469 packagePath = monolithicFile.getAbsolutePath(); 11470 if (isFwdLocked()) { 11471 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11472 } else { 11473 resourcePath = packagePath; 11474 } 11475 } else { 11476 packagePath = mountFile.getAbsolutePath(); 11477 resourcePath = packagePath; 11478 } 11479 } 11480 11481 int doPostInstall(int status, int uid) { 11482 if (status != PackageManager.INSTALL_SUCCEEDED) { 11483 cleanUp(); 11484 } else { 11485 final int groupOwner; 11486 final String protectedFile; 11487 if (isFwdLocked()) { 11488 groupOwner = UserHandle.getSharedAppGid(uid); 11489 protectedFile = RES_FILE_NAME; 11490 } else { 11491 groupOwner = -1; 11492 protectedFile = null; 11493 } 11494 11495 if (uid < Process.FIRST_APPLICATION_UID 11496 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11497 Slog.e(TAG, "Failed to finalize " + cid); 11498 PackageHelper.destroySdDir(cid); 11499 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11500 } 11501 11502 boolean mounted = PackageHelper.isContainerMounted(cid); 11503 if (!mounted) { 11504 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11505 } 11506 } 11507 return status; 11508 } 11509 11510 private void cleanUp() { 11511 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11512 11513 // Destroy secure container 11514 PackageHelper.destroySdDir(cid); 11515 } 11516 11517 private List<String> getAllCodePaths() { 11518 final File codeFile = new File(getCodePath()); 11519 if (codeFile != null && codeFile.exists()) { 11520 try { 11521 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11522 return pkg.getAllCodePaths(); 11523 } catch (PackageParserException e) { 11524 // Ignored; we tried our best 11525 } 11526 } 11527 return Collections.EMPTY_LIST; 11528 } 11529 11530 void cleanUpResourcesLI() { 11531 // Enumerate all code paths before deleting 11532 cleanUpResourcesLI(getAllCodePaths()); 11533 } 11534 11535 private void cleanUpResourcesLI(List<String> allCodePaths) { 11536 cleanUp(); 11537 removeDexFiles(allCodePaths, instructionSets); 11538 } 11539 11540 String getPackageName() { 11541 return getAsecPackageName(cid); 11542 } 11543 11544 boolean doPostDeleteLI(boolean delete) { 11545 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11546 final List<String> allCodePaths = getAllCodePaths(); 11547 boolean mounted = PackageHelper.isContainerMounted(cid); 11548 if (mounted) { 11549 // Unmount first 11550 if (PackageHelper.unMountSdDir(cid)) { 11551 mounted = false; 11552 } 11553 } 11554 if (!mounted && delete) { 11555 cleanUpResourcesLI(allCodePaths); 11556 } 11557 return !mounted; 11558 } 11559 11560 @Override 11561 int doPreCopy() { 11562 if (isFwdLocked()) { 11563 if (!PackageHelper.fixSdPermissions(cid, 11564 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11565 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11566 } 11567 } 11568 11569 return PackageManager.INSTALL_SUCCEEDED; 11570 } 11571 11572 @Override 11573 int doPostCopy(int uid) { 11574 if (isFwdLocked()) { 11575 if (uid < Process.FIRST_APPLICATION_UID 11576 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11577 RES_FILE_NAME)) { 11578 Slog.e(TAG, "Failed to finalize " + cid); 11579 PackageHelper.destroySdDir(cid); 11580 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11581 } 11582 } 11583 11584 return PackageManager.INSTALL_SUCCEEDED; 11585 } 11586 } 11587 11588 /** 11589 * Logic to handle movement of existing installed applications. 11590 */ 11591 class MoveInstallArgs extends InstallArgs { 11592 private File codeFile; 11593 private File resourceFile; 11594 11595 /** New install */ 11596 MoveInstallArgs(InstallParams params) { 11597 super(params.origin, params.move, params.observer, params.installFlags, 11598 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11599 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11600 params.grantedRuntimePermissions); 11601 } 11602 11603 int copyApk(IMediaContainerService imcs, boolean temp) { 11604 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11605 + move.fromUuid + " to " + move.toUuid); 11606 synchronized (mInstaller) { 11607 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11608 move.dataAppName, move.appId, move.seinfo) != 0) { 11609 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11610 } 11611 } 11612 11613 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11614 resourceFile = codeFile; 11615 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11616 11617 return PackageManager.INSTALL_SUCCEEDED; 11618 } 11619 11620 int doPreInstall(int status) { 11621 if (status != PackageManager.INSTALL_SUCCEEDED) { 11622 cleanUp(move.toUuid); 11623 } 11624 return status; 11625 } 11626 11627 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11628 if (status != PackageManager.INSTALL_SUCCEEDED) { 11629 cleanUp(move.toUuid); 11630 return false; 11631 } 11632 11633 // Reflect the move in app info 11634 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11635 pkg.applicationInfo.setCodePath(pkg.codePath); 11636 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11637 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11638 pkg.applicationInfo.setResourcePath(pkg.codePath); 11639 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11640 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11641 11642 return true; 11643 } 11644 11645 int doPostInstall(int status, int uid) { 11646 if (status == PackageManager.INSTALL_SUCCEEDED) { 11647 cleanUp(move.fromUuid); 11648 } else { 11649 cleanUp(move.toUuid); 11650 } 11651 return status; 11652 } 11653 11654 @Override 11655 String getCodePath() { 11656 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11657 } 11658 11659 @Override 11660 String getResourcePath() { 11661 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11662 } 11663 11664 private boolean cleanUp(String volumeUuid) { 11665 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11666 move.dataAppName); 11667 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11668 synchronized (mInstallLock) { 11669 // Clean up both app data and code 11670 removeDataDirsLI(volumeUuid, move.packageName); 11671 if (codeFile.isDirectory()) { 11672 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11673 } else { 11674 codeFile.delete(); 11675 } 11676 } 11677 return true; 11678 } 11679 11680 void cleanUpResourcesLI() { 11681 throw new UnsupportedOperationException(); 11682 } 11683 11684 boolean doPostDeleteLI(boolean delete) { 11685 throw new UnsupportedOperationException(); 11686 } 11687 } 11688 11689 static String getAsecPackageName(String packageCid) { 11690 int idx = packageCid.lastIndexOf("-"); 11691 if (idx == -1) { 11692 return packageCid; 11693 } 11694 return packageCid.substring(0, idx); 11695 } 11696 11697 // Utility method used to create code paths based on package name and available index. 11698 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11699 String idxStr = ""; 11700 int idx = 1; 11701 // Fall back to default value of idx=1 if prefix is not 11702 // part of oldCodePath 11703 if (oldCodePath != null) { 11704 String subStr = oldCodePath; 11705 // Drop the suffix right away 11706 if (suffix != null && subStr.endsWith(suffix)) { 11707 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11708 } 11709 // If oldCodePath already contains prefix find out the 11710 // ending index to either increment or decrement. 11711 int sidx = subStr.lastIndexOf(prefix); 11712 if (sidx != -1) { 11713 subStr = subStr.substring(sidx + prefix.length()); 11714 if (subStr != null) { 11715 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11716 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11717 } 11718 try { 11719 idx = Integer.parseInt(subStr); 11720 if (idx <= 1) { 11721 idx++; 11722 } else { 11723 idx--; 11724 } 11725 } catch(NumberFormatException e) { 11726 } 11727 } 11728 } 11729 } 11730 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11731 return prefix + idxStr; 11732 } 11733 11734 private File getNextCodePath(File targetDir, String packageName) { 11735 int suffix = 1; 11736 File result; 11737 do { 11738 result = new File(targetDir, packageName + "-" + suffix); 11739 suffix++; 11740 } while (result.exists()); 11741 return result; 11742 } 11743 11744 // Utility method that returns the relative package path with respect 11745 // to the installation directory. Like say for /data/data/com.test-1.apk 11746 // string com.test-1 is returned. 11747 static String deriveCodePathName(String codePath) { 11748 if (codePath == null) { 11749 return null; 11750 } 11751 final File codeFile = new File(codePath); 11752 final String name = codeFile.getName(); 11753 if (codeFile.isDirectory()) { 11754 return name; 11755 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11756 final int lastDot = name.lastIndexOf('.'); 11757 return name.substring(0, lastDot); 11758 } else { 11759 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11760 return null; 11761 } 11762 } 11763 11764 class PackageInstalledInfo { 11765 String name; 11766 int uid; 11767 // The set of users that originally had this package installed. 11768 int[] origUsers; 11769 // The set of users that now have this package installed. 11770 int[] newUsers; 11771 PackageParser.Package pkg; 11772 int returnCode; 11773 String returnMsg; 11774 PackageRemovedInfo removedInfo; 11775 11776 public void setError(int code, String msg) { 11777 returnCode = code; 11778 returnMsg = msg; 11779 Slog.w(TAG, msg); 11780 } 11781 11782 public void setError(String msg, PackageParserException e) { 11783 returnCode = e.error; 11784 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11785 Slog.w(TAG, msg, e); 11786 } 11787 11788 public void setError(String msg, PackageManagerException e) { 11789 returnCode = e.error; 11790 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11791 Slog.w(TAG, msg, e); 11792 } 11793 11794 // In some error cases we want to convey more info back to the observer 11795 String origPackage; 11796 String origPermission; 11797 } 11798 11799 /* 11800 * Install a non-existing package. 11801 */ 11802 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11803 UserHandle user, String installerPackageName, String volumeUuid, 11804 PackageInstalledInfo res) { 11805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11806 11807 // Remember this for later, in case we need to rollback this install 11808 String pkgName = pkg.packageName; 11809 11810 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11811 final boolean dataDirExists = Environment 11812 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11813 11814 synchronized(mPackages) { 11815 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11816 // A package with the same name is already installed, though 11817 // it has been renamed to an older name. The package we 11818 // are trying to install should be installed as an update to 11819 // the existing one, but that has not been requested, so bail. 11820 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11821 + " without first uninstalling package running as " 11822 + mSettings.mRenamedPackages.get(pkgName)); 11823 return; 11824 } 11825 if (mPackages.containsKey(pkgName)) { 11826 // Don't allow installation over an existing package with the same name. 11827 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11828 + " without first uninstalling."); 11829 return; 11830 } 11831 } 11832 11833 try { 11834 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11835 System.currentTimeMillis(), user); 11836 11837 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11838 // delete the partially installed application. the data directory will have to be 11839 // restored if it was already existing 11840 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11841 // remove package from internal structures. Note that we want deletePackageX to 11842 // delete the package data and cache directories that it created in 11843 // scanPackageLocked, unless those directories existed before we even tried to 11844 // install. 11845 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11846 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11847 res.removedInfo, true); 11848 } 11849 11850 } catch (PackageManagerException e) { 11851 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11852 } 11853 11854 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11855 } 11856 11857 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11858 // Can't rotate keys during boot or if sharedUser. 11859 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11860 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11861 return false; 11862 } 11863 // app is using upgradeKeySets; make sure all are valid 11864 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11865 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11866 for (int i = 0; i < upgradeKeySets.length; i++) { 11867 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11868 Slog.wtf(TAG, "Package " 11869 + (oldPs.name != null ? oldPs.name : "<null>") 11870 + " contains upgrade-key-set reference to unknown key-set: " 11871 + upgradeKeySets[i] 11872 + " reverting to signatures check."); 11873 return false; 11874 } 11875 } 11876 return true; 11877 } 11878 11879 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11880 // Upgrade keysets are being used. Determine if new package has a superset of the 11881 // required keys. 11882 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11883 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11884 for (int i = 0; i < upgradeKeySets.length; i++) { 11885 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11886 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11887 return true; 11888 } 11889 } 11890 return false; 11891 } 11892 11893 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11894 UserHandle user, String installerPackageName, String volumeUuid, 11895 PackageInstalledInfo res) { 11896 final PackageParser.Package oldPackage; 11897 final String pkgName = pkg.packageName; 11898 final int[] allUsers; 11899 final boolean[] perUserInstalled; 11900 11901 // First find the old package info and check signatures 11902 synchronized(mPackages) { 11903 oldPackage = mPackages.get(pkgName); 11904 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11905 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11906 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11907 if(!checkUpgradeKeySetLP(ps, pkg)) { 11908 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11909 "New package not signed by keys specified by upgrade-keysets: " 11910 + pkgName); 11911 return; 11912 } 11913 } else { 11914 // default to original signature matching 11915 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11916 != PackageManager.SIGNATURE_MATCH) { 11917 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11918 "New package has a different signature: " + pkgName); 11919 return; 11920 } 11921 } 11922 11923 // In case of rollback, remember per-user/profile install state 11924 allUsers = sUserManager.getUserIds(); 11925 perUserInstalled = new boolean[allUsers.length]; 11926 for (int i = 0; i < allUsers.length; i++) { 11927 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11928 } 11929 } 11930 11931 boolean sysPkg = (isSystemApp(oldPackage)); 11932 if (sysPkg) { 11933 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11934 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11935 } else { 11936 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11937 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11938 } 11939 } 11940 11941 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11942 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11943 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11944 String volumeUuid, PackageInstalledInfo res) { 11945 String pkgName = deletedPackage.packageName; 11946 boolean deletedPkg = true; 11947 boolean updatedSettings = false; 11948 11949 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11950 + deletedPackage); 11951 long origUpdateTime; 11952 if (pkg.mExtras != null) { 11953 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11954 } else { 11955 origUpdateTime = 0; 11956 } 11957 11958 // First delete the existing package while retaining the data directory 11959 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11960 res.removedInfo, true)) { 11961 // If the existing package wasn't successfully deleted 11962 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11963 deletedPkg = false; 11964 } else { 11965 // Successfully deleted the old package; proceed with replace. 11966 11967 // If deleted package lived in a container, give users a chance to 11968 // relinquish resources before killing. 11969 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11970 if (DEBUG_INSTALL) { 11971 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11972 } 11973 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11974 final ArrayList<String> pkgList = new ArrayList<String>(1); 11975 pkgList.add(deletedPackage.applicationInfo.packageName); 11976 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11977 } 11978 11979 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11980 try { 11981 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 11982 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11983 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11984 perUserInstalled, res, user); 11985 updatedSettings = true; 11986 } catch (PackageManagerException e) { 11987 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11988 } 11989 } 11990 11991 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11992 // remove package from internal structures. Note that we want deletePackageX to 11993 // delete the package data and cache directories that it created in 11994 // scanPackageLocked, unless those directories existed before we even tried to 11995 // install. 11996 if(updatedSettings) { 11997 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11998 deletePackageLI( 11999 pkgName, null, true, allUsers, perUserInstalled, 12000 PackageManager.DELETE_KEEP_DATA, 12001 res.removedInfo, true); 12002 } 12003 // Since we failed to install the new package we need to restore the old 12004 // package that we deleted. 12005 if (deletedPkg) { 12006 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12007 File restoreFile = new File(deletedPackage.codePath); 12008 // Parse old package 12009 boolean oldExternal = isExternal(deletedPackage); 12010 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12011 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12012 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12013 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12014 try { 12015 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 12016 } catch (PackageManagerException e) { 12017 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12018 + e.getMessage()); 12019 return; 12020 } 12021 // Restore of old package succeeded. Update permissions. 12022 // writer 12023 synchronized (mPackages) { 12024 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12025 UPDATE_PERMISSIONS_ALL); 12026 // can downgrade to reader 12027 mSettings.writeLPr(); 12028 } 12029 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12030 } 12031 } 12032 } 12033 12034 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12035 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12036 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12037 String volumeUuid, PackageInstalledInfo res) { 12038 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12039 + ", old=" + deletedPackage); 12040 boolean disabledSystem = false; 12041 boolean updatedSettings = false; 12042 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12043 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12044 != 0) { 12045 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12046 } 12047 String packageName = deletedPackage.packageName; 12048 if (packageName == null) { 12049 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12050 "Attempt to delete null packageName."); 12051 return; 12052 } 12053 PackageParser.Package oldPkg; 12054 PackageSetting oldPkgSetting; 12055 // reader 12056 synchronized (mPackages) { 12057 oldPkg = mPackages.get(packageName); 12058 oldPkgSetting = mSettings.mPackages.get(packageName); 12059 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12060 (oldPkgSetting == null)) { 12061 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12062 "Couldn't find package:" + packageName + " information"); 12063 return; 12064 } 12065 } 12066 12067 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12068 12069 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12070 res.removedInfo.removedPackage = packageName; 12071 // Remove existing system package 12072 removePackageLI(oldPkgSetting, true); 12073 // writer 12074 synchronized (mPackages) { 12075 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12076 if (!disabledSystem && deletedPackage != null) { 12077 // We didn't need to disable the .apk as a current system package, 12078 // which means we are replacing another update that is already 12079 // installed. We need to make sure to delete the older one's .apk. 12080 res.removedInfo.args = createInstallArgsForExisting(0, 12081 deletedPackage.applicationInfo.getCodePath(), 12082 deletedPackage.applicationInfo.getResourcePath(), 12083 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12084 } else { 12085 res.removedInfo.args = null; 12086 } 12087 } 12088 12089 // Successfully disabled the old package. Now proceed with re-installation 12090 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12091 12092 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12093 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12094 12095 PackageParser.Package newPackage = null; 12096 try { 12097 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12098 if (newPackage.mExtras != null) { 12099 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12100 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12101 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12102 12103 // is the update attempting to change shared user? that isn't going to work... 12104 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12105 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12106 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12107 + " to " + newPkgSetting.sharedUser); 12108 updatedSettings = true; 12109 } 12110 } 12111 12112 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12113 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12114 perUserInstalled, res, user); 12115 updatedSettings = true; 12116 } 12117 12118 } catch (PackageManagerException e) { 12119 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12120 } 12121 12122 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12123 // Re installation failed. Restore old information 12124 // Remove new pkg information 12125 if (newPackage != null) { 12126 removeInstalledPackageLI(newPackage, true); 12127 } 12128 // Add back the old system package 12129 try { 12130 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12131 } catch (PackageManagerException e) { 12132 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12133 } 12134 // Restore the old system information in Settings 12135 synchronized (mPackages) { 12136 if (disabledSystem) { 12137 mSettings.enableSystemPackageLPw(packageName); 12138 } 12139 if (updatedSettings) { 12140 mSettings.setInstallerPackageName(packageName, 12141 oldPkgSetting.installerPackageName); 12142 } 12143 mSettings.writeLPr(); 12144 } 12145 } 12146 } 12147 12148 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12149 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12150 UserHandle user) { 12151 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12152 12153 String pkgName = newPackage.packageName; 12154 synchronized (mPackages) { 12155 //write settings. the installStatus will be incomplete at this stage. 12156 //note that the new package setting would have already been 12157 //added to mPackages. It hasn't been persisted yet. 12158 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12159 mSettings.writeLPr(); 12160 } 12161 12162 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12163 synchronized (mPackages) { 12164 updatePermissionsLPw(newPackage.packageName, newPackage, 12165 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12166 ? UPDATE_PERMISSIONS_ALL : 0)); 12167 // For system-bundled packages, we assume that installing an upgraded version 12168 // of the package implies that the user actually wants to run that new code, 12169 // so we enable the package. 12170 PackageSetting ps = mSettings.mPackages.get(pkgName); 12171 if (ps != null) { 12172 if (isSystemApp(newPackage)) { 12173 // NB: implicit assumption that system package upgrades apply to all users 12174 if (DEBUG_INSTALL) { 12175 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12176 } 12177 if (res.origUsers != null) { 12178 for (int userHandle : res.origUsers) { 12179 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12180 userHandle, installerPackageName); 12181 } 12182 } 12183 // Also convey the prior install/uninstall state 12184 if (allUsers != null && perUserInstalled != null) { 12185 for (int i = 0; i < allUsers.length; i++) { 12186 if (DEBUG_INSTALL) { 12187 Slog.d(TAG, " user " + allUsers[i] 12188 + " => " + perUserInstalled[i]); 12189 } 12190 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12191 } 12192 // these install state changes will be persisted in the 12193 // upcoming call to mSettings.writeLPr(). 12194 } 12195 } 12196 // It's implied that when a user requests installation, they want the app to be 12197 // installed and enabled. 12198 int userId = user.getIdentifier(); 12199 if (userId != UserHandle.USER_ALL) { 12200 ps.setInstalled(true, userId); 12201 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12202 } 12203 } 12204 res.name = pkgName; 12205 res.uid = newPackage.applicationInfo.uid; 12206 res.pkg = newPackage; 12207 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12208 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12209 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12210 //to update install status 12211 mSettings.writeLPr(); 12212 } 12213 12214 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12215 } 12216 12217 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12218 try { 12219 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12220 installPackageLI(args, res); 12221 } finally { 12222 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12223 } 12224 } 12225 12226 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12227 final int installFlags = args.installFlags; 12228 final String installerPackageName = args.installerPackageName; 12229 final String volumeUuid = args.volumeUuid; 12230 final File tmpPackageFile = new File(args.getCodePath()); 12231 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12232 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12233 || (args.volumeUuid != null)); 12234 boolean replace = false; 12235 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12236 if (args.move != null) { 12237 // moving a complete application; perfom an initial scan on the new install location 12238 scanFlags |= SCAN_INITIAL; 12239 } 12240 // Result object to be returned 12241 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12242 12243 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12244 12245 // Retrieve PackageSettings and parse package 12246 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12247 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12248 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12249 PackageParser pp = new PackageParser(); 12250 pp.setSeparateProcesses(mSeparateProcesses); 12251 pp.setDisplayMetrics(mMetrics); 12252 12253 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12254 final PackageParser.Package pkg; 12255 try { 12256 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12257 } catch (PackageParserException e) { 12258 res.setError("Failed parse during installPackageLI", e); 12259 return; 12260 } finally { 12261 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12262 } 12263 12264 // Mark that we have an install time CPU ABI override. 12265 pkg.cpuAbiOverride = args.abiOverride; 12266 12267 String pkgName = res.name = pkg.packageName; 12268 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12269 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12270 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12271 return; 12272 } 12273 } 12274 12275 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12276 try { 12277 pp.collectCertificates(pkg, parseFlags); 12278 pp.collectManifestDigest(pkg); 12279 } catch (PackageParserException e) { 12280 res.setError("Failed collect during installPackageLI", e); 12281 return; 12282 } finally { 12283 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12284 } 12285 12286 /* If the installer passed in a manifest digest, compare it now. */ 12287 if (args.manifestDigest != null) { 12288 if (DEBUG_INSTALL) { 12289 final String parsedManifest = pkg.manifestDigest == null ? "null" 12290 : pkg.manifestDigest.toString(); 12291 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12292 + parsedManifest); 12293 } 12294 12295 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12296 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12297 return; 12298 } 12299 } else if (DEBUG_INSTALL) { 12300 final String parsedManifest = pkg.manifestDigest == null 12301 ? "null" : pkg.manifestDigest.toString(); 12302 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12303 } 12304 12305 // Get rid of all references to package scan path via parser. 12306 pp = null; 12307 String oldCodePath = null; 12308 boolean systemApp = false; 12309 synchronized (mPackages) { 12310 // Check if installing already existing package 12311 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12312 String oldName = mSettings.mRenamedPackages.get(pkgName); 12313 if (pkg.mOriginalPackages != null 12314 && pkg.mOriginalPackages.contains(oldName) 12315 && mPackages.containsKey(oldName)) { 12316 // This package is derived from an original package, 12317 // and this device has been updating from that original 12318 // name. We must continue using the original name, so 12319 // rename the new package here. 12320 pkg.setPackageName(oldName); 12321 pkgName = pkg.packageName; 12322 replace = true; 12323 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12324 + oldName + " pkgName=" + pkgName); 12325 } else if (mPackages.containsKey(pkgName)) { 12326 // This package, under its official name, already exists 12327 // on the device; we should replace it. 12328 replace = true; 12329 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12330 } 12331 12332 // Prevent apps opting out from runtime permissions 12333 if (replace) { 12334 PackageParser.Package oldPackage = mPackages.get(pkgName); 12335 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12336 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12337 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12338 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12339 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12340 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12341 + " doesn't support runtime permissions but the old" 12342 + " target SDK " + oldTargetSdk + " does."); 12343 return; 12344 } 12345 } 12346 } 12347 12348 PackageSetting ps = mSettings.mPackages.get(pkgName); 12349 if (ps != null) { 12350 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12351 12352 // Quick sanity check that we're signed correctly if updating; 12353 // we'll check this again later when scanning, but we want to 12354 // bail early here before tripping over redefined permissions. 12355 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12356 if (!checkUpgradeKeySetLP(ps, pkg)) { 12357 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12358 + pkg.packageName + " upgrade keys do not match the " 12359 + "previously installed version"); 12360 return; 12361 } 12362 } else { 12363 try { 12364 verifySignaturesLP(ps, pkg); 12365 } catch (PackageManagerException e) { 12366 res.setError(e.error, e.getMessage()); 12367 return; 12368 } 12369 } 12370 12371 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12372 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12373 systemApp = (ps.pkg.applicationInfo.flags & 12374 ApplicationInfo.FLAG_SYSTEM) != 0; 12375 } 12376 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12377 } 12378 12379 // Check whether the newly-scanned package wants to define an already-defined perm 12380 int N = pkg.permissions.size(); 12381 for (int i = N-1; i >= 0; i--) { 12382 PackageParser.Permission perm = pkg.permissions.get(i); 12383 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12384 if (bp != null) { 12385 // If the defining package is signed with our cert, it's okay. This 12386 // also includes the "updating the same package" case, of course. 12387 // "updating same package" could also involve key-rotation. 12388 final boolean sigsOk; 12389 if (bp.sourcePackage.equals(pkg.packageName) 12390 && (bp.packageSetting instanceof PackageSetting) 12391 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12392 scanFlags))) { 12393 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12394 } else { 12395 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12396 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12397 } 12398 if (!sigsOk) { 12399 // If the owning package is the system itself, we log but allow 12400 // install to proceed; we fail the install on all other permission 12401 // redefinitions. 12402 if (!bp.sourcePackage.equals("android")) { 12403 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12404 + pkg.packageName + " attempting to redeclare permission " 12405 + perm.info.name + " already owned by " + bp.sourcePackage); 12406 res.origPermission = perm.info.name; 12407 res.origPackage = bp.sourcePackage; 12408 return; 12409 } else { 12410 Slog.w(TAG, "Package " + pkg.packageName 12411 + " attempting to redeclare system permission " 12412 + perm.info.name + "; ignoring new declaration"); 12413 pkg.permissions.remove(i); 12414 } 12415 } 12416 } 12417 } 12418 12419 } 12420 12421 if (systemApp && onExternal) { 12422 // Disable updates to system apps on sdcard 12423 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12424 "Cannot install updates to system apps on sdcard"); 12425 return; 12426 } 12427 12428 if (args.move != null) { 12429 // We did an in-place move, so dex is ready to roll 12430 scanFlags |= SCAN_NO_DEX; 12431 scanFlags |= SCAN_MOVE; 12432 12433 synchronized (mPackages) { 12434 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12435 if (ps == null) { 12436 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12437 "Missing settings for moved package " + pkgName); 12438 } 12439 12440 // We moved the entire application as-is, so bring over the 12441 // previously derived ABI information. 12442 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12443 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12444 } 12445 12446 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12447 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12448 scanFlags |= SCAN_NO_DEX; 12449 12450 try { 12451 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12452 true /* extract libs */); 12453 } catch (PackageManagerException pme) { 12454 Slog.e(TAG, "Error deriving application ABI", pme); 12455 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12456 return; 12457 } 12458 12459 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12460 int result = mPackageDexOptimizer 12461 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12462 false /* defer */, false /* inclDependencies */); 12463 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12464 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12465 return; 12466 } 12467 } 12468 12469 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12470 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12471 return; 12472 } 12473 12474 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12475 12476 if (replace) { 12477 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12478 installerPackageName, volumeUuid, res); 12479 } else { 12480 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12481 args.user, installerPackageName, volumeUuid, res); 12482 } 12483 synchronized (mPackages) { 12484 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12485 if (ps != null) { 12486 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12487 } 12488 } 12489 } 12490 12491 private void startIntentFilterVerifications(int userId, boolean replacing, 12492 PackageParser.Package pkg) { 12493 if (mIntentFilterVerifierComponent == null) { 12494 Slog.w(TAG, "No IntentFilter verification will not be done as " 12495 + "there is no IntentFilterVerifier available!"); 12496 return; 12497 } 12498 12499 final int verifierUid = getPackageUid( 12500 mIntentFilterVerifierComponent.getPackageName(), 12501 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12502 12503 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12504 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12505 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12506 mHandler.sendMessage(msg); 12507 } 12508 12509 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12510 PackageParser.Package pkg) { 12511 int size = pkg.activities.size(); 12512 if (size == 0) { 12513 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12514 "No activity, so no need to verify any IntentFilter!"); 12515 return; 12516 } 12517 12518 final boolean hasDomainURLs = hasDomainURLs(pkg); 12519 if (!hasDomainURLs) { 12520 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12521 "No domain URLs, so no need to verify any IntentFilter!"); 12522 return; 12523 } 12524 12525 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12526 + " if any IntentFilter from the " + size 12527 + " Activities needs verification ..."); 12528 12529 int count = 0; 12530 final String packageName = pkg.packageName; 12531 12532 synchronized (mPackages) { 12533 // If this is a new install and we see that we've already run verification for this 12534 // package, we have nothing to do: it means the state was restored from backup. 12535 if (!replacing) { 12536 IntentFilterVerificationInfo ivi = 12537 mSettings.getIntentFilterVerificationLPr(packageName); 12538 if (ivi != null) { 12539 if (DEBUG_DOMAIN_VERIFICATION) { 12540 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12541 + ivi.getStatusString()); 12542 } 12543 return; 12544 } 12545 } 12546 12547 // If any filters need to be verified, then all need to be. 12548 boolean needToVerify = false; 12549 for (PackageParser.Activity a : pkg.activities) { 12550 for (ActivityIntentInfo filter : a.intents) { 12551 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12552 if (DEBUG_DOMAIN_VERIFICATION) { 12553 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12554 } 12555 needToVerify = true; 12556 break; 12557 } 12558 } 12559 } 12560 12561 if (needToVerify) { 12562 final int verificationId = mIntentFilterVerificationToken++; 12563 for (PackageParser.Activity a : pkg.activities) { 12564 for (ActivityIntentInfo filter : a.intents) { 12565 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12566 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12567 "Verification needed for IntentFilter:" + filter.toString()); 12568 mIntentFilterVerifier.addOneIntentFilterVerification( 12569 verifierUid, userId, verificationId, filter, packageName); 12570 count++; 12571 } 12572 } 12573 } 12574 } 12575 } 12576 12577 if (count > 0) { 12578 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12579 + " IntentFilter verification" + (count > 1 ? "s" : "") 12580 + " for userId:" + userId); 12581 mIntentFilterVerifier.startVerifications(userId); 12582 } else { 12583 if (DEBUG_DOMAIN_VERIFICATION) { 12584 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12585 } 12586 } 12587 } 12588 12589 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12590 final ComponentName cn = filter.activity.getComponentName(); 12591 final String packageName = cn.getPackageName(); 12592 12593 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12594 packageName); 12595 if (ivi == null) { 12596 return true; 12597 } 12598 int status = ivi.getStatus(); 12599 switch (status) { 12600 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12601 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12602 return true; 12603 12604 default: 12605 // Nothing to do 12606 return false; 12607 } 12608 } 12609 12610 private static boolean isMultiArch(PackageSetting ps) { 12611 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12612 } 12613 12614 private static boolean isMultiArch(ApplicationInfo info) { 12615 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12616 } 12617 12618 private static boolean isExternal(PackageParser.Package pkg) { 12619 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12620 } 12621 12622 private static boolean isExternal(PackageSetting ps) { 12623 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12624 } 12625 12626 private static boolean isExternal(ApplicationInfo info) { 12627 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12628 } 12629 12630 private static boolean isSystemApp(PackageParser.Package pkg) { 12631 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12632 } 12633 12634 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12635 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12636 } 12637 12638 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12639 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12640 } 12641 12642 private static boolean isSystemApp(PackageSetting ps) { 12643 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12644 } 12645 12646 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12647 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12648 } 12649 12650 private int packageFlagsToInstallFlags(PackageSetting ps) { 12651 int installFlags = 0; 12652 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12653 // This existing package was an external ASEC install when we have 12654 // the external flag without a UUID 12655 installFlags |= PackageManager.INSTALL_EXTERNAL; 12656 } 12657 if (ps.isForwardLocked()) { 12658 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12659 } 12660 return installFlags; 12661 } 12662 12663 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12664 if (isExternal(pkg)) { 12665 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12666 return mSettings.getExternalVersion(); 12667 } else { 12668 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12669 } 12670 } else { 12671 return mSettings.getInternalVersion(); 12672 } 12673 } 12674 12675 private void deleteTempPackageFiles() { 12676 final FilenameFilter filter = new FilenameFilter() { 12677 public boolean accept(File dir, String name) { 12678 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12679 } 12680 }; 12681 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12682 file.delete(); 12683 } 12684 } 12685 12686 @Override 12687 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12688 int flags) { 12689 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12690 flags); 12691 } 12692 12693 @Override 12694 public void deletePackage(final String packageName, 12695 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12696 mContext.enforceCallingOrSelfPermission( 12697 android.Manifest.permission.DELETE_PACKAGES, null); 12698 Preconditions.checkNotNull(packageName); 12699 Preconditions.checkNotNull(observer); 12700 final int uid = Binder.getCallingUid(); 12701 if (UserHandle.getUserId(uid) != userId) { 12702 mContext.enforceCallingPermission( 12703 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12704 "deletePackage for user " + userId); 12705 } 12706 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12707 try { 12708 observer.onPackageDeleted(packageName, 12709 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12710 } catch (RemoteException re) { 12711 } 12712 return; 12713 } 12714 12715 boolean uninstallBlocked = false; 12716 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12717 int[] users = sUserManager.getUserIds(); 12718 for (int i = 0; i < users.length; ++i) { 12719 if (getBlockUninstallForUser(packageName, users[i])) { 12720 uninstallBlocked = true; 12721 break; 12722 } 12723 } 12724 } else { 12725 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12726 } 12727 if (uninstallBlocked) { 12728 try { 12729 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12730 null); 12731 } catch (RemoteException re) { 12732 } 12733 return; 12734 } 12735 12736 if (DEBUG_REMOVE) { 12737 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12738 } 12739 // Queue up an async operation since the package deletion may take a little while. 12740 mHandler.post(new Runnable() { 12741 public void run() { 12742 mHandler.removeCallbacks(this); 12743 final int returnCode = deletePackageX(packageName, userId, flags); 12744 if (observer != null) { 12745 try { 12746 observer.onPackageDeleted(packageName, returnCode, null); 12747 } catch (RemoteException e) { 12748 Log.i(TAG, "Observer no longer exists."); 12749 } //end catch 12750 } //end if 12751 } //end run 12752 }); 12753 } 12754 12755 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12756 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12757 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12758 try { 12759 if (dpm != null) { 12760 if (dpm.isDeviceOwner(packageName)) { 12761 return true; 12762 } 12763 int[] users; 12764 if (userId == UserHandle.USER_ALL) { 12765 users = sUserManager.getUserIds(); 12766 } else { 12767 users = new int[]{userId}; 12768 } 12769 for (int i = 0; i < users.length; ++i) { 12770 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12771 return true; 12772 } 12773 } 12774 } 12775 } catch (RemoteException e) { 12776 } 12777 return false; 12778 } 12779 12780 /** 12781 * This method is an internal method that could be get invoked either 12782 * to delete an installed package or to clean up a failed installation. 12783 * After deleting an installed package, a broadcast is sent to notify any 12784 * listeners that the package has been installed. For cleaning up a failed 12785 * installation, the broadcast is not necessary since the package's 12786 * installation wouldn't have sent the initial broadcast either 12787 * The key steps in deleting a package are 12788 * deleting the package information in internal structures like mPackages, 12789 * deleting the packages base directories through installd 12790 * updating mSettings to reflect current status 12791 * persisting settings for later use 12792 * sending a broadcast if necessary 12793 */ 12794 private int deletePackageX(String packageName, int userId, int flags) { 12795 final PackageRemovedInfo info = new PackageRemovedInfo(); 12796 final boolean res; 12797 12798 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12799 ? UserHandle.ALL : new UserHandle(userId); 12800 12801 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12802 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12803 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12804 } 12805 12806 boolean removedForAllUsers = false; 12807 boolean systemUpdate = false; 12808 12809 // for the uninstall-updates case and restricted profiles, remember the per- 12810 // userhandle installed state 12811 int[] allUsers; 12812 boolean[] perUserInstalled; 12813 synchronized (mPackages) { 12814 PackageSetting ps = mSettings.mPackages.get(packageName); 12815 allUsers = sUserManager.getUserIds(); 12816 perUserInstalled = new boolean[allUsers.length]; 12817 for (int i = 0; i < allUsers.length; i++) { 12818 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12819 } 12820 } 12821 12822 synchronized (mInstallLock) { 12823 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12824 res = deletePackageLI(packageName, removeForUser, 12825 true, allUsers, perUserInstalled, 12826 flags | REMOVE_CHATTY, info, true); 12827 systemUpdate = info.isRemovedPackageSystemUpdate; 12828 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12829 removedForAllUsers = true; 12830 } 12831 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12832 + " removedForAllUsers=" + removedForAllUsers); 12833 } 12834 12835 if (res) { 12836 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12837 12838 // If the removed package was a system update, the old system package 12839 // was re-enabled; we need to broadcast this information 12840 if (systemUpdate) { 12841 Bundle extras = new Bundle(1); 12842 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12843 ? info.removedAppId : info.uid); 12844 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12845 12846 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12847 extras, null, null, null); 12848 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12849 extras, null, null, null); 12850 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12851 null, packageName, null, null); 12852 } 12853 } 12854 // Force a gc here. 12855 Runtime.getRuntime().gc(); 12856 // Delete the resources here after sending the broadcast to let 12857 // other processes clean up before deleting resources. 12858 if (info.args != null) { 12859 synchronized (mInstallLock) { 12860 info.args.doPostDeleteLI(true); 12861 } 12862 } 12863 12864 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12865 } 12866 12867 class PackageRemovedInfo { 12868 String removedPackage; 12869 int uid = -1; 12870 int removedAppId = -1; 12871 int[] removedUsers = null; 12872 boolean isRemovedPackageSystemUpdate = false; 12873 // Clean up resources deleted packages. 12874 InstallArgs args = null; 12875 12876 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12877 Bundle extras = new Bundle(1); 12878 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12879 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12880 if (replacing) { 12881 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12882 } 12883 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12884 if (removedPackage != null) { 12885 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12886 extras, null, null, removedUsers); 12887 if (fullRemove && !replacing) { 12888 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12889 extras, null, null, removedUsers); 12890 } 12891 } 12892 if (removedAppId >= 0) { 12893 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12894 removedUsers); 12895 } 12896 } 12897 } 12898 12899 /* 12900 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12901 * flag is not set, the data directory is removed as well. 12902 * make sure this flag is set for partially installed apps. If not its meaningless to 12903 * delete a partially installed application. 12904 */ 12905 private void removePackageDataLI(PackageSetting ps, 12906 int[] allUserHandles, boolean[] perUserInstalled, 12907 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12908 String packageName = ps.name; 12909 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12910 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12911 // Retrieve object to delete permissions for shared user later on 12912 final PackageSetting deletedPs; 12913 // reader 12914 synchronized (mPackages) { 12915 deletedPs = mSettings.mPackages.get(packageName); 12916 if (outInfo != null) { 12917 outInfo.removedPackage = packageName; 12918 outInfo.removedUsers = deletedPs != null 12919 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12920 : null; 12921 } 12922 } 12923 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12924 removeDataDirsLI(ps.volumeUuid, packageName); 12925 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12926 } 12927 // writer 12928 synchronized (mPackages) { 12929 if (deletedPs != null) { 12930 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12931 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12932 clearDefaultBrowserIfNeeded(packageName); 12933 if (outInfo != null) { 12934 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12935 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12936 } 12937 updatePermissionsLPw(deletedPs.name, null, 0); 12938 if (deletedPs.sharedUser != null) { 12939 // Remove permissions associated with package. Since runtime 12940 // permissions are per user we have to kill the removed package 12941 // or packages running under the shared user of the removed 12942 // package if revoking the permissions requested only by the removed 12943 // package is successful and this causes a change in gids. 12944 for (int userId : UserManagerService.getInstance().getUserIds()) { 12945 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12946 userId); 12947 if (userIdToKill == UserHandle.USER_ALL 12948 || userIdToKill >= UserHandle.USER_OWNER) { 12949 // If gids changed for this user, kill all affected packages. 12950 mHandler.post(new Runnable() { 12951 @Override 12952 public void run() { 12953 // This has to happen with no lock held. 12954 killApplication(deletedPs.name, deletedPs.appId, 12955 KILL_APP_REASON_GIDS_CHANGED); 12956 } 12957 }); 12958 break; 12959 } 12960 } 12961 } 12962 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12963 } 12964 // make sure to preserve per-user disabled state if this removal was just 12965 // a downgrade of a system app to the factory package 12966 if (allUserHandles != null && perUserInstalled != null) { 12967 if (DEBUG_REMOVE) { 12968 Slog.d(TAG, "Propagating install state across downgrade"); 12969 } 12970 for (int i = 0; i < allUserHandles.length; i++) { 12971 if (DEBUG_REMOVE) { 12972 Slog.d(TAG, " user " + allUserHandles[i] 12973 + " => " + perUserInstalled[i]); 12974 } 12975 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12976 } 12977 } 12978 } 12979 // can downgrade to reader 12980 if (writeSettings) { 12981 // Save settings now 12982 mSettings.writeLPr(); 12983 } 12984 } 12985 if (outInfo != null) { 12986 // A user ID was deleted here. Go through all users and remove it 12987 // from KeyStore. 12988 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12989 } 12990 } 12991 12992 static boolean locationIsPrivileged(File path) { 12993 try { 12994 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12995 .getCanonicalPath(); 12996 return path.getCanonicalPath().startsWith(privilegedAppDir); 12997 } catch (IOException e) { 12998 Slog.e(TAG, "Unable to access code path " + path); 12999 } 13000 return false; 13001 } 13002 13003 /* 13004 * Tries to delete system package. 13005 */ 13006 private boolean deleteSystemPackageLI(PackageSetting newPs, 13007 int[] allUserHandles, boolean[] perUserInstalled, 13008 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13009 final boolean applyUserRestrictions 13010 = (allUserHandles != null) && (perUserInstalled != null); 13011 PackageSetting disabledPs = null; 13012 // Confirm if the system package has been updated 13013 // An updated system app can be deleted. This will also have to restore 13014 // the system pkg from system partition 13015 // reader 13016 synchronized (mPackages) { 13017 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13018 } 13019 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13020 + " disabledPs=" + disabledPs); 13021 if (disabledPs == null) { 13022 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13023 return false; 13024 } else if (DEBUG_REMOVE) { 13025 Slog.d(TAG, "Deleting system pkg from data partition"); 13026 } 13027 if (DEBUG_REMOVE) { 13028 if (applyUserRestrictions) { 13029 Slog.d(TAG, "Remembering install states:"); 13030 for (int i = 0; i < allUserHandles.length; i++) { 13031 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13032 } 13033 } 13034 } 13035 // Delete the updated package 13036 outInfo.isRemovedPackageSystemUpdate = true; 13037 if (disabledPs.versionCode < newPs.versionCode) { 13038 // Delete data for downgrades 13039 flags &= ~PackageManager.DELETE_KEEP_DATA; 13040 } else { 13041 // Preserve data by setting flag 13042 flags |= PackageManager.DELETE_KEEP_DATA; 13043 } 13044 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13045 allUserHandles, perUserInstalled, outInfo, writeSettings); 13046 if (!ret) { 13047 return false; 13048 } 13049 // writer 13050 synchronized (mPackages) { 13051 // Reinstate the old system package 13052 mSettings.enableSystemPackageLPw(newPs.name); 13053 // Remove any native libraries from the upgraded package. 13054 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13055 } 13056 // Install the system package 13057 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13058 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13059 if (locationIsPrivileged(disabledPs.codePath)) { 13060 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13061 } 13062 13063 final PackageParser.Package newPkg; 13064 try { 13065 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13066 } catch (PackageManagerException e) { 13067 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13068 return false; 13069 } 13070 13071 // writer 13072 synchronized (mPackages) { 13073 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13074 13075 // Propagate the permissions state as we do not want to drop on the floor 13076 // runtime permissions. The update permissions method below will take 13077 // care of removing obsolete permissions and grant install permissions. 13078 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13079 updatePermissionsLPw(newPkg.packageName, newPkg, 13080 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13081 13082 if (applyUserRestrictions) { 13083 if (DEBUG_REMOVE) { 13084 Slog.d(TAG, "Propagating install state across reinstall"); 13085 } 13086 for (int i = 0; i < allUserHandles.length; i++) { 13087 if (DEBUG_REMOVE) { 13088 Slog.d(TAG, " user " + allUserHandles[i] 13089 + " => " + perUserInstalled[i]); 13090 } 13091 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13092 13093 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13094 } 13095 // Regardless of writeSettings we need to ensure that this restriction 13096 // state propagation is persisted 13097 mSettings.writeAllUsersPackageRestrictionsLPr(); 13098 } 13099 // can downgrade to reader here 13100 if (writeSettings) { 13101 mSettings.writeLPr(); 13102 } 13103 } 13104 return true; 13105 } 13106 13107 private boolean deleteInstalledPackageLI(PackageSetting ps, 13108 boolean deleteCodeAndResources, int flags, 13109 int[] allUserHandles, boolean[] perUserInstalled, 13110 PackageRemovedInfo outInfo, boolean writeSettings) { 13111 if (outInfo != null) { 13112 outInfo.uid = ps.appId; 13113 } 13114 13115 // Delete package data from internal structures and also remove data if flag is set 13116 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13117 13118 // Delete application code and resources 13119 if (deleteCodeAndResources && (outInfo != null)) { 13120 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13121 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13122 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13123 } 13124 return true; 13125 } 13126 13127 @Override 13128 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13129 int userId) { 13130 mContext.enforceCallingOrSelfPermission( 13131 android.Manifest.permission.DELETE_PACKAGES, null); 13132 synchronized (mPackages) { 13133 PackageSetting ps = mSettings.mPackages.get(packageName); 13134 if (ps == null) { 13135 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13136 return false; 13137 } 13138 if (!ps.getInstalled(userId)) { 13139 // Can't block uninstall for an app that is not installed or enabled. 13140 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13141 return false; 13142 } 13143 ps.setBlockUninstall(blockUninstall, userId); 13144 mSettings.writePackageRestrictionsLPr(userId); 13145 } 13146 return true; 13147 } 13148 13149 @Override 13150 public boolean getBlockUninstallForUser(String packageName, int userId) { 13151 synchronized (mPackages) { 13152 PackageSetting ps = mSettings.mPackages.get(packageName); 13153 if (ps == null) { 13154 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13155 return false; 13156 } 13157 return ps.getBlockUninstall(userId); 13158 } 13159 } 13160 13161 /* 13162 * This method handles package deletion in general 13163 */ 13164 private boolean deletePackageLI(String packageName, UserHandle user, 13165 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13166 int flags, PackageRemovedInfo outInfo, 13167 boolean writeSettings) { 13168 if (packageName == null) { 13169 Slog.w(TAG, "Attempt to delete null packageName."); 13170 return false; 13171 } 13172 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13173 PackageSetting ps; 13174 boolean dataOnly = false; 13175 int removeUser = -1; 13176 int appId = -1; 13177 synchronized (mPackages) { 13178 ps = mSettings.mPackages.get(packageName); 13179 if (ps == null) { 13180 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13181 return false; 13182 } 13183 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13184 && user.getIdentifier() != UserHandle.USER_ALL) { 13185 // The caller is asking that the package only be deleted for a single 13186 // user. To do this, we just mark its uninstalled state and delete 13187 // its data. If this is a system app, we only allow this to happen if 13188 // they have set the special DELETE_SYSTEM_APP which requests different 13189 // semantics than normal for uninstalling system apps. 13190 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13191 final int userId = user.getIdentifier(); 13192 ps.setUserState(userId, 13193 COMPONENT_ENABLED_STATE_DEFAULT, 13194 false, //installed 13195 true, //stopped 13196 true, //notLaunched 13197 false, //hidden 13198 null, null, null, 13199 false, // blockUninstall 13200 ps.readUserState(userId).domainVerificationStatus, 0); 13201 if (!isSystemApp(ps)) { 13202 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13203 // Other user still have this package installed, so all 13204 // we need to do is clear this user's data and save that 13205 // it is uninstalled. 13206 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13207 removeUser = user.getIdentifier(); 13208 appId = ps.appId; 13209 scheduleWritePackageRestrictionsLocked(removeUser); 13210 } else { 13211 // We need to set it back to 'installed' so the uninstall 13212 // broadcasts will be sent correctly. 13213 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13214 ps.setInstalled(true, user.getIdentifier()); 13215 } 13216 } else { 13217 // This is a system app, so we assume that the 13218 // other users still have this package installed, so all 13219 // we need to do is clear this user's data and save that 13220 // it is uninstalled. 13221 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13222 removeUser = user.getIdentifier(); 13223 appId = ps.appId; 13224 scheduleWritePackageRestrictionsLocked(removeUser); 13225 } 13226 } 13227 } 13228 13229 if (removeUser >= 0) { 13230 // From above, we determined that we are deleting this only 13231 // for a single user. Continue the work here. 13232 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13233 if (outInfo != null) { 13234 outInfo.removedPackage = packageName; 13235 outInfo.removedAppId = appId; 13236 outInfo.removedUsers = new int[] {removeUser}; 13237 } 13238 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13239 removeKeystoreDataIfNeeded(removeUser, appId); 13240 schedulePackageCleaning(packageName, removeUser, false); 13241 synchronized (mPackages) { 13242 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13243 scheduleWritePackageRestrictionsLocked(removeUser); 13244 } 13245 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13246 } 13247 return true; 13248 } 13249 13250 if (dataOnly) { 13251 // Delete application data first 13252 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13253 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13254 return true; 13255 } 13256 13257 boolean ret = false; 13258 if (isSystemApp(ps)) { 13259 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13260 // When an updated system application is deleted we delete the existing resources as well and 13261 // fall back to existing code in system partition 13262 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13263 flags, outInfo, writeSettings); 13264 } else { 13265 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13266 // Kill application pre-emptively especially for apps on sd. 13267 killApplication(packageName, ps.appId, "uninstall pkg"); 13268 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13269 allUserHandles, perUserInstalled, 13270 outInfo, writeSettings); 13271 } 13272 13273 return ret; 13274 } 13275 13276 private final class ClearStorageConnection implements ServiceConnection { 13277 IMediaContainerService mContainerService; 13278 13279 @Override 13280 public void onServiceConnected(ComponentName name, IBinder service) { 13281 synchronized (this) { 13282 mContainerService = IMediaContainerService.Stub.asInterface(service); 13283 notifyAll(); 13284 } 13285 } 13286 13287 @Override 13288 public void onServiceDisconnected(ComponentName name) { 13289 } 13290 } 13291 13292 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13293 final boolean mounted; 13294 if (Environment.isExternalStorageEmulated()) { 13295 mounted = true; 13296 } else { 13297 final String status = Environment.getExternalStorageState(); 13298 13299 mounted = status.equals(Environment.MEDIA_MOUNTED) 13300 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13301 } 13302 13303 if (!mounted) { 13304 return; 13305 } 13306 13307 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13308 int[] users; 13309 if (userId == UserHandle.USER_ALL) { 13310 users = sUserManager.getUserIds(); 13311 } else { 13312 users = new int[] { userId }; 13313 } 13314 final ClearStorageConnection conn = new ClearStorageConnection(); 13315 if (mContext.bindServiceAsUser( 13316 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13317 try { 13318 for (int curUser : users) { 13319 long timeout = SystemClock.uptimeMillis() + 5000; 13320 synchronized (conn) { 13321 long now = SystemClock.uptimeMillis(); 13322 while (conn.mContainerService == null && now < timeout) { 13323 try { 13324 conn.wait(timeout - now); 13325 } catch (InterruptedException e) { 13326 } 13327 } 13328 } 13329 if (conn.mContainerService == null) { 13330 return; 13331 } 13332 13333 final UserEnvironment userEnv = new UserEnvironment(curUser); 13334 clearDirectory(conn.mContainerService, 13335 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13336 if (allData) { 13337 clearDirectory(conn.mContainerService, 13338 userEnv.buildExternalStorageAppDataDirs(packageName)); 13339 clearDirectory(conn.mContainerService, 13340 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13341 } 13342 } 13343 } finally { 13344 mContext.unbindService(conn); 13345 } 13346 } 13347 } 13348 13349 @Override 13350 public void clearApplicationUserData(final String packageName, 13351 final IPackageDataObserver observer, final int userId) { 13352 mContext.enforceCallingOrSelfPermission( 13353 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13354 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13355 // Queue up an async operation since the package deletion may take a little while. 13356 mHandler.post(new Runnable() { 13357 public void run() { 13358 mHandler.removeCallbacks(this); 13359 final boolean succeeded; 13360 synchronized (mInstallLock) { 13361 succeeded = clearApplicationUserDataLI(packageName, userId); 13362 } 13363 clearExternalStorageDataSync(packageName, userId, true); 13364 if (succeeded) { 13365 // invoke DeviceStorageMonitor's update method to clear any notifications 13366 DeviceStorageMonitorInternal 13367 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13368 if (dsm != null) { 13369 dsm.checkMemory(); 13370 } 13371 } 13372 if(observer != null) { 13373 try { 13374 observer.onRemoveCompleted(packageName, succeeded); 13375 } catch (RemoteException e) { 13376 Log.i(TAG, "Observer no longer exists."); 13377 } 13378 } //end if observer 13379 } //end run 13380 }); 13381 } 13382 13383 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13384 if (packageName == null) { 13385 Slog.w(TAG, "Attempt to delete null packageName."); 13386 return false; 13387 } 13388 13389 // Try finding details about the requested package 13390 PackageParser.Package pkg; 13391 synchronized (mPackages) { 13392 pkg = mPackages.get(packageName); 13393 if (pkg == null) { 13394 final PackageSetting ps = mSettings.mPackages.get(packageName); 13395 if (ps != null) { 13396 pkg = ps.pkg; 13397 } 13398 } 13399 13400 if (pkg == null) { 13401 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13402 return false; 13403 } 13404 13405 PackageSetting ps = (PackageSetting) pkg.mExtras; 13406 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13407 } 13408 13409 // Always delete data directories for package, even if we found no other 13410 // record of app. This helps users recover from UID mismatches without 13411 // resorting to a full data wipe. 13412 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13413 if (retCode < 0) { 13414 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13415 return false; 13416 } 13417 13418 final int appId = pkg.applicationInfo.uid; 13419 removeKeystoreDataIfNeeded(userId, appId); 13420 13421 // Create a native library symlink only if we have native libraries 13422 // and if the native libraries are 32 bit libraries. We do not provide 13423 // this symlink for 64 bit libraries. 13424 if (pkg.applicationInfo.primaryCpuAbi != null && 13425 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13426 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13427 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13428 nativeLibPath, userId) < 0) { 13429 Slog.w(TAG, "Failed linking native library dir"); 13430 return false; 13431 } 13432 } 13433 13434 return true; 13435 } 13436 13437 /** 13438 * Reverts user permission state changes (permissions and flags) in 13439 * all packages for a given user. 13440 * 13441 * @param userId The device user for which to do a reset. 13442 */ 13443 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13444 final int packageCount = mPackages.size(); 13445 for (int i = 0; i < packageCount; i++) { 13446 PackageParser.Package pkg = mPackages.valueAt(i); 13447 PackageSetting ps = (PackageSetting) pkg.mExtras; 13448 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13449 } 13450 } 13451 13452 /** 13453 * Reverts user permission state changes (permissions and flags). 13454 * 13455 * @param ps The package for which to reset. 13456 * @param userId The device user for which to do a reset. 13457 */ 13458 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13459 final PackageSetting ps, final int userId) { 13460 if (ps.pkg == null) { 13461 return; 13462 } 13463 13464 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13465 | FLAG_PERMISSION_USER_FIXED 13466 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13467 13468 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13469 | FLAG_PERMISSION_POLICY_FIXED; 13470 13471 boolean writeInstallPermissions = false; 13472 boolean writeRuntimePermissions = false; 13473 13474 final int permissionCount = ps.pkg.requestedPermissions.size(); 13475 for (int i = 0; i < permissionCount; i++) { 13476 String permission = ps.pkg.requestedPermissions.get(i); 13477 13478 BasePermission bp = mSettings.mPermissions.get(permission); 13479 if (bp == null) { 13480 continue; 13481 } 13482 13483 // If shared user we just reset the state to which only this app contributed. 13484 if (ps.sharedUser != null) { 13485 boolean used = false; 13486 final int packageCount = ps.sharedUser.packages.size(); 13487 for (int j = 0; j < packageCount; j++) { 13488 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13489 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13490 && pkg.pkg.requestedPermissions.contains(permission)) { 13491 used = true; 13492 break; 13493 } 13494 } 13495 if (used) { 13496 continue; 13497 } 13498 } 13499 13500 PermissionsState permissionsState = ps.getPermissionsState(); 13501 13502 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13503 13504 // Always clear the user settable flags. 13505 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13506 bp.name) != null; 13507 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13508 if (hasInstallState) { 13509 writeInstallPermissions = true; 13510 } else { 13511 writeRuntimePermissions = true; 13512 } 13513 } 13514 13515 // Below is only runtime permission handling. 13516 if (!bp.isRuntime()) { 13517 continue; 13518 } 13519 13520 // Never clobber system or policy. 13521 if ((oldFlags & policyOrSystemFlags) != 0) { 13522 continue; 13523 } 13524 13525 // If this permission was granted by default, make sure it is. 13526 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13527 if (permissionsState.grantRuntimePermission(bp, userId) 13528 != PERMISSION_OPERATION_FAILURE) { 13529 writeRuntimePermissions = true; 13530 } 13531 } else { 13532 // Otherwise, reset the permission. 13533 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13534 switch (revokeResult) { 13535 case PERMISSION_OPERATION_SUCCESS: { 13536 writeRuntimePermissions = true; 13537 } break; 13538 13539 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13540 writeRuntimePermissions = true; 13541 final int appId = ps.appId; 13542 mHandler.post(new Runnable() { 13543 @Override 13544 public void run() { 13545 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13546 } 13547 }); 13548 } break; 13549 } 13550 } 13551 } 13552 13553 // Synchronously write as we are taking permissions away. 13554 if (writeRuntimePermissions) { 13555 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13556 } 13557 13558 // Synchronously write as we are taking permissions away. 13559 if (writeInstallPermissions) { 13560 mSettings.writeLPr(); 13561 } 13562 } 13563 13564 /** 13565 * Remove entries from the keystore daemon. Will only remove it if the 13566 * {@code appId} is valid. 13567 */ 13568 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13569 if (appId < 0) { 13570 return; 13571 } 13572 13573 final KeyStore keyStore = KeyStore.getInstance(); 13574 if (keyStore != null) { 13575 if (userId == UserHandle.USER_ALL) { 13576 for (final int individual : sUserManager.getUserIds()) { 13577 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13578 } 13579 } else { 13580 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13581 } 13582 } else { 13583 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13584 } 13585 } 13586 13587 @Override 13588 public void deleteApplicationCacheFiles(final String packageName, 13589 final IPackageDataObserver observer) { 13590 mContext.enforceCallingOrSelfPermission( 13591 android.Manifest.permission.DELETE_CACHE_FILES, null); 13592 // Queue up an async operation since the package deletion may take a little while. 13593 final int userId = UserHandle.getCallingUserId(); 13594 mHandler.post(new Runnable() { 13595 public void run() { 13596 mHandler.removeCallbacks(this); 13597 final boolean succeded; 13598 synchronized (mInstallLock) { 13599 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13600 } 13601 clearExternalStorageDataSync(packageName, userId, false); 13602 if (observer != null) { 13603 try { 13604 observer.onRemoveCompleted(packageName, succeded); 13605 } catch (RemoteException e) { 13606 Log.i(TAG, "Observer no longer exists."); 13607 } 13608 } //end if observer 13609 } //end run 13610 }); 13611 } 13612 13613 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13614 if (packageName == null) { 13615 Slog.w(TAG, "Attempt to delete null packageName."); 13616 return false; 13617 } 13618 PackageParser.Package p; 13619 synchronized (mPackages) { 13620 p = mPackages.get(packageName); 13621 } 13622 if (p == null) { 13623 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13624 return false; 13625 } 13626 final ApplicationInfo applicationInfo = p.applicationInfo; 13627 if (applicationInfo == null) { 13628 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13629 return false; 13630 } 13631 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13632 if (retCode < 0) { 13633 Slog.w(TAG, "Couldn't remove cache files for package: " 13634 + packageName + " u" + userId); 13635 return false; 13636 } 13637 return true; 13638 } 13639 13640 @Override 13641 public void getPackageSizeInfo(final String packageName, int userHandle, 13642 final IPackageStatsObserver observer) { 13643 mContext.enforceCallingOrSelfPermission( 13644 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13645 if (packageName == null) { 13646 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13647 } 13648 13649 PackageStats stats = new PackageStats(packageName, userHandle); 13650 13651 /* 13652 * Queue up an async operation since the package measurement may take a 13653 * little while. 13654 */ 13655 Message msg = mHandler.obtainMessage(INIT_COPY); 13656 msg.obj = new MeasureParams(stats, observer); 13657 mHandler.sendMessage(msg); 13658 } 13659 13660 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13661 PackageStats pStats) { 13662 if (packageName == null) { 13663 Slog.w(TAG, "Attempt to get size of null packageName."); 13664 return false; 13665 } 13666 PackageParser.Package p; 13667 boolean dataOnly = false; 13668 String libDirRoot = null; 13669 String asecPath = null; 13670 PackageSetting ps = null; 13671 synchronized (mPackages) { 13672 p = mPackages.get(packageName); 13673 ps = mSettings.mPackages.get(packageName); 13674 if(p == null) { 13675 dataOnly = true; 13676 if((ps == null) || (ps.pkg == null)) { 13677 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13678 return false; 13679 } 13680 p = ps.pkg; 13681 } 13682 if (ps != null) { 13683 libDirRoot = ps.legacyNativeLibraryPathString; 13684 } 13685 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13686 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13687 if (secureContainerId != null) { 13688 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13689 } 13690 } 13691 } 13692 String publicSrcDir = null; 13693 if(!dataOnly) { 13694 final ApplicationInfo applicationInfo = p.applicationInfo; 13695 if (applicationInfo == null) { 13696 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13697 return false; 13698 } 13699 if (p.isForwardLocked()) { 13700 publicSrcDir = applicationInfo.getBaseResourcePath(); 13701 } 13702 } 13703 // TODO: extend to measure size of split APKs 13704 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13705 // not just the first level. 13706 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13707 // just the primary. 13708 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13709 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13710 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13711 if (res < 0) { 13712 return false; 13713 } 13714 13715 // Fix-up for forward-locked applications in ASEC containers. 13716 if (!isExternal(p)) { 13717 pStats.codeSize += pStats.externalCodeSize; 13718 pStats.externalCodeSize = 0L; 13719 } 13720 13721 return true; 13722 } 13723 13724 13725 @Override 13726 public void addPackageToPreferred(String packageName) { 13727 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13728 } 13729 13730 @Override 13731 public void removePackageFromPreferred(String packageName) { 13732 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13733 } 13734 13735 @Override 13736 public List<PackageInfo> getPreferredPackages(int flags) { 13737 return new ArrayList<PackageInfo>(); 13738 } 13739 13740 private int getUidTargetSdkVersionLockedLPr(int uid) { 13741 Object obj = mSettings.getUserIdLPr(uid); 13742 if (obj instanceof SharedUserSetting) { 13743 final SharedUserSetting sus = (SharedUserSetting) obj; 13744 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13745 final Iterator<PackageSetting> it = sus.packages.iterator(); 13746 while (it.hasNext()) { 13747 final PackageSetting ps = it.next(); 13748 if (ps.pkg != null) { 13749 int v = ps.pkg.applicationInfo.targetSdkVersion; 13750 if (v < vers) vers = v; 13751 } 13752 } 13753 return vers; 13754 } else if (obj instanceof PackageSetting) { 13755 final PackageSetting ps = (PackageSetting) obj; 13756 if (ps.pkg != null) { 13757 return ps.pkg.applicationInfo.targetSdkVersion; 13758 } 13759 } 13760 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13761 } 13762 13763 @Override 13764 public void addPreferredActivity(IntentFilter filter, int match, 13765 ComponentName[] set, ComponentName activity, int userId) { 13766 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13767 "Adding preferred"); 13768 } 13769 13770 private void addPreferredActivityInternal(IntentFilter filter, int match, 13771 ComponentName[] set, ComponentName activity, boolean always, int userId, 13772 String opname) { 13773 // writer 13774 int callingUid = Binder.getCallingUid(); 13775 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13776 if (filter.countActions() == 0) { 13777 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13778 return; 13779 } 13780 synchronized (mPackages) { 13781 if (mContext.checkCallingOrSelfPermission( 13782 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13783 != PackageManager.PERMISSION_GRANTED) { 13784 if (getUidTargetSdkVersionLockedLPr(callingUid) 13785 < Build.VERSION_CODES.FROYO) { 13786 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13787 + callingUid); 13788 return; 13789 } 13790 mContext.enforceCallingOrSelfPermission( 13791 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13792 } 13793 13794 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13795 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13796 + userId + ":"); 13797 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13798 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13799 scheduleWritePackageRestrictionsLocked(userId); 13800 } 13801 } 13802 13803 @Override 13804 public void replacePreferredActivity(IntentFilter filter, int match, 13805 ComponentName[] set, ComponentName activity, int userId) { 13806 if (filter.countActions() != 1) { 13807 throw new IllegalArgumentException( 13808 "replacePreferredActivity expects filter to have only 1 action."); 13809 } 13810 if (filter.countDataAuthorities() != 0 13811 || filter.countDataPaths() != 0 13812 || filter.countDataSchemes() > 1 13813 || filter.countDataTypes() != 0) { 13814 throw new IllegalArgumentException( 13815 "replacePreferredActivity expects filter to have no data authorities, " + 13816 "paths, or types; and at most one scheme."); 13817 } 13818 13819 final int callingUid = Binder.getCallingUid(); 13820 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13821 synchronized (mPackages) { 13822 if (mContext.checkCallingOrSelfPermission( 13823 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13824 != PackageManager.PERMISSION_GRANTED) { 13825 if (getUidTargetSdkVersionLockedLPr(callingUid) 13826 < Build.VERSION_CODES.FROYO) { 13827 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13828 + Binder.getCallingUid()); 13829 return; 13830 } 13831 mContext.enforceCallingOrSelfPermission( 13832 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13833 } 13834 13835 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13836 if (pir != null) { 13837 // Get all of the existing entries that exactly match this filter. 13838 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13839 if (existing != null && existing.size() == 1) { 13840 PreferredActivity cur = existing.get(0); 13841 if (DEBUG_PREFERRED) { 13842 Slog.i(TAG, "Checking replace of preferred:"); 13843 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13844 if (!cur.mPref.mAlways) { 13845 Slog.i(TAG, " -- CUR; not mAlways!"); 13846 } else { 13847 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13848 Slog.i(TAG, " -- CUR: mSet=" 13849 + Arrays.toString(cur.mPref.mSetComponents)); 13850 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13851 Slog.i(TAG, " -- NEW: mMatch=" 13852 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13853 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13854 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13855 } 13856 } 13857 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13858 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13859 && cur.mPref.sameSet(set)) { 13860 // Setting the preferred activity to what it happens to be already 13861 if (DEBUG_PREFERRED) { 13862 Slog.i(TAG, "Replacing with same preferred activity " 13863 + cur.mPref.mShortComponent + " for user " 13864 + userId + ":"); 13865 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13866 } 13867 return; 13868 } 13869 } 13870 13871 if (existing != null) { 13872 if (DEBUG_PREFERRED) { 13873 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13874 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13875 } 13876 for (int i = 0; i < existing.size(); i++) { 13877 PreferredActivity pa = existing.get(i); 13878 if (DEBUG_PREFERRED) { 13879 Slog.i(TAG, "Removing existing preferred activity " 13880 + pa.mPref.mComponent + ":"); 13881 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13882 } 13883 pir.removeFilter(pa); 13884 } 13885 } 13886 } 13887 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13888 "Replacing preferred"); 13889 } 13890 } 13891 13892 @Override 13893 public void clearPackagePreferredActivities(String packageName) { 13894 final int uid = Binder.getCallingUid(); 13895 // writer 13896 synchronized (mPackages) { 13897 PackageParser.Package pkg = mPackages.get(packageName); 13898 if (pkg == null || pkg.applicationInfo.uid != uid) { 13899 if (mContext.checkCallingOrSelfPermission( 13900 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13901 != PackageManager.PERMISSION_GRANTED) { 13902 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13903 < Build.VERSION_CODES.FROYO) { 13904 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13905 + Binder.getCallingUid()); 13906 return; 13907 } 13908 mContext.enforceCallingOrSelfPermission( 13909 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13910 } 13911 } 13912 13913 int user = UserHandle.getCallingUserId(); 13914 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13915 scheduleWritePackageRestrictionsLocked(user); 13916 } 13917 } 13918 } 13919 13920 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13921 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13922 ArrayList<PreferredActivity> removed = null; 13923 boolean changed = false; 13924 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13925 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13926 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13927 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13928 continue; 13929 } 13930 Iterator<PreferredActivity> it = pir.filterIterator(); 13931 while (it.hasNext()) { 13932 PreferredActivity pa = it.next(); 13933 // Mark entry for removal only if it matches the package name 13934 // and the entry is of type "always". 13935 if (packageName == null || 13936 (pa.mPref.mComponent.getPackageName().equals(packageName) 13937 && pa.mPref.mAlways)) { 13938 if (removed == null) { 13939 removed = new ArrayList<PreferredActivity>(); 13940 } 13941 removed.add(pa); 13942 } 13943 } 13944 if (removed != null) { 13945 for (int j=0; j<removed.size(); j++) { 13946 PreferredActivity pa = removed.get(j); 13947 pir.removeFilter(pa); 13948 } 13949 changed = true; 13950 } 13951 } 13952 return changed; 13953 } 13954 13955 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13956 private void clearIntentFilterVerificationsLPw(int userId) { 13957 final int packageCount = mPackages.size(); 13958 for (int i = 0; i < packageCount; i++) { 13959 PackageParser.Package pkg = mPackages.valueAt(i); 13960 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13961 } 13962 } 13963 13964 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13965 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13966 if (userId == UserHandle.USER_ALL) { 13967 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13968 sUserManager.getUserIds())) { 13969 for (int oneUserId : sUserManager.getUserIds()) { 13970 scheduleWritePackageRestrictionsLocked(oneUserId); 13971 } 13972 } 13973 } else { 13974 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13975 scheduleWritePackageRestrictionsLocked(userId); 13976 } 13977 } 13978 } 13979 13980 void clearDefaultBrowserIfNeeded(String packageName) { 13981 for (int oneUserId : sUserManager.getUserIds()) { 13982 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13983 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13984 if (packageName.equals(defaultBrowserPackageName)) { 13985 setDefaultBrowserPackageName(null, oneUserId); 13986 } 13987 } 13988 } 13989 13990 @Override 13991 public void resetApplicationPreferences(int userId) { 13992 mContext.enforceCallingOrSelfPermission( 13993 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13994 // writer 13995 synchronized (mPackages) { 13996 final long identity = Binder.clearCallingIdentity(); 13997 try { 13998 clearPackagePreferredActivitiesLPw(null, userId); 13999 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14000 // TODO: We have to reset the default SMS and Phone. This requires 14001 // significant refactoring to keep all default apps in the package 14002 // manager (cleaner but more work) or have the services provide 14003 // callbacks to the package manager to request a default app reset. 14004 applyFactoryDefaultBrowserLPw(userId); 14005 clearIntentFilterVerificationsLPw(userId); 14006 primeDomainVerificationsLPw(userId); 14007 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14008 scheduleWritePackageRestrictionsLocked(userId); 14009 } finally { 14010 Binder.restoreCallingIdentity(identity); 14011 } 14012 } 14013 } 14014 14015 @Override 14016 public int getPreferredActivities(List<IntentFilter> outFilters, 14017 List<ComponentName> outActivities, String packageName) { 14018 14019 int num = 0; 14020 final int userId = UserHandle.getCallingUserId(); 14021 // reader 14022 synchronized (mPackages) { 14023 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14024 if (pir != null) { 14025 final Iterator<PreferredActivity> it = pir.filterIterator(); 14026 while (it.hasNext()) { 14027 final PreferredActivity pa = it.next(); 14028 if (packageName == null 14029 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14030 && pa.mPref.mAlways)) { 14031 if (outFilters != null) { 14032 outFilters.add(new IntentFilter(pa)); 14033 } 14034 if (outActivities != null) { 14035 outActivities.add(pa.mPref.mComponent); 14036 } 14037 } 14038 } 14039 } 14040 } 14041 14042 return num; 14043 } 14044 14045 @Override 14046 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14047 int userId) { 14048 int callingUid = Binder.getCallingUid(); 14049 if (callingUid != Process.SYSTEM_UID) { 14050 throw new SecurityException( 14051 "addPersistentPreferredActivity can only be run by the system"); 14052 } 14053 if (filter.countActions() == 0) { 14054 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14055 return; 14056 } 14057 synchronized (mPackages) { 14058 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14059 " :"); 14060 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14061 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14062 new PersistentPreferredActivity(filter, activity)); 14063 scheduleWritePackageRestrictionsLocked(userId); 14064 } 14065 } 14066 14067 @Override 14068 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14069 int callingUid = Binder.getCallingUid(); 14070 if (callingUid != Process.SYSTEM_UID) { 14071 throw new SecurityException( 14072 "clearPackagePersistentPreferredActivities can only be run by the system"); 14073 } 14074 ArrayList<PersistentPreferredActivity> removed = null; 14075 boolean changed = false; 14076 synchronized (mPackages) { 14077 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14078 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14079 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14080 .valueAt(i); 14081 if (userId != thisUserId) { 14082 continue; 14083 } 14084 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14085 while (it.hasNext()) { 14086 PersistentPreferredActivity ppa = it.next(); 14087 // Mark entry for removal only if it matches the package name. 14088 if (ppa.mComponent.getPackageName().equals(packageName)) { 14089 if (removed == null) { 14090 removed = new ArrayList<PersistentPreferredActivity>(); 14091 } 14092 removed.add(ppa); 14093 } 14094 } 14095 if (removed != null) { 14096 for (int j=0; j<removed.size(); j++) { 14097 PersistentPreferredActivity ppa = removed.get(j); 14098 ppir.removeFilter(ppa); 14099 } 14100 changed = true; 14101 } 14102 } 14103 14104 if (changed) { 14105 scheduleWritePackageRestrictionsLocked(userId); 14106 } 14107 } 14108 } 14109 14110 /** 14111 * Common machinery for picking apart a restored XML blob and passing 14112 * it to a caller-supplied functor to be applied to the running system. 14113 */ 14114 private void restoreFromXml(XmlPullParser parser, int userId, 14115 String expectedStartTag, BlobXmlRestorer functor) 14116 throws IOException, XmlPullParserException { 14117 int type; 14118 while ((type = parser.next()) != XmlPullParser.START_TAG 14119 && type != XmlPullParser.END_DOCUMENT) { 14120 } 14121 if (type != XmlPullParser.START_TAG) { 14122 // oops didn't find a start tag?! 14123 if (DEBUG_BACKUP) { 14124 Slog.e(TAG, "Didn't find start tag during restore"); 14125 } 14126 return; 14127 } 14128 14129 // this is supposed to be TAG_PREFERRED_BACKUP 14130 if (!expectedStartTag.equals(parser.getName())) { 14131 if (DEBUG_BACKUP) { 14132 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14133 } 14134 return; 14135 } 14136 14137 // skip interfering stuff, then we're aligned with the backing implementation 14138 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14139 functor.apply(parser, userId); 14140 } 14141 14142 private interface BlobXmlRestorer { 14143 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14144 } 14145 14146 /** 14147 * Non-Binder method, support for the backup/restore mechanism: write the 14148 * full set of preferred activities in its canonical XML format. Returns the 14149 * XML output as a byte array, or null if there is none. 14150 */ 14151 @Override 14152 public byte[] getPreferredActivityBackup(int userId) { 14153 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14154 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14155 } 14156 14157 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14158 try { 14159 final XmlSerializer serializer = new FastXmlSerializer(); 14160 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14161 serializer.startDocument(null, true); 14162 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14163 14164 synchronized (mPackages) { 14165 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14166 } 14167 14168 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14169 serializer.endDocument(); 14170 serializer.flush(); 14171 } catch (Exception e) { 14172 if (DEBUG_BACKUP) { 14173 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14174 } 14175 return null; 14176 } 14177 14178 return dataStream.toByteArray(); 14179 } 14180 14181 @Override 14182 public void restorePreferredActivities(byte[] backup, int userId) { 14183 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14184 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14185 } 14186 14187 try { 14188 final XmlPullParser parser = Xml.newPullParser(); 14189 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14190 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14191 new BlobXmlRestorer() { 14192 @Override 14193 public void apply(XmlPullParser parser, int userId) 14194 throws XmlPullParserException, IOException { 14195 synchronized (mPackages) { 14196 mSettings.readPreferredActivitiesLPw(parser, userId); 14197 } 14198 } 14199 } ); 14200 } catch (Exception e) { 14201 if (DEBUG_BACKUP) { 14202 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14203 } 14204 } 14205 } 14206 14207 /** 14208 * Non-Binder method, support for the backup/restore mechanism: write the 14209 * default browser (etc) settings in its canonical XML format. Returns the default 14210 * browser XML representation as a byte array, or null if there is none. 14211 */ 14212 @Override 14213 public byte[] getDefaultAppsBackup(int userId) { 14214 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14215 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14216 } 14217 14218 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14219 try { 14220 final XmlSerializer serializer = new FastXmlSerializer(); 14221 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14222 serializer.startDocument(null, true); 14223 serializer.startTag(null, TAG_DEFAULT_APPS); 14224 14225 synchronized (mPackages) { 14226 mSettings.writeDefaultAppsLPr(serializer, userId); 14227 } 14228 14229 serializer.endTag(null, TAG_DEFAULT_APPS); 14230 serializer.endDocument(); 14231 serializer.flush(); 14232 } catch (Exception e) { 14233 if (DEBUG_BACKUP) { 14234 Slog.e(TAG, "Unable to write default apps for backup", e); 14235 } 14236 return null; 14237 } 14238 14239 return dataStream.toByteArray(); 14240 } 14241 14242 @Override 14243 public void restoreDefaultApps(byte[] backup, int userId) { 14244 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14245 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14246 } 14247 14248 try { 14249 final XmlPullParser parser = Xml.newPullParser(); 14250 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14251 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14252 new BlobXmlRestorer() { 14253 @Override 14254 public void apply(XmlPullParser parser, int userId) 14255 throws XmlPullParserException, IOException { 14256 synchronized (mPackages) { 14257 mSettings.readDefaultAppsLPw(parser, userId); 14258 } 14259 } 14260 } ); 14261 } catch (Exception e) { 14262 if (DEBUG_BACKUP) { 14263 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14264 } 14265 } 14266 } 14267 14268 @Override 14269 public byte[] getIntentFilterVerificationBackup(int userId) { 14270 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14271 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14272 } 14273 14274 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14275 try { 14276 final XmlSerializer serializer = new FastXmlSerializer(); 14277 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14278 serializer.startDocument(null, true); 14279 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14280 14281 synchronized (mPackages) { 14282 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14283 } 14284 14285 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14286 serializer.endDocument(); 14287 serializer.flush(); 14288 } catch (Exception e) { 14289 if (DEBUG_BACKUP) { 14290 Slog.e(TAG, "Unable to write default apps for backup", e); 14291 } 14292 return null; 14293 } 14294 14295 return dataStream.toByteArray(); 14296 } 14297 14298 @Override 14299 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14300 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14301 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14302 } 14303 14304 try { 14305 final XmlPullParser parser = Xml.newPullParser(); 14306 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14307 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14308 new BlobXmlRestorer() { 14309 @Override 14310 public void apply(XmlPullParser parser, int userId) 14311 throws XmlPullParserException, IOException { 14312 synchronized (mPackages) { 14313 mSettings.readAllDomainVerificationsLPr(parser, userId); 14314 mSettings.writeLPr(); 14315 } 14316 } 14317 } ); 14318 } catch (Exception e) { 14319 if (DEBUG_BACKUP) { 14320 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14321 } 14322 } 14323 } 14324 14325 @Override 14326 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14327 int sourceUserId, int targetUserId, int flags) { 14328 mContext.enforceCallingOrSelfPermission( 14329 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14330 int callingUid = Binder.getCallingUid(); 14331 enforceOwnerRights(ownerPackage, callingUid); 14332 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14333 if (intentFilter.countActions() == 0) { 14334 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14335 return; 14336 } 14337 synchronized (mPackages) { 14338 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14339 ownerPackage, targetUserId, flags); 14340 CrossProfileIntentResolver resolver = 14341 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14342 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14343 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14344 if (existing != null) { 14345 int size = existing.size(); 14346 for (int i = 0; i < size; i++) { 14347 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14348 return; 14349 } 14350 } 14351 } 14352 resolver.addFilter(newFilter); 14353 scheduleWritePackageRestrictionsLocked(sourceUserId); 14354 } 14355 } 14356 14357 @Override 14358 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14359 mContext.enforceCallingOrSelfPermission( 14360 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14361 int callingUid = Binder.getCallingUid(); 14362 enforceOwnerRights(ownerPackage, callingUid); 14363 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14364 synchronized (mPackages) { 14365 CrossProfileIntentResolver resolver = 14366 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14367 ArraySet<CrossProfileIntentFilter> set = 14368 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14369 for (CrossProfileIntentFilter filter : set) { 14370 if (filter.getOwnerPackage().equals(ownerPackage)) { 14371 resolver.removeFilter(filter); 14372 } 14373 } 14374 scheduleWritePackageRestrictionsLocked(sourceUserId); 14375 } 14376 } 14377 14378 // Enforcing that callingUid is owning pkg on userId 14379 private void enforceOwnerRights(String pkg, int callingUid) { 14380 // The system owns everything. 14381 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14382 return; 14383 } 14384 int callingUserId = UserHandle.getUserId(callingUid); 14385 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14386 if (pi == null) { 14387 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14388 + callingUserId); 14389 } 14390 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14391 throw new SecurityException("Calling uid " + callingUid 14392 + " does not own package " + pkg); 14393 } 14394 } 14395 14396 @Override 14397 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14398 Intent intent = new Intent(Intent.ACTION_MAIN); 14399 intent.addCategory(Intent.CATEGORY_HOME); 14400 14401 final int callingUserId = UserHandle.getCallingUserId(); 14402 List<ResolveInfo> list = queryIntentActivities(intent, null, 14403 PackageManager.GET_META_DATA, callingUserId); 14404 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14405 true, false, false, callingUserId); 14406 14407 allHomeCandidates.clear(); 14408 if (list != null) { 14409 for (ResolveInfo ri : list) { 14410 allHomeCandidates.add(ri); 14411 } 14412 } 14413 return (preferred == null || preferred.activityInfo == null) 14414 ? null 14415 : new ComponentName(preferred.activityInfo.packageName, 14416 preferred.activityInfo.name); 14417 } 14418 14419 @Override 14420 public void setApplicationEnabledSetting(String appPackageName, 14421 int newState, int flags, int userId, String callingPackage) { 14422 if (!sUserManager.exists(userId)) return; 14423 if (callingPackage == null) { 14424 callingPackage = Integer.toString(Binder.getCallingUid()); 14425 } 14426 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14427 } 14428 14429 @Override 14430 public void setComponentEnabledSetting(ComponentName componentName, 14431 int newState, int flags, int userId) { 14432 if (!sUserManager.exists(userId)) return; 14433 setEnabledSetting(componentName.getPackageName(), 14434 componentName.getClassName(), newState, flags, userId, null); 14435 } 14436 14437 private void setEnabledSetting(final String packageName, String className, int newState, 14438 final int flags, int userId, String callingPackage) { 14439 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14440 || newState == COMPONENT_ENABLED_STATE_ENABLED 14441 || newState == COMPONENT_ENABLED_STATE_DISABLED 14442 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14443 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14444 throw new IllegalArgumentException("Invalid new component state: " 14445 + newState); 14446 } 14447 PackageSetting pkgSetting; 14448 final int uid = Binder.getCallingUid(); 14449 final int permission = mContext.checkCallingOrSelfPermission( 14450 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14451 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14452 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14453 boolean sendNow = false; 14454 boolean isApp = (className == null); 14455 String componentName = isApp ? packageName : className; 14456 int packageUid = -1; 14457 ArrayList<String> components; 14458 14459 // writer 14460 synchronized (mPackages) { 14461 pkgSetting = mSettings.mPackages.get(packageName); 14462 if (pkgSetting == null) { 14463 if (className == null) { 14464 throw new IllegalArgumentException( 14465 "Unknown package: " + packageName); 14466 } 14467 throw new IllegalArgumentException( 14468 "Unknown component: " + packageName 14469 + "/" + className); 14470 } 14471 // Allow root and verify that userId is not being specified by a different user 14472 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14473 throw new SecurityException( 14474 "Permission Denial: attempt to change component state from pid=" 14475 + Binder.getCallingPid() 14476 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14477 } 14478 if (className == null) { 14479 // We're dealing with an application/package level state change 14480 if (pkgSetting.getEnabled(userId) == newState) { 14481 // Nothing to do 14482 return; 14483 } 14484 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14485 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14486 // Don't care about who enables an app. 14487 callingPackage = null; 14488 } 14489 pkgSetting.setEnabled(newState, userId, callingPackage); 14490 // pkgSetting.pkg.mSetEnabled = newState; 14491 } else { 14492 // We're dealing with a component level state change 14493 // First, verify that this is a valid class name. 14494 PackageParser.Package pkg = pkgSetting.pkg; 14495 if (pkg == null || !pkg.hasComponentClassName(className)) { 14496 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14497 throw new IllegalArgumentException("Component class " + className 14498 + " does not exist in " + packageName); 14499 } else { 14500 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14501 + className + " does not exist in " + packageName); 14502 } 14503 } 14504 switch (newState) { 14505 case COMPONENT_ENABLED_STATE_ENABLED: 14506 if (!pkgSetting.enableComponentLPw(className, userId)) { 14507 return; 14508 } 14509 break; 14510 case COMPONENT_ENABLED_STATE_DISABLED: 14511 if (!pkgSetting.disableComponentLPw(className, userId)) { 14512 return; 14513 } 14514 break; 14515 case COMPONENT_ENABLED_STATE_DEFAULT: 14516 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14517 return; 14518 } 14519 break; 14520 default: 14521 Slog.e(TAG, "Invalid new component state: " + newState); 14522 return; 14523 } 14524 } 14525 scheduleWritePackageRestrictionsLocked(userId); 14526 components = mPendingBroadcasts.get(userId, packageName); 14527 final boolean newPackage = components == null; 14528 if (newPackage) { 14529 components = new ArrayList<String>(); 14530 } 14531 if (!components.contains(componentName)) { 14532 components.add(componentName); 14533 } 14534 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14535 sendNow = true; 14536 // Purge entry from pending broadcast list if another one exists already 14537 // since we are sending one right away. 14538 mPendingBroadcasts.remove(userId, packageName); 14539 } else { 14540 if (newPackage) { 14541 mPendingBroadcasts.put(userId, packageName, components); 14542 } 14543 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14544 // Schedule a message 14545 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14546 } 14547 } 14548 } 14549 14550 long callingId = Binder.clearCallingIdentity(); 14551 try { 14552 if (sendNow) { 14553 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14554 sendPackageChangedBroadcast(packageName, 14555 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14556 } 14557 } finally { 14558 Binder.restoreCallingIdentity(callingId); 14559 } 14560 } 14561 14562 private void sendPackageChangedBroadcast(String packageName, 14563 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14564 if (DEBUG_INSTALL) 14565 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14566 + componentNames); 14567 Bundle extras = new Bundle(4); 14568 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14569 String nameList[] = new String[componentNames.size()]; 14570 componentNames.toArray(nameList); 14571 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14572 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14573 extras.putInt(Intent.EXTRA_UID, packageUid); 14574 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14575 new int[] {UserHandle.getUserId(packageUid)}); 14576 } 14577 14578 @Override 14579 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14580 if (!sUserManager.exists(userId)) return; 14581 final int uid = Binder.getCallingUid(); 14582 final int permission = mContext.checkCallingOrSelfPermission( 14583 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14584 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14585 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14586 // writer 14587 synchronized (mPackages) { 14588 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14589 allowedByPermission, uid, userId)) { 14590 scheduleWritePackageRestrictionsLocked(userId); 14591 } 14592 } 14593 } 14594 14595 @Override 14596 public String getInstallerPackageName(String packageName) { 14597 // reader 14598 synchronized (mPackages) { 14599 return mSettings.getInstallerPackageNameLPr(packageName); 14600 } 14601 } 14602 14603 @Override 14604 public int getApplicationEnabledSetting(String packageName, int userId) { 14605 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14606 int uid = Binder.getCallingUid(); 14607 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14608 // reader 14609 synchronized (mPackages) { 14610 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14611 } 14612 } 14613 14614 @Override 14615 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14616 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14617 int uid = Binder.getCallingUid(); 14618 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14619 // reader 14620 synchronized (mPackages) { 14621 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14622 } 14623 } 14624 14625 @Override 14626 public void enterSafeMode() { 14627 enforceSystemOrRoot("Only the system can request entering safe mode"); 14628 14629 if (!mSystemReady) { 14630 mSafeMode = true; 14631 } 14632 } 14633 14634 @Override 14635 public void systemReady() { 14636 mSystemReady = true; 14637 14638 // Read the compatibilty setting when the system is ready. 14639 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14640 mContext.getContentResolver(), 14641 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14642 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14643 if (DEBUG_SETTINGS) { 14644 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14645 } 14646 14647 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14648 14649 synchronized (mPackages) { 14650 // Verify that all of the preferred activity components actually 14651 // exist. It is possible for applications to be updated and at 14652 // that point remove a previously declared activity component that 14653 // had been set as a preferred activity. We try to clean this up 14654 // the next time we encounter that preferred activity, but it is 14655 // possible for the user flow to never be able to return to that 14656 // situation so here we do a sanity check to make sure we haven't 14657 // left any junk around. 14658 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14659 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14660 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14661 removed.clear(); 14662 for (PreferredActivity pa : pir.filterSet()) { 14663 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14664 removed.add(pa); 14665 } 14666 } 14667 if (removed.size() > 0) { 14668 for (int r=0; r<removed.size(); r++) { 14669 PreferredActivity pa = removed.get(r); 14670 Slog.w(TAG, "Removing dangling preferred activity: " 14671 + pa.mPref.mComponent); 14672 pir.removeFilter(pa); 14673 } 14674 mSettings.writePackageRestrictionsLPr( 14675 mSettings.mPreferredActivities.keyAt(i)); 14676 } 14677 } 14678 14679 for (int userId : UserManagerService.getInstance().getUserIds()) { 14680 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14681 grantPermissionsUserIds = ArrayUtils.appendInt( 14682 grantPermissionsUserIds, userId); 14683 } 14684 } 14685 } 14686 sUserManager.systemReady(); 14687 14688 // If we upgraded grant all default permissions before kicking off. 14689 for (int userId : grantPermissionsUserIds) { 14690 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14691 } 14692 14693 // Kick off any messages waiting for system ready 14694 if (mPostSystemReadyMessages != null) { 14695 for (Message msg : mPostSystemReadyMessages) { 14696 msg.sendToTarget(); 14697 } 14698 mPostSystemReadyMessages = null; 14699 } 14700 14701 // Watch for external volumes that come and go over time 14702 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14703 storage.registerListener(mStorageListener); 14704 14705 mInstallerService.systemReady(); 14706 mPackageDexOptimizer.systemReady(); 14707 14708 MountServiceInternal mountServiceInternal = LocalServices.getService( 14709 MountServiceInternal.class); 14710 mountServiceInternal.addExternalStoragePolicy( 14711 new MountServiceInternal.ExternalStorageMountPolicy() { 14712 @Override 14713 public int getMountMode(int uid, String packageName) { 14714 if (Process.isIsolated(uid)) { 14715 return Zygote.MOUNT_EXTERNAL_NONE; 14716 } 14717 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14718 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14719 } 14720 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14721 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14722 } 14723 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14724 return Zygote.MOUNT_EXTERNAL_READ; 14725 } 14726 return Zygote.MOUNT_EXTERNAL_WRITE; 14727 } 14728 14729 @Override 14730 public boolean hasExternalStorage(int uid, String packageName) { 14731 return true; 14732 } 14733 }); 14734 } 14735 14736 @Override 14737 public boolean isSafeMode() { 14738 return mSafeMode; 14739 } 14740 14741 @Override 14742 public boolean hasSystemUidErrors() { 14743 return mHasSystemUidErrors; 14744 } 14745 14746 static String arrayToString(int[] array) { 14747 StringBuffer buf = new StringBuffer(128); 14748 buf.append('['); 14749 if (array != null) { 14750 for (int i=0; i<array.length; i++) { 14751 if (i > 0) buf.append(", "); 14752 buf.append(array[i]); 14753 } 14754 } 14755 buf.append(']'); 14756 return buf.toString(); 14757 } 14758 14759 static class DumpState { 14760 public static final int DUMP_LIBS = 1 << 0; 14761 public static final int DUMP_FEATURES = 1 << 1; 14762 public static final int DUMP_RESOLVERS = 1 << 2; 14763 public static final int DUMP_PERMISSIONS = 1 << 3; 14764 public static final int DUMP_PACKAGES = 1 << 4; 14765 public static final int DUMP_SHARED_USERS = 1 << 5; 14766 public static final int DUMP_MESSAGES = 1 << 6; 14767 public static final int DUMP_PROVIDERS = 1 << 7; 14768 public static final int DUMP_VERIFIERS = 1 << 8; 14769 public static final int DUMP_PREFERRED = 1 << 9; 14770 public static final int DUMP_PREFERRED_XML = 1 << 10; 14771 public static final int DUMP_KEYSETS = 1 << 11; 14772 public static final int DUMP_VERSION = 1 << 12; 14773 public static final int DUMP_INSTALLS = 1 << 13; 14774 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14775 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14776 14777 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14778 14779 private int mTypes; 14780 14781 private int mOptions; 14782 14783 private boolean mTitlePrinted; 14784 14785 private SharedUserSetting mSharedUser; 14786 14787 public boolean isDumping(int type) { 14788 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14789 return true; 14790 } 14791 14792 return (mTypes & type) != 0; 14793 } 14794 14795 public void setDump(int type) { 14796 mTypes |= type; 14797 } 14798 14799 public boolean isOptionEnabled(int option) { 14800 return (mOptions & option) != 0; 14801 } 14802 14803 public void setOptionEnabled(int option) { 14804 mOptions |= option; 14805 } 14806 14807 public boolean onTitlePrinted() { 14808 final boolean printed = mTitlePrinted; 14809 mTitlePrinted = true; 14810 return printed; 14811 } 14812 14813 public boolean getTitlePrinted() { 14814 return mTitlePrinted; 14815 } 14816 14817 public void setTitlePrinted(boolean enabled) { 14818 mTitlePrinted = enabled; 14819 } 14820 14821 public SharedUserSetting getSharedUser() { 14822 return mSharedUser; 14823 } 14824 14825 public void setSharedUser(SharedUserSetting user) { 14826 mSharedUser = user; 14827 } 14828 } 14829 14830 @Override 14831 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14832 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14833 != PackageManager.PERMISSION_GRANTED) { 14834 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14835 + Binder.getCallingPid() 14836 + ", uid=" + Binder.getCallingUid() 14837 + " without permission " 14838 + android.Manifest.permission.DUMP); 14839 return; 14840 } 14841 14842 DumpState dumpState = new DumpState(); 14843 boolean fullPreferred = false; 14844 boolean checkin = false; 14845 14846 String packageName = null; 14847 ArraySet<String> permissionNames = null; 14848 14849 int opti = 0; 14850 while (opti < args.length) { 14851 String opt = args[opti]; 14852 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14853 break; 14854 } 14855 opti++; 14856 14857 if ("-a".equals(opt)) { 14858 // Right now we only know how to print all. 14859 } else if ("-h".equals(opt)) { 14860 pw.println("Package manager dump options:"); 14861 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14862 pw.println(" --checkin: dump for a checkin"); 14863 pw.println(" -f: print details of intent filters"); 14864 pw.println(" -h: print this help"); 14865 pw.println(" cmd may be one of:"); 14866 pw.println(" l[ibraries]: list known shared libraries"); 14867 pw.println(" f[ibraries]: list device features"); 14868 pw.println(" k[eysets]: print known keysets"); 14869 pw.println(" r[esolvers]: dump intent resolvers"); 14870 pw.println(" perm[issions]: dump permissions"); 14871 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14872 pw.println(" pref[erred]: print preferred package settings"); 14873 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14874 pw.println(" prov[iders]: dump content providers"); 14875 pw.println(" p[ackages]: dump installed packages"); 14876 pw.println(" s[hared-users]: dump shared user IDs"); 14877 pw.println(" m[essages]: print collected runtime messages"); 14878 pw.println(" v[erifiers]: print package verifier info"); 14879 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14880 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14881 pw.println(" version: print database version info"); 14882 pw.println(" write: write current settings now"); 14883 pw.println(" installs: details about install sessions"); 14884 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14885 pw.println(" <package.name>: info about given package"); 14886 return; 14887 } else if ("--checkin".equals(opt)) { 14888 checkin = true; 14889 } else if ("-f".equals(opt)) { 14890 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14891 } else { 14892 pw.println("Unknown argument: " + opt + "; use -h for help"); 14893 } 14894 } 14895 14896 // Is the caller requesting to dump a particular piece of data? 14897 if (opti < args.length) { 14898 String cmd = args[opti]; 14899 opti++; 14900 // Is this a package name? 14901 if ("android".equals(cmd) || cmd.contains(".")) { 14902 packageName = cmd; 14903 // When dumping a single package, we always dump all of its 14904 // filter information since the amount of data will be reasonable. 14905 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14906 } else if ("check-permission".equals(cmd)) { 14907 if (opti >= args.length) { 14908 pw.println("Error: check-permission missing permission argument"); 14909 return; 14910 } 14911 String perm = args[opti]; 14912 opti++; 14913 if (opti >= args.length) { 14914 pw.println("Error: check-permission missing package argument"); 14915 return; 14916 } 14917 String pkg = args[opti]; 14918 opti++; 14919 int user = UserHandle.getUserId(Binder.getCallingUid()); 14920 if (opti < args.length) { 14921 try { 14922 user = Integer.parseInt(args[opti]); 14923 } catch (NumberFormatException e) { 14924 pw.println("Error: check-permission user argument is not a number: " 14925 + args[opti]); 14926 return; 14927 } 14928 } 14929 pw.println(checkPermission(perm, pkg, user)); 14930 return; 14931 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14932 dumpState.setDump(DumpState.DUMP_LIBS); 14933 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14934 dumpState.setDump(DumpState.DUMP_FEATURES); 14935 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14936 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14937 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14938 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14939 } else if ("permission".equals(cmd)) { 14940 if (opti >= args.length) { 14941 pw.println("Error: permission requires permission name"); 14942 return; 14943 } 14944 permissionNames = new ArraySet<>(); 14945 while (opti < args.length) { 14946 permissionNames.add(args[opti]); 14947 opti++; 14948 } 14949 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14950 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14951 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14952 dumpState.setDump(DumpState.DUMP_PREFERRED); 14953 } else if ("preferred-xml".equals(cmd)) { 14954 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14955 if (opti < args.length && "--full".equals(args[opti])) { 14956 fullPreferred = true; 14957 opti++; 14958 } 14959 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14960 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14961 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14962 dumpState.setDump(DumpState.DUMP_PACKAGES); 14963 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14964 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14965 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14966 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14967 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14968 dumpState.setDump(DumpState.DUMP_MESSAGES); 14969 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14970 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14971 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14972 || "intent-filter-verifiers".equals(cmd)) { 14973 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14974 } else if ("version".equals(cmd)) { 14975 dumpState.setDump(DumpState.DUMP_VERSION); 14976 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14977 dumpState.setDump(DumpState.DUMP_KEYSETS); 14978 } else if ("installs".equals(cmd)) { 14979 dumpState.setDump(DumpState.DUMP_INSTALLS); 14980 } else if ("write".equals(cmd)) { 14981 synchronized (mPackages) { 14982 mSettings.writeLPr(); 14983 pw.println("Settings written."); 14984 return; 14985 } 14986 } 14987 } 14988 14989 if (checkin) { 14990 pw.println("vers,1"); 14991 } 14992 14993 // reader 14994 synchronized (mPackages) { 14995 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14996 if (!checkin) { 14997 if (dumpState.onTitlePrinted()) 14998 pw.println(); 14999 pw.println("Database versions:"); 15000 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15001 } 15002 } 15003 15004 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15005 if (!checkin) { 15006 if (dumpState.onTitlePrinted()) 15007 pw.println(); 15008 pw.println("Verifiers:"); 15009 pw.print(" Required: "); 15010 pw.print(mRequiredVerifierPackage); 15011 pw.print(" (uid="); 15012 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15013 pw.println(")"); 15014 } else if (mRequiredVerifierPackage != null) { 15015 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15016 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15017 } 15018 } 15019 15020 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15021 packageName == null) { 15022 if (mIntentFilterVerifierComponent != null) { 15023 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15024 if (!checkin) { 15025 if (dumpState.onTitlePrinted()) 15026 pw.println(); 15027 pw.println("Intent Filter Verifier:"); 15028 pw.print(" Using: "); 15029 pw.print(verifierPackageName); 15030 pw.print(" (uid="); 15031 pw.print(getPackageUid(verifierPackageName, 0)); 15032 pw.println(")"); 15033 } else if (verifierPackageName != null) { 15034 pw.print("ifv,"); pw.print(verifierPackageName); 15035 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15036 } 15037 } else { 15038 pw.println(); 15039 pw.println("No Intent Filter Verifier available!"); 15040 } 15041 } 15042 15043 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15044 boolean printedHeader = false; 15045 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15046 while (it.hasNext()) { 15047 String name = it.next(); 15048 SharedLibraryEntry ent = mSharedLibraries.get(name); 15049 if (!checkin) { 15050 if (!printedHeader) { 15051 if (dumpState.onTitlePrinted()) 15052 pw.println(); 15053 pw.println("Libraries:"); 15054 printedHeader = true; 15055 } 15056 pw.print(" "); 15057 } else { 15058 pw.print("lib,"); 15059 } 15060 pw.print(name); 15061 if (!checkin) { 15062 pw.print(" -> "); 15063 } 15064 if (ent.path != null) { 15065 if (!checkin) { 15066 pw.print("(jar) "); 15067 pw.print(ent.path); 15068 } else { 15069 pw.print(",jar,"); 15070 pw.print(ent.path); 15071 } 15072 } else { 15073 if (!checkin) { 15074 pw.print("(apk) "); 15075 pw.print(ent.apk); 15076 } else { 15077 pw.print(",apk,"); 15078 pw.print(ent.apk); 15079 } 15080 } 15081 pw.println(); 15082 } 15083 } 15084 15085 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15086 if (dumpState.onTitlePrinted()) 15087 pw.println(); 15088 if (!checkin) { 15089 pw.println("Features:"); 15090 } 15091 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15092 while (it.hasNext()) { 15093 String name = it.next(); 15094 if (!checkin) { 15095 pw.print(" "); 15096 } else { 15097 pw.print("feat,"); 15098 } 15099 pw.println(name); 15100 } 15101 } 15102 15103 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15104 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15105 : "Activity Resolver Table:", " ", packageName, 15106 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15107 dumpState.setTitlePrinted(true); 15108 } 15109 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15110 : "Receiver Resolver Table:", " ", packageName, 15111 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15112 dumpState.setTitlePrinted(true); 15113 } 15114 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15115 : "Service Resolver Table:", " ", packageName, 15116 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15117 dumpState.setTitlePrinted(true); 15118 } 15119 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15120 : "Provider Resolver Table:", " ", packageName, 15121 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15122 dumpState.setTitlePrinted(true); 15123 } 15124 } 15125 15126 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15127 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15128 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15129 int user = mSettings.mPreferredActivities.keyAt(i); 15130 if (pir.dump(pw, 15131 dumpState.getTitlePrinted() 15132 ? "\nPreferred Activities User " + user + ":" 15133 : "Preferred Activities User " + user + ":", " ", 15134 packageName, true, false)) { 15135 dumpState.setTitlePrinted(true); 15136 } 15137 } 15138 } 15139 15140 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15141 pw.flush(); 15142 FileOutputStream fout = new FileOutputStream(fd); 15143 BufferedOutputStream str = new BufferedOutputStream(fout); 15144 XmlSerializer serializer = new FastXmlSerializer(); 15145 try { 15146 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15147 serializer.startDocument(null, true); 15148 serializer.setFeature( 15149 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15150 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15151 serializer.endDocument(); 15152 serializer.flush(); 15153 } catch (IllegalArgumentException e) { 15154 pw.println("Failed writing: " + e); 15155 } catch (IllegalStateException e) { 15156 pw.println("Failed writing: " + e); 15157 } catch (IOException e) { 15158 pw.println("Failed writing: " + e); 15159 } 15160 } 15161 15162 if (!checkin 15163 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15164 && packageName == null) { 15165 pw.println(); 15166 int count = mSettings.mPackages.size(); 15167 if (count == 0) { 15168 pw.println("No applications!"); 15169 pw.println(); 15170 } else { 15171 final String prefix = " "; 15172 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15173 if (allPackageSettings.size() == 0) { 15174 pw.println("No domain preferred apps!"); 15175 pw.println(); 15176 } else { 15177 pw.println("App verification status:"); 15178 pw.println(); 15179 count = 0; 15180 for (PackageSetting ps : allPackageSettings) { 15181 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15182 if (ivi == null || ivi.getPackageName() == null) continue; 15183 pw.println(prefix + "Package: " + ivi.getPackageName()); 15184 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15185 pw.println(prefix + "Status: " + ivi.getStatusString()); 15186 pw.println(); 15187 count++; 15188 } 15189 if (count == 0) { 15190 pw.println(prefix + "No app verification established."); 15191 pw.println(); 15192 } 15193 for (int userId : sUserManager.getUserIds()) { 15194 pw.println("App linkages for user " + userId + ":"); 15195 pw.println(); 15196 count = 0; 15197 for (PackageSetting ps : allPackageSettings) { 15198 final long status = ps.getDomainVerificationStatusForUser(userId); 15199 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15200 continue; 15201 } 15202 pw.println(prefix + "Package: " + ps.name); 15203 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15204 String statusStr = IntentFilterVerificationInfo. 15205 getStatusStringFromValue(status); 15206 pw.println(prefix + "Status: " + statusStr); 15207 pw.println(); 15208 count++; 15209 } 15210 if (count == 0) { 15211 pw.println(prefix + "No configured app linkages."); 15212 pw.println(); 15213 } 15214 } 15215 } 15216 } 15217 } 15218 15219 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15220 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15221 if (packageName == null && permissionNames == null) { 15222 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15223 if (iperm == 0) { 15224 if (dumpState.onTitlePrinted()) 15225 pw.println(); 15226 pw.println("AppOp Permissions:"); 15227 } 15228 pw.print(" AppOp Permission "); 15229 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15230 pw.println(":"); 15231 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15232 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15233 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15234 } 15235 } 15236 } 15237 } 15238 15239 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15240 boolean printedSomething = false; 15241 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15242 if (packageName != null && !packageName.equals(p.info.packageName)) { 15243 continue; 15244 } 15245 if (!printedSomething) { 15246 if (dumpState.onTitlePrinted()) 15247 pw.println(); 15248 pw.println("Registered ContentProviders:"); 15249 printedSomething = true; 15250 } 15251 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15252 pw.print(" "); pw.println(p.toString()); 15253 } 15254 printedSomething = false; 15255 for (Map.Entry<String, PackageParser.Provider> entry : 15256 mProvidersByAuthority.entrySet()) { 15257 PackageParser.Provider p = entry.getValue(); 15258 if (packageName != null && !packageName.equals(p.info.packageName)) { 15259 continue; 15260 } 15261 if (!printedSomething) { 15262 if (dumpState.onTitlePrinted()) 15263 pw.println(); 15264 pw.println("ContentProvider Authorities:"); 15265 printedSomething = true; 15266 } 15267 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15268 pw.print(" "); pw.println(p.toString()); 15269 if (p.info != null && p.info.applicationInfo != null) { 15270 final String appInfo = p.info.applicationInfo.toString(); 15271 pw.print(" applicationInfo="); pw.println(appInfo); 15272 } 15273 } 15274 } 15275 15276 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15277 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15278 } 15279 15280 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15281 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15282 } 15283 15284 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15285 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15286 } 15287 15288 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15289 // XXX should handle packageName != null by dumping only install data that 15290 // the given package is involved with. 15291 if (dumpState.onTitlePrinted()) pw.println(); 15292 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15293 } 15294 15295 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15296 if (dumpState.onTitlePrinted()) pw.println(); 15297 mSettings.dumpReadMessagesLPr(pw, dumpState); 15298 15299 pw.println(); 15300 pw.println("Package warning messages:"); 15301 BufferedReader in = null; 15302 String line = null; 15303 try { 15304 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15305 while ((line = in.readLine()) != null) { 15306 if (line.contains("ignored: updated version")) continue; 15307 pw.println(line); 15308 } 15309 } catch (IOException ignored) { 15310 } finally { 15311 IoUtils.closeQuietly(in); 15312 } 15313 } 15314 15315 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15316 BufferedReader in = null; 15317 String line = null; 15318 try { 15319 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15320 while ((line = in.readLine()) != null) { 15321 if (line.contains("ignored: updated version")) continue; 15322 pw.print("msg,"); 15323 pw.println(line); 15324 } 15325 } catch (IOException ignored) { 15326 } finally { 15327 IoUtils.closeQuietly(in); 15328 } 15329 } 15330 } 15331 } 15332 15333 private String dumpDomainString(String packageName) { 15334 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15335 List<IntentFilter> filters = getAllIntentFilters(packageName); 15336 15337 ArraySet<String> result = new ArraySet<>(); 15338 if (iviList.size() > 0) { 15339 for (IntentFilterVerificationInfo ivi : iviList) { 15340 for (String host : ivi.getDomains()) { 15341 result.add(host); 15342 } 15343 } 15344 } 15345 if (filters != null && filters.size() > 0) { 15346 for (IntentFilter filter : filters) { 15347 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15348 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15349 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15350 result.addAll(filter.getHostsList()); 15351 } 15352 } 15353 } 15354 15355 StringBuilder sb = new StringBuilder(result.size() * 16); 15356 for (String domain : result) { 15357 if (sb.length() > 0) sb.append(" "); 15358 sb.append(domain); 15359 } 15360 return sb.toString(); 15361 } 15362 15363 // ------- apps on sdcard specific code ------- 15364 static final boolean DEBUG_SD_INSTALL = false; 15365 15366 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15367 15368 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15369 15370 private boolean mMediaMounted = false; 15371 15372 static String getEncryptKey() { 15373 try { 15374 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15375 SD_ENCRYPTION_KEYSTORE_NAME); 15376 if (sdEncKey == null) { 15377 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15378 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15379 if (sdEncKey == null) { 15380 Slog.e(TAG, "Failed to create encryption keys"); 15381 return null; 15382 } 15383 } 15384 return sdEncKey; 15385 } catch (NoSuchAlgorithmException nsae) { 15386 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15387 return null; 15388 } catch (IOException ioe) { 15389 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15390 return null; 15391 } 15392 } 15393 15394 /* 15395 * Update media status on PackageManager. 15396 */ 15397 @Override 15398 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15399 int callingUid = Binder.getCallingUid(); 15400 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15401 throw new SecurityException("Media status can only be updated by the system"); 15402 } 15403 // reader; this apparently protects mMediaMounted, but should probably 15404 // be a different lock in that case. 15405 synchronized (mPackages) { 15406 Log.i(TAG, "Updating external media status from " 15407 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15408 + (mediaStatus ? "mounted" : "unmounted")); 15409 if (DEBUG_SD_INSTALL) 15410 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15411 + ", mMediaMounted=" + mMediaMounted); 15412 if (mediaStatus == mMediaMounted) { 15413 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15414 : 0, -1); 15415 mHandler.sendMessage(msg); 15416 return; 15417 } 15418 mMediaMounted = mediaStatus; 15419 } 15420 // Queue up an async operation since the package installation may take a 15421 // little while. 15422 mHandler.post(new Runnable() { 15423 public void run() { 15424 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15425 } 15426 }); 15427 } 15428 15429 /** 15430 * Called by MountService when the initial ASECs to scan are available. 15431 * Should block until all the ASEC containers are finished being scanned. 15432 */ 15433 public void scanAvailableAsecs() { 15434 updateExternalMediaStatusInner(true, false, false); 15435 if (mShouldRestoreconData) { 15436 SELinuxMMAC.setRestoreconDone(); 15437 mShouldRestoreconData = false; 15438 } 15439 } 15440 15441 /* 15442 * Collect information of applications on external media, map them against 15443 * existing containers and update information based on current mount status. 15444 * Please note that we always have to report status if reportStatus has been 15445 * set to true especially when unloading packages. 15446 */ 15447 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15448 boolean externalStorage) { 15449 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15450 int[] uidArr = EmptyArray.INT; 15451 15452 final String[] list = PackageHelper.getSecureContainerList(); 15453 if (ArrayUtils.isEmpty(list)) { 15454 Log.i(TAG, "No secure containers found"); 15455 } else { 15456 // Process list of secure containers and categorize them 15457 // as active or stale based on their package internal state. 15458 15459 // reader 15460 synchronized (mPackages) { 15461 for (String cid : list) { 15462 // Leave stages untouched for now; installer service owns them 15463 if (PackageInstallerService.isStageName(cid)) continue; 15464 15465 if (DEBUG_SD_INSTALL) 15466 Log.i(TAG, "Processing container " + cid); 15467 String pkgName = getAsecPackageName(cid); 15468 if (pkgName == null) { 15469 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15470 continue; 15471 } 15472 if (DEBUG_SD_INSTALL) 15473 Log.i(TAG, "Looking for pkg : " + pkgName); 15474 15475 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15476 if (ps == null) { 15477 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15478 continue; 15479 } 15480 15481 /* 15482 * Skip packages that are not external if we're unmounting 15483 * external storage. 15484 */ 15485 if (externalStorage && !isMounted && !isExternal(ps)) { 15486 continue; 15487 } 15488 15489 final AsecInstallArgs args = new AsecInstallArgs(cid, 15490 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15491 // The package status is changed only if the code path 15492 // matches between settings and the container id. 15493 if (ps.codePathString != null 15494 && ps.codePathString.startsWith(args.getCodePath())) { 15495 if (DEBUG_SD_INSTALL) { 15496 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15497 + " at code path: " + ps.codePathString); 15498 } 15499 15500 // We do have a valid package installed on sdcard 15501 processCids.put(args, ps.codePathString); 15502 final int uid = ps.appId; 15503 if (uid != -1) { 15504 uidArr = ArrayUtils.appendInt(uidArr, uid); 15505 } 15506 } else { 15507 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15508 + ps.codePathString); 15509 } 15510 } 15511 } 15512 15513 Arrays.sort(uidArr); 15514 } 15515 15516 // Process packages with valid entries. 15517 if (isMounted) { 15518 if (DEBUG_SD_INSTALL) 15519 Log.i(TAG, "Loading packages"); 15520 loadMediaPackages(processCids, uidArr); 15521 startCleaningPackages(); 15522 mInstallerService.onSecureContainersAvailable(); 15523 } else { 15524 if (DEBUG_SD_INSTALL) 15525 Log.i(TAG, "Unloading packages"); 15526 unloadMediaPackages(processCids, uidArr, reportStatus); 15527 } 15528 } 15529 15530 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15531 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15532 final int size = infos.size(); 15533 final String[] packageNames = new String[size]; 15534 final int[] packageUids = new int[size]; 15535 for (int i = 0; i < size; i++) { 15536 final ApplicationInfo info = infos.get(i); 15537 packageNames[i] = info.packageName; 15538 packageUids[i] = info.uid; 15539 } 15540 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15541 finishedReceiver); 15542 } 15543 15544 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15545 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15546 sendResourcesChangedBroadcast(mediaStatus, replacing, 15547 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15548 } 15549 15550 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15551 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15552 int size = pkgList.length; 15553 if (size > 0) { 15554 // Send broadcasts here 15555 Bundle extras = new Bundle(); 15556 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15557 if (uidArr != null) { 15558 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15559 } 15560 if (replacing) { 15561 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15562 } 15563 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15564 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15565 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15566 } 15567 } 15568 15569 /* 15570 * Look at potentially valid container ids from processCids If package 15571 * information doesn't match the one on record or package scanning fails, 15572 * the cid is added to list of removeCids. We currently don't delete stale 15573 * containers. 15574 */ 15575 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15576 ArrayList<String> pkgList = new ArrayList<String>(); 15577 Set<AsecInstallArgs> keys = processCids.keySet(); 15578 15579 for (AsecInstallArgs args : keys) { 15580 String codePath = processCids.get(args); 15581 if (DEBUG_SD_INSTALL) 15582 Log.i(TAG, "Loading container : " + args.cid); 15583 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15584 try { 15585 // Make sure there are no container errors first. 15586 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15587 Slog.e(TAG, "Failed to mount cid : " + args.cid 15588 + " when installing from sdcard"); 15589 continue; 15590 } 15591 // Check code path here. 15592 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15593 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15594 + " does not match one in settings " + codePath); 15595 continue; 15596 } 15597 // Parse package 15598 int parseFlags = mDefParseFlags; 15599 if (args.isExternalAsec()) { 15600 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15601 } 15602 if (args.isFwdLocked()) { 15603 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15604 } 15605 15606 synchronized (mInstallLock) { 15607 PackageParser.Package pkg = null; 15608 try { 15609 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15610 } catch (PackageManagerException e) { 15611 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15612 } 15613 // Scan the package 15614 if (pkg != null) { 15615 /* 15616 * TODO why is the lock being held? doPostInstall is 15617 * called in other places without the lock. This needs 15618 * to be straightened out. 15619 */ 15620 // writer 15621 synchronized (mPackages) { 15622 retCode = PackageManager.INSTALL_SUCCEEDED; 15623 pkgList.add(pkg.packageName); 15624 // Post process args 15625 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15626 pkg.applicationInfo.uid); 15627 } 15628 } else { 15629 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15630 } 15631 } 15632 15633 } finally { 15634 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15635 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15636 } 15637 } 15638 } 15639 // writer 15640 synchronized (mPackages) { 15641 // If the platform SDK has changed since the last time we booted, 15642 // we need to re-grant app permission to catch any new ones that 15643 // appear. This is really a hack, and means that apps can in some 15644 // cases get permissions that the user didn't initially explicitly 15645 // allow... it would be nice to have some better way to handle 15646 // this situation. 15647 final VersionInfo ver = mSettings.getExternalVersion(); 15648 15649 int updateFlags = UPDATE_PERMISSIONS_ALL; 15650 if (ver.sdkVersion != mSdkVersion) { 15651 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15652 + mSdkVersion + "; regranting permissions for external"); 15653 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15654 } 15655 updatePermissionsLPw(null, null, updateFlags); 15656 15657 // Yay, everything is now upgraded 15658 ver.forceCurrent(); 15659 15660 // can downgrade to reader 15661 // Persist settings 15662 mSettings.writeLPr(); 15663 } 15664 // Send a broadcast to let everyone know we are done processing 15665 if (pkgList.size() > 0) { 15666 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15667 } 15668 } 15669 15670 /* 15671 * Utility method to unload a list of specified containers 15672 */ 15673 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15674 // Just unmount all valid containers. 15675 for (AsecInstallArgs arg : cidArgs) { 15676 synchronized (mInstallLock) { 15677 arg.doPostDeleteLI(false); 15678 } 15679 } 15680 } 15681 15682 /* 15683 * Unload packages mounted on external media. This involves deleting package 15684 * data from internal structures, sending broadcasts about diabled packages, 15685 * gc'ing to free up references, unmounting all secure containers 15686 * corresponding to packages on external media, and posting a 15687 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15688 * that we always have to post this message if status has been requested no 15689 * matter what. 15690 */ 15691 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15692 final boolean reportStatus) { 15693 if (DEBUG_SD_INSTALL) 15694 Log.i(TAG, "unloading media packages"); 15695 ArrayList<String> pkgList = new ArrayList<String>(); 15696 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15697 final Set<AsecInstallArgs> keys = processCids.keySet(); 15698 for (AsecInstallArgs args : keys) { 15699 String pkgName = args.getPackageName(); 15700 if (DEBUG_SD_INSTALL) 15701 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15702 // Delete package internally 15703 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15704 synchronized (mInstallLock) { 15705 boolean res = deletePackageLI(pkgName, null, false, null, null, 15706 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15707 if (res) { 15708 pkgList.add(pkgName); 15709 } else { 15710 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15711 failedList.add(args); 15712 } 15713 } 15714 } 15715 15716 // reader 15717 synchronized (mPackages) { 15718 // We didn't update the settings after removing each package; 15719 // write them now for all packages. 15720 mSettings.writeLPr(); 15721 } 15722 15723 // We have to absolutely send UPDATED_MEDIA_STATUS only 15724 // after confirming that all the receivers processed the ordered 15725 // broadcast when packages get disabled, force a gc to clean things up. 15726 // and unload all the containers. 15727 if (pkgList.size() > 0) { 15728 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15729 new IIntentReceiver.Stub() { 15730 public void performReceive(Intent intent, int resultCode, String data, 15731 Bundle extras, boolean ordered, boolean sticky, 15732 int sendingUser) throws RemoteException { 15733 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15734 reportStatus ? 1 : 0, 1, keys); 15735 mHandler.sendMessage(msg); 15736 } 15737 }); 15738 } else { 15739 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15740 keys); 15741 mHandler.sendMessage(msg); 15742 } 15743 } 15744 15745 private void loadPrivatePackages(VolumeInfo vol) { 15746 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15747 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15748 synchronized (mInstallLock) { 15749 synchronized (mPackages) { 15750 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15751 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15752 for (PackageSetting ps : packages) { 15753 final PackageParser.Package pkg; 15754 try { 15755 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15756 loaded.add(pkg.applicationInfo); 15757 } catch (PackageManagerException e) { 15758 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15759 } 15760 15761 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15762 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15763 } 15764 } 15765 15766 int updateFlags = UPDATE_PERMISSIONS_ALL; 15767 if (ver.sdkVersion != mSdkVersion) { 15768 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15769 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15770 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15771 } 15772 updatePermissionsLPw(null, null, updateFlags); 15773 15774 // Yay, everything is now upgraded 15775 ver.forceCurrent(); 15776 15777 mSettings.writeLPr(); 15778 } 15779 } 15780 15781 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15782 sendResourcesChangedBroadcast(true, false, loaded, null); 15783 } 15784 15785 private void unloadPrivatePackages(VolumeInfo vol) { 15786 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15787 synchronized (mInstallLock) { 15788 synchronized (mPackages) { 15789 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15790 for (PackageSetting ps : packages) { 15791 if (ps.pkg == null) continue; 15792 15793 final ApplicationInfo info = ps.pkg.applicationInfo; 15794 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15795 if (deletePackageLI(ps.name, null, false, null, null, 15796 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15797 unloaded.add(info); 15798 } else { 15799 Slog.w(TAG, "Failed to unload " + ps.codePath); 15800 } 15801 } 15802 15803 mSettings.writeLPr(); 15804 } 15805 } 15806 15807 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15808 sendResourcesChangedBroadcast(false, false, unloaded, null); 15809 } 15810 15811 /** 15812 * Examine all users present on given mounted volume, and destroy data 15813 * belonging to users that are no longer valid, or whose user ID has been 15814 * recycled. 15815 */ 15816 private void reconcileUsers(String volumeUuid) { 15817 final File[] files = FileUtils 15818 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15819 for (File file : files) { 15820 if (!file.isDirectory()) continue; 15821 15822 final int userId; 15823 final UserInfo info; 15824 try { 15825 userId = Integer.parseInt(file.getName()); 15826 info = sUserManager.getUserInfo(userId); 15827 } catch (NumberFormatException e) { 15828 Slog.w(TAG, "Invalid user directory " + file); 15829 continue; 15830 } 15831 15832 boolean destroyUser = false; 15833 if (info == null) { 15834 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15835 + " because no matching user was found"); 15836 destroyUser = true; 15837 } else { 15838 try { 15839 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15840 } catch (IOException e) { 15841 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15842 + " because we failed to enforce serial number: " + e); 15843 destroyUser = true; 15844 } 15845 } 15846 15847 if (destroyUser) { 15848 synchronized (mInstallLock) { 15849 mInstaller.removeUserDataDirs(volumeUuid, userId); 15850 } 15851 } 15852 } 15853 15854 final UserManager um = mContext.getSystemService(UserManager.class); 15855 for (UserInfo user : um.getUsers()) { 15856 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15857 if (userDir.exists()) continue; 15858 15859 try { 15860 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15861 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15862 } catch (IOException e) { 15863 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15864 } 15865 } 15866 } 15867 15868 /** 15869 * Examine all apps present on given mounted volume, and destroy apps that 15870 * aren't expected, either due to uninstallation or reinstallation on 15871 * another volume. 15872 */ 15873 private void reconcileApps(String volumeUuid) { 15874 final File[] files = FileUtils 15875 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15876 for (File file : files) { 15877 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15878 && !PackageInstallerService.isStageName(file.getName()); 15879 if (!isPackage) { 15880 // Ignore entries which are not packages 15881 continue; 15882 } 15883 15884 boolean destroyApp = false; 15885 String packageName = null; 15886 try { 15887 final PackageLite pkg = PackageParser.parsePackageLite(file, 15888 PackageParser.PARSE_MUST_BE_APK); 15889 packageName = pkg.packageName; 15890 15891 synchronized (mPackages) { 15892 final PackageSetting ps = mSettings.mPackages.get(packageName); 15893 if (ps == null) { 15894 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15895 + volumeUuid + " because we found no install record"); 15896 destroyApp = true; 15897 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15898 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15899 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15900 destroyApp = true; 15901 } 15902 } 15903 15904 } catch (PackageParserException e) { 15905 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15906 destroyApp = true; 15907 } 15908 15909 if (destroyApp) { 15910 synchronized (mInstallLock) { 15911 if (packageName != null) { 15912 removeDataDirsLI(volumeUuid, packageName); 15913 } 15914 if (file.isDirectory()) { 15915 mInstaller.rmPackageDir(file.getAbsolutePath()); 15916 } else { 15917 file.delete(); 15918 } 15919 } 15920 } 15921 } 15922 } 15923 15924 private void unfreezePackage(String packageName) { 15925 synchronized (mPackages) { 15926 final PackageSetting ps = mSettings.mPackages.get(packageName); 15927 if (ps != null) { 15928 ps.frozen = false; 15929 } 15930 } 15931 } 15932 15933 @Override 15934 public int movePackage(final String packageName, final String volumeUuid) { 15935 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15936 15937 final int moveId = mNextMoveId.getAndIncrement(); 15938 try { 15939 movePackageInternal(packageName, volumeUuid, moveId); 15940 } catch (PackageManagerException e) { 15941 Slog.w(TAG, "Failed to move " + packageName, e); 15942 mMoveCallbacks.notifyStatusChanged(moveId, 15943 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15944 } 15945 return moveId; 15946 } 15947 15948 private void movePackageInternal(final String packageName, final String volumeUuid, 15949 final int moveId) throws PackageManagerException { 15950 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15951 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15952 final PackageManager pm = mContext.getPackageManager(); 15953 15954 final boolean currentAsec; 15955 final String currentVolumeUuid; 15956 final File codeFile; 15957 final String installerPackageName; 15958 final String packageAbiOverride; 15959 final int appId; 15960 final String seinfo; 15961 final String label; 15962 15963 // reader 15964 synchronized (mPackages) { 15965 final PackageParser.Package pkg = mPackages.get(packageName); 15966 final PackageSetting ps = mSettings.mPackages.get(packageName); 15967 if (pkg == null || ps == null) { 15968 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15969 } 15970 15971 if (pkg.applicationInfo.isSystemApp()) { 15972 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15973 "Cannot move system application"); 15974 } 15975 15976 if (pkg.applicationInfo.isExternalAsec()) { 15977 currentAsec = true; 15978 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 15979 } else if (pkg.applicationInfo.isForwardLocked()) { 15980 currentAsec = true; 15981 currentVolumeUuid = "forward_locked"; 15982 } else { 15983 currentAsec = false; 15984 currentVolumeUuid = ps.volumeUuid; 15985 15986 final File probe = new File(pkg.codePath); 15987 final File probeOat = new File(probe, "oat"); 15988 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15989 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15990 "Move only supported for modern cluster style installs"); 15991 } 15992 } 15993 15994 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 15995 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15996 "Package already moved to " + volumeUuid); 15997 } 15998 15999 if (ps.frozen) { 16000 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16001 "Failed to move already frozen package"); 16002 } 16003 ps.frozen = true; 16004 16005 codeFile = new File(pkg.codePath); 16006 installerPackageName = ps.installerPackageName; 16007 packageAbiOverride = ps.cpuAbiOverrideString; 16008 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16009 seinfo = pkg.applicationInfo.seinfo; 16010 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16011 } 16012 16013 // Now that we're guarded by frozen state, kill app during move 16014 final long token = Binder.clearCallingIdentity(); 16015 try { 16016 killApplication(packageName, appId, "move pkg"); 16017 } finally { 16018 Binder.restoreCallingIdentity(token); 16019 } 16020 16021 final Bundle extras = new Bundle(); 16022 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16023 extras.putString(Intent.EXTRA_TITLE, label); 16024 mMoveCallbacks.notifyCreated(moveId, extras); 16025 16026 int installFlags; 16027 final boolean moveCompleteApp; 16028 final File measurePath; 16029 16030 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16031 installFlags = INSTALL_INTERNAL; 16032 moveCompleteApp = !currentAsec; 16033 measurePath = Environment.getDataAppDirectory(volumeUuid); 16034 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16035 installFlags = INSTALL_EXTERNAL; 16036 moveCompleteApp = false; 16037 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16038 } else { 16039 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16040 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16041 || !volume.isMountedWritable()) { 16042 unfreezePackage(packageName); 16043 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16044 "Move location not mounted private volume"); 16045 } 16046 16047 Preconditions.checkState(!currentAsec); 16048 16049 installFlags = INSTALL_INTERNAL; 16050 moveCompleteApp = true; 16051 measurePath = Environment.getDataAppDirectory(volumeUuid); 16052 } 16053 16054 final PackageStats stats = new PackageStats(null, -1); 16055 synchronized (mInstaller) { 16056 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16057 unfreezePackage(packageName); 16058 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16059 "Failed to measure package size"); 16060 } 16061 } 16062 16063 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16064 + stats.dataSize); 16065 16066 final long startFreeBytes = measurePath.getFreeSpace(); 16067 final long sizeBytes; 16068 if (moveCompleteApp) { 16069 sizeBytes = stats.codeSize + stats.dataSize; 16070 } else { 16071 sizeBytes = stats.codeSize; 16072 } 16073 16074 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16075 unfreezePackage(packageName); 16076 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16077 "Not enough free space to move"); 16078 } 16079 16080 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16081 16082 final CountDownLatch installedLatch = new CountDownLatch(1); 16083 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16084 @Override 16085 public void onUserActionRequired(Intent intent) throws RemoteException { 16086 throw new IllegalStateException(); 16087 } 16088 16089 @Override 16090 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16091 Bundle extras) throws RemoteException { 16092 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16093 + PackageManager.installStatusToString(returnCode, msg)); 16094 16095 installedLatch.countDown(); 16096 16097 // Regardless of success or failure of the move operation, 16098 // always unfreeze the package 16099 unfreezePackage(packageName); 16100 16101 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16102 switch (status) { 16103 case PackageInstaller.STATUS_SUCCESS: 16104 mMoveCallbacks.notifyStatusChanged(moveId, 16105 PackageManager.MOVE_SUCCEEDED); 16106 break; 16107 case PackageInstaller.STATUS_FAILURE_STORAGE: 16108 mMoveCallbacks.notifyStatusChanged(moveId, 16109 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16110 break; 16111 default: 16112 mMoveCallbacks.notifyStatusChanged(moveId, 16113 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16114 break; 16115 } 16116 } 16117 }; 16118 16119 final MoveInfo move; 16120 if (moveCompleteApp) { 16121 // Kick off a thread to report progress estimates 16122 new Thread() { 16123 @Override 16124 public void run() { 16125 while (true) { 16126 try { 16127 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16128 break; 16129 } 16130 } catch (InterruptedException ignored) { 16131 } 16132 16133 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16134 final int progress = 10 + (int) MathUtils.constrain( 16135 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16136 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16137 } 16138 } 16139 }.start(); 16140 16141 final String dataAppName = codeFile.getName(); 16142 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16143 dataAppName, appId, seinfo); 16144 } else { 16145 move = null; 16146 } 16147 16148 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16149 16150 final Message msg = mHandler.obtainMessage(INIT_COPY); 16151 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16152 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16153 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16154 mHandler.sendMessage(msg); 16155 } 16156 16157 @Override 16158 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16159 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16160 16161 final int realMoveId = mNextMoveId.getAndIncrement(); 16162 final Bundle extras = new Bundle(); 16163 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16164 mMoveCallbacks.notifyCreated(realMoveId, extras); 16165 16166 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16167 @Override 16168 public void onCreated(int moveId, Bundle extras) { 16169 // Ignored 16170 } 16171 16172 @Override 16173 public void onStatusChanged(int moveId, int status, long estMillis) { 16174 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16175 } 16176 }; 16177 16178 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16179 storage.setPrimaryStorageUuid(volumeUuid, callback); 16180 return realMoveId; 16181 } 16182 16183 @Override 16184 public int getMoveStatus(int moveId) { 16185 mContext.enforceCallingOrSelfPermission( 16186 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16187 return mMoveCallbacks.mLastStatus.get(moveId); 16188 } 16189 16190 @Override 16191 public void registerMoveCallback(IPackageMoveObserver callback) { 16192 mContext.enforceCallingOrSelfPermission( 16193 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16194 mMoveCallbacks.register(callback); 16195 } 16196 16197 @Override 16198 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16199 mContext.enforceCallingOrSelfPermission( 16200 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16201 mMoveCallbacks.unregister(callback); 16202 } 16203 16204 @Override 16205 public boolean setInstallLocation(int loc) { 16206 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16207 null); 16208 if (getInstallLocation() == loc) { 16209 return true; 16210 } 16211 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16212 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16213 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16214 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16215 return true; 16216 } 16217 return false; 16218 } 16219 16220 @Override 16221 public int getInstallLocation() { 16222 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16223 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16224 PackageHelper.APP_INSTALL_AUTO); 16225 } 16226 16227 /** Called by UserManagerService */ 16228 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16229 mDirtyUsers.remove(userHandle); 16230 mSettings.removeUserLPw(userHandle); 16231 mPendingBroadcasts.remove(userHandle); 16232 if (mInstaller != null) { 16233 // Technically, we shouldn't be doing this with the package lock 16234 // held. However, this is very rare, and there is already so much 16235 // other disk I/O going on, that we'll let it slide for now. 16236 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16237 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16238 final String volumeUuid = vol.getFsUuid(); 16239 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16240 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16241 } 16242 } 16243 mUserNeedsBadging.delete(userHandle); 16244 removeUnusedPackagesLILPw(userManager, userHandle); 16245 } 16246 16247 /** 16248 * We're removing userHandle and would like to remove any downloaded packages 16249 * that are no longer in use by any other user. 16250 * @param userHandle the user being removed 16251 */ 16252 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16253 final boolean DEBUG_CLEAN_APKS = false; 16254 int [] users = userManager.getUserIdsLPr(); 16255 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16256 while (psit.hasNext()) { 16257 PackageSetting ps = psit.next(); 16258 if (ps.pkg == null) { 16259 continue; 16260 } 16261 final String packageName = ps.pkg.packageName; 16262 // Skip over if system app 16263 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16264 continue; 16265 } 16266 if (DEBUG_CLEAN_APKS) { 16267 Slog.i(TAG, "Checking package " + packageName); 16268 } 16269 boolean keep = false; 16270 for (int i = 0; i < users.length; i++) { 16271 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16272 keep = true; 16273 if (DEBUG_CLEAN_APKS) { 16274 Slog.i(TAG, " Keeping package " + packageName + " for user " 16275 + users[i]); 16276 } 16277 break; 16278 } 16279 } 16280 if (!keep) { 16281 if (DEBUG_CLEAN_APKS) { 16282 Slog.i(TAG, " Removing package " + packageName); 16283 } 16284 mHandler.post(new Runnable() { 16285 public void run() { 16286 deletePackageX(packageName, userHandle, 0); 16287 } //end run 16288 }); 16289 } 16290 } 16291 } 16292 16293 /** Called by UserManagerService */ 16294 void createNewUserLILPw(int userHandle) { 16295 if (mInstaller != null) { 16296 mInstaller.createUserConfig(userHandle); 16297 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16298 applyFactoryDefaultBrowserLPw(userHandle); 16299 primeDomainVerificationsLPw(userHandle); 16300 } 16301 } 16302 16303 void newUserCreated(final int userHandle) { 16304 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16305 } 16306 16307 @Override 16308 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16309 mContext.enforceCallingOrSelfPermission( 16310 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16311 "Only package verification agents can read the verifier device identity"); 16312 16313 synchronized (mPackages) { 16314 return mSettings.getVerifierDeviceIdentityLPw(); 16315 } 16316 } 16317 16318 @Override 16319 public void setPermissionEnforced(String permission, boolean enforced) { 16320 // TODO: Now that we no longer change GID for storage, this should to away. 16321 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16322 "setPermissionEnforced"); 16323 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16324 synchronized (mPackages) { 16325 if (mSettings.mReadExternalStorageEnforced == null 16326 || mSettings.mReadExternalStorageEnforced != enforced) { 16327 mSettings.mReadExternalStorageEnforced = enforced; 16328 mSettings.writeLPr(); 16329 } 16330 } 16331 // kill any non-foreground processes so we restart them and 16332 // grant/revoke the GID. 16333 final IActivityManager am = ActivityManagerNative.getDefault(); 16334 if (am != null) { 16335 final long token = Binder.clearCallingIdentity(); 16336 try { 16337 am.killProcessesBelowForeground("setPermissionEnforcement"); 16338 } catch (RemoteException e) { 16339 } finally { 16340 Binder.restoreCallingIdentity(token); 16341 } 16342 } 16343 } else { 16344 throw new IllegalArgumentException("No selective enforcement for " + permission); 16345 } 16346 } 16347 16348 @Override 16349 @Deprecated 16350 public boolean isPermissionEnforced(String permission) { 16351 return true; 16352 } 16353 16354 @Override 16355 public boolean isStorageLow() { 16356 final long token = Binder.clearCallingIdentity(); 16357 try { 16358 final DeviceStorageMonitorInternal 16359 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16360 if (dsm != null) { 16361 return dsm.isMemoryLow(); 16362 } else { 16363 return false; 16364 } 16365 } finally { 16366 Binder.restoreCallingIdentity(token); 16367 } 16368 } 16369 16370 @Override 16371 public IPackageInstaller getPackageInstaller() { 16372 return mInstallerService; 16373 } 16374 16375 private boolean userNeedsBadging(int userId) { 16376 int index = mUserNeedsBadging.indexOfKey(userId); 16377 if (index < 0) { 16378 final UserInfo userInfo; 16379 final long token = Binder.clearCallingIdentity(); 16380 try { 16381 userInfo = sUserManager.getUserInfo(userId); 16382 } finally { 16383 Binder.restoreCallingIdentity(token); 16384 } 16385 final boolean b; 16386 if (userInfo != null && userInfo.isManagedProfile()) { 16387 b = true; 16388 } else { 16389 b = false; 16390 } 16391 mUserNeedsBadging.put(userId, b); 16392 return b; 16393 } 16394 return mUserNeedsBadging.valueAt(index); 16395 } 16396 16397 @Override 16398 public KeySet getKeySetByAlias(String packageName, String alias) { 16399 if (packageName == null || alias == null) { 16400 return null; 16401 } 16402 synchronized(mPackages) { 16403 final PackageParser.Package pkg = mPackages.get(packageName); 16404 if (pkg == null) { 16405 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16406 throw new IllegalArgumentException("Unknown package: " + packageName); 16407 } 16408 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16409 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16410 } 16411 } 16412 16413 @Override 16414 public KeySet getSigningKeySet(String packageName) { 16415 if (packageName == null) { 16416 return null; 16417 } 16418 synchronized(mPackages) { 16419 final PackageParser.Package pkg = mPackages.get(packageName); 16420 if (pkg == null) { 16421 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16422 throw new IllegalArgumentException("Unknown package: " + packageName); 16423 } 16424 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16425 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16426 throw new SecurityException("May not access signing KeySet of other apps."); 16427 } 16428 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16429 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16430 } 16431 } 16432 16433 @Override 16434 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16435 if (packageName == null || ks == null) { 16436 return false; 16437 } 16438 synchronized(mPackages) { 16439 final PackageParser.Package pkg = mPackages.get(packageName); 16440 if (pkg == null) { 16441 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16442 throw new IllegalArgumentException("Unknown package: " + packageName); 16443 } 16444 IBinder ksh = ks.getToken(); 16445 if (ksh instanceof KeySetHandle) { 16446 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16447 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16448 } 16449 return false; 16450 } 16451 } 16452 16453 @Override 16454 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16455 if (packageName == null || ks == null) { 16456 return false; 16457 } 16458 synchronized(mPackages) { 16459 final PackageParser.Package pkg = mPackages.get(packageName); 16460 if (pkg == null) { 16461 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16462 throw new IllegalArgumentException("Unknown package: " + packageName); 16463 } 16464 IBinder ksh = ks.getToken(); 16465 if (ksh instanceof KeySetHandle) { 16466 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16467 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16468 } 16469 return false; 16470 } 16471 } 16472 16473 public void getUsageStatsIfNoPackageUsageInfo() { 16474 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16475 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16476 if (usm == null) { 16477 throw new IllegalStateException("UsageStatsManager must be initialized"); 16478 } 16479 long now = System.currentTimeMillis(); 16480 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16481 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16482 String packageName = entry.getKey(); 16483 PackageParser.Package pkg = mPackages.get(packageName); 16484 if (pkg == null) { 16485 continue; 16486 } 16487 UsageStats usage = entry.getValue(); 16488 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16489 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16490 } 16491 } 16492 } 16493 16494 /** 16495 * Check and throw if the given before/after packages would be considered a 16496 * downgrade. 16497 */ 16498 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16499 throws PackageManagerException { 16500 if (after.versionCode < before.mVersionCode) { 16501 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16502 "Update version code " + after.versionCode + " is older than current " 16503 + before.mVersionCode); 16504 } else if (after.versionCode == before.mVersionCode) { 16505 if (after.baseRevisionCode < before.baseRevisionCode) { 16506 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16507 "Update base revision code " + after.baseRevisionCode 16508 + " is older than current " + before.baseRevisionCode); 16509 } 16510 16511 if (!ArrayUtils.isEmpty(after.splitNames)) { 16512 for (int i = 0; i < after.splitNames.length; i++) { 16513 final String splitName = after.splitNames[i]; 16514 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16515 if (j != -1) { 16516 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16517 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16518 "Update split " + splitName + " revision code " 16519 + after.splitRevisionCodes[i] + " is older than current " 16520 + before.splitRevisionCodes[j]); 16521 } 16522 } 16523 } 16524 } 16525 } 16526 } 16527 16528 private static class MoveCallbacks extends Handler { 16529 private static final int MSG_CREATED = 1; 16530 private static final int MSG_STATUS_CHANGED = 2; 16531 16532 private final RemoteCallbackList<IPackageMoveObserver> 16533 mCallbacks = new RemoteCallbackList<>(); 16534 16535 private final SparseIntArray mLastStatus = new SparseIntArray(); 16536 16537 public MoveCallbacks(Looper looper) { 16538 super(looper); 16539 } 16540 16541 public void register(IPackageMoveObserver callback) { 16542 mCallbacks.register(callback); 16543 } 16544 16545 public void unregister(IPackageMoveObserver callback) { 16546 mCallbacks.unregister(callback); 16547 } 16548 16549 @Override 16550 public void handleMessage(Message msg) { 16551 final SomeArgs args = (SomeArgs) msg.obj; 16552 final int n = mCallbacks.beginBroadcast(); 16553 for (int i = 0; i < n; i++) { 16554 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16555 try { 16556 invokeCallback(callback, msg.what, args); 16557 } catch (RemoteException ignored) { 16558 } 16559 } 16560 mCallbacks.finishBroadcast(); 16561 args.recycle(); 16562 } 16563 16564 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16565 throws RemoteException { 16566 switch (what) { 16567 case MSG_CREATED: { 16568 callback.onCreated(args.argi1, (Bundle) args.arg2); 16569 break; 16570 } 16571 case MSG_STATUS_CHANGED: { 16572 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16573 break; 16574 } 16575 } 16576 } 16577 16578 private void notifyCreated(int moveId, Bundle extras) { 16579 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16580 16581 final SomeArgs args = SomeArgs.obtain(); 16582 args.argi1 = moveId; 16583 args.arg2 = extras; 16584 obtainMessage(MSG_CREATED, args).sendToTarget(); 16585 } 16586 16587 private void notifyStatusChanged(int moveId, int status) { 16588 notifyStatusChanged(moveId, status, -1); 16589 } 16590 16591 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16592 Slog.v(TAG, "Move " + moveId + " status " + status); 16593 16594 final SomeArgs args = SomeArgs.obtain(); 16595 args.argi1 = moveId; 16596 args.argi2 = status; 16597 args.arg3 = estMillis; 16598 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16599 16600 synchronized (mLastStatus) { 16601 mLastStatus.put(moveId, status); 16602 } 16603 } 16604 } 16605 16606 private final class OnPermissionChangeListeners extends Handler { 16607 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16608 16609 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16610 new RemoteCallbackList<>(); 16611 16612 public OnPermissionChangeListeners(Looper looper) { 16613 super(looper); 16614 } 16615 16616 @Override 16617 public void handleMessage(Message msg) { 16618 switch (msg.what) { 16619 case MSG_ON_PERMISSIONS_CHANGED: { 16620 final int uid = msg.arg1; 16621 handleOnPermissionsChanged(uid); 16622 } break; 16623 } 16624 } 16625 16626 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16627 mPermissionListeners.register(listener); 16628 16629 } 16630 16631 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16632 mPermissionListeners.unregister(listener); 16633 } 16634 16635 public void onPermissionsChanged(int uid) { 16636 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16637 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16638 } 16639 } 16640 16641 private void handleOnPermissionsChanged(int uid) { 16642 final int count = mPermissionListeners.beginBroadcast(); 16643 try { 16644 for (int i = 0; i < count; i++) { 16645 IOnPermissionsChangeListener callback = mPermissionListeners 16646 .getBroadcastItem(i); 16647 try { 16648 callback.onPermissionsChanged(uid); 16649 } catch (RemoteException e) { 16650 Log.e(TAG, "Permission listener is dead", e); 16651 } 16652 } 16653 } finally { 16654 mPermissionListeners.finishBroadcast(); 16655 } 16656 } 16657 } 16658 16659 private class PackageManagerInternalImpl extends PackageManagerInternal { 16660 @Override 16661 public void setLocationPackagesProvider(PackagesProvider provider) { 16662 synchronized (mPackages) { 16663 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16664 } 16665 } 16666 16667 @Override 16668 public void setImePackagesProvider(PackagesProvider provider) { 16669 synchronized (mPackages) { 16670 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16671 } 16672 } 16673 16674 @Override 16675 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16676 synchronized (mPackages) { 16677 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16678 } 16679 } 16680 16681 @Override 16682 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16683 synchronized (mPackages) { 16684 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16685 } 16686 } 16687 16688 @Override 16689 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16690 synchronized (mPackages) { 16691 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16692 } 16693 } 16694 16695 @Override 16696 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16697 synchronized (mPackages) { 16698 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16699 } 16700 } 16701 16702 @Override 16703 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16704 synchronized (mPackages) { 16705 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16706 } 16707 } 16708 16709 @Override 16710 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16711 synchronized (mPackages) { 16712 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16713 packageName, userId); 16714 } 16715 } 16716 16717 @Override 16718 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16719 synchronized (mPackages) { 16720 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16721 packageName, userId); 16722 } 16723 } 16724 @Override 16725 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16726 synchronized (mPackages) { 16727 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16728 packageName, userId); 16729 } 16730 } 16731 } 16732 16733 @Override 16734 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16735 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16736 synchronized (mPackages) { 16737 final long identity = Binder.clearCallingIdentity(); 16738 try { 16739 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16740 packageNames, userId); 16741 } finally { 16742 Binder.restoreCallingIdentity(identity); 16743 } 16744 } 16745 } 16746 16747 private static void enforceSystemOrPhoneCaller(String tag) { 16748 int callingUid = Binder.getCallingUid(); 16749 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16750 throw new SecurityException( 16751 "Cannot call " + tag + " from UID " + callingUid); 16752 } 16753 } 16754} 16755