PackageManagerService.java revision dcd96ead8457466fb3dfb5978eb1e7e5b560ba91
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.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_EXTERNAL_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.INSTALL_EXTERNAL; 28import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 29import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 46import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 47import static android.content.pm.PackageManager.INSTALL_INTERNAL; 48import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 53import static android.content.pm.PackageManager.MATCH_ALL; 54import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 55import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 56import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 57import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 58import static android.content.pm.PackageManager.PERMISSION_GRANTED; 59import static android.content.pm.PackageParser.isApkFile; 60import static android.os.Process.PACKAGE_INFO_GID; 61import static android.os.Process.SYSTEM_UID; 62import static android.system.OsConstants.O_CREAT; 63import static android.system.OsConstants.O_RDWR; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 66import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 67import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 68import static com.android.internal.util.ArrayUtils.appendInt; 69import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 72import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 73import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 74 75import android.Manifest; 76import android.app.ActivityManager; 77import android.app.ActivityManagerNative; 78import android.app.AppGlobals; 79import android.app.IActivityManager; 80import android.app.admin.IDevicePolicyManager; 81import android.app.backup.IBackupManager; 82import android.app.usage.UsageStats; 83import android.app.usage.UsageStatsManager; 84import android.content.BroadcastReceiver; 85import android.content.ComponentName; 86import android.content.Context; 87import android.content.IIntentReceiver; 88import android.content.Intent; 89import android.content.IntentFilter; 90import android.content.IntentSender; 91import android.content.IntentSender.SendIntentException; 92import android.content.ServiceConnection; 93import android.content.pm.ActivityInfo; 94import android.content.pm.ApplicationInfo; 95import android.content.pm.FeatureInfo; 96import android.content.pm.IOnPermissionsChangeListener; 97import android.content.pm.IPackageDataObserver; 98import android.content.pm.IPackageDeleteObserver; 99import android.content.pm.IPackageDeleteObserver2; 100import android.content.pm.IPackageInstallObserver2; 101import android.content.pm.IPackageInstaller; 102import android.content.pm.IPackageManager; 103import android.content.pm.IPackageMoveObserver; 104import android.content.pm.IPackageStatsObserver; 105import android.content.pm.InstrumentationInfo; 106import android.content.pm.IntentFilterVerificationInfo; 107import android.content.pm.KeySet; 108import android.content.pm.ManifestDigest; 109import android.content.pm.PackageCleanItem; 110import android.content.pm.PackageInfo; 111import android.content.pm.PackageInfoLite; 112import android.content.pm.PackageInstaller; 113import android.content.pm.PackageManager; 114import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 115import android.content.pm.PackageManagerInternal; 116import android.content.pm.PackageParser; 117import android.content.pm.PackageParser.ActivityIntentInfo; 118import android.content.pm.PackageParser.PackageLite; 119import android.content.pm.PackageParser.PackageParserException; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Debug; 140import android.os.Environment; 141import android.os.Environment.UserEnvironment; 142import android.os.FileUtils; 143import android.os.Handler; 144import android.os.IBinder; 145import android.os.Looper; 146import android.os.Message; 147import android.os.Parcel; 148import android.os.ParcelFileDescriptor; 149import android.os.Process; 150import android.os.RemoteCallbackList; 151import android.os.RemoteException; 152import android.os.SELinux; 153import android.os.ServiceManager; 154import android.os.SystemClock; 155import android.os.SystemProperties; 156import android.os.UserHandle; 157import android.os.UserManager; 158import android.os.storage.IMountService; 159import android.os.storage.StorageEventListener; 160import android.os.storage.StorageManager; 161import android.os.storage.VolumeInfo; 162import android.os.storage.VolumeRecord; 163import android.security.KeyStore; 164import android.security.SystemKeyStore; 165import android.system.ErrnoException; 166import android.system.Os; 167import android.system.StructStat; 168import android.text.TextUtils; 169import android.text.format.DateUtils; 170import android.util.ArrayMap; 171import android.util.ArraySet; 172import android.util.AtomicFile; 173import android.util.DisplayMetrics; 174import android.util.EventLog; 175import android.util.ExceptionUtils; 176import android.util.Log; 177import android.util.LogPrinter; 178import android.util.MathUtils; 179import android.util.PrintStreamPrinter; 180import android.util.Slog; 181import android.util.SparseArray; 182import android.util.SparseBooleanArray; 183import android.util.SparseIntArray; 184import android.util.Xml; 185import android.view.Display; 186 187import dalvik.system.DexFile; 188import dalvik.system.VMRuntime; 189 190import libcore.io.IoUtils; 191import libcore.util.EmptyArray; 192 193import com.android.internal.R; 194import com.android.internal.app.IMediaContainerService; 195import com.android.internal.app.ResolverActivity; 196import com.android.internal.content.NativeLibraryHelper; 197import com.android.internal.content.PackageHelper; 198import com.android.internal.os.IParcelFileDescriptorFactory; 199import com.android.internal.os.SomeArgs; 200import com.android.internal.os.Zygote; 201import com.android.internal.util.ArrayUtils; 202import com.android.internal.util.FastPrintWriter; 203import com.android.internal.util.FastXmlSerializer; 204import com.android.internal.util.IndentingPrintWriter; 205import com.android.internal.util.Preconditions; 206import com.android.server.EventLogTags; 207import com.android.server.FgThread; 208import com.android.server.IntentResolver; 209import com.android.server.LocalServices; 210import com.android.server.ServiceThread; 211import com.android.server.SystemConfig; 212import com.android.server.Watchdog; 213import com.android.server.pm.PermissionsState.PermissionState; 214import com.android.server.pm.Settings.DatabaseVersion; 215import com.android.server.storage.DeviceStorageMonitorInternal; 216 217import org.xmlpull.v1.XmlPullParser; 218import org.xmlpull.v1.XmlPullParserException; 219import org.xmlpull.v1.XmlSerializer; 220 221import java.io.BufferedInputStream; 222import java.io.BufferedOutputStream; 223import java.io.BufferedReader; 224import java.io.ByteArrayInputStream; 225import java.io.ByteArrayOutputStream; 226import java.io.File; 227import java.io.FileDescriptor; 228import java.io.FileNotFoundException; 229import java.io.FileOutputStream; 230import java.io.FileReader; 231import java.io.FilenameFilter; 232import java.io.IOException; 233import java.io.InputStream; 234import java.io.PrintWriter; 235import java.nio.charset.StandardCharsets; 236import java.security.NoSuchAlgorithmException; 237import java.security.PublicKey; 238import java.security.cert.CertificateEncodingException; 239import java.security.cert.CertificateException; 240import java.text.SimpleDateFormat; 241import java.util.ArrayList; 242import java.util.Arrays; 243import java.util.Collection; 244import java.util.Collections; 245import java.util.Comparator; 246import java.util.Date; 247import java.util.Iterator; 248import java.util.List; 249import java.util.Map; 250import java.util.Objects; 251import java.util.Set; 252import java.util.concurrent.CountDownLatch; 253import java.util.concurrent.TimeUnit; 254import java.util.concurrent.atomic.AtomicBoolean; 255import java.util.concurrent.atomic.AtomicInteger; 256import java.util.concurrent.atomic.AtomicLong; 257 258/** 259 * Keep track of all those .apks everywhere. 260 * 261 * This is very central to the platform's security; please run the unit 262 * tests whenever making modifications here: 263 * 264mmm frameworks/base/tests/AndroidTests 265adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 266adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 267 * 268 * {@hide} 269 */ 270public class PackageManagerService extends IPackageManager.Stub { 271 static final String TAG = "PackageManager"; 272 static final boolean DEBUG_SETTINGS = false; 273 static final boolean DEBUG_PREFERRED = false; 274 static final boolean DEBUG_UPGRADE = false; 275 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 276 private static final boolean DEBUG_BACKUP = true; 277 private static final boolean DEBUG_INSTALL = false; 278 private static final boolean DEBUG_REMOVE = false; 279 private static final boolean DEBUG_BROADCASTS = false; 280 private static final boolean DEBUG_SHOW_INFO = false; 281 private static final boolean DEBUG_PACKAGE_INFO = false; 282 private static final boolean DEBUG_INTENT_MATCHING = false; 283 private static final boolean DEBUG_PACKAGE_SCANNING = false; 284 private static final boolean DEBUG_VERIFY = false; 285 private static final boolean DEBUG_DEXOPT = false; 286 private static final boolean DEBUG_ABI_SELECTION = false; 287 288 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 289 290 private static final int RADIO_UID = Process.PHONE_UID; 291 private static final int LOG_UID = Process.LOG_UID; 292 private static final int NFC_UID = Process.NFC_UID; 293 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 294 private static final int SHELL_UID = Process.SHELL_UID; 295 296 // Cap the size of permission trees that 3rd party apps can define 297 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 298 299 // Suffix used during package installation when copying/moving 300 // package apks to install directory. 301 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 302 303 static final int SCAN_NO_DEX = 1<<1; 304 static final int SCAN_FORCE_DEX = 1<<2; 305 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 306 static final int SCAN_NEW_INSTALL = 1<<4; 307 static final int SCAN_NO_PATHS = 1<<5; 308 static final int SCAN_UPDATE_TIME = 1<<6; 309 static final int SCAN_DEFER_DEX = 1<<7; 310 static final int SCAN_BOOTING = 1<<8; 311 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 312 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 313 static final int SCAN_REQUIRE_KNOWN = 1<<12; 314 static final int SCAN_MOVE = 1<<13; 315 static final int SCAN_INITIAL = 1<<14; 316 317 static final int REMOVE_CHATTY = 1<<16; 318 319 private static final int[] EMPTY_INT_ARRAY = new int[0]; 320 321 /** 322 * Timeout (in milliseconds) after which the watchdog should declare that 323 * our handler thread is wedged. The usual default for such things is one 324 * minute but we sometimes do very lengthy I/O operations on this thread, 325 * such as installing multi-gigabyte applications, so ours needs to be longer. 326 */ 327 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 328 329 /** 330 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 331 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 332 * settings entry if available, otherwise we use the hardcoded default. If it's been 333 * more than this long since the last fstrim, we force one during the boot sequence. 334 * 335 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 336 * one gets run at the next available charging+idle time. This final mandatory 337 * no-fstrim check kicks in only of the other scheduling criteria is never met. 338 */ 339 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 340 341 /** 342 * Whether verification is enabled by default. 343 */ 344 private static final boolean DEFAULT_VERIFY_ENABLE = true; 345 346 /** 347 * The default maximum time to wait for the verification agent to return in 348 * milliseconds. 349 */ 350 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 351 352 /** 353 * The default response for package verification timeout. 354 * 355 * This can be either PackageManager.VERIFICATION_ALLOW or 356 * PackageManager.VERIFICATION_REJECT. 357 */ 358 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 359 360 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 361 362 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 363 DEFAULT_CONTAINER_PACKAGE, 364 "com.android.defcontainer.DefaultContainerService"); 365 366 private static final String KILL_APP_REASON_GIDS_CHANGED = 367 "permission grant or revoke changed gids"; 368 369 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 370 "permissions revoked"; 371 372 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 373 374 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 375 376 /** Permission grant: not grant the permission. */ 377 private static final int GRANT_DENIED = 1; 378 379 /** Permission grant: grant the permission as an install permission. */ 380 private static final int GRANT_INSTALL = 2; 381 382 /** Permission grant: grant the permission as an install permission for a legacy app. */ 383 private static final int GRANT_INSTALL_LEGACY = 3; 384 385 /** Permission grant: grant the permission as a runtime one. */ 386 private static final int GRANT_RUNTIME = 4; 387 388 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 389 private static final int GRANT_UPGRADE = 5; 390 391 /** Canonical intent used to identify what counts as a "web browser" app */ 392 private static final Intent sBrowserIntent; 393 static { 394 sBrowserIntent = new Intent(); 395 sBrowserIntent.setAction(Intent.ACTION_VIEW); 396 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 397 sBrowserIntent.setData(Uri.parse("http:")); 398 } 399 400 final ServiceThread mHandlerThread; 401 402 final PackageHandler mHandler; 403 404 /** 405 * Messages for {@link #mHandler} that need to wait for system ready before 406 * being dispatched. 407 */ 408 private ArrayList<Message> mPostSystemReadyMessages; 409 410 final int mSdkVersion = Build.VERSION.SDK_INT; 411 412 final Context mContext; 413 final boolean mFactoryTest; 414 final boolean mOnlyCore; 415 final boolean mLazyDexOpt; 416 final long mDexOptLRUThresholdInMills; 417 final DisplayMetrics mMetrics; 418 final int mDefParseFlags; 419 final String[] mSeparateProcesses; 420 final boolean mIsUpgrade; 421 422 // This is where all application persistent data goes. 423 final File mAppDataDir; 424 425 // This is where all application persistent data goes for secondary users. 426 final File mUserAppDataDir; 427 428 /** The location for ASEC container files on internal storage. */ 429 final String mAsecInternalPath; 430 431 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 432 // LOCK HELD. Can be called with mInstallLock held. 433 final Installer mInstaller; 434 435 /** Directory where installed third-party apps stored */ 436 final File mAppInstallDir; 437 438 /** 439 * Directory to which applications installed internally have their 440 * 32 bit native libraries copied. 441 */ 442 private File mAppLib32InstallDir; 443 444 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 445 // apps. 446 final File mDrmAppPrivateInstallDir; 447 448 // ---------------------------------------------------------------- 449 450 // Lock for state used when installing and doing other long running 451 // operations. Methods that must be called with this lock held have 452 // the suffix "LI". 453 final Object mInstallLock = new Object(); 454 455 // ---------------------------------------------------------------- 456 457 // Keys are String (package name), values are Package. This also serves 458 // as the lock for the global state. Methods that must be called with 459 // this lock held have the prefix "LP". 460 final ArrayMap<String, PackageParser.Package> mPackages = 461 new ArrayMap<String, PackageParser.Package>(); 462 463 // Tracks available target package names -> overlay package paths. 464 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 465 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 466 467 final Settings mSettings; 468 boolean mRestoredSettings; 469 470 // System configuration read by SystemConfig. 471 final int[] mGlobalGids; 472 final SparseArray<ArraySet<String>> mSystemPermissions; 473 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 474 475 // If mac_permissions.xml was found for seinfo labeling. 476 boolean mFoundPolicyFile; 477 478 // If a recursive restorecon of /data/data/<pkg> is needed. 479 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 480 481 public static final class SharedLibraryEntry { 482 public final String path; 483 public final String apk; 484 485 SharedLibraryEntry(String _path, String _apk) { 486 path = _path; 487 apk = _apk; 488 } 489 } 490 491 // Currently known shared libraries. 492 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 493 new ArrayMap<String, SharedLibraryEntry>(); 494 495 // All available activities, for your resolving pleasure. 496 final ActivityIntentResolver mActivities = 497 new ActivityIntentResolver(); 498 499 // All available receivers, for your resolving pleasure. 500 final ActivityIntentResolver mReceivers = 501 new ActivityIntentResolver(); 502 503 // All available services, for your resolving pleasure. 504 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 505 506 // All available providers, for your resolving pleasure. 507 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 508 509 // Mapping from provider base names (first directory in content URI codePath) 510 // to the provider information. 511 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 512 new ArrayMap<String, PackageParser.Provider>(); 513 514 // Mapping from instrumentation class names to info about them. 515 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 516 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 517 518 // Mapping from permission names to info about them. 519 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 520 new ArrayMap<String, PackageParser.PermissionGroup>(); 521 522 // Packages whose data we have transfered into another package, thus 523 // should no longer exist. 524 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 525 526 // Broadcast actions that are only available to the system. 527 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 528 529 /** List of packages waiting for verification. */ 530 final SparseArray<PackageVerificationState> mPendingVerification 531 = new SparseArray<PackageVerificationState>(); 532 533 /** Set of packages associated with each app op permission. */ 534 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 535 536 final PackageInstallerService mInstallerService; 537 538 private final PackageDexOptimizer mPackageDexOptimizer; 539 540 private AtomicInteger mNextMoveId = new AtomicInteger(); 541 private final MoveCallbacks mMoveCallbacks; 542 543 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 544 545 // Cache of users who need badging. 546 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 547 548 /** Token for keys in mPendingVerification. */ 549 private int mPendingVerificationToken = 0; 550 551 volatile boolean mSystemReady; 552 volatile boolean mSafeMode; 553 volatile boolean mHasSystemUidErrors; 554 555 ApplicationInfo mAndroidApplication; 556 final ActivityInfo mResolveActivity = new ActivityInfo(); 557 final ResolveInfo mResolveInfo = new ResolveInfo(); 558 ComponentName mResolveComponentName; 559 PackageParser.Package mPlatformPackage; 560 ComponentName mCustomResolverComponentName; 561 562 boolean mResolverReplaced = false; 563 564 private final ComponentName mIntentFilterVerifierComponent; 565 private int mIntentFilterVerificationToken = 0; 566 567 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 568 = new SparseArray<IntentFilterVerificationState>(); 569 570 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 571 new DefaultPermissionGrantPolicy(this); 572 573 private static class IFVerificationParams { 574 PackageParser.Package pkg; 575 boolean replacing; 576 int userId; 577 int verifierUid; 578 579 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 580 int _userId, int _verifierUid) { 581 pkg = _pkg; 582 replacing = _replacing; 583 userId = _userId; 584 replacing = _replacing; 585 verifierUid = _verifierUid; 586 } 587 } 588 589 private interface IntentFilterVerifier<T extends IntentFilter> { 590 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 591 T filter, String packageName); 592 void startVerifications(int userId); 593 void receiveVerificationResponse(int verificationId); 594 } 595 596 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 597 private Context mContext; 598 private ComponentName mIntentFilterVerifierComponent; 599 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 600 601 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 602 mContext = context; 603 mIntentFilterVerifierComponent = verifierComponent; 604 } 605 606 private String getDefaultScheme() { 607 return IntentFilter.SCHEME_HTTPS; 608 } 609 610 @Override 611 public void startVerifications(int userId) { 612 // Launch verifications requests 613 int count = mCurrentIntentFilterVerifications.size(); 614 for (int n=0; n<count; n++) { 615 int verificationId = mCurrentIntentFilterVerifications.get(n); 616 final IntentFilterVerificationState ivs = 617 mIntentFilterVerificationStates.get(verificationId); 618 619 String packageName = ivs.getPackageName(); 620 621 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 622 final int filterCount = filters.size(); 623 ArraySet<String> domainsSet = new ArraySet<>(); 624 for (int m=0; m<filterCount; m++) { 625 PackageParser.ActivityIntentInfo filter = filters.get(m); 626 domainsSet.addAll(filter.getHostsList()); 627 } 628 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 629 synchronized (mPackages) { 630 if (mSettings.createIntentFilterVerificationIfNeededLPw( 631 packageName, domainsList) != null) { 632 scheduleWriteSettingsLocked(); 633 } 634 } 635 sendVerificationRequest(userId, verificationId, ivs); 636 } 637 mCurrentIntentFilterVerifications.clear(); 638 } 639 640 private void sendVerificationRequest(int userId, int verificationId, 641 IntentFilterVerificationState ivs) { 642 643 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 644 verificationIntent.putExtra( 645 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 646 verificationId); 647 verificationIntent.putExtra( 648 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 649 getDefaultScheme()); 650 verificationIntent.putExtra( 651 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 652 ivs.getHostsString()); 653 verificationIntent.putExtra( 654 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 655 ivs.getPackageName()); 656 verificationIntent.setComponent(mIntentFilterVerifierComponent); 657 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 658 659 UserHandle user = new UserHandle(userId); 660 mContext.sendBroadcastAsUser(verificationIntent, user); 661 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 662 "Sending IntentFilter verification broadcast"); 663 } 664 665 public void receiveVerificationResponse(int verificationId) { 666 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 667 668 final boolean verified = ivs.isVerified(); 669 670 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 671 final int count = filters.size(); 672 if (DEBUG_DOMAIN_VERIFICATION) { 673 Slog.i(TAG, "Received verification response " + verificationId 674 + " for " + count + " filters, verified=" + verified); 675 } 676 for (int n=0; n<count; n++) { 677 PackageParser.ActivityIntentInfo filter = filters.get(n); 678 filter.setVerified(verified); 679 680 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 681 + " verified with result:" + verified + " and hosts:" 682 + ivs.getHostsString()); 683 } 684 685 mIntentFilterVerificationStates.remove(verificationId); 686 687 final String packageName = ivs.getPackageName(); 688 IntentFilterVerificationInfo ivi = null; 689 690 synchronized (mPackages) { 691 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 692 } 693 if (ivi == null) { 694 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 695 + verificationId + " packageName:" + packageName); 696 return; 697 } 698 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 699 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 700 701 synchronized (mPackages) { 702 if (verified) { 703 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 704 } else { 705 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 706 } 707 scheduleWriteSettingsLocked(); 708 709 final int userId = ivs.getUserId(); 710 if (userId != UserHandle.USER_ALL) { 711 final int userStatus = 712 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 713 714 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 715 boolean needUpdate = false; 716 717 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 718 // already been set by the User thru the Disambiguation dialog 719 switch (userStatus) { 720 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 721 if (verified) { 722 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 723 } else { 724 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 725 } 726 needUpdate = true; 727 break; 728 729 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 730 if (verified) { 731 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 732 needUpdate = true; 733 } 734 break; 735 736 default: 737 // Nothing to do 738 } 739 740 if (needUpdate) { 741 mSettings.updateIntentFilterVerificationStatusLPw( 742 packageName, updatedStatus, userId); 743 scheduleWritePackageRestrictionsLocked(userId); 744 } 745 } 746 } 747 } 748 749 @Override 750 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 751 ActivityIntentInfo filter, String packageName) { 752 if (!hasValidDomains(filter)) { 753 return false; 754 } 755 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 756 if (ivs == null) { 757 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 758 packageName); 759 } 760 if (DEBUG_DOMAIN_VERIFICATION) { 761 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 762 } 763 ivs.addFilter(filter); 764 return true; 765 } 766 767 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 768 int userId, int verificationId, String packageName) { 769 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 770 verifierUid, userId, packageName); 771 ivs.setPendingState(); 772 synchronized (mPackages) { 773 mIntentFilterVerificationStates.append(verificationId, ivs); 774 mCurrentIntentFilterVerifications.add(verificationId); 775 } 776 return ivs; 777 } 778 } 779 780 private static boolean hasValidDomains(ActivityIntentInfo filter) { 781 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 782 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 783 if (!hasHTTPorHTTPS) { 784 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 785 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 786 return false; 787 } 788 return true; 789 } 790 791 private IntentFilterVerifier mIntentFilterVerifier; 792 793 // Set of pending broadcasts for aggregating enable/disable of components. 794 static class PendingPackageBroadcasts { 795 // for each user id, a map of <package name -> components within that package> 796 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 797 798 public PendingPackageBroadcasts() { 799 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 800 } 801 802 public ArrayList<String> get(int userId, String packageName) { 803 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 804 return packages.get(packageName); 805 } 806 807 public void put(int userId, String packageName, ArrayList<String> components) { 808 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 809 packages.put(packageName, components); 810 } 811 812 public void remove(int userId, String packageName) { 813 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 814 if (packages != null) { 815 packages.remove(packageName); 816 } 817 } 818 819 public void remove(int userId) { 820 mUidMap.remove(userId); 821 } 822 823 public int userIdCount() { 824 return mUidMap.size(); 825 } 826 827 public int userIdAt(int n) { 828 return mUidMap.keyAt(n); 829 } 830 831 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 832 return mUidMap.get(userId); 833 } 834 835 public int size() { 836 // total number of pending broadcast entries across all userIds 837 int num = 0; 838 for (int i = 0; i< mUidMap.size(); i++) { 839 num += mUidMap.valueAt(i).size(); 840 } 841 return num; 842 } 843 844 public void clear() { 845 mUidMap.clear(); 846 } 847 848 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 849 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 850 if (map == null) { 851 map = new ArrayMap<String, ArrayList<String>>(); 852 mUidMap.put(userId, map); 853 } 854 return map; 855 } 856 } 857 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 858 859 // Service Connection to remote media container service to copy 860 // package uri's from external media onto secure containers 861 // or internal storage. 862 private IMediaContainerService mContainerService = null; 863 864 static final int SEND_PENDING_BROADCAST = 1; 865 static final int MCS_BOUND = 3; 866 static final int END_COPY = 4; 867 static final int INIT_COPY = 5; 868 static final int MCS_UNBIND = 6; 869 static final int START_CLEANING_PACKAGE = 7; 870 static final int FIND_INSTALL_LOC = 8; 871 static final int POST_INSTALL = 9; 872 static final int MCS_RECONNECT = 10; 873 static final int MCS_GIVE_UP = 11; 874 static final int UPDATED_MEDIA_STATUS = 12; 875 static final int WRITE_SETTINGS = 13; 876 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 877 static final int PACKAGE_VERIFIED = 15; 878 static final int CHECK_PENDING_VERIFICATION = 16; 879 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 880 static final int INTENT_FILTER_VERIFIED = 18; 881 882 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 883 884 // Delay time in millisecs 885 static final int BROADCAST_DELAY = 10 * 1000; 886 887 static UserManagerService sUserManager; 888 889 // Stores a list of users whose package restrictions file needs to be updated 890 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 891 892 final private DefaultContainerConnection mDefContainerConn = 893 new DefaultContainerConnection(); 894 class DefaultContainerConnection implements ServiceConnection { 895 public void onServiceConnected(ComponentName name, IBinder service) { 896 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 897 IMediaContainerService imcs = 898 IMediaContainerService.Stub.asInterface(service); 899 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 900 } 901 902 public void onServiceDisconnected(ComponentName name) { 903 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 904 } 905 } 906 907 // Recordkeeping of restore-after-install operations that are currently in flight 908 // between the Package Manager and the Backup Manager 909 class PostInstallData { 910 public InstallArgs args; 911 public PackageInstalledInfo res; 912 913 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 914 args = _a; 915 res = _r; 916 } 917 } 918 919 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 920 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 921 922 // XML tags for backup/restore of various bits of state 923 private static final String TAG_PREFERRED_BACKUP = "pa"; 924 private static final String TAG_DEFAULT_APPS = "da"; 925 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 926 927 private final String mRequiredVerifierPackage; 928 929 private final PackageUsage mPackageUsage = new PackageUsage(); 930 931 private class PackageUsage { 932 private static final int WRITE_INTERVAL 933 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 934 935 private final Object mFileLock = new Object(); 936 private final AtomicLong mLastWritten = new AtomicLong(0); 937 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 938 939 private boolean mIsHistoricalPackageUsageAvailable = true; 940 941 boolean isHistoricalPackageUsageAvailable() { 942 return mIsHistoricalPackageUsageAvailable; 943 } 944 945 void write(boolean force) { 946 if (force) { 947 writeInternal(); 948 return; 949 } 950 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 951 && !DEBUG_DEXOPT) { 952 return; 953 } 954 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 955 new Thread("PackageUsage_DiskWriter") { 956 @Override 957 public void run() { 958 try { 959 writeInternal(); 960 } finally { 961 mBackgroundWriteRunning.set(false); 962 } 963 } 964 }.start(); 965 } 966 } 967 968 private void writeInternal() { 969 synchronized (mPackages) { 970 synchronized (mFileLock) { 971 AtomicFile file = getFile(); 972 FileOutputStream f = null; 973 try { 974 f = file.startWrite(); 975 BufferedOutputStream out = new BufferedOutputStream(f); 976 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 977 StringBuilder sb = new StringBuilder(); 978 for (PackageParser.Package pkg : mPackages.values()) { 979 if (pkg.mLastPackageUsageTimeInMills == 0) { 980 continue; 981 } 982 sb.setLength(0); 983 sb.append(pkg.packageName); 984 sb.append(' '); 985 sb.append((long)pkg.mLastPackageUsageTimeInMills); 986 sb.append('\n'); 987 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 988 } 989 out.flush(); 990 file.finishWrite(f); 991 } catch (IOException e) { 992 if (f != null) { 993 file.failWrite(f); 994 } 995 Log.e(TAG, "Failed to write package usage times", e); 996 } 997 } 998 } 999 mLastWritten.set(SystemClock.elapsedRealtime()); 1000 } 1001 1002 void readLP() { 1003 synchronized (mFileLock) { 1004 AtomicFile file = getFile(); 1005 BufferedInputStream in = null; 1006 try { 1007 in = new BufferedInputStream(file.openRead()); 1008 StringBuffer sb = new StringBuffer(); 1009 while (true) { 1010 String packageName = readToken(in, sb, ' '); 1011 if (packageName == null) { 1012 break; 1013 } 1014 String timeInMillisString = readToken(in, sb, '\n'); 1015 if (timeInMillisString == null) { 1016 throw new IOException("Failed to find last usage time for package " 1017 + packageName); 1018 } 1019 PackageParser.Package pkg = mPackages.get(packageName); 1020 if (pkg == null) { 1021 continue; 1022 } 1023 long timeInMillis; 1024 try { 1025 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1026 } catch (NumberFormatException e) { 1027 throw new IOException("Failed to parse " + timeInMillisString 1028 + " as a long.", e); 1029 } 1030 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1031 } 1032 } catch (FileNotFoundException expected) { 1033 mIsHistoricalPackageUsageAvailable = false; 1034 } catch (IOException e) { 1035 Log.w(TAG, "Failed to read package usage times", e); 1036 } finally { 1037 IoUtils.closeQuietly(in); 1038 } 1039 } 1040 mLastWritten.set(SystemClock.elapsedRealtime()); 1041 } 1042 1043 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1044 throws IOException { 1045 sb.setLength(0); 1046 while (true) { 1047 int ch = in.read(); 1048 if (ch == -1) { 1049 if (sb.length() == 0) { 1050 return null; 1051 } 1052 throw new IOException("Unexpected EOF"); 1053 } 1054 if (ch == endOfToken) { 1055 return sb.toString(); 1056 } 1057 sb.append((char)ch); 1058 } 1059 } 1060 1061 private AtomicFile getFile() { 1062 File dataDir = Environment.getDataDirectory(); 1063 File systemDir = new File(dataDir, "system"); 1064 File fname = new File(systemDir, "package-usage.list"); 1065 return new AtomicFile(fname); 1066 } 1067 } 1068 1069 class PackageHandler extends Handler { 1070 private boolean mBound = false; 1071 final ArrayList<HandlerParams> mPendingInstalls = 1072 new ArrayList<HandlerParams>(); 1073 1074 private boolean connectToService() { 1075 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1076 " DefaultContainerService"); 1077 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1078 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1079 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1080 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1081 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1082 mBound = true; 1083 return true; 1084 } 1085 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1086 return false; 1087 } 1088 1089 private void disconnectService() { 1090 mContainerService = null; 1091 mBound = false; 1092 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1093 mContext.unbindService(mDefContainerConn); 1094 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1095 } 1096 1097 PackageHandler(Looper looper) { 1098 super(looper); 1099 } 1100 1101 public void handleMessage(Message msg) { 1102 try { 1103 doHandleMessage(msg); 1104 } finally { 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 } 1107 } 1108 1109 void doHandleMessage(Message msg) { 1110 switch (msg.what) { 1111 case INIT_COPY: { 1112 HandlerParams params = (HandlerParams) msg.obj; 1113 int idx = mPendingInstalls.size(); 1114 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1115 // If a bind was already initiated we dont really 1116 // need to do anything. The pending install 1117 // will be processed later on. 1118 if (!mBound) { 1119 // If this is the only one pending we might 1120 // have to bind to the service again. 1121 if (!connectToService()) { 1122 Slog.e(TAG, "Failed to bind to media container service"); 1123 params.serviceError(); 1124 return; 1125 } else { 1126 // Once we bind to the service, the first 1127 // pending request will be processed. 1128 mPendingInstalls.add(idx, params); 1129 } 1130 } else { 1131 mPendingInstalls.add(idx, params); 1132 // Already bound to the service. Just make 1133 // sure we trigger off processing the first request. 1134 if (idx == 0) { 1135 mHandler.sendEmptyMessage(MCS_BOUND); 1136 } 1137 } 1138 break; 1139 } 1140 case MCS_BOUND: { 1141 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1142 if (msg.obj != null) { 1143 mContainerService = (IMediaContainerService) msg.obj; 1144 } 1145 if (mContainerService == null) { 1146 if (!mBound) { 1147 // Something seriously wrong since we are not bound and we are not 1148 // waiting for connection. Bail out. 1149 Slog.e(TAG, "Cannot bind to media container service"); 1150 for (HandlerParams params : mPendingInstalls) { 1151 // Indicate service bind error 1152 params.serviceError(); 1153 } 1154 mPendingInstalls.clear(); 1155 } else { 1156 Slog.w(TAG, "Waiting to connect to media container service"); 1157 } 1158 } else if (mPendingInstalls.size() > 0) { 1159 HandlerParams params = mPendingInstalls.get(0); 1160 if (params != null) { 1161 if (params.startCopy()) { 1162 // We are done... look for more work or to 1163 // go idle. 1164 if (DEBUG_SD_INSTALL) Log.i(TAG, 1165 "Checking for more work or unbind..."); 1166 // Delete pending install 1167 if (mPendingInstalls.size() > 0) { 1168 mPendingInstalls.remove(0); 1169 } 1170 if (mPendingInstalls.size() == 0) { 1171 if (mBound) { 1172 if (DEBUG_SD_INSTALL) Log.i(TAG, 1173 "Posting delayed MCS_UNBIND"); 1174 removeMessages(MCS_UNBIND); 1175 Message ubmsg = obtainMessage(MCS_UNBIND); 1176 // Unbind after a little delay, to avoid 1177 // continual thrashing. 1178 sendMessageDelayed(ubmsg, 10000); 1179 } 1180 } else { 1181 // There are more pending requests in queue. 1182 // Just post MCS_BOUND message to trigger processing 1183 // of next pending install. 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, 1185 "Posting MCS_BOUND for next work"); 1186 mHandler.sendEmptyMessage(MCS_BOUND); 1187 } 1188 } 1189 } 1190 } else { 1191 // Should never happen ideally. 1192 Slog.w(TAG, "Empty queue"); 1193 } 1194 break; 1195 } 1196 case MCS_RECONNECT: { 1197 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1198 if (mPendingInstalls.size() > 0) { 1199 if (mBound) { 1200 disconnectService(); 1201 } 1202 if (!connectToService()) { 1203 Slog.e(TAG, "Failed to bind to media container service"); 1204 for (HandlerParams params : mPendingInstalls) { 1205 // Indicate service bind error 1206 params.serviceError(); 1207 } 1208 mPendingInstalls.clear(); 1209 } 1210 } 1211 break; 1212 } 1213 case MCS_UNBIND: { 1214 // If there is no actual work left, then time to unbind. 1215 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1216 1217 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1218 if (mBound) { 1219 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1220 1221 disconnectService(); 1222 } 1223 } else if (mPendingInstalls.size() > 0) { 1224 // There are more pending requests in queue. 1225 // Just post MCS_BOUND message to trigger processing 1226 // of next pending install. 1227 mHandler.sendEmptyMessage(MCS_BOUND); 1228 } 1229 1230 break; 1231 } 1232 case MCS_GIVE_UP: { 1233 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1234 mPendingInstalls.remove(0); 1235 break; 1236 } 1237 case SEND_PENDING_BROADCAST: { 1238 String packages[]; 1239 ArrayList<String> components[]; 1240 int size = 0; 1241 int uids[]; 1242 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1243 synchronized (mPackages) { 1244 if (mPendingBroadcasts == null) { 1245 return; 1246 } 1247 size = mPendingBroadcasts.size(); 1248 if (size <= 0) { 1249 // Nothing to be done. Just return 1250 return; 1251 } 1252 packages = new String[size]; 1253 components = new ArrayList[size]; 1254 uids = new int[size]; 1255 int i = 0; // filling out the above arrays 1256 1257 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1258 int packageUserId = mPendingBroadcasts.userIdAt(n); 1259 Iterator<Map.Entry<String, ArrayList<String>>> it 1260 = mPendingBroadcasts.packagesForUserId(packageUserId) 1261 .entrySet().iterator(); 1262 while (it.hasNext() && i < size) { 1263 Map.Entry<String, ArrayList<String>> ent = it.next(); 1264 packages[i] = ent.getKey(); 1265 components[i] = ent.getValue(); 1266 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1267 uids[i] = (ps != null) 1268 ? UserHandle.getUid(packageUserId, ps.appId) 1269 : -1; 1270 i++; 1271 } 1272 } 1273 size = i; 1274 mPendingBroadcasts.clear(); 1275 } 1276 // Send broadcasts 1277 for (int i = 0; i < size; i++) { 1278 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1279 } 1280 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1281 break; 1282 } 1283 case START_CLEANING_PACKAGE: { 1284 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1285 final String packageName = (String)msg.obj; 1286 final int userId = msg.arg1; 1287 final boolean andCode = msg.arg2 != 0; 1288 synchronized (mPackages) { 1289 if (userId == UserHandle.USER_ALL) { 1290 int[] users = sUserManager.getUserIds(); 1291 for (int user : users) { 1292 mSettings.addPackageToCleanLPw( 1293 new PackageCleanItem(user, packageName, andCode)); 1294 } 1295 } else { 1296 mSettings.addPackageToCleanLPw( 1297 new PackageCleanItem(userId, packageName, andCode)); 1298 } 1299 } 1300 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1301 startCleaningPackages(); 1302 } break; 1303 case POST_INSTALL: { 1304 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1305 PostInstallData data = mRunningInstalls.get(msg.arg1); 1306 mRunningInstalls.delete(msg.arg1); 1307 boolean deleteOld = false; 1308 1309 if (data != null) { 1310 InstallArgs args = data.args; 1311 PackageInstalledInfo res = data.res; 1312 1313 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1314 final String packageName = res.pkg.applicationInfo.packageName; 1315 res.removedInfo.sendBroadcast(false, true, false); 1316 Bundle extras = new Bundle(1); 1317 extras.putInt(Intent.EXTRA_UID, res.uid); 1318 1319 // Now that we successfully installed the package, grant runtime 1320 // permissions if requested before broadcasting the install. 1321 if ((args.installFlags 1322 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1323 grantRequestedRuntimePermissions(res.pkg, 1324 args.user.getIdentifier()); 1325 } 1326 1327 // Determine the set of users who are adding this 1328 // package for the first time vs. those who are seeing 1329 // an update. 1330 int[] firstUsers; 1331 int[] updateUsers = new int[0]; 1332 if (res.origUsers == null || res.origUsers.length == 0) { 1333 firstUsers = res.newUsers; 1334 } else { 1335 firstUsers = new int[0]; 1336 for (int i=0; i<res.newUsers.length; i++) { 1337 int user = res.newUsers[i]; 1338 boolean isNew = true; 1339 for (int j=0; j<res.origUsers.length; j++) { 1340 if (res.origUsers[j] == user) { 1341 isNew = false; 1342 break; 1343 } 1344 } 1345 if (isNew) { 1346 int[] newFirst = new int[firstUsers.length+1]; 1347 System.arraycopy(firstUsers, 0, newFirst, 0, 1348 firstUsers.length); 1349 newFirst[firstUsers.length] = user; 1350 firstUsers = newFirst; 1351 } else { 1352 int[] newUpdate = new int[updateUsers.length+1]; 1353 System.arraycopy(updateUsers, 0, newUpdate, 0, 1354 updateUsers.length); 1355 newUpdate[updateUsers.length] = user; 1356 updateUsers = newUpdate; 1357 } 1358 } 1359 } 1360 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1361 packageName, extras, null, null, firstUsers); 1362 final boolean update = res.removedInfo.removedPackage != null; 1363 if (update) { 1364 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1365 } 1366 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1367 packageName, extras, null, null, updateUsers); 1368 if (update) { 1369 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1370 packageName, extras, null, null, updateUsers); 1371 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1372 null, null, packageName, null, updateUsers); 1373 1374 // treat asec-hosted packages like removable media on upgrade 1375 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1376 if (DEBUG_INSTALL) { 1377 Slog.i(TAG, "upgrading pkg " + res.pkg 1378 + " is ASEC-hosted -> AVAILABLE"); 1379 } 1380 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1381 ArrayList<String> pkgList = new ArrayList<String>(1); 1382 pkgList.add(packageName); 1383 sendResourcesChangedBroadcast(true, true, 1384 pkgList,uidArray, null); 1385 } 1386 } 1387 if (res.removedInfo.args != null) { 1388 // Remove the replaced package's older resources safely now 1389 deleteOld = true; 1390 } 1391 1392 // If this app is a browser and it's newly-installed for some 1393 // users, clear any default-browser state in those users 1394 if (firstUsers.length > 0) { 1395 // the app's nature doesn't depend on the user, so we can just 1396 // check its browser nature in any user and generalize. 1397 if (packageIsBrowser(packageName, firstUsers[0])) { 1398 synchronized (mPackages) { 1399 for (int userId : firstUsers) { 1400 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1401 } 1402 } 1403 } 1404 } 1405 // Log current value of "unknown sources" setting 1406 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1407 getUnknownSourcesSettings()); 1408 } 1409 // Force a gc to clear up things 1410 Runtime.getRuntime().gc(); 1411 // We delete after a gc for applications on sdcard. 1412 if (deleteOld) { 1413 synchronized (mInstallLock) { 1414 res.removedInfo.args.doPostDeleteLI(true); 1415 } 1416 } 1417 if (args.observer != null) { 1418 try { 1419 Bundle extras = extrasForInstallResult(res); 1420 args.observer.onPackageInstalled(res.name, res.returnCode, 1421 res.returnMsg, extras); 1422 } catch (RemoteException e) { 1423 Slog.i(TAG, "Observer no longer exists."); 1424 } 1425 } 1426 } else { 1427 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1428 } 1429 } break; 1430 case UPDATED_MEDIA_STATUS: { 1431 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1432 boolean reportStatus = msg.arg1 == 1; 1433 boolean doGc = msg.arg2 == 1; 1434 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1435 if (doGc) { 1436 // Force a gc to clear up stale containers. 1437 Runtime.getRuntime().gc(); 1438 } 1439 if (msg.obj != null) { 1440 @SuppressWarnings("unchecked") 1441 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1442 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1443 // Unload containers 1444 unloadAllContainers(args); 1445 } 1446 if (reportStatus) { 1447 try { 1448 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1449 PackageHelper.getMountService().finishMediaUpdate(); 1450 } catch (RemoteException e) { 1451 Log.e(TAG, "MountService not running?"); 1452 } 1453 } 1454 } break; 1455 case WRITE_SETTINGS: { 1456 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1457 synchronized (mPackages) { 1458 removeMessages(WRITE_SETTINGS); 1459 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1460 mSettings.writeLPr(); 1461 mDirtyUsers.clear(); 1462 } 1463 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1464 } break; 1465 case WRITE_PACKAGE_RESTRICTIONS: { 1466 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1467 synchronized (mPackages) { 1468 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1469 for (int userId : mDirtyUsers) { 1470 mSettings.writePackageRestrictionsLPr(userId); 1471 } 1472 mDirtyUsers.clear(); 1473 } 1474 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1475 } break; 1476 case CHECK_PENDING_VERIFICATION: { 1477 final int verificationId = msg.arg1; 1478 final PackageVerificationState state = mPendingVerification.get(verificationId); 1479 1480 if ((state != null) && !state.timeoutExtended()) { 1481 final InstallArgs args = state.getInstallArgs(); 1482 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1483 1484 Slog.i(TAG, "Verification timed out for " + originUri); 1485 mPendingVerification.remove(verificationId); 1486 1487 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1488 1489 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1490 Slog.i(TAG, "Continuing with installation of " + originUri); 1491 state.setVerifierResponse(Binder.getCallingUid(), 1492 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1493 broadcastPackageVerified(verificationId, originUri, 1494 PackageManager.VERIFICATION_ALLOW, 1495 state.getInstallArgs().getUser()); 1496 try { 1497 ret = args.copyApk(mContainerService, true); 1498 } catch (RemoteException e) { 1499 Slog.e(TAG, "Could not contact the ContainerService"); 1500 } 1501 } else { 1502 broadcastPackageVerified(verificationId, originUri, 1503 PackageManager.VERIFICATION_REJECT, 1504 state.getInstallArgs().getUser()); 1505 } 1506 1507 processPendingInstall(args, ret); 1508 mHandler.sendEmptyMessage(MCS_UNBIND); 1509 } 1510 break; 1511 } 1512 case PACKAGE_VERIFIED: { 1513 final int verificationId = msg.arg1; 1514 1515 final PackageVerificationState state = mPendingVerification.get(verificationId); 1516 if (state == null) { 1517 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1518 break; 1519 } 1520 1521 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1522 1523 state.setVerifierResponse(response.callerUid, response.code); 1524 1525 if (state.isVerificationComplete()) { 1526 mPendingVerification.remove(verificationId); 1527 1528 final InstallArgs args = state.getInstallArgs(); 1529 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1530 1531 int ret; 1532 if (state.isInstallAllowed()) { 1533 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1534 broadcastPackageVerified(verificationId, originUri, 1535 response.code, state.getInstallArgs().getUser()); 1536 try { 1537 ret = args.copyApk(mContainerService, true); 1538 } catch (RemoteException e) { 1539 Slog.e(TAG, "Could not contact the ContainerService"); 1540 } 1541 } else { 1542 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1543 } 1544 1545 processPendingInstall(args, ret); 1546 1547 mHandler.sendEmptyMessage(MCS_UNBIND); 1548 } 1549 1550 break; 1551 } 1552 case START_INTENT_FILTER_VERIFICATIONS: { 1553 IFVerificationParams params = (IFVerificationParams) msg.obj; 1554 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1555 params.replacing, params.pkg); 1556 break; 1557 } 1558 case INTENT_FILTER_VERIFIED: { 1559 final int verificationId = msg.arg1; 1560 1561 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1562 verificationId); 1563 if (state == null) { 1564 Slog.w(TAG, "Invalid IntentFilter verification token " 1565 + verificationId + " received"); 1566 break; 1567 } 1568 1569 final int userId = state.getUserId(); 1570 1571 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1572 "Processing IntentFilter verification with token:" 1573 + verificationId + " and userId:" + userId); 1574 1575 final IntentFilterVerificationResponse response = 1576 (IntentFilterVerificationResponse) msg.obj; 1577 1578 state.setVerifierResponse(response.callerUid, response.code); 1579 1580 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1581 "IntentFilter verification with token:" + verificationId 1582 + " and userId:" + userId 1583 + " is settings verifier response with response code:" 1584 + response.code); 1585 1586 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1587 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1588 + response.getFailedDomainsString()); 1589 } 1590 1591 if (state.isVerificationComplete()) { 1592 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1593 } else { 1594 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1595 "IntentFilter verification with token:" + verificationId 1596 + " was not said to be complete"); 1597 } 1598 1599 break; 1600 } 1601 } 1602 } 1603 } 1604 1605 private StorageEventListener mStorageListener = new StorageEventListener() { 1606 @Override 1607 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1608 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1609 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1610 // TODO: ensure that private directories exist for all active users 1611 // TODO: remove user data whose serial number doesn't match 1612 loadPrivatePackages(vol); 1613 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1614 unloadPrivatePackages(vol); 1615 } 1616 } 1617 1618 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1619 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1620 updateExternalMediaStatus(true, false); 1621 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1622 updateExternalMediaStatus(false, false); 1623 } 1624 } 1625 } 1626 1627 @Override 1628 public void onVolumeForgotten(String fsUuid) { 1629 // TODO: remove all packages hosted on this uuid 1630 } 1631 }; 1632 1633 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1634 if (userId >= UserHandle.USER_OWNER) { 1635 grantRequestedRuntimePermissionsForUser(pkg, userId); 1636 } else if (userId == UserHandle.USER_ALL) { 1637 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1638 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1639 } 1640 } 1641 1642 // We could have touched GID membership, so flush out packages.list 1643 synchronized (mPackages) { 1644 mSettings.writePackageListLPr(); 1645 } 1646 } 1647 1648 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1649 SettingBase sb = (SettingBase) pkg.mExtras; 1650 if (sb == null) { 1651 return; 1652 } 1653 1654 PermissionsState permissionsState = sb.getPermissionsState(); 1655 1656 for (String permission : pkg.requestedPermissions) { 1657 BasePermission bp = mSettings.mPermissions.get(permission); 1658 if (bp != null && bp.isRuntime()) { 1659 permissionsState.grantRuntimePermission(bp, userId); 1660 } 1661 } 1662 } 1663 1664 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1665 Bundle extras = null; 1666 switch (res.returnCode) { 1667 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1668 extras = new Bundle(); 1669 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1670 res.origPermission); 1671 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1672 res.origPackage); 1673 break; 1674 } 1675 case PackageManager.INSTALL_SUCCEEDED: { 1676 extras = new Bundle(); 1677 extras.putBoolean(Intent.EXTRA_REPLACING, 1678 res.removedInfo != null && res.removedInfo.removedPackage != null); 1679 break; 1680 } 1681 } 1682 return extras; 1683 } 1684 1685 void scheduleWriteSettingsLocked() { 1686 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1687 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1688 } 1689 } 1690 1691 void scheduleWritePackageRestrictionsLocked(int userId) { 1692 if (!sUserManager.exists(userId)) return; 1693 mDirtyUsers.add(userId); 1694 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1695 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1696 } 1697 } 1698 1699 public static PackageManagerService main(Context context, Installer installer, 1700 boolean factoryTest, boolean onlyCore) { 1701 PackageManagerService m = new PackageManagerService(context, installer, 1702 factoryTest, onlyCore); 1703 ServiceManager.addService("package", m); 1704 return m; 1705 } 1706 1707 static String[] splitString(String str, char sep) { 1708 int count = 1; 1709 int i = 0; 1710 while ((i=str.indexOf(sep, i)) >= 0) { 1711 count++; 1712 i++; 1713 } 1714 1715 String[] res = new String[count]; 1716 i=0; 1717 count = 0; 1718 int lastI=0; 1719 while ((i=str.indexOf(sep, i)) >= 0) { 1720 res[count] = str.substring(lastI, i); 1721 count++; 1722 i++; 1723 lastI = i; 1724 } 1725 res[count] = str.substring(lastI, str.length()); 1726 return res; 1727 } 1728 1729 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1730 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1731 Context.DISPLAY_SERVICE); 1732 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1733 } 1734 1735 public PackageManagerService(Context context, Installer installer, 1736 boolean factoryTest, boolean onlyCore) { 1737 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1738 SystemClock.uptimeMillis()); 1739 1740 if (mSdkVersion <= 0) { 1741 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1742 } 1743 1744 mContext = context; 1745 mFactoryTest = factoryTest; 1746 mOnlyCore = onlyCore; 1747 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1748 mMetrics = new DisplayMetrics(); 1749 mSettings = new Settings(mPackages); 1750 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1751 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1752 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1753 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1754 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1755 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1756 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1757 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1758 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1759 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1760 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1761 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1762 1763 // TODO: add a property to control this? 1764 long dexOptLRUThresholdInMinutes; 1765 if (mLazyDexOpt) { 1766 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1767 } else { 1768 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1769 } 1770 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1771 1772 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1773 if (separateProcesses != null && separateProcesses.length() > 0) { 1774 if ("*".equals(separateProcesses)) { 1775 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1776 mSeparateProcesses = null; 1777 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1778 } else { 1779 mDefParseFlags = 0; 1780 mSeparateProcesses = separateProcesses.split(","); 1781 Slog.w(TAG, "Running with debug.separate_processes: " 1782 + separateProcesses); 1783 } 1784 } else { 1785 mDefParseFlags = 0; 1786 mSeparateProcesses = null; 1787 } 1788 1789 mInstaller = installer; 1790 mPackageDexOptimizer = new PackageDexOptimizer(this); 1791 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1792 1793 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1794 FgThread.get().getLooper()); 1795 1796 getDefaultDisplayMetrics(context, mMetrics); 1797 1798 SystemConfig systemConfig = SystemConfig.getInstance(); 1799 mGlobalGids = systemConfig.getGlobalGids(); 1800 mSystemPermissions = systemConfig.getSystemPermissions(); 1801 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1802 1803 synchronized (mInstallLock) { 1804 // writer 1805 synchronized (mPackages) { 1806 mHandlerThread = new ServiceThread(TAG, 1807 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1808 mHandlerThread.start(); 1809 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1810 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1811 1812 File dataDir = Environment.getDataDirectory(); 1813 mAppDataDir = new File(dataDir, "data"); 1814 mAppInstallDir = new File(dataDir, "app"); 1815 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1816 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1817 mUserAppDataDir = new File(dataDir, "user"); 1818 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1819 1820 sUserManager = new UserManagerService(context, this, 1821 mInstallLock, mPackages); 1822 1823 // Propagate permission configuration in to package manager. 1824 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1825 = systemConfig.getPermissions(); 1826 for (int i=0; i<permConfig.size(); i++) { 1827 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1828 BasePermission bp = mSettings.mPermissions.get(perm.name); 1829 if (bp == null) { 1830 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1831 mSettings.mPermissions.put(perm.name, bp); 1832 } 1833 if (perm.gids != null) { 1834 bp.setGids(perm.gids, perm.perUser); 1835 } 1836 } 1837 1838 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1839 for (int i=0; i<libConfig.size(); i++) { 1840 mSharedLibraries.put(libConfig.keyAt(i), 1841 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1842 } 1843 1844 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1845 1846 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1847 mSdkVersion, mOnlyCore); 1848 1849 String customResolverActivity = Resources.getSystem().getString( 1850 R.string.config_customResolverActivity); 1851 if (TextUtils.isEmpty(customResolverActivity)) { 1852 customResolverActivity = null; 1853 } else { 1854 mCustomResolverComponentName = ComponentName.unflattenFromString( 1855 customResolverActivity); 1856 } 1857 1858 long startTime = SystemClock.uptimeMillis(); 1859 1860 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1861 startTime); 1862 1863 // Set flag to monitor and not change apk file paths when 1864 // scanning install directories. 1865 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1866 1867 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1868 1869 /** 1870 * Add everything in the in the boot class path to the 1871 * list of process files because dexopt will have been run 1872 * if necessary during zygote startup. 1873 */ 1874 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1875 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1876 1877 if (bootClassPath != null) { 1878 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1879 for (String element : bootClassPathElements) { 1880 alreadyDexOpted.add(element); 1881 } 1882 } else { 1883 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1884 } 1885 1886 if (systemServerClassPath != null) { 1887 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1888 for (String element : systemServerClassPathElements) { 1889 alreadyDexOpted.add(element); 1890 } 1891 } else { 1892 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1893 } 1894 1895 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1896 final String[] dexCodeInstructionSets = 1897 getDexCodeInstructionSets( 1898 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1899 1900 /** 1901 * Ensure all external libraries have had dexopt run on them. 1902 */ 1903 if (mSharedLibraries.size() > 0) { 1904 // NOTE: For now, we're compiling these system "shared libraries" 1905 // (and framework jars) into all available architectures. It's possible 1906 // to compile them only when we come across an app that uses them (there's 1907 // already logic for that in scanPackageLI) but that adds some complexity. 1908 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1909 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1910 final String lib = libEntry.path; 1911 if (lib == null) { 1912 continue; 1913 } 1914 1915 try { 1916 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1917 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1918 alreadyDexOpted.add(lib); 1919 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1920 } 1921 } catch (FileNotFoundException e) { 1922 Slog.w(TAG, "Library not found: " + lib); 1923 } catch (IOException e) { 1924 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1925 + e.getMessage()); 1926 } 1927 } 1928 } 1929 } 1930 1931 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1932 1933 // Gross hack for now: we know this file doesn't contain any 1934 // code, so don't dexopt it to avoid the resulting log spew. 1935 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1936 1937 // Gross hack for now: we know this file is only part of 1938 // the boot class path for art, so don't dexopt it to 1939 // avoid the resulting log spew. 1940 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1941 1942 /** 1943 * There are a number of commands implemented in Java, which 1944 * we currently need to do the dexopt on so that they can be 1945 * run from a non-root shell. 1946 */ 1947 String[] frameworkFiles = frameworkDir.list(); 1948 if (frameworkFiles != null) { 1949 // TODO: We could compile these only for the most preferred ABI. We should 1950 // first double check that the dex files for these commands are not referenced 1951 // by other system apps. 1952 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1953 for (int i=0; i<frameworkFiles.length; i++) { 1954 File libPath = new File(frameworkDir, frameworkFiles[i]); 1955 String path = libPath.getPath(); 1956 // Skip the file if we already did it. 1957 if (alreadyDexOpted.contains(path)) { 1958 continue; 1959 } 1960 // Skip the file if it is not a type we want to dexopt. 1961 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1962 continue; 1963 } 1964 try { 1965 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1966 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1967 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1968 } 1969 } catch (FileNotFoundException e) { 1970 Slog.w(TAG, "Jar not found: " + path); 1971 } catch (IOException e) { 1972 Slog.w(TAG, "Exception reading jar: " + path, e); 1973 } 1974 } 1975 } 1976 } 1977 1978 // Collect vendor overlay packages. 1979 // (Do this before scanning any apps.) 1980 // For security and version matching reason, only consider 1981 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1982 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1983 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1984 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1985 1986 // Find base frameworks (resource packages without code). 1987 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1988 | PackageParser.PARSE_IS_SYSTEM_DIR 1989 | PackageParser.PARSE_IS_PRIVILEGED, 1990 scanFlags | SCAN_NO_DEX, 0); 1991 1992 // Collected privileged system packages. 1993 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1994 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1995 | PackageParser.PARSE_IS_SYSTEM_DIR 1996 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1997 1998 // Collect ordinary system packages. 1999 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2000 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2001 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2002 2003 // Collect all vendor packages. 2004 File vendorAppDir = new File("/vendor/app"); 2005 try { 2006 vendorAppDir = vendorAppDir.getCanonicalFile(); 2007 } catch (IOException e) { 2008 // failed to look up canonical path, continue with original one 2009 } 2010 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2011 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2012 2013 // Collect all OEM packages. 2014 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2015 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2016 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2017 2018 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2019 mInstaller.moveFiles(); 2020 2021 // Prune any system packages that no longer exist. 2022 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2023 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2024 if (!mOnlyCore) { 2025 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2026 while (psit.hasNext()) { 2027 PackageSetting ps = psit.next(); 2028 2029 /* 2030 * If this is not a system app, it can't be a 2031 * disable system app. 2032 */ 2033 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2034 continue; 2035 } 2036 2037 /* 2038 * If the package is scanned, it's not erased. 2039 */ 2040 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2041 if (scannedPkg != null) { 2042 /* 2043 * If the system app is both scanned and in the 2044 * disabled packages list, then it must have been 2045 * added via OTA. Remove it from the currently 2046 * scanned package so the previously user-installed 2047 * application can be scanned. 2048 */ 2049 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2050 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2051 + ps.name + "; removing system app. Last known codePath=" 2052 + ps.codePathString + ", installStatus=" + ps.installStatus 2053 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2054 + scannedPkg.mVersionCode); 2055 removePackageLI(ps, true); 2056 expectingBetter.put(ps.name, ps.codePath); 2057 } 2058 2059 continue; 2060 } 2061 2062 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2063 psit.remove(); 2064 logCriticalInfo(Log.WARN, "System package " + ps.name 2065 + " no longer exists; wiping its data"); 2066 removeDataDirsLI(null, ps.name); 2067 } else { 2068 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2069 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2070 possiblyDeletedUpdatedSystemApps.add(ps.name); 2071 } 2072 } 2073 } 2074 } 2075 2076 //look for any incomplete package installations 2077 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2078 //clean up list 2079 for(int i = 0; i < deletePkgsList.size(); i++) { 2080 //clean up here 2081 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2082 } 2083 //delete tmp files 2084 deleteTempPackageFiles(); 2085 2086 // Remove any shared userIDs that have no associated packages 2087 mSettings.pruneSharedUsersLPw(); 2088 2089 if (!mOnlyCore) { 2090 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2091 SystemClock.uptimeMillis()); 2092 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2093 2094 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2095 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2096 2097 /** 2098 * Remove disable package settings for any updated system 2099 * apps that were removed via an OTA. If they're not a 2100 * previously-updated app, remove them completely. 2101 * Otherwise, just revoke their system-level permissions. 2102 */ 2103 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2104 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2105 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2106 2107 String msg; 2108 if (deletedPkg == null) { 2109 msg = "Updated system package " + deletedAppName 2110 + " no longer exists; wiping its data"; 2111 removeDataDirsLI(null, deletedAppName); 2112 } else { 2113 msg = "Updated system app + " + deletedAppName 2114 + " no longer present; removing system privileges for " 2115 + deletedAppName; 2116 2117 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2118 2119 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2120 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2121 } 2122 logCriticalInfo(Log.WARN, msg); 2123 } 2124 2125 /** 2126 * Make sure all system apps that we expected to appear on 2127 * the userdata partition actually showed up. If they never 2128 * appeared, crawl back and revive the system version. 2129 */ 2130 for (int i = 0; i < expectingBetter.size(); i++) { 2131 final String packageName = expectingBetter.keyAt(i); 2132 if (!mPackages.containsKey(packageName)) { 2133 final File scanFile = expectingBetter.valueAt(i); 2134 2135 logCriticalInfo(Log.WARN, "Expected better " + packageName 2136 + " but never showed up; reverting to system"); 2137 2138 final int reparseFlags; 2139 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2140 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2141 | PackageParser.PARSE_IS_SYSTEM_DIR 2142 | PackageParser.PARSE_IS_PRIVILEGED; 2143 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2144 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2145 | PackageParser.PARSE_IS_SYSTEM_DIR; 2146 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2147 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2148 | PackageParser.PARSE_IS_SYSTEM_DIR; 2149 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2150 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2151 | PackageParser.PARSE_IS_SYSTEM_DIR; 2152 } else { 2153 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2154 continue; 2155 } 2156 2157 mSettings.enableSystemPackageLPw(packageName); 2158 2159 try { 2160 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2161 } catch (PackageManagerException e) { 2162 Slog.e(TAG, "Failed to parse original system package: " 2163 + e.getMessage()); 2164 } 2165 } 2166 } 2167 } 2168 2169 // Now that we know all of the shared libraries, update all clients to have 2170 // the correct library paths. 2171 updateAllSharedLibrariesLPw(); 2172 2173 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2174 // NOTE: We ignore potential failures here during a system scan (like 2175 // the rest of the commands above) because there's precious little we 2176 // can do about it. A settings error is reported, though. 2177 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2178 false /* force dexopt */, false /* defer dexopt */); 2179 } 2180 2181 // Now that we know all the packages we are keeping, 2182 // read and update their last usage times. 2183 mPackageUsage.readLP(); 2184 2185 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2186 SystemClock.uptimeMillis()); 2187 Slog.i(TAG, "Time to scan packages: " 2188 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2189 + " seconds"); 2190 2191 // If the platform SDK has changed since the last time we booted, 2192 // we need to re-grant app permission to catch any new ones that 2193 // appear. This is really a hack, and means that apps can in some 2194 // cases get permissions that the user didn't initially explicitly 2195 // allow... it would be nice to have some better way to handle 2196 // this situation. 2197 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2198 != mSdkVersion; 2199 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2200 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2201 + "; regranting permissions for internal storage"); 2202 mSettings.mInternalSdkPlatform = mSdkVersion; 2203 2204 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2205 | (regrantPermissions 2206 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2207 : 0)); 2208 2209 // If this is the first boot, and it is a normal boot, then 2210 // we need to initialize the default preferred apps. 2211 if (!mRestoredSettings && !onlyCore) { 2212 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2213 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2214 } 2215 2216 // If this is first boot after an OTA, and a normal boot, then 2217 // we need to clear code cache directories. 2218 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2219 if (mIsUpgrade && !onlyCore) { 2220 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2221 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2222 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2223 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2224 } 2225 mSettings.mFingerprint = Build.FINGERPRINT; 2226 } 2227 2228 primeDomainVerificationsLPw(); 2229 checkDefaultBrowser(); 2230 2231 // All the changes are done during package scanning. 2232 mSettings.updateInternalDatabaseVersion(); 2233 2234 // can downgrade to reader 2235 mSettings.writeLPr(); 2236 2237 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2238 SystemClock.uptimeMillis()); 2239 2240 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2241 2242 mInstallerService = new PackageInstallerService(context, this); 2243 2244 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2245 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2246 mIntentFilterVerifierComponent); 2247 2248 } // synchronized (mPackages) 2249 } // synchronized (mInstallLock) 2250 2251 // Now after opening every single application zip, make sure they 2252 // are all flushed. Not really needed, but keeps things nice and 2253 // tidy. 2254 Runtime.getRuntime().gc(); 2255 2256 // Expose private service for system components to use. 2257 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2258 } 2259 2260 @Override 2261 public boolean isFirstBoot() { 2262 return !mRestoredSettings; 2263 } 2264 2265 @Override 2266 public boolean isOnlyCoreApps() { 2267 return mOnlyCore; 2268 } 2269 2270 @Override 2271 public boolean isUpgrade() { 2272 return mIsUpgrade; 2273 } 2274 2275 private String getRequiredVerifierLPr() { 2276 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2277 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2278 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2279 2280 String requiredVerifier = null; 2281 2282 final int N = receivers.size(); 2283 for (int i = 0; i < N; i++) { 2284 final ResolveInfo info = receivers.get(i); 2285 2286 if (info.activityInfo == null) { 2287 continue; 2288 } 2289 2290 final String packageName = info.activityInfo.packageName; 2291 2292 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2293 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2294 continue; 2295 } 2296 2297 if (requiredVerifier != null) { 2298 throw new RuntimeException("There can be only one required verifier"); 2299 } 2300 2301 requiredVerifier = packageName; 2302 } 2303 2304 return requiredVerifier; 2305 } 2306 2307 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2308 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2309 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2310 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2311 2312 ComponentName verifierComponentName = null; 2313 2314 int priority = -1000; 2315 final int N = receivers.size(); 2316 for (int i = 0; i < N; i++) { 2317 final ResolveInfo info = receivers.get(i); 2318 2319 if (info.activityInfo == null) { 2320 continue; 2321 } 2322 2323 final String packageName = info.activityInfo.packageName; 2324 2325 final PackageSetting ps = mSettings.mPackages.get(packageName); 2326 if (ps == null) { 2327 continue; 2328 } 2329 2330 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2331 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2332 continue; 2333 } 2334 2335 // Select the IntentFilterVerifier with the highest priority 2336 if (priority < info.priority) { 2337 priority = info.priority; 2338 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2339 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2340 + verifierComponentName + " with priority: " + info.priority); 2341 } 2342 } 2343 2344 return verifierComponentName; 2345 } 2346 2347 private void primeDomainVerificationsLPw() { 2348 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2349 boolean updated = false; 2350 ArraySet<String> allHostsSet = new ArraySet<>(); 2351 for (PackageParser.Package pkg : mPackages.values()) { 2352 final String packageName = pkg.packageName; 2353 if (!hasDomainURLs(pkg)) { 2354 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2355 "package with no domain URLs: " + packageName); 2356 continue; 2357 } 2358 if (!pkg.isSystemApp()) { 2359 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2360 "No priming domain verifications for a non system package : " + 2361 packageName); 2362 continue; 2363 } 2364 for (PackageParser.Activity a : pkg.activities) { 2365 for (ActivityIntentInfo filter : a.intents) { 2366 if (hasValidDomains(filter)) { 2367 allHostsSet.addAll(filter.getHostsList()); 2368 } 2369 } 2370 } 2371 if (allHostsSet.size() == 0) { 2372 allHostsSet.add("*"); 2373 } 2374 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2375 IntentFilterVerificationInfo ivi = 2376 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2377 if (ivi != null) { 2378 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2379 "Priming domain verifications for package: " + packageName + 2380 " with hosts:" + ivi.getDomainsString()); 2381 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2382 updated = true; 2383 } 2384 else { 2385 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2386 "No priming domain verifications for package: " + packageName); 2387 } 2388 allHostsSet.clear(); 2389 } 2390 if (updated) { 2391 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2392 "Will need to write primed domain verifications"); 2393 } 2394 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2395 } 2396 2397 private void applyFactoryDefaultBrowserLPw(int userId) { 2398 // The default browser app's package name is stored in a string resource, 2399 // with a product-specific overlay used for vendor customization. 2400 String browserPkg = mContext.getResources().getString( 2401 com.android.internal.R.string.default_browser); 2402 if (browserPkg != null) { 2403 // non-empty string => required to be a known package 2404 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2405 if (ps == null) { 2406 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2407 browserPkg = null; 2408 } else { 2409 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2410 } 2411 } 2412 2413 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2414 // default. If there's more than one, just leave everything alone. 2415 if (browserPkg == null) { 2416 calculateDefaultBrowserLPw(userId); 2417 } 2418 } 2419 2420 private void calculateDefaultBrowserLPw(int userId) { 2421 List<String> allBrowsers = resolveAllBrowserApps(userId); 2422 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2423 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2424 } 2425 2426 private List<String> resolveAllBrowserApps(int userId) { 2427 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2428 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2429 PackageManager.MATCH_ALL, userId); 2430 2431 final int count = list.size(); 2432 List<String> result = new ArrayList<String>(count); 2433 for (int i=0; i<count; i++) { 2434 ResolveInfo info = list.get(i); 2435 if (info.activityInfo == null 2436 || !info.handleAllWebDataURI 2437 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2438 || result.contains(info.activityInfo.packageName)) { 2439 continue; 2440 } 2441 result.add(info.activityInfo.packageName); 2442 } 2443 2444 return result; 2445 } 2446 2447 private boolean packageIsBrowser(String packageName, int userId) { 2448 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2449 PackageManager.MATCH_ALL, userId); 2450 final int N = list.size(); 2451 for (int i = 0; i < N; i++) { 2452 ResolveInfo info = list.get(i); 2453 if (packageName.equals(info.activityInfo.packageName)) { 2454 return true; 2455 } 2456 } 2457 return false; 2458 } 2459 2460 private void checkDefaultBrowser() { 2461 final int myUserId = UserHandle.myUserId(); 2462 final String packageName = getDefaultBrowserPackageName(myUserId); 2463 if (packageName != null) { 2464 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2465 if (info == null) { 2466 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2467 synchronized (mPackages) { 2468 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2469 } 2470 } 2471 } 2472 } 2473 2474 @Override 2475 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2476 throws RemoteException { 2477 try { 2478 return super.onTransact(code, data, reply, flags); 2479 } catch (RuntimeException e) { 2480 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2481 Slog.wtf(TAG, "Package Manager Crash", e); 2482 } 2483 throw e; 2484 } 2485 } 2486 2487 void cleanupInstallFailedPackage(PackageSetting ps) { 2488 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2489 2490 removeDataDirsLI(ps.volumeUuid, ps.name); 2491 if (ps.codePath != null) { 2492 if (ps.codePath.isDirectory()) { 2493 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2494 } else { 2495 ps.codePath.delete(); 2496 } 2497 } 2498 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2499 if (ps.resourcePath.isDirectory()) { 2500 FileUtils.deleteContents(ps.resourcePath); 2501 } 2502 ps.resourcePath.delete(); 2503 } 2504 mSettings.removePackageLPw(ps.name); 2505 } 2506 2507 static int[] appendInts(int[] cur, int[] add) { 2508 if (add == null) return cur; 2509 if (cur == null) return add; 2510 final int N = add.length; 2511 for (int i=0; i<N; i++) { 2512 cur = appendInt(cur, add[i]); 2513 } 2514 return cur; 2515 } 2516 2517 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2518 if (!sUserManager.exists(userId)) return null; 2519 final PackageSetting ps = (PackageSetting) p.mExtras; 2520 if (ps == null) { 2521 return null; 2522 } 2523 2524 final PermissionsState permissionsState = ps.getPermissionsState(); 2525 2526 final int[] gids = permissionsState.computeGids(userId); 2527 final Set<String> permissions = permissionsState.getPermissions(userId); 2528 final PackageUserState state = ps.readUserState(userId); 2529 2530 return PackageParser.generatePackageInfo(p, gids, flags, 2531 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2532 } 2533 2534 @Override 2535 public boolean isPackageFrozen(String packageName) { 2536 synchronized (mPackages) { 2537 final PackageSetting ps = mSettings.mPackages.get(packageName); 2538 if (ps != null) { 2539 return ps.frozen; 2540 } 2541 } 2542 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2543 return true; 2544 } 2545 2546 @Override 2547 public boolean isPackageAvailable(String packageName, int userId) { 2548 if (!sUserManager.exists(userId)) return false; 2549 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2550 synchronized (mPackages) { 2551 PackageParser.Package p = mPackages.get(packageName); 2552 if (p != null) { 2553 final PackageSetting ps = (PackageSetting) p.mExtras; 2554 if (ps != null) { 2555 final PackageUserState state = ps.readUserState(userId); 2556 if (state != null) { 2557 return PackageParser.isAvailable(state); 2558 } 2559 } 2560 } 2561 } 2562 return false; 2563 } 2564 2565 @Override 2566 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2567 if (!sUserManager.exists(userId)) return null; 2568 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2569 // reader 2570 synchronized (mPackages) { 2571 PackageParser.Package p = mPackages.get(packageName); 2572 if (DEBUG_PACKAGE_INFO) 2573 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2574 if (p != null) { 2575 return generatePackageInfo(p, flags, userId); 2576 } 2577 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2578 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2579 } 2580 } 2581 return null; 2582 } 2583 2584 @Override 2585 public String[] currentToCanonicalPackageNames(String[] names) { 2586 String[] out = new String[names.length]; 2587 // reader 2588 synchronized (mPackages) { 2589 for (int i=names.length-1; i>=0; i--) { 2590 PackageSetting ps = mSettings.mPackages.get(names[i]); 2591 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2592 } 2593 } 2594 return out; 2595 } 2596 2597 @Override 2598 public String[] canonicalToCurrentPackageNames(String[] names) { 2599 String[] out = new String[names.length]; 2600 // reader 2601 synchronized (mPackages) { 2602 for (int i=names.length-1; i>=0; i--) { 2603 String cur = mSettings.mRenamedPackages.get(names[i]); 2604 out[i] = cur != null ? cur : names[i]; 2605 } 2606 } 2607 return out; 2608 } 2609 2610 @Override 2611 public int getPackageUid(String packageName, int userId) { 2612 if (!sUserManager.exists(userId)) return -1; 2613 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2614 2615 // reader 2616 synchronized (mPackages) { 2617 PackageParser.Package p = mPackages.get(packageName); 2618 if(p != null) { 2619 return UserHandle.getUid(userId, p.applicationInfo.uid); 2620 } 2621 PackageSetting ps = mSettings.mPackages.get(packageName); 2622 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2623 return -1; 2624 } 2625 p = ps.pkg; 2626 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2627 } 2628 } 2629 2630 @Override 2631 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2632 if (!sUserManager.exists(userId)) { 2633 return null; 2634 } 2635 2636 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2637 "getPackageGids"); 2638 2639 // reader 2640 synchronized (mPackages) { 2641 PackageParser.Package p = mPackages.get(packageName); 2642 if (DEBUG_PACKAGE_INFO) { 2643 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2644 } 2645 if (p != null) { 2646 PackageSetting ps = (PackageSetting) p.mExtras; 2647 return ps.getPermissionsState().computeGids(userId); 2648 } 2649 } 2650 2651 return null; 2652 } 2653 2654 @Override 2655 public int getMountExternalMode(int uid) { 2656 if (Process.isIsolated(uid)) { 2657 return Zygote.MOUNT_EXTERNAL_NONE; 2658 } else { 2659 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2660 return Zygote.MOUNT_EXTERNAL_WRITE; 2661 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2662 return Zygote.MOUNT_EXTERNAL_READ; 2663 } else { 2664 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2665 } 2666 } 2667 } 2668 2669 static PermissionInfo generatePermissionInfo( 2670 BasePermission bp, int flags) { 2671 if (bp.perm != null) { 2672 return PackageParser.generatePermissionInfo(bp.perm, flags); 2673 } 2674 PermissionInfo pi = new PermissionInfo(); 2675 pi.name = bp.name; 2676 pi.packageName = bp.sourcePackage; 2677 pi.nonLocalizedLabel = bp.name; 2678 pi.protectionLevel = bp.protectionLevel; 2679 return pi; 2680 } 2681 2682 @Override 2683 public PermissionInfo getPermissionInfo(String name, int flags) { 2684 // reader 2685 synchronized (mPackages) { 2686 final BasePermission p = mSettings.mPermissions.get(name); 2687 if (p != null) { 2688 return generatePermissionInfo(p, flags); 2689 } 2690 return null; 2691 } 2692 } 2693 2694 @Override 2695 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2696 // reader 2697 synchronized (mPackages) { 2698 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2699 for (BasePermission p : mSettings.mPermissions.values()) { 2700 if (group == null) { 2701 if (p.perm == null || p.perm.info.group == null) { 2702 out.add(generatePermissionInfo(p, flags)); 2703 } 2704 } else { 2705 if (p.perm != null && group.equals(p.perm.info.group)) { 2706 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2707 } 2708 } 2709 } 2710 2711 if (out.size() > 0) { 2712 return out; 2713 } 2714 return mPermissionGroups.containsKey(group) ? out : null; 2715 } 2716 } 2717 2718 @Override 2719 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2720 // reader 2721 synchronized (mPackages) { 2722 return PackageParser.generatePermissionGroupInfo( 2723 mPermissionGroups.get(name), flags); 2724 } 2725 } 2726 2727 @Override 2728 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2729 // reader 2730 synchronized (mPackages) { 2731 final int N = mPermissionGroups.size(); 2732 ArrayList<PermissionGroupInfo> out 2733 = new ArrayList<PermissionGroupInfo>(N); 2734 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2735 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2736 } 2737 return out; 2738 } 2739 } 2740 2741 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2742 int userId) { 2743 if (!sUserManager.exists(userId)) return null; 2744 PackageSetting ps = mSettings.mPackages.get(packageName); 2745 if (ps != null) { 2746 if (ps.pkg == null) { 2747 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2748 flags, userId); 2749 if (pInfo != null) { 2750 return pInfo.applicationInfo; 2751 } 2752 return null; 2753 } 2754 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2755 ps.readUserState(userId), userId); 2756 } 2757 return null; 2758 } 2759 2760 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2761 int userId) { 2762 if (!sUserManager.exists(userId)) return null; 2763 PackageSetting ps = mSettings.mPackages.get(packageName); 2764 if (ps != null) { 2765 PackageParser.Package pkg = ps.pkg; 2766 if (pkg == null) { 2767 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2768 return null; 2769 } 2770 // Only data remains, so we aren't worried about code paths 2771 pkg = new PackageParser.Package(packageName); 2772 pkg.applicationInfo.packageName = packageName; 2773 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2774 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2775 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2776 packageName, userId).getAbsolutePath(); 2777 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2778 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2779 } 2780 return generatePackageInfo(pkg, flags, userId); 2781 } 2782 return null; 2783 } 2784 2785 @Override 2786 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2787 if (!sUserManager.exists(userId)) return null; 2788 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2789 // writer 2790 synchronized (mPackages) { 2791 PackageParser.Package p = mPackages.get(packageName); 2792 if (DEBUG_PACKAGE_INFO) Log.v( 2793 TAG, "getApplicationInfo " + packageName 2794 + ": " + p); 2795 if (p != null) { 2796 PackageSetting ps = mSettings.mPackages.get(packageName); 2797 if (ps == null) return null; 2798 // Note: isEnabledLP() does not apply here - always return info 2799 return PackageParser.generateApplicationInfo( 2800 p, flags, ps.readUserState(userId), userId); 2801 } 2802 if ("android".equals(packageName)||"system".equals(packageName)) { 2803 return mAndroidApplication; 2804 } 2805 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2806 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2807 } 2808 } 2809 return null; 2810 } 2811 2812 @Override 2813 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2814 final IPackageDataObserver observer) { 2815 mContext.enforceCallingOrSelfPermission( 2816 android.Manifest.permission.CLEAR_APP_CACHE, null); 2817 // Queue up an async operation since clearing cache may take a little while. 2818 mHandler.post(new Runnable() { 2819 public void run() { 2820 mHandler.removeCallbacks(this); 2821 int retCode = -1; 2822 synchronized (mInstallLock) { 2823 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2824 if (retCode < 0) { 2825 Slog.w(TAG, "Couldn't clear application caches"); 2826 } 2827 } 2828 if (observer != null) { 2829 try { 2830 observer.onRemoveCompleted(null, (retCode >= 0)); 2831 } catch (RemoteException e) { 2832 Slog.w(TAG, "RemoveException when invoking call back"); 2833 } 2834 } 2835 } 2836 }); 2837 } 2838 2839 @Override 2840 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2841 final IntentSender pi) { 2842 mContext.enforceCallingOrSelfPermission( 2843 android.Manifest.permission.CLEAR_APP_CACHE, null); 2844 // Queue up an async operation since clearing cache may take a little while. 2845 mHandler.post(new Runnable() { 2846 public void run() { 2847 mHandler.removeCallbacks(this); 2848 int retCode = -1; 2849 synchronized (mInstallLock) { 2850 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2851 if (retCode < 0) { 2852 Slog.w(TAG, "Couldn't clear application caches"); 2853 } 2854 } 2855 if(pi != null) { 2856 try { 2857 // Callback via pending intent 2858 int code = (retCode >= 0) ? 1 : 0; 2859 pi.sendIntent(null, code, null, 2860 null, null); 2861 } catch (SendIntentException e1) { 2862 Slog.i(TAG, "Failed to send pending intent"); 2863 } 2864 } 2865 } 2866 }); 2867 } 2868 2869 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2870 synchronized (mInstallLock) { 2871 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2872 throw new IOException("Failed to free enough space"); 2873 } 2874 } 2875 } 2876 2877 @Override 2878 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2879 if (!sUserManager.exists(userId)) return null; 2880 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2881 synchronized (mPackages) { 2882 PackageParser.Activity a = mActivities.mActivities.get(component); 2883 2884 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2885 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2886 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2887 if (ps == null) return null; 2888 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2889 userId); 2890 } 2891 if (mResolveComponentName.equals(component)) { 2892 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2893 new PackageUserState(), userId); 2894 } 2895 } 2896 return null; 2897 } 2898 2899 @Override 2900 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2901 String resolvedType) { 2902 synchronized (mPackages) { 2903 PackageParser.Activity a = mActivities.mActivities.get(component); 2904 if (a == null) { 2905 return false; 2906 } 2907 for (int i=0; i<a.intents.size(); i++) { 2908 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2909 intent.getData(), intent.getCategories(), TAG) >= 0) { 2910 return true; 2911 } 2912 } 2913 return false; 2914 } 2915 } 2916 2917 @Override 2918 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2919 if (!sUserManager.exists(userId)) return null; 2920 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2921 synchronized (mPackages) { 2922 PackageParser.Activity a = mReceivers.mActivities.get(component); 2923 if (DEBUG_PACKAGE_INFO) Log.v( 2924 TAG, "getReceiverInfo " + component + ": " + a); 2925 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2926 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2927 if (ps == null) return null; 2928 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2929 userId); 2930 } 2931 } 2932 return null; 2933 } 2934 2935 @Override 2936 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2937 if (!sUserManager.exists(userId)) return null; 2938 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2939 synchronized (mPackages) { 2940 PackageParser.Service s = mServices.mServices.get(component); 2941 if (DEBUG_PACKAGE_INFO) Log.v( 2942 TAG, "getServiceInfo " + component + ": " + s); 2943 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2944 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2945 if (ps == null) return null; 2946 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2947 userId); 2948 } 2949 } 2950 return null; 2951 } 2952 2953 @Override 2954 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2955 if (!sUserManager.exists(userId)) return null; 2956 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2957 synchronized (mPackages) { 2958 PackageParser.Provider p = mProviders.mProviders.get(component); 2959 if (DEBUG_PACKAGE_INFO) Log.v( 2960 TAG, "getProviderInfo " + component + ": " + p); 2961 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2962 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2963 if (ps == null) return null; 2964 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2965 userId); 2966 } 2967 } 2968 return null; 2969 } 2970 2971 @Override 2972 public String[] getSystemSharedLibraryNames() { 2973 Set<String> libSet; 2974 synchronized (mPackages) { 2975 libSet = mSharedLibraries.keySet(); 2976 int size = libSet.size(); 2977 if (size > 0) { 2978 String[] libs = new String[size]; 2979 libSet.toArray(libs); 2980 return libs; 2981 } 2982 } 2983 return null; 2984 } 2985 2986 /** 2987 * @hide 2988 */ 2989 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2990 synchronized (mPackages) { 2991 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2992 if (lib != null && lib.apk != null) { 2993 return mPackages.get(lib.apk); 2994 } 2995 } 2996 return null; 2997 } 2998 2999 @Override 3000 public FeatureInfo[] getSystemAvailableFeatures() { 3001 Collection<FeatureInfo> featSet; 3002 synchronized (mPackages) { 3003 featSet = mAvailableFeatures.values(); 3004 int size = featSet.size(); 3005 if (size > 0) { 3006 FeatureInfo[] features = new FeatureInfo[size+1]; 3007 featSet.toArray(features); 3008 FeatureInfo fi = new FeatureInfo(); 3009 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3010 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3011 features[size] = fi; 3012 return features; 3013 } 3014 } 3015 return null; 3016 } 3017 3018 @Override 3019 public boolean hasSystemFeature(String name) { 3020 synchronized (mPackages) { 3021 return mAvailableFeatures.containsKey(name); 3022 } 3023 } 3024 3025 private void checkValidCaller(int uid, int userId) { 3026 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3027 return; 3028 3029 throw new SecurityException("Caller uid=" + uid 3030 + " is not privileged to communicate with user=" + userId); 3031 } 3032 3033 @Override 3034 public int checkPermission(String permName, String pkgName, int userId) { 3035 if (!sUserManager.exists(userId)) { 3036 return PackageManager.PERMISSION_DENIED; 3037 } 3038 3039 synchronized (mPackages) { 3040 final PackageParser.Package p = mPackages.get(pkgName); 3041 if (p != null && p.mExtras != null) { 3042 final PackageSetting ps = (PackageSetting) p.mExtras; 3043 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3044 return PackageManager.PERMISSION_GRANTED; 3045 } 3046 } 3047 } 3048 3049 return PackageManager.PERMISSION_DENIED; 3050 } 3051 3052 @Override 3053 public int checkUidPermission(String permName, int uid) { 3054 final int userId = UserHandle.getUserId(uid); 3055 3056 if (!sUserManager.exists(userId)) { 3057 return PackageManager.PERMISSION_DENIED; 3058 } 3059 3060 synchronized (mPackages) { 3061 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3062 if (obj != null) { 3063 final SettingBase ps = (SettingBase) obj; 3064 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3065 return PackageManager.PERMISSION_GRANTED; 3066 } 3067 } else { 3068 ArraySet<String> perms = mSystemPermissions.get(uid); 3069 if (perms != null && perms.contains(permName)) { 3070 return PackageManager.PERMISSION_GRANTED; 3071 } 3072 } 3073 } 3074 3075 return PackageManager.PERMISSION_DENIED; 3076 } 3077 3078 /** 3079 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3080 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3081 * @param checkShell TODO(yamasani): 3082 * @param message the message to log on security exception 3083 */ 3084 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3085 boolean checkShell, String message) { 3086 if (userId < 0) { 3087 throw new IllegalArgumentException("Invalid userId " + userId); 3088 } 3089 if (checkShell) { 3090 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3091 } 3092 if (userId == UserHandle.getUserId(callingUid)) return; 3093 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3094 if (requireFullPermission) { 3095 mContext.enforceCallingOrSelfPermission( 3096 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3097 } else { 3098 try { 3099 mContext.enforceCallingOrSelfPermission( 3100 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3101 } catch (SecurityException se) { 3102 mContext.enforceCallingOrSelfPermission( 3103 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3104 } 3105 } 3106 } 3107 } 3108 3109 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3110 if (callingUid == Process.SHELL_UID) { 3111 if (userHandle >= 0 3112 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3113 throw new SecurityException("Shell does not have permission to access user " 3114 + userHandle); 3115 } else if (userHandle < 0) { 3116 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3117 + Debug.getCallers(3)); 3118 } 3119 } 3120 } 3121 3122 private BasePermission findPermissionTreeLP(String permName) { 3123 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3124 if (permName.startsWith(bp.name) && 3125 permName.length() > bp.name.length() && 3126 permName.charAt(bp.name.length()) == '.') { 3127 return bp; 3128 } 3129 } 3130 return null; 3131 } 3132 3133 private BasePermission checkPermissionTreeLP(String permName) { 3134 if (permName != null) { 3135 BasePermission bp = findPermissionTreeLP(permName); 3136 if (bp != null) { 3137 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3138 return bp; 3139 } 3140 throw new SecurityException("Calling uid " 3141 + Binder.getCallingUid() 3142 + " is not allowed to add to permission tree " 3143 + bp.name + " owned by uid " + bp.uid); 3144 } 3145 } 3146 throw new SecurityException("No permission tree found for " + permName); 3147 } 3148 3149 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3150 if (s1 == null) { 3151 return s2 == null; 3152 } 3153 if (s2 == null) { 3154 return false; 3155 } 3156 if (s1.getClass() != s2.getClass()) { 3157 return false; 3158 } 3159 return s1.equals(s2); 3160 } 3161 3162 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3163 if (pi1.icon != pi2.icon) return false; 3164 if (pi1.logo != pi2.logo) return false; 3165 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3166 if (!compareStrings(pi1.name, pi2.name)) return false; 3167 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3168 // We'll take care of setting this one. 3169 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3170 // These are not currently stored in settings. 3171 //if (!compareStrings(pi1.group, pi2.group)) return false; 3172 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3173 //if (pi1.labelRes != pi2.labelRes) return false; 3174 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3175 return true; 3176 } 3177 3178 int permissionInfoFootprint(PermissionInfo info) { 3179 int size = info.name.length(); 3180 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3181 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3182 return size; 3183 } 3184 3185 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3186 int size = 0; 3187 for (BasePermission perm : mSettings.mPermissions.values()) { 3188 if (perm.uid == tree.uid) { 3189 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3190 } 3191 } 3192 return size; 3193 } 3194 3195 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3196 // We calculate the max size of permissions defined by this uid and throw 3197 // if that plus the size of 'info' would exceed our stated maximum. 3198 if (tree.uid != Process.SYSTEM_UID) { 3199 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3200 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3201 throw new SecurityException("Permission tree size cap exceeded"); 3202 } 3203 } 3204 } 3205 3206 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3207 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3208 throw new SecurityException("Label must be specified in permission"); 3209 } 3210 BasePermission tree = checkPermissionTreeLP(info.name); 3211 BasePermission bp = mSettings.mPermissions.get(info.name); 3212 boolean added = bp == null; 3213 boolean changed = true; 3214 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3215 if (added) { 3216 enforcePermissionCapLocked(info, tree); 3217 bp = new BasePermission(info.name, tree.sourcePackage, 3218 BasePermission.TYPE_DYNAMIC); 3219 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3220 throw new SecurityException( 3221 "Not allowed to modify non-dynamic permission " 3222 + info.name); 3223 } else { 3224 if (bp.protectionLevel == fixedLevel 3225 && bp.perm.owner.equals(tree.perm.owner) 3226 && bp.uid == tree.uid 3227 && comparePermissionInfos(bp.perm.info, info)) { 3228 changed = false; 3229 } 3230 } 3231 bp.protectionLevel = fixedLevel; 3232 info = new PermissionInfo(info); 3233 info.protectionLevel = fixedLevel; 3234 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3235 bp.perm.info.packageName = tree.perm.info.packageName; 3236 bp.uid = tree.uid; 3237 if (added) { 3238 mSettings.mPermissions.put(info.name, bp); 3239 } 3240 if (changed) { 3241 if (!async) { 3242 mSettings.writeLPr(); 3243 } else { 3244 scheduleWriteSettingsLocked(); 3245 } 3246 } 3247 return added; 3248 } 3249 3250 @Override 3251 public boolean addPermission(PermissionInfo info) { 3252 synchronized (mPackages) { 3253 return addPermissionLocked(info, false); 3254 } 3255 } 3256 3257 @Override 3258 public boolean addPermissionAsync(PermissionInfo info) { 3259 synchronized (mPackages) { 3260 return addPermissionLocked(info, true); 3261 } 3262 } 3263 3264 @Override 3265 public void removePermission(String name) { 3266 synchronized (mPackages) { 3267 checkPermissionTreeLP(name); 3268 BasePermission bp = mSettings.mPermissions.get(name); 3269 if (bp != null) { 3270 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3271 throw new SecurityException( 3272 "Not allowed to modify non-dynamic permission " 3273 + name); 3274 } 3275 mSettings.mPermissions.remove(name); 3276 mSettings.writeLPr(); 3277 } 3278 } 3279 } 3280 3281 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3282 BasePermission bp) { 3283 int index = pkg.requestedPermissions.indexOf(bp.name); 3284 if (index == -1) { 3285 throw new SecurityException("Package " + pkg.packageName 3286 + " has not requested permission " + bp.name); 3287 } 3288 if (!bp.isRuntime()) { 3289 throw new SecurityException("Permission " + bp.name 3290 + " is not a changeable permission type"); 3291 } 3292 } 3293 3294 @Override 3295 public void grantRuntimePermission(String packageName, String name, final int userId) { 3296 if (!sUserManager.exists(userId)) { 3297 Log.e(TAG, "No such user:" + userId); 3298 return; 3299 } 3300 3301 mContext.enforceCallingOrSelfPermission( 3302 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3303 "grantRuntimePermission"); 3304 3305 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3306 "grantRuntimePermission"); 3307 3308 final int uid; 3309 final SettingBase sb; 3310 3311 synchronized (mPackages) { 3312 final PackageParser.Package pkg = mPackages.get(packageName); 3313 if (pkg == null) { 3314 throw new IllegalArgumentException("Unknown package: " + packageName); 3315 } 3316 3317 final BasePermission bp = mSettings.mPermissions.get(name); 3318 if (bp == null) { 3319 throw new IllegalArgumentException("Unknown permission: " + name); 3320 } 3321 3322 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3323 3324 uid = pkg.applicationInfo.uid; 3325 sb = (SettingBase) pkg.mExtras; 3326 if (sb == null) { 3327 throw new IllegalArgumentException("Unknown package: " + packageName); 3328 } 3329 3330 final PermissionsState permissionsState = sb.getPermissionsState(); 3331 3332 final int flags = permissionsState.getPermissionFlags(name, userId); 3333 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3334 throw new SecurityException("Cannot grant system fixed permission: " 3335 + name + " for package: " + packageName); 3336 } 3337 3338 final int result = permissionsState.grantRuntimePermission(bp, userId); 3339 switch (result) { 3340 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3341 return; 3342 } 3343 3344 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3345 mHandler.post(new Runnable() { 3346 @Override 3347 public void run() { 3348 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3349 } 3350 }); 3351 } break; 3352 } 3353 3354 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3355 3356 // Not critical if that is lost - app has to request again. 3357 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3358 } 3359 3360 if (READ_EXTERNAL_STORAGE.equals(name) 3361 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3362 final long token = Binder.clearCallingIdentity(); 3363 try { 3364 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3365 storage.remountUid(uid); 3366 } finally { 3367 Binder.restoreCallingIdentity(token); 3368 } 3369 } 3370 } 3371 3372 @Override 3373 public void revokeRuntimePermission(String packageName, String name, int userId) { 3374 if (!sUserManager.exists(userId)) { 3375 Log.e(TAG, "No such user:" + userId); 3376 return; 3377 } 3378 3379 mContext.enforceCallingOrSelfPermission( 3380 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3381 "revokeRuntimePermission"); 3382 3383 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3384 "revokeRuntimePermission"); 3385 3386 final SettingBase sb; 3387 3388 synchronized (mPackages) { 3389 final PackageParser.Package pkg = mPackages.get(packageName); 3390 if (pkg == null) { 3391 throw new IllegalArgumentException("Unknown package: " + packageName); 3392 } 3393 3394 final BasePermission bp = mSettings.mPermissions.get(name); 3395 if (bp == null) { 3396 throw new IllegalArgumentException("Unknown permission: " + name); 3397 } 3398 3399 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3400 3401 sb = (SettingBase) pkg.mExtras; 3402 if (sb == null) { 3403 throw new IllegalArgumentException("Unknown package: " + packageName); 3404 } 3405 3406 final PermissionsState permissionsState = sb.getPermissionsState(); 3407 3408 final int flags = permissionsState.getPermissionFlags(name, userId); 3409 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3410 throw new SecurityException("Cannot revoke system fixed permission: " 3411 + name + " for package: " + packageName); 3412 } 3413 3414 if (permissionsState.revokeRuntimePermission(bp, userId) == 3415 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3416 return; 3417 } 3418 3419 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3420 3421 // Critical, after this call app should never have the permission. 3422 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3423 } 3424 3425 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3426 } 3427 3428 @Override 3429 public void resetRuntimePermissions() { 3430 mContext.enforceCallingOrSelfPermission( 3431 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3432 "revokeRuntimePermission"); 3433 3434 int callingUid = Binder.getCallingUid(); 3435 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3436 mContext.enforceCallingOrSelfPermission( 3437 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3438 "resetRuntimePermissions"); 3439 } 3440 3441 final int[] userIds; 3442 3443 synchronized (mPackages) { 3444 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3445 final int userCount = UserManagerService.getInstance().getUserIds().length; 3446 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3447 } 3448 3449 for (int userId : userIds) { 3450 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3451 } 3452 } 3453 3454 @Override 3455 public int getPermissionFlags(String name, String packageName, int userId) { 3456 if (!sUserManager.exists(userId)) { 3457 return 0; 3458 } 3459 3460 mContext.enforceCallingOrSelfPermission( 3461 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3462 "getPermissionFlags"); 3463 3464 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3465 "getPermissionFlags"); 3466 3467 synchronized (mPackages) { 3468 final PackageParser.Package pkg = mPackages.get(packageName); 3469 if (pkg == null) { 3470 throw new IllegalArgumentException("Unknown package: " + packageName); 3471 } 3472 3473 final BasePermission bp = mSettings.mPermissions.get(name); 3474 if (bp == null) { 3475 throw new IllegalArgumentException("Unknown permission: " + name); 3476 } 3477 3478 SettingBase sb = (SettingBase) pkg.mExtras; 3479 if (sb == null) { 3480 throw new IllegalArgumentException("Unknown package: " + packageName); 3481 } 3482 3483 PermissionsState permissionsState = sb.getPermissionsState(); 3484 return permissionsState.getPermissionFlags(name, userId); 3485 } 3486 } 3487 3488 @Override 3489 public void updatePermissionFlags(String name, String packageName, int flagMask, 3490 int flagValues, int userId) { 3491 if (!sUserManager.exists(userId)) { 3492 return; 3493 } 3494 3495 mContext.enforceCallingOrSelfPermission( 3496 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3497 "updatePermissionFlags"); 3498 3499 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3500 "updatePermissionFlags"); 3501 3502 // Only the system can change system fixed flags. 3503 if (getCallingUid() != Process.SYSTEM_UID) { 3504 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3505 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3506 } 3507 3508 synchronized (mPackages) { 3509 final PackageParser.Package pkg = mPackages.get(packageName); 3510 if (pkg == null) { 3511 throw new IllegalArgumentException("Unknown package: " + packageName); 3512 } 3513 3514 final BasePermission bp = mSettings.mPermissions.get(name); 3515 if (bp == null) { 3516 throw new IllegalArgumentException("Unknown permission: " + name); 3517 } 3518 3519 SettingBase sb = (SettingBase) pkg.mExtras; 3520 if (sb == null) { 3521 throw new IllegalArgumentException("Unknown package: " + packageName); 3522 } 3523 3524 PermissionsState permissionsState = sb.getPermissionsState(); 3525 3526 // Only the package manager can change flags for system component permissions. 3527 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3528 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3529 return; 3530 } 3531 3532 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3533 3534 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3535 // Install and runtime permissions are stored in different places, 3536 // so figure out what permission changed and persist the change. 3537 if (permissionsState.getInstallPermissionState(name) != null) { 3538 scheduleWriteSettingsLocked(); 3539 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3540 || hadState) { 3541 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3542 } 3543 } 3544 } 3545 } 3546 3547 /** 3548 * Update the permission flags for all packages and runtime permissions of a user in order 3549 * to allow device or profile owner to remove POLICY_FIXED. 3550 */ 3551 @Override 3552 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3553 if (!sUserManager.exists(userId)) { 3554 return; 3555 } 3556 3557 mContext.enforceCallingOrSelfPermission( 3558 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3559 "updatePermissionFlagsForAllApps"); 3560 3561 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3562 "updatePermissionFlagsForAllApps"); 3563 3564 // Only the system can change system fixed flags. 3565 if (getCallingUid() != Process.SYSTEM_UID) { 3566 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3567 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3568 } 3569 3570 synchronized (mPackages) { 3571 boolean changed = false; 3572 final int packageCount = mPackages.size(); 3573 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3574 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3575 SettingBase sb = (SettingBase) pkg.mExtras; 3576 if (sb == null) { 3577 continue; 3578 } 3579 PermissionsState permissionsState = sb.getPermissionsState(); 3580 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3581 userId, flagMask, flagValues); 3582 } 3583 if (changed) { 3584 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3585 } 3586 } 3587 } 3588 3589 @Override 3590 public boolean shouldShowRequestPermissionRationale(String permissionName, 3591 String packageName, int userId) { 3592 if (UserHandle.getCallingUserId() != userId) { 3593 mContext.enforceCallingPermission( 3594 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3595 "canShowRequestPermissionRationale for user " + userId); 3596 } 3597 3598 final int uid = getPackageUid(packageName, userId); 3599 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3600 return false; 3601 } 3602 3603 if (checkPermission(permissionName, packageName, userId) 3604 == PackageManager.PERMISSION_GRANTED) { 3605 return false; 3606 } 3607 3608 final int flags; 3609 3610 final long identity = Binder.clearCallingIdentity(); 3611 try { 3612 flags = getPermissionFlags(permissionName, 3613 packageName, userId); 3614 } finally { 3615 Binder.restoreCallingIdentity(identity); 3616 } 3617 3618 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3619 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3620 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3621 3622 if ((flags & fixedFlags) != 0) { 3623 return false; 3624 } 3625 3626 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3627 } 3628 3629 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3630 BasePermission bp = mSettings.mPermissions.get(permission); 3631 if (bp == null) { 3632 throw new SecurityException("Missing " + permission + " permission"); 3633 } 3634 3635 SettingBase sb = (SettingBase) pkg.mExtras; 3636 PermissionsState permissionsState = sb.getPermissionsState(); 3637 3638 if (permissionsState.grantInstallPermission(bp) != 3639 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3640 scheduleWriteSettingsLocked(); 3641 } 3642 } 3643 3644 @Override 3645 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3646 mContext.enforceCallingOrSelfPermission( 3647 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3648 "addOnPermissionsChangeListener"); 3649 3650 synchronized (mPackages) { 3651 mOnPermissionChangeListeners.addListenerLocked(listener); 3652 } 3653 } 3654 3655 @Override 3656 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3657 synchronized (mPackages) { 3658 mOnPermissionChangeListeners.removeListenerLocked(listener); 3659 } 3660 } 3661 3662 @Override 3663 public boolean isProtectedBroadcast(String actionName) { 3664 synchronized (mPackages) { 3665 return mProtectedBroadcasts.contains(actionName); 3666 } 3667 } 3668 3669 @Override 3670 public int checkSignatures(String pkg1, String pkg2) { 3671 synchronized (mPackages) { 3672 final PackageParser.Package p1 = mPackages.get(pkg1); 3673 final PackageParser.Package p2 = mPackages.get(pkg2); 3674 if (p1 == null || p1.mExtras == null 3675 || p2 == null || p2.mExtras == null) { 3676 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3677 } 3678 return compareSignatures(p1.mSignatures, p2.mSignatures); 3679 } 3680 } 3681 3682 @Override 3683 public int checkUidSignatures(int uid1, int uid2) { 3684 // Map to base uids. 3685 uid1 = UserHandle.getAppId(uid1); 3686 uid2 = UserHandle.getAppId(uid2); 3687 // reader 3688 synchronized (mPackages) { 3689 Signature[] s1; 3690 Signature[] s2; 3691 Object obj = mSettings.getUserIdLPr(uid1); 3692 if (obj != null) { 3693 if (obj instanceof SharedUserSetting) { 3694 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3695 } else if (obj instanceof PackageSetting) { 3696 s1 = ((PackageSetting)obj).signatures.mSignatures; 3697 } else { 3698 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3699 } 3700 } else { 3701 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3702 } 3703 obj = mSettings.getUserIdLPr(uid2); 3704 if (obj != null) { 3705 if (obj instanceof SharedUserSetting) { 3706 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3707 } else if (obj instanceof PackageSetting) { 3708 s2 = ((PackageSetting)obj).signatures.mSignatures; 3709 } else { 3710 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3711 } 3712 } else { 3713 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3714 } 3715 return compareSignatures(s1, s2); 3716 } 3717 } 3718 3719 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3720 final long identity = Binder.clearCallingIdentity(); 3721 try { 3722 if (sb instanceof SharedUserSetting) { 3723 SharedUserSetting sus = (SharedUserSetting) sb; 3724 final int packageCount = sus.packages.size(); 3725 for (int i = 0; i < packageCount; i++) { 3726 PackageSetting susPs = sus.packages.valueAt(i); 3727 if (userId == UserHandle.USER_ALL) { 3728 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3729 } else { 3730 final int uid = UserHandle.getUid(userId, susPs.appId); 3731 killUid(uid, reason); 3732 } 3733 } 3734 } else if (sb instanceof PackageSetting) { 3735 PackageSetting ps = (PackageSetting) sb; 3736 if (userId == UserHandle.USER_ALL) { 3737 killApplication(ps.pkg.packageName, ps.appId, reason); 3738 } else { 3739 final int uid = UserHandle.getUid(userId, ps.appId); 3740 killUid(uid, reason); 3741 } 3742 } 3743 } finally { 3744 Binder.restoreCallingIdentity(identity); 3745 } 3746 } 3747 3748 private static void killUid(int uid, String reason) { 3749 IActivityManager am = ActivityManagerNative.getDefault(); 3750 if (am != null) { 3751 try { 3752 am.killUid(uid, reason); 3753 } catch (RemoteException e) { 3754 /* ignore - same process */ 3755 } 3756 } 3757 } 3758 3759 /** 3760 * Compares two sets of signatures. Returns: 3761 * <br /> 3762 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3763 * <br /> 3764 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3765 * <br /> 3766 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3767 * <br /> 3768 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3769 * <br /> 3770 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3771 */ 3772 static int compareSignatures(Signature[] s1, Signature[] s2) { 3773 if (s1 == null) { 3774 return s2 == null 3775 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3776 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3777 } 3778 3779 if (s2 == null) { 3780 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3781 } 3782 3783 if (s1.length != s2.length) { 3784 return PackageManager.SIGNATURE_NO_MATCH; 3785 } 3786 3787 // Since both signature sets are of size 1, we can compare without HashSets. 3788 if (s1.length == 1) { 3789 return s1[0].equals(s2[0]) ? 3790 PackageManager.SIGNATURE_MATCH : 3791 PackageManager.SIGNATURE_NO_MATCH; 3792 } 3793 3794 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3795 for (Signature sig : s1) { 3796 set1.add(sig); 3797 } 3798 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3799 for (Signature sig : s2) { 3800 set2.add(sig); 3801 } 3802 // Make sure s2 contains all signatures in s1. 3803 if (set1.equals(set2)) { 3804 return PackageManager.SIGNATURE_MATCH; 3805 } 3806 return PackageManager.SIGNATURE_NO_MATCH; 3807 } 3808 3809 /** 3810 * If the database version for this type of package (internal storage or 3811 * external storage) is less than the version where package signatures 3812 * were updated, return true. 3813 */ 3814 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3815 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3816 DatabaseVersion.SIGNATURE_END_ENTITY)) 3817 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3818 DatabaseVersion.SIGNATURE_END_ENTITY)); 3819 } 3820 3821 /** 3822 * Used for backward compatibility to make sure any packages with 3823 * certificate chains get upgraded to the new style. {@code existingSigs} 3824 * will be in the old format (since they were stored on disk from before the 3825 * system upgrade) and {@code scannedSigs} will be in the newer format. 3826 */ 3827 private int compareSignaturesCompat(PackageSignatures existingSigs, 3828 PackageParser.Package scannedPkg) { 3829 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3830 return PackageManager.SIGNATURE_NO_MATCH; 3831 } 3832 3833 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3834 for (Signature sig : existingSigs.mSignatures) { 3835 existingSet.add(sig); 3836 } 3837 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3838 for (Signature sig : scannedPkg.mSignatures) { 3839 try { 3840 Signature[] chainSignatures = sig.getChainSignatures(); 3841 for (Signature chainSig : chainSignatures) { 3842 scannedCompatSet.add(chainSig); 3843 } 3844 } catch (CertificateEncodingException e) { 3845 scannedCompatSet.add(sig); 3846 } 3847 } 3848 /* 3849 * Make sure the expanded scanned set contains all signatures in the 3850 * existing one. 3851 */ 3852 if (scannedCompatSet.equals(existingSet)) { 3853 // Migrate the old signatures to the new scheme. 3854 existingSigs.assignSignatures(scannedPkg.mSignatures); 3855 // The new KeySets will be re-added later in the scanning process. 3856 synchronized (mPackages) { 3857 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3858 } 3859 return PackageManager.SIGNATURE_MATCH; 3860 } 3861 return PackageManager.SIGNATURE_NO_MATCH; 3862 } 3863 3864 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3865 if (isExternal(scannedPkg)) { 3866 return mSettings.isExternalDatabaseVersionOlderThan( 3867 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3868 } else { 3869 return mSettings.isInternalDatabaseVersionOlderThan( 3870 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3871 } 3872 } 3873 3874 private int compareSignaturesRecover(PackageSignatures existingSigs, 3875 PackageParser.Package scannedPkg) { 3876 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3877 return PackageManager.SIGNATURE_NO_MATCH; 3878 } 3879 3880 String msg = null; 3881 try { 3882 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3883 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3884 + scannedPkg.packageName); 3885 return PackageManager.SIGNATURE_MATCH; 3886 } 3887 } catch (CertificateException e) { 3888 msg = e.getMessage(); 3889 } 3890 3891 logCriticalInfo(Log.INFO, 3892 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3893 return PackageManager.SIGNATURE_NO_MATCH; 3894 } 3895 3896 @Override 3897 public String[] getPackagesForUid(int uid) { 3898 uid = UserHandle.getAppId(uid); 3899 // reader 3900 synchronized (mPackages) { 3901 Object obj = mSettings.getUserIdLPr(uid); 3902 if (obj instanceof SharedUserSetting) { 3903 final SharedUserSetting sus = (SharedUserSetting) obj; 3904 final int N = sus.packages.size(); 3905 final String[] res = new String[N]; 3906 final Iterator<PackageSetting> it = sus.packages.iterator(); 3907 int i = 0; 3908 while (it.hasNext()) { 3909 res[i++] = it.next().name; 3910 } 3911 return res; 3912 } else if (obj instanceof PackageSetting) { 3913 final PackageSetting ps = (PackageSetting) obj; 3914 return new String[] { ps.name }; 3915 } 3916 } 3917 return null; 3918 } 3919 3920 @Override 3921 public String getNameForUid(int uid) { 3922 // reader 3923 synchronized (mPackages) { 3924 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3925 if (obj instanceof SharedUserSetting) { 3926 final SharedUserSetting sus = (SharedUserSetting) obj; 3927 return sus.name + ":" + sus.userId; 3928 } else if (obj instanceof PackageSetting) { 3929 final PackageSetting ps = (PackageSetting) obj; 3930 return ps.name; 3931 } 3932 } 3933 return null; 3934 } 3935 3936 @Override 3937 public int getUidForSharedUser(String sharedUserName) { 3938 if(sharedUserName == null) { 3939 return -1; 3940 } 3941 // reader 3942 synchronized (mPackages) { 3943 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3944 if (suid == null) { 3945 return -1; 3946 } 3947 return suid.userId; 3948 } 3949 } 3950 3951 @Override 3952 public int getFlagsForUid(int uid) { 3953 synchronized (mPackages) { 3954 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3955 if (obj instanceof SharedUserSetting) { 3956 final SharedUserSetting sus = (SharedUserSetting) obj; 3957 return sus.pkgFlags; 3958 } else if (obj instanceof PackageSetting) { 3959 final PackageSetting ps = (PackageSetting) obj; 3960 return ps.pkgFlags; 3961 } 3962 } 3963 return 0; 3964 } 3965 3966 @Override 3967 public int getPrivateFlagsForUid(int uid) { 3968 synchronized (mPackages) { 3969 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3970 if (obj instanceof SharedUserSetting) { 3971 final SharedUserSetting sus = (SharedUserSetting) obj; 3972 return sus.pkgPrivateFlags; 3973 } else if (obj instanceof PackageSetting) { 3974 final PackageSetting ps = (PackageSetting) obj; 3975 return ps.pkgPrivateFlags; 3976 } 3977 } 3978 return 0; 3979 } 3980 3981 @Override 3982 public boolean isUidPrivileged(int uid) { 3983 uid = UserHandle.getAppId(uid); 3984 // reader 3985 synchronized (mPackages) { 3986 Object obj = mSettings.getUserIdLPr(uid); 3987 if (obj instanceof SharedUserSetting) { 3988 final SharedUserSetting sus = (SharedUserSetting) obj; 3989 final Iterator<PackageSetting> it = sus.packages.iterator(); 3990 while (it.hasNext()) { 3991 if (it.next().isPrivileged()) { 3992 return true; 3993 } 3994 } 3995 } else if (obj instanceof PackageSetting) { 3996 final PackageSetting ps = (PackageSetting) obj; 3997 return ps.isPrivileged(); 3998 } 3999 } 4000 return false; 4001 } 4002 4003 @Override 4004 public String[] getAppOpPermissionPackages(String permissionName) { 4005 synchronized (mPackages) { 4006 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4007 if (pkgs == null) { 4008 return null; 4009 } 4010 return pkgs.toArray(new String[pkgs.size()]); 4011 } 4012 } 4013 4014 @Override 4015 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4016 int flags, int userId) { 4017 if (!sUserManager.exists(userId)) return null; 4018 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4019 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4020 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4021 } 4022 4023 @Override 4024 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4025 IntentFilter filter, int match, ComponentName activity) { 4026 final int userId = UserHandle.getCallingUserId(); 4027 if (DEBUG_PREFERRED) { 4028 Log.v(TAG, "setLastChosenActivity intent=" + intent 4029 + " resolvedType=" + resolvedType 4030 + " flags=" + flags 4031 + " filter=" + filter 4032 + " match=" + match 4033 + " activity=" + activity); 4034 filter.dump(new PrintStreamPrinter(System.out), " "); 4035 } 4036 intent.setComponent(null); 4037 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4038 // Find any earlier preferred or last chosen entries and nuke them 4039 findPreferredActivity(intent, resolvedType, 4040 flags, query, 0, false, true, false, userId); 4041 // Add the new activity as the last chosen for this filter 4042 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4043 "Setting last chosen"); 4044 } 4045 4046 @Override 4047 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4048 final int userId = UserHandle.getCallingUserId(); 4049 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4050 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4051 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4052 false, false, false, userId); 4053 } 4054 4055 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4056 int flags, List<ResolveInfo> query, int userId) { 4057 if (query != null) { 4058 final int N = query.size(); 4059 if (N == 1) { 4060 return query.get(0); 4061 } else if (N > 1) { 4062 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4063 // If there is more than one activity with the same priority, 4064 // then let the user decide between them. 4065 ResolveInfo r0 = query.get(0); 4066 ResolveInfo r1 = query.get(1); 4067 if (DEBUG_INTENT_MATCHING || debug) { 4068 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4069 + r1.activityInfo.name + "=" + r1.priority); 4070 } 4071 // If the first activity has a higher priority, or a different 4072 // default, then it is always desireable to pick it. 4073 if (r0.priority != r1.priority 4074 || r0.preferredOrder != r1.preferredOrder 4075 || r0.isDefault != r1.isDefault) { 4076 return query.get(0); 4077 } 4078 // If we have saved a preference for a preferred activity for 4079 // this Intent, use that. 4080 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4081 flags, query, r0.priority, true, false, debug, userId); 4082 if (ri != null) { 4083 return ri; 4084 } 4085 if (userId != 0) { 4086 ri = new ResolveInfo(mResolveInfo); 4087 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4088 ri.activityInfo.applicationInfo = new ApplicationInfo( 4089 ri.activityInfo.applicationInfo); 4090 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4091 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4092 return ri; 4093 } 4094 return mResolveInfo; 4095 } 4096 } 4097 return null; 4098 } 4099 4100 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4101 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4102 final int N = query.size(); 4103 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4104 .get(userId); 4105 // Get the list of persistent preferred activities that handle the intent 4106 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4107 List<PersistentPreferredActivity> pprefs = ppir != null 4108 ? ppir.queryIntent(intent, resolvedType, 4109 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4110 : null; 4111 if (pprefs != null && pprefs.size() > 0) { 4112 final int M = pprefs.size(); 4113 for (int i=0; i<M; i++) { 4114 final PersistentPreferredActivity ppa = pprefs.get(i); 4115 if (DEBUG_PREFERRED || debug) { 4116 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4117 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4118 + "\n component=" + ppa.mComponent); 4119 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4120 } 4121 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4122 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4123 if (DEBUG_PREFERRED || debug) { 4124 Slog.v(TAG, "Found persistent preferred activity:"); 4125 if (ai != null) { 4126 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4127 } else { 4128 Slog.v(TAG, " null"); 4129 } 4130 } 4131 if (ai == null) { 4132 // This previously registered persistent preferred activity 4133 // component is no longer known. Ignore it and do NOT remove it. 4134 continue; 4135 } 4136 for (int j=0; j<N; j++) { 4137 final ResolveInfo ri = query.get(j); 4138 if (!ri.activityInfo.applicationInfo.packageName 4139 .equals(ai.applicationInfo.packageName)) { 4140 continue; 4141 } 4142 if (!ri.activityInfo.name.equals(ai.name)) { 4143 continue; 4144 } 4145 // Found a persistent preference that can handle the intent. 4146 if (DEBUG_PREFERRED || debug) { 4147 Slog.v(TAG, "Returning persistent preferred activity: " + 4148 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4149 } 4150 return ri; 4151 } 4152 } 4153 } 4154 return null; 4155 } 4156 4157 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4158 List<ResolveInfo> query, int priority, boolean always, 4159 boolean removeMatches, boolean debug, int userId) { 4160 if (!sUserManager.exists(userId)) return null; 4161 // writer 4162 synchronized (mPackages) { 4163 if (intent.getSelector() != null) { 4164 intent = intent.getSelector(); 4165 } 4166 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4167 4168 // Try to find a matching persistent preferred activity. 4169 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4170 debug, userId); 4171 4172 // If a persistent preferred activity matched, use it. 4173 if (pri != null) { 4174 return pri; 4175 } 4176 4177 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4178 // Get the list of preferred activities that handle the intent 4179 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4180 List<PreferredActivity> prefs = pir != null 4181 ? pir.queryIntent(intent, resolvedType, 4182 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4183 : null; 4184 if (prefs != null && prefs.size() > 0) { 4185 boolean changed = false; 4186 try { 4187 // First figure out how good the original match set is. 4188 // We will only allow preferred activities that came 4189 // from the same match quality. 4190 int match = 0; 4191 4192 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4193 4194 final int N = query.size(); 4195 for (int j=0; j<N; j++) { 4196 final ResolveInfo ri = query.get(j); 4197 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4198 + ": 0x" + Integer.toHexString(match)); 4199 if (ri.match > match) { 4200 match = ri.match; 4201 } 4202 } 4203 4204 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4205 + Integer.toHexString(match)); 4206 4207 match &= IntentFilter.MATCH_CATEGORY_MASK; 4208 final int M = prefs.size(); 4209 for (int i=0; i<M; i++) { 4210 final PreferredActivity pa = prefs.get(i); 4211 if (DEBUG_PREFERRED || debug) { 4212 Slog.v(TAG, "Checking PreferredActivity ds=" 4213 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4214 + "\n component=" + pa.mPref.mComponent); 4215 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4216 } 4217 if (pa.mPref.mMatch != match) { 4218 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4219 + Integer.toHexString(pa.mPref.mMatch)); 4220 continue; 4221 } 4222 // If it's not an "always" type preferred activity and that's what we're 4223 // looking for, skip it. 4224 if (always && !pa.mPref.mAlways) { 4225 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4226 continue; 4227 } 4228 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4229 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4230 if (DEBUG_PREFERRED || debug) { 4231 Slog.v(TAG, "Found preferred activity:"); 4232 if (ai != null) { 4233 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4234 } else { 4235 Slog.v(TAG, " null"); 4236 } 4237 } 4238 if (ai == null) { 4239 // This previously registered preferred activity 4240 // component is no longer known. Most likely an update 4241 // to the app was installed and in the new version this 4242 // component no longer exists. Clean it up by removing 4243 // it from the preferred activities list, and skip it. 4244 Slog.w(TAG, "Removing dangling preferred activity: " 4245 + pa.mPref.mComponent); 4246 pir.removeFilter(pa); 4247 changed = true; 4248 continue; 4249 } 4250 for (int j=0; j<N; j++) { 4251 final ResolveInfo ri = query.get(j); 4252 if (!ri.activityInfo.applicationInfo.packageName 4253 .equals(ai.applicationInfo.packageName)) { 4254 continue; 4255 } 4256 if (!ri.activityInfo.name.equals(ai.name)) { 4257 continue; 4258 } 4259 4260 if (removeMatches) { 4261 pir.removeFilter(pa); 4262 changed = true; 4263 if (DEBUG_PREFERRED) { 4264 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4265 } 4266 break; 4267 } 4268 4269 // Okay we found a previously set preferred or last chosen app. 4270 // If the result set is different from when this 4271 // was created, we need to clear it and re-ask the 4272 // user their preference, if we're looking for an "always" type entry. 4273 if (always && !pa.mPref.sameSet(query)) { 4274 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4275 + intent + " type " + resolvedType); 4276 if (DEBUG_PREFERRED) { 4277 Slog.v(TAG, "Removing preferred activity since set changed " 4278 + pa.mPref.mComponent); 4279 } 4280 pir.removeFilter(pa); 4281 // Re-add the filter as a "last chosen" entry (!always) 4282 PreferredActivity lastChosen = new PreferredActivity( 4283 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4284 pir.addFilter(lastChosen); 4285 changed = true; 4286 return null; 4287 } 4288 4289 // Yay! Either the set matched or we're looking for the last chosen 4290 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4291 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4292 return ri; 4293 } 4294 } 4295 } finally { 4296 if (changed) { 4297 if (DEBUG_PREFERRED) { 4298 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4299 } 4300 scheduleWritePackageRestrictionsLocked(userId); 4301 } 4302 } 4303 } 4304 } 4305 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4306 return null; 4307 } 4308 4309 /* 4310 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4311 */ 4312 @Override 4313 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4314 int targetUserId) { 4315 mContext.enforceCallingOrSelfPermission( 4316 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4317 List<CrossProfileIntentFilter> matches = 4318 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4319 if (matches != null) { 4320 int size = matches.size(); 4321 for (int i = 0; i < size; i++) { 4322 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4323 } 4324 } 4325 if (hasWebURI(intent)) { 4326 // cross-profile app linking works only towards the parent. 4327 final UserInfo parent = getProfileParent(sourceUserId); 4328 synchronized(mPackages) { 4329 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4330 parent.id) != null; 4331 } 4332 } 4333 return false; 4334 } 4335 4336 private UserInfo getProfileParent(int userId) { 4337 final long identity = Binder.clearCallingIdentity(); 4338 try { 4339 return sUserManager.getProfileParent(userId); 4340 } finally { 4341 Binder.restoreCallingIdentity(identity); 4342 } 4343 } 4344 4345 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4346 String resolvedType, int userId) { 4347 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4348 if (resolver != null) { 4349 return resolver.queryIntent(intent, resolvedType, false, userId); 4350 } 4351 return null; 4352 } 4353 4354 @Override 4355 public List<ResolveInfo> queryIntentActivities(Intent intent, 4356 String resolvedType, int flags, int userId) { 4357 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4358 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4359 ComponentName comp = intent.getComponent(); 4360 if (comp == null) { 4361 if (intent.getSelector() != null) { 4362 intent = intent.getSelector(); 4363 comp = intent.getComponent(); 4364 } 4365 } 4366 4367 if (comp != null) { 4368 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4369 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4370 if (ai != null) { 4371 final ResolveInfo ri = new ResolveInfo(); 4372 ri.activityInfo = ai; 4373 list.add(ri); 4374 } 4375 return list; 4376 } 4377 4378 // reader 4379 synchronized (mPackages) { 4380 final String pkgName = intent.getPackage(); 4381 if (pkgName == null) { 4382 List<CrossProfileIntentFilter> matchingFilters = 4383 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4384 // Check for results that need to skip the current profile. 4385 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4386 resolvedType, flags, userId); 4387 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4388 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4389 result.add(xpResolveInfo); 4390 return filterIfNotPrimaryUser(result, userId); 4391 } 4392 4393 // Check for results in the current profile. 4394 List<ResolveInfo> result = mActivities.queryIntent( 4395 intent, resolvedType, flags, userId); 4396 4397 // Check for cross profile results. 4398 xpResolveInfo = queryCrossProfileIntents( 4399 matchingFilters, intent, resolvedType, flags, userId); 4400 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4401 result.add(xpResolveInfo); 4402 Collections.sort(result, mResolvePrioritySorter); 4403 } 4404 result = filterIfNotPrimaryUser(result, userId); 4405 if (hasWebURI(intent)) { 4406 CrossProfileDomainInfo xpDomainInfo = null; 4407 final UserInfo parent = getProfileParent(userId); 4408 if (parent != null) { 4409 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4410 flags, userId, parent.id); 4411 } 4412 if (xpDomainInfo != null) { 4413 if (xpResolveInfo != null) { 4414 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4415 // in the result. 4416 result.remove(xpResolveInfo); 4417 } 4418 if (result.size() == 0) { 4419 result.add(xpDomainInfo.resolveInfo); 4420 return result; 4421 } 4422 } else if (result.size() <= 1) { 4423 return result; 4424 } 4425 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4426 xpDomainInfo); 4427 Collections.sort(result, mResolvePrioritySorter); 4428 } 4429 return result; 4430 } 4431 final PackageParser.Package pkg = mPackages.get(pkgName); 4432 if (pkg != null) { 4433 return filterIfNotPrimaryUser( 4434 mActivities.queryIntentForPackage( 4435 intent, resolvedType, flags, pkg.activities, userId), 4436 userId); 4437 } 4438 return new ArrayList<ResolveInfo>(); 4439 } 4440 } 4441 4442 private static class CrossProfileDomainInfo { 4443 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4444 ResolveInfo resolveInfo; 4445 /* Best domain verification status of the activities found in the other profile */ 4446 int bestDomainVerificationStatus; 4447 } 4448 4449 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4450 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4451 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4452 sourceUserId)) { 4453 return null; 4454 } 4455 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4456 resolvedType, flags, parentUserId); 4457 4458 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4459 return null; 4460 } 4461 CrossProfileDomainInfo result = null; 4462 int size = resultTargetUser.size(); 4463 for (int i = 0; i < size; i++) { 4464 ResolveInfo riTargetUser = resultTargetUser.get(i); 4465 // Intent filter verification is only for filters that specify a host. So don't return 4466 // those that handle all web uris. 4467 if (riTargetUser.handleAllWebDataURI) { 4468 continue; 4469 } 4470 String packageName = riTargetUser.activityInfo.packageName; 4471 PackageSetting ps = mSettings.mPackages.get(packageName); 4472 if (ps == null) { 4473 continue; 4474 } 4475 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4476 if (result == null) { 4477 result = new CrossProfileDomainInfo(); 4478 result.resolveInfo = 4479 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4480 result.bestDomainVerificationStatus = status; 4481 } else { 4482 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4483 result.bestDomainVerificationStatus); 4484 } 4485 } 4486 return result; 4487 } 4488 4489 /** 4490 * Verification statuses are ordered from the worse to the best, except for 4491 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4492 */ 4493 private int bestDomainVerificationStatus(int status1, int status2) { 4494 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4495 return status2; 4496 } 4497 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4498 return status1; 4499 } 4500 return (int) MathUtils.max(status1, status2); 4501 } 4502 4503 private boolean isUserEnabled(int userId) { 4504 long callingId = Binder.clearCallingIdentity(); 4505 try { 4506 UserInfo userInfo = sUserManager.getUserInfo(userId); 4507 return userInfo != null && userInfo.isEnabled(); 4508 } finally { 4509 Binder.restoreCallingIdentity(callingId); 4510 } 4511 } 4512 4513 /** 4514 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4515 * 4516 * @return filtered list 4517 */ 4518 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4519 if (userId == UserHandle.USER_OWNER) { 4520 return resolveInfos; 4521 } 4522 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4523 ResolveInfo info = resolveInfos.get(i); 4524 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4525 resolveInfos.remove(i); 4526 } 4527 } 4528 return resolveInfos; 4529 } 4530 4531 private static boolean hasWebURI(Intent intent) { 4532 if (intent.getData() == null) { 4533 return false; 4534 } 4535 final String scheme = intent.getScheme(); 4536 if (TextUtils.isEmpty(scheme)) { 4537 return false; 4538 } 4539 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4540 } 4541 4542 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4543 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4544 if (DEBUG_PREFERRED) { 4545 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4546 candidates.size()); 4547 } 4548 4549 final int userId = UserHandle.getCallingUserId(); 4550 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4551 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4552 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4553 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4554 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4555 4556 synchronized (mPackages) { 4557 final int count = candidates.size(); 4558 // First, try to use the domain preferred app. Partition the candidates into four lists: 4559 // one for the final results, one for the "do not use ever", one for "undefined status" 4560 // and finally one for "Browser App type". 4561 for (int n=0; n<count; n++) { 4562 ResolveInfo info = candidates.get(n); 4563 String packageName = info.activityInfo.packageName; 4564 PackageSetting ps = mSettings.mPackages.get(packageName); 4565 if (ps != null) { 4566 // Add to the special match all list (Browser use case) 4567 if (info.handleAllWebDataURI) { 4568 matchAllList.add(info); 4569 continue; 4570 } 4571 // Try to get the status from User settings first 4572 int status = getDomainVerificationStatusLPr(ps, userId); 4573 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4574 alwaysList.add(info); 4575 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4576 neverList.add(info); 4577 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4578 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4579 undefinedList.add(info); 4580 } 4581 } 4582 } 4583 // First try to add the "always" resolution for the current user if there is any 4584 if (alwaysList.size() > 0) { 4585 result.addAll(alwaysList); 4586 // if there is an "always" for the parent user, add it. 4587 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4588 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4589 result.add(xpDomainInfo.resolveInfo); 4590 } else { 4591 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4592 result.addAll(undefinedList); 4593 if (xpDomainInfo != null && ( 4594 xpDomainInfo.bestDomainVerificationStatus 4595 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4596 || xpDomainInfo.bestDomainVerificationStatus 4597 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4598 result.add(xpDomainInfo.resolveInfo); 4599 } 4600 // Also add Browsers (all of them or only the default one) 4601 if ((flags & MATCH_ALL) != 0) { 4602 result.addAll(matchAllList); 4603 } else { 4604 // Try to add the Default Browser if we can 4605 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4606 UserHandle.myUserId()); 4607 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4608 boolean defaultBrowserFound = false; 4609 final int browserCount = matchAllList.size(); 4610 for (int n=0; n<browserCount; n++) { 4611 ResolveInfo browser = matchAllList.get(n); 4612 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4613 result.add(browser); 4614 defaultBrowserFound = true; 4615 break; 4616 } 4617 } 4618 if (!defaultBrowserFound) { 4619 result.addAll(matchAllList); 4620 } 4621 } else { 4622 result.addAll(matchAllList); 4623 } 4624 } 4625 4626 // If there is nothing selected, add all candidates and remove the ones that the User 4627 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4628 if (result.size() == 0) { 4629 result.addAll(candidates); 4630 result.removeAll(neverList); 4631 } 4632 } 4633 } 4634 if (DEBUG_PREFERRED) { 4635 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4636 result.size()); 4637 } 4638 return result; 4639 } 4640 4641 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4642 int status = ps.getDomainVerificationStatusForUser(userId); 4643 // if none available, get the master status 4644 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4645 if (ps.getIntentFilterVerificationInfo() != null) { 4646 status = ps.getIntentFilterVerificationInfo().getStatus(); 4647 } 4648 } 4649 return status; 4650 } 4651 4652 private ResolveInfo querySkipCurrentProfileIntents( 4653 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4654 int flags, int sourceUserId) { 4655 if (matchingFilters != null) { 4656 int size = matchingFilters.size(); 4657 for (int i = 0; i < size; i ++) { 4658 CrossProfileIntentFilter filter = matchingFilters.get(i); 4659 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4660 // Checking if there are activities in the target user that can handle the 4661 // intent. 4662 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4663 flags, sourceUserId); 4664 if (resolveInfo != null) { 4665 return resolveInfo; 4666 } 4667 } 4668 } 4669 } 4670 return null; 4671 } 4672 4673 // Return matching ResolveInfo if any for skip current profile intent filters. 4674 private ResolveInfo queryCrossProfileIntents( 4675 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4676 int flags, int sourceUserId) { 4677 if (matchingFilters != null) { 4678 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4679 // match the same intent. For performance reasons, it is better not to 4680 // run queryIntent twice for the same userId 4681 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4682 int size = matchingFilters.size(); 4683 for (int i = 0; i < size; i++) { 4684 CrossProfileIntentFilter filter = matchingFilters.get(i); 4685 int targetUserId = filter.getTargetUserId(); 4686 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4687 && !alreadyTriedUserIds.get(targetUserId)) { 4688 // Checking if there are activities in the target user that can handle the 4689 // intent. 4690 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4691 flags, sourceUserId); 4692 if (resolveInfo != null) return resolveInfo; 4693 alreadyTriedUserIds.put(targetUserId, true); 4694 } 4695 } 4696 } 4697 return null; 4698 } 4699 4700 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4701 String resolvedType, int flags, int sourceUserId) { 4702 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4703 resolvedType, flags, filter.getTargetUserId()); 4704 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4705 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4706 } 4707 return null; 4708 } 4709 4710 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4711 int sourceUserId, int targetUserId) { 4712 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4713 String className; 4714 if (targetUserId == UserHandle.USER_OWNER) { 4715 className = FORWARD_INTENT_TO_USER_OWNER; 4716 } else { 4717 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4718 } 4719 ComponentName forwardingActivityComponentName = new ComponentName( 4720 mAndroidApplication.packageName, className); 4721 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4722 sourceUserId); 4723 if (targetUserId == UserHandle.USER_OWNER) { 4724 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4725 forwardingResolveInfo.noResourceId = true; 4726 } 4727 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4728 forwardingResolveInfo.priority = 0; 4729 forwardingResolveInfo.preferredOrder = 0; 4730 forwardingResolveInfo.match = 0; 4731 forwardingResolveInfo.isDefault = true; 4732 forwardingResolveInfo.filter = filter; 4733 forwardingResolveInfo.targetUserId = targetUserId; 4734 return forwardingResolveInfo; 4735 } 4736 4737 @Override 4738 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4739 Intent[] specifics, String[] specificTypes, Intent intent, 4740 String resolvedType, int flags, int userId) { 4741 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4742 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4743 false, "query intent activity options"); 4744 final String resultsAction = intent.getAction(); 4745 4746 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4747 | PackageManager.GET_RESOLVED_FILTER, userId); 4748 4749 if (DEBUG_INTENT_MATCHING) { 4750 Log.v(TAG, "Query " + intent + ": " + results); 4751 } 4752 4753 int specificsPos = 0; 4754 int N; 4755 4756 // todo: note that the algorithm used here is O(N^2). This 4757 // isn't a problem in our current environment, but if we start running 4758 // into situations where we have more than 5 or 10 matches then this 4759 // should probably be changed to something smarter... 4760 4761 // First we go through and resolve each of the specific items 4762 // that were supplied, taking care of removing any corresponding 4763 // duplicate items in the generic resolve list. 4764 if (specifics != null) { 4765 for (int i=0; i<specifics.length; i++) { 4766 final Intent sintent = specifics[i]; 4767 if (sintent == null) { 4768 continue; 4769 } 4770 4771 if (DEBUG_INTENT_MATCHING) { 4772 Log.v(TAG, "Specific #" + i + ": " + sintent); 4773 } 4774 4775 String action = sintent.getAction(); 4776 if (resultsAction != null && resultsAction.equals(action)) { 4777 // If this action was explicitly requested, then don't 4778 // remove things that have it. 4779 action = null; 4780 } 4781 4782 ResolveInfo ri = null; 4783 ActivityInfo ai = null; 4784 4785 ComponentName comp = sintent.getComponent(); 4786 if (comp == null) { 4787 ri = resolveIntent( 4788 sintent, 4789 specificTypes != null ? specificTypes[i] : null, 4790 flags, userId); 4791 if (ri == null) { 4792 continue; 4793 } 4794 if (ri == mResolveInfo) { 4795 // ACK! Must do something better with this. 4796 } 4797 ai = ri.activityInfo; 4798 comp = new ComponentName(ai.applicationInfo.packageName, 4799 ai.name); 4800 } else { 4801 ai = getActivityInfo(comp, flags, userId); 4802 if (ai == null) { 4803 continue; 4804 } 4805 } 4806 4807 // Look for any generic query activities that are duplicates 4808 // of this specific one, and remove them from the results. 4809 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4810 N = results.size(); 4811 int j; 4812 for (j=specificsPos; j<N; j++) { 4813 ResolveInfo sri = results.get(j); 4814 if ((sri.activityInfo.name.equals(comp.getClassName()) 4815 && sri.activityInfo.applicationInfo.packageName.equals( 4816 comp.getPackageName())) 4817 || (action != null && sri.filter.matchAction(action))) { 4818 results.remove(j); 4819 if (DEBUG_INTENT_MATCHING) Log.v( 4820 TAG, "Removing duplicate item from " + j 4821 + " due to specific " + specificsPos); 4822 if (ri == null) { 4823 ri = sri; 4824 } 4825 j--; 4826 N--; 4827 } 4828 } 4829 4830 // Add this specific item to its proper place. 4831 if (ri == null) { 4832 ri = new ResolveInfo(); 4833 ri.activityInfo = ai; 4834 } 4835 results.add(specificsPos, ri); 4836 ri.specificIndex = i; 4837 specificsPos++; 4838 } 4839 } 4840 4841 // Now we go through the remaining generic results and remove any 4842 // duplicate actions that are found here. 4843 N = results.size(); 4844 for (int i=specificsPos; i<N-1; i++) { 4845 final ResolveInfo rii = results.get(i); 4846 if (rii.filter == null) { 4847 continue; 4848 } 4849 4850 // Iterate over all of the actions of this result's intent 4851 // filter... typically this should be just one. 4852 final Iterator<String> it = rii.filter.actionsIterator(); 4853 if (it == null) { 4854 continue; 4855 } 4856 while (it.hasNext()) { 4857 final String action = it.next(); 4858 if (resultsAction != null && resultsAction.equals(action)) { 4859 // If this action was explicitly requested, then don't 4860 // remove things that have it. 4861 continue; 4862 } 4863 for (int j=i+1; j<N; j++) { 4864 final ResolveInfo rij = results.get(j); 4865 if (rij.filter != null && rij.filter.hasAction(action)) { 4866 results.remove(j); 4867 if (DEBUG_INTENT_MATCHING) Log.v( 4868 TAG, "Removing duplicate item from " + j 4869 + " due to action " + action + " at " + i); 4870 j--; 4871 N--; 4872 } 4873 } 4874 } 4875 4876 // If the caller didn't request filter information, drop it now 4877 // so we don't have to marshall/unmarshall it. 4878 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4879 rii.filter = null; 4880 } 4881 } 4882 4883 // Filter out the caller activity if so requested. 4884 if (caller != null) { 4885 N = results.size(); 4886 for (int i=0; i<N; i++) { 4887 ActivityInfo ainfo = results.get(i).activityInfo; 4888 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4889 && caller.getClassName().equals(ainfo.name)) { 4890 results.remove(i); 4891 break; 4892 } 4893 } 4894 } 4895 4896 // If the caller didn't request filter information, 4897 // drop them now so we don't have to 4898 // marshall/unmarshall it. 4899 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4900 N = results.size(); 4901 for (int i=0; i<N; i++) { 4902 results.get(i).filter = null; 4903 } 4904 } 4905 4906 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4907 return results; 4908 } 4909 4910 @Override 4911 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4912 int userId) { 4913 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4914 ComponentName comp = intent.getComponent(); 4915 if (comp == null) { 4916 if (intent.getSelector() != null) { 4917 intent = intent.getSelector(); 4918 comp = intent.getComponent(); 4919 } 4920 } 4921 if (comp != null) { 4922 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4923 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4924 if (ai != null) { 4925 ResolveInfo ri = new ResolveInfo(); 4926 ri.activityInfo = ai; 4927 list.add(ri); 4928 } 4929 return list; 4930 } 4931 4932 // reader 4933 synchronized (mPackages) { 4934 String pkgName = intent.getPackage(); 4935 if (pkgName == null) { 4936 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4937 } 4938 final PackageParser.Package pkg = mPackages.get(pkgName); 4939 if (pkg != null) { 4940 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4941 userId); 4942 } 4943 return null; 4944 } 4945 } 4946 4947 @Override 4948 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4949 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4950 if (!sUserManager.exists(userId)) return null; 4951 if (query != null) { 4952 if (query.size() >= 1) { 4953 // If there is more than one service with the same priority, 4954 // just arbitrarily pick the first one. 4955 return query.get(0); 4956 } 4957 } 4958 return null; 4959 } 4960 4961 @Override 4962 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4963 int userId) { 4964 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4965 ComponentName comp = intent.getComponent(); 4966 if (comp == null) { 4967 if (intent.getSelector() != null) { 4968 intent = intent.getSelector(); 4969 comp = intent.getComponent(); 4970 } 4971 } 4972 if (comp != null) { 4973 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4974 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4975 if (si != null) { 4976 final ResolveInfo ri = new ResolveInfo(); 4977 ri.serviceInfo = si; 4978 list.add(ri); 4979 } 4980 return list; 4981 } 4982 4983 // reader 4984 synchronized (mPackages) { 4985 String pkgName = intent.getPackage(); 4986 if (pkgName == null) { 4987 return mServices.queryIntent(intent, resolvedType, flags, userId); 4988 } 4989 final PackageParser.Package pkg = mPackages.get(pkgName); 4990 if (pkg != null) { 4991 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4992 userId); 4993 } 4994 return null; 4995 } 4996 } 4997 4998 @Override 4999 public List<ResolveInfo> queryIntentContentProviders( 5000 Intent intent, String resolvedType, int flags, int userId) { 5001 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5002 ComponentName comp = intent.getComponent(); 5003 if (comp == null) { 5004 if (intent.getSelector() != null) { 5005 intent = intent.getSelector(); 5006 comp = intent.getComponent(); 5007 } 5008 } 5009 if (comp != null) { 5010 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5011 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5012 if (pi != null) { 5013 final ResolveInfo ri = new ResolveInfo(); 5014 ri.providerInfo = pi; 5015 list.add(ri); 5016 } 5017 return list; 5018 } 5019 5020 // reader 5021 synchronized (mPackages) { 5022 String pkgName = intent.getPackage(); 5023 if (pkgName == null) { 5024 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5025 } 5026 final PackageParser.Package pkg = mPackages.get(pkgName); 5027 if (pkg != null) { 5028 return mProviders.queryIntentForPackage( 5029 intent, resolvedType, flags, pkg.providers, userId); 5030 } 5031 return null; 5032 } 5033 } 5034 5035 @Override 5036 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5037 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5038 5039 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5040 5041 // writer 5042 synchronized (mPackages) { 5043 ArrayList<PackageInfo> list; 5044 if (listUninstalled) { 5045 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5046 for (PackageSetting ps : mSettings.mPackages.values()) { 5047 PackageInfo pi; 5048 if (ps.pkg != null) { 5049 pi = generatePackageInfo(ps.pkg, flags, userId); 5050 } else { 5051 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5052 } 5053 if (pi != null) { 5054 list.add(pi); 5055 } 5056 } 5057 } else { 5058 list = new ArrayList<PackageInfo>(mPackages.size()); 5059 for (PackageParser.Package p : mPackages.values()) { 5060 PackageInfo pi = generatePackageInfo(p, flags, userId); 5061 if (pi != null) { 5062 list.add(pi); 5063 } 5064 } 5065 } 5066 5067 return new ParceledListSlice<PackageInfo>(list); 5068 } 5069 } 5070 5071 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5072 String[] permissions, boolean[] tmp, int flags, int userId) { 5073 int numMatch = 0; 5074 final PermissionsState permissionsState = ps.getPermissionsState(); 5075 for (int i=0; i<permissions.length; i++) { 5076 final String permission = permissions[i]; 5077 if (permissionsState.hasPermission(permission, userId)) { 5078 tmp[i] = true; 5079 numMatch++; 5080 } else { 5081 tmp[i] = false; 5082 } 5083 } 5084 if (numMatch == 0) { 5085 return; 5086 } 5087 PackageInfo pi; 5088 if (ps.pkg != null) { 5089 pi = generatePackageInfo(ps.pkg, flags, userId); 5090 } else { 5091 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5092 } 5093 // The above might return null in cases of uninstalled apps or install-state 5094 // skew across users/profiles. 5095 if (pi != null) { 5096 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5097 if (numMatch == permissions.length) { 5098 pi.requestedPermissions = permissions; 5099 } else { 5100 pi.requestedPermissions = new String[numMatch]; 5101 numMatch = 0; 5102 for (int i=0; i<permissions.length; i++) { 5103 if (tmp[i]) { 5104 pi.requestedPermissions[numMatch] = permissions[i]; 5105 numMatch++; 5106 } 5107 } 5108 } 5109 } 5110 list.add(pi); 5111 } 5112 } 5113 5114 @Override 5115 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5116 String[] permissions, int flags, int userId) { 5117 if (!sUserManager.exists(userId)) return null; 5118 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5119 5120 // writer 5121 synchronized (mPackages) { 5122 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5123 boolean[] tmpBools = new boolean[permissions.length]; 5124 if (listUninstalled) { 5125 for (PackageSetting ps : mSettings.mPackages.values()) { 5126 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5127 } 5128 } else { 5129 for (PackageParser.Package pkg : mPackages.values()) { 5130 PackageSetting ps = (PackageSetting)pkg.mExtras; 5131 if (ps != null) { 5132 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5133 userId); 5134 } 5135 } 5136 } 5137 5138 return new ParceledListSlice<PackageInfo>(list); 5139 } 5140 } 5141 5142 @Override 5143 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5144 if (!sUserManager.exists(userId)) return null; 5145 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5146 5147 // writer 5148 synchronized (mPackages) { 5149 ArrayList<ApplicationInfo> list; 5150 if (listUninstalled) { 5151 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5152 for (PackageSetting ps : mSettings.mPackages.values()) { 5153 ApplicationInfo ai; 5154 if (ps.pkg != null) { 5155 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5156 ps.readUserState(userId), userId); 5157 } else { 5158 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5159 } 5160 if (ai != null) { 5161 list.add(ai); 5162 } 5163 } 5164 } else { 5165 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5166 for (PackageParser.Package p : mPackages.values()) { 5167 if (p.mExtras != null) { 5168 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5169 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5170 if (ai != null) { 5171 list.add(ai); 5172 } 5173 } 5174 } 5175 } 5176 5177 return new ParceledListSlice<ApplicationInfo>(list); 5178 } 5179 } 5180 5181 public List<ApplicationInfo> getPersistentApplications(int flags) { 5182 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5183 5184 // reader 5185 synchronized (mPackages) { 5186 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5187 final int userId = UserHandle.getCallingUserId(); 5188 while (i.hasNext()) { 5189 final PackageParser.Package p = i.next(); 5190 if (p.applicationInfo != null 5191 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5192 && (!mSafeMode || isSystemApp(p))) { 5193 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5194 if (ps != null) { 5195 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5196 ps.readUserState(userId), userId); 5197 if (ai != null) { 5198 finalList.add(ai); 5199 } 5200 } 5201 } 5202 } 5203 } 5204 5205 return finalList; 5206 } 5207 5208 @Override 5209 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5210 if (!sUserManager.exists(userId)) return null; 5211 // reader 5212 synchronized (mPackages) { 5213 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5214 PackageSetting ps = provider != null 5215 ? mSettings.mPackages.get(provider.owner.packageName) 5216 : null; 5217 return ps != null 5218 && mSettings.isEnabledLPr(provider.info, flags, userId) 5219 && (!mSafeMode || (provider.info.applicationInfo.flags 5220 &ApplicationInfo.FLAG_SYSTEM) != 0) 5221 ? PackageParser.generateProviderInfo(provider, flags, 5222 ps.readUserState(userId), userId) 5223 : null; 5224 } 5225 } 5226 5227 /** 5228 * @deprecated 5229 */ 5230 @Deprecated 5231 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5232 // reader 5233 synchronized (mPackages) { 5234 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5235 .entrySet().iterator(); 5236 final int userId = UserHandle.getCallingUserId(); 5237 while (i.hasNext()) { 5238 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5239 PackageParser.Provider p = entry.getValue(); 5240 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5241 5242 if (ps != null && p.syncable 5243 && (!mSafeMode || (p.info.applicationInfo.flags 5244 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5245 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5246 ps.readUserState(userId), userId); 5247 if (info != null) { 5248 outNames.add(entry.getKey()); 5249 outInfo.add(info); 5250 } 5251 } 5252 } 5253 } 5254 } 5255 5256 @Override 5257 public List<ProviderInfo> queryContentProviders(String processName, 5258 int uid, int flags) { 5259 ArrayList<ProviderInfo> finalList = null; 5260 // reader 5261 synchronized (mPackages) { 5262 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5263 final int userId = processName != null ? 5264 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5265 while (i.hasNext()) { 5266 final PackageParser.Provider p = i.next(); 5267 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5268 if (ps != null && p.info.authority != null 5269 && (processName == null 5270 || (p.info.processName.equals(processName) 5271 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5272 && mSettings.isEnabledLPr(p.info, flags, userId) 5273 && (!mSafeMode 5274 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5275 if (finalList == null) { 5276 finalList = new ArrayList<ProviderInfo>(3); 5277 } 5278 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5279 ps.readUserState(userId), userId); 5280 if (info != null) { 5281 finalList.add(info); 5282 } 5283 } 5284 } 5285 } 5286 5287 if (finalList != null) { 5288 Collections.sort(finalList, mProviderInitOrderSorter); 5289 } 5290 5291 return finalList; 5292 } 5293 5294 @Override 5295 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5296 int flags) { 5297 // reader 5298 synchronized (mPackages) { 5299 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5300 return PackageParser.generateInstrumentationInfo(i, flags); 5301 } 5302 } 5303 5304 @Override 5305 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5306 int flags) { 5307 ArrayList<InstrumentationInfo> finalList = 5308 new ArrayList<InstrumentationInfo>(); 5309 5310 // reader 5311 synchronized (mPackages) { 5312 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5313 while (i.hasNext()) { 5314 final PackageParser.Instrumentation p = i.next(); 5315 if (targetPackage == null 5316 || targetPackage.equals(p.info.targetPackage)) { 5317 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5318 flags); 5319 if (ii != null) { 5320 finalList.add(ii); 5321 } 5322 } 5323 } 5324 } 5325 5326 return finalList; 5327 } 5328 5329 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5330 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5331 if (overlays == null) { 5332 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5333 return; 5334 } 5335 for (PackageParser.Package opkg : overlays.values()) { 5336 // Not much to do if idmap fails: we already logged the error 5337 // and we certainly don't want to abort installation of pkg simply 5338 // because an overlay didn't fit properly. For these reasons, 5339 // ignore the return value of createIdmapForPackagePairLI. 5340 createIdmapForPackagePairLI(pkg, opkg); 5341 } 5342 } 5343 5344 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5345 PackageParser.Package opkg) { 5346 if (!opkg.mTrustedOverlay) { 5347 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5348 opkg.baseCodePath + ": overlay not trusted"); 5349 return false; 5350 } 5351 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5352 if (overlaySet == null) { 5353 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5354 opkg.baseCodePath + " but target package has no known overlays"); 5355 return false; 5356 } 5357 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5358 // TODO: generate idmap for split APKs 5359 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5360 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5361 + opkg.baseCodePath); 5362 return false; 5363 } 5364 PackageParser.Package[] overlayArray = 5365 overlaySet.values().toArray(new PackageParser.Package[0]); 5366 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5367 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5368 return p1.mOverlayPriority - p2.mOverlayPriority; 5369 } 5370 }; 5371 Arrays.sort(overlayArray, cmp); 5372 5373 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5374 int i = 0; 5375 for (PackageParser.Package p : overlayArray) { 5376 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5377 } 5378 return true; 5379 } 5380 5381 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5382 final File[] files = dir.listFiles(); 5383 if (ArrayUtils.isEmpty(files)) { 5384 Log.d(TAG, "No files in app dir " + dir); 5385 return; 5386 } 5387 5388 if (DEBUG_PACKAGE_SCANNING) { 5389 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5390 + " flags=0x" + Integer.toHexString(parseFlags)); 5391 } 5392 5393 for (File file : files) { 5394 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5395 && !PackageInstallerService.isStageName(file.getName()); 5396 if (!isPackage) { 5397 // Ignore entries which are not packages 5398 continue; 5399 } 5400 try { 5401 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5402 scanFlags, currentTime, null); 5403 } catch (PackageManagerException e) { 5404 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5405 5406 // Delete invalid userdata apps 5407 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5408 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5409 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5410 if (file.isDirectory()) { 5411 mInstaller.rmPackageDir(file.getAbsolutePath()); 5412 } else { 5413 file.delete(); 5414 } 5415 } 5416 } 5417 } 5418 } 5419 5420 private static File getSettingsProblemFile() { 5421 File dataDir = Environment.getDataDirectory(); 5422 File systemDir = new File(dataDir, "system"); 5423 File fname = new File(systemDir, "uiderrors.txt"); 5424 return fname; 5425 } 5426 5427 static void reportSettingsProblem(int priority, String msg) { 5428 logCriticalInfo(priority, msg); 5429 } 5430 5431 static void logCriticalInfo(int priority, String msg) { 5432 Slog.println(priority, TAG, msg); 5433 EventLogTags.writePmCriticalInfo(msg); 5434 try { 5435 File fname = getSettingsProblemFile(); 5436 FileOutputStream out = new FileOutputStream(fname, true); 5437 PrintWriter pw = new FastPrintWriter(out); 5438 SimpleDateFormat formatter = new SimpleDateFormat(); 5439 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5440 pw.println(dateString + ": " + msg); 5441 pw.close(); 5442 FileUtils.setPermissions( 5443 fname.toString(), 5444 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5445 -1, -1); 5446 } catch (java.io.IOException e) { 5447 } 5448 } 5449 5450 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5451 PackageParser.Package pkg, File srcFile, int parseFlags) 5452 throws PackageManagerException { 5453 if (ps != null 5454 && ps.codePath.equals(srcFile) 5455 && ps.timeStamp == srcFile.lastModified() 5456 && !isCompatSignatureUpdateNeeded(pkg) 5457 && !isRecoverSignatureUpdateNeeded(pkg)) { 5458 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5459 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5460 ArraySet<PublicKey> signingKs; 5461 synchronized (mPackages) { 5462 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5463 } 5464 if (ps.signatures.mSignatures != null 5465 && ps.signatures.mSignatures.length != 0 5466 && signingKs != null) { 5467 // Optimization: reuse the existing cached certificates 5468 // if the package appears to be unchanged. 5469 pkg.mSignatures = ps.signatures.mSignatures; 5470 pkg.mSigningKeys = signingKs; 5471 return; 5472 } 5473 5474 Slog.w(TAG, "PackageSetting for " + ps.name 5475 + " is missing signatures. Collecting certs again to recover them."); 5476 } else { 5477 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5478 } 5479 5480 try { 5481 pp.collectCertificates(pkg, parseFlags); 5482 pp.collectManifestDigest(pkg); 5483 } catch (PackageParserException e) { 5484 throw PackageManagerException.from(e); 5485 } 5486 } 5487 5488 /* 5489 * Scan a package and return the newly parsed package. 5490 * Returns null in case of errors and the error code is stored in mLastScanError 5491 */ 5492 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5493 long currentTime, UserHandle user) throws PackageManagerException { 5494 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5495 parseFlags |= mDefParseFlags; 5496 PackageParser pp = new PackageParser(); 5497 pp.setSeparateProcesses(mSeparateProcesses); 5498 pp.setOnlyCoreApps(mOnlyCore); 5499 pp.setDisplayMetrics(mMetrics); 5500 5501 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5502 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5503 } 5504 5505 final PackageParser.Package pkg; 5506 try { 5507 pkg = pp.parsePackage(scanFile, parseFlags); 5508 } catch (PackageParserException e) { 5509 throw PackageManagerException.from(e); 5510 } 5511 5512 PackageSetting ps = null; 5513 PackageSetting updatedPkg; 5514 // reader 5515 synchronized (mPackages) { 5516 // Look to see if we already know about this package. 5517 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5518 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5519 // This package has been renamed to its original name. Let's 5520 // use that. 5521 ps = mSettings.peekPackageLPr(oldName); 5522 } 5523 // If there was no original package, see one for the real package name. 5524 if (ps == null) { 5525 ps = mSettings.peekPackageLPr(pkg.packageName); 5526 } 5527 // Check to see if this package could be hiding/updating a system 5528 // package. Must look for it either under the original or real 5529 // package name depending on our state. 5530 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5531 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5532 } 5533 boolean updatedPkgBetter = false; 5534 // First check if this is a system package that may involve an update 5535 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5536 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5537 // it needs to drop FLAG_PRIVILEGED. 5538 if (locationIsPrivileged(scanFile)) { 5539 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5540 } else { 5541 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5542 } 5543 5544 if (ps != null && !ps.codePath.equals(scanFile)) { 5545 // The path has changed from what was last scanned... check the 5546 // version of the new path against what we have stored to determine 5547 // what to do. 5548 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5549 if (pkg.mVersionCode <= ps.versionCode) { 5550 // The system package has been updated and the code path does not match 5551 // Ignore entry. Skip it. 5552 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5553 + " ignored: updated version " + ps.versionCode 5554 + " better than this " + pkg.mVersionCode); 5555 if (!updatedPkg.codePath.equals(scanFile)) { 5556 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5557 + ps.name + " changing from " + updatedPkg.codePathString 5558 + " to " + scanFile); 5559 updatedPkg.codePath = scanFile; 5560 updatedPkg.codePathString = scanFile.toString(); 5561 updatedPkg.resourcePath = scanFile; 5562 updatedPkg.resourcePathString = scanFile.toString(); 5563 } 5564 updatedPkg.pkg = pkg; 5565 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5566 } else { 5567 // The current app on the system partition is better than 5568 // what we have updated to on the data partition; switch 5569 // back to the system partition version. 5570 // At this point, its safely assumed that package installation for 5571 // apps in system partition will go through. If not there won't be a working 5572 // version of the app 5573 // writer 5574 synchronized (mPackages) { 5575 // Just remove the loaded entries from package lists. 5576 mPackages.remove(ps.name); 5577 } 5578 5579 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5580 + " reverting from " + ps.codePathString 5581 + ": new version " + pkg.mVersionCode 5582 + " better than installed " + ps.versionCode); 5583 5584 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5585 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5586 synchronized (mInstallLock) { 5587 args.cleanUpResourcesLI(); 5588 } 5589 synchronized (mPackages) { 5590 mSettings.enableSystemPackageLPw(ps.name); 5591 } 5592 updatedPkgBetter = true; 5593 } 5594 } 5595 } 5596 5597 if (updatedPkg != null) { 5598 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5599 // initially 5600 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5601 5602 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5603 // flag set initially 5604 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5605 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5606 } 5607 } 5608 5609 // Verify certificates against what was last scanned 5610 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5611 5612 /* 5613 * A new system app appeared, but we already had a non-system one of the 5614 * same name installed earlier. 5615 */ 5616 boolean shouldHideSystemApp = false; 5617 if (updatedPkg == null && ps != null 5618 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5619 /* 5620 * Check to make sure the signatures match first. If they don't, 5621 * wipe the installed application and its data. 5622 */ 5623 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5624 != PackageManager.SIGNATURE_MATCH) { 5625 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5626 + " signatures don't match existing userdata copy; removing"); 5627 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5628 ps = null; 5629 } else { 5630 /* 5631 * If the newly-added system app is an older version than the 5632 * already installed version, hide it. It will be scanned later 5633 * and re-added like an update. 5634 */ 5635 if (pkg.mVersionCode <= ps.versionCode) { 5636 shouldHideSystemApp = true; 5637 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5638 + " but new version " + pkg.mVersionCode + " better than installed " 5639 + ps.versionCode + "; hiding system"); 5640 } else { 5641 /* 5642 * The newly found system app is a newer version that the 5643 * one previously installed. Simply remove the 5644 * already-installed application and replace it with our own 5645 * while keeping the application data. 5646 */ 5647 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5648 + " reverting from " + ps.codePathString + ": new version " 5649 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5650 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5651 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5652 synchronized (mInstallLock) { 5653 args.cleanUpResourcesLI(); 5654 } 5655 } 5656 } 5657 } 5658 5659 // The apk is forward locked (not public) if its code and resources 5660 // are kept in different files. (except for app in either system or 5661 // vendor path). 5662 // TODO grab this value from PackageSettings 5663 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5664 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5665 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5666 } 5667 } 5668 5669 // TODO: extend to support forward-locked splits 5670 String resourcePath = null; 5671 String baseResourcePath = null; 5672 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5673 if (ps != null && ps.resourcePathString != null) { 5674 resourcePath = ps.resourcePathString; 5675 baseResourcePath = ps.resourcePathString; 5676 } else { 5677 // Should not happen at all. Just log an error. 5678 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5679 } 5680 } else { 5681 resourcePath = pkg.codePath; 5682 baseResourcePath = pkg.baseCodePath; 5683 } 5684 5685 // Set application objects path explicitly. 5686 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5687 pkg.applicationInfo.setCodePath(pkg.codePath); 5688 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5689 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5690 pkg.applicationInfo.setResourcePath(resourcePath); 5691 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5692 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5693 5694 // Note that we invoke the following method only if we are about to unpack an application 5695 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5696 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5697 5698 /* 5699 * If the system app should be overridden by a previously installed 5700 * data, hide the system app now and let the /data/app scan pick it up 5701 * again. 5702 */ 5703 if (shouldHideSystemApp) { 5704 synchronized (mPackages) { 5705 /* 5706 * We have to grant systems permissions before we hide, because 5707 * grantPermissions will assume the package update is trying to 5708 * expand its permissions. 5709 */ 5710 grantPermissionsLPw(pkg, true, pkg.packageName); 5711 mSettings.disableSystemPackageLPw(pkg.packageName); 5712 } 5713 } 5714 5715 return scannedPkg; 5716 } 5717 5718 private static String fixProcessName(String defProcessName, 5719 String processName, int uid) { 5720 if (processName == null) { 5721 return defProcessName; 5722 } 5723 return processName; 5724 } 5725 5726 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5727 throws PackageManagerException { 5728 if (pkgSetting.signatures.mSignatures != null) { 5729 // Already existing package. Make sure signatures match 5730 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5731 == PackageManager.SIGNATURE_MATCH; 5732 if (!match) { 5733 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5734 == PackageManager.SIGNATURE_MATCH; 5735 } 5736 if (!match) { 5737 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5738 == PackageManager.SIGNATURE_MATCH; 5739 } 5740 if (!match) { 5741 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5742 + pkg.packageName + " signatures do not match the " 5743 + "previously installed version; ignoring!"); 5744 } 5745 } 5746 5747 // Check for shared user signatures 5748 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5749 // Already existing package. Make sure signatures match 5750 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5751 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5752 if (!match) { 5753 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5754 == PackageManager.SIGNATURE_MATCH; 5755 } 5756 if (!match) { 5757 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5758 == PackageManager.SIGNATURE_MATCH; 5759 } 5760 if (!match) { 5761 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5762 "Package " + pkg.packageName 5763 + " has no signatures that match those in shared user " 5764 + pkgSetting.sharedUser.name + "; ignoring!"); 5765 } 5766 } 5767 } 5768 5769 /** 5770 * Enforces that only the system UID or root's UID can call a method exposed 5771 * via Binder. 5772 * 5773 * @param message used as message if SecurityException is thrown 5774 * @throws SecurityException if the caller is not system or root 5775 */ 5776 private static final void enforceSystemOrRoot(String message) { 5777 final int uid = Binder.getCallingUid(); 5778 if (uid != Process.SYSTEM_UID && uid != 0) { 5779 throw new SecurityException(message); 5780 } 5781 } 5782 5783 @Override 5784 public void performBootDexOpt() { 5785 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5786 5787 // Before everything else, see whether we need to fstrim. 5788 try { 5789 IMountService ms = PackageHelper.getMountService(); 5790 if (ms != null) { 5791 final boolean isUpgrade = isUpgrade(); 5792 boolean doTrim = isUpgrade; 5793 if (doTrim) { 5794 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5795 } else { 5796 final long interval = android.provider.Settings.Global.getLong( 5797 mContext.getContentResolver(), 5798 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5799 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5800 if (interval > 0) { 5801 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5802 if (timeSinceLast > interval) { 5803 doTrim = true; 5804 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5805 + "; running immediately"); 5806 } 5807 } 5808 } 5809 if (doTrim) { 5810 if (!isFirstBoot()) { 5811 try { 5812 ActivityManagerNative.getDefault().showBootMessage( 5813 mContext.getResources().getString( 5814 R.string.android_upgrading_fstrim), true); 5815 } catch (RemoteException e) { 5816 } 5817 } 5818 ms.runMaintenance(); 5819 } 5820 } else { 5821 Slog.e(TAG, "Mount service unavailable!"); 5822 } 5823 } catch (RemoteException e) { 5824 // Can't happen; MountService is local 5825 } 5826 5827 final ArraySet<PackageParser.Package> pkgs; 5828 synchronized (mPackages) { 5829 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5830 } 5831 5832 if (pkgs != null) { 5833 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5834 // in case the device runs out of space. 5835 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5836 // Give priority to core apps. 5837 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5838 PackageParser.Package pkg = it.next(); 5839 if (pkg.coreApp) { 5840 if (DEBUG_DEXOPT) { 5841 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5842 } 5843 sortedPkgs.add(pkg); 5844 it.remove(); 5845 } 5846 } 5847 // Give priority to system apps that listen for pre boot complete. 5848 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5849 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5850 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5851 PackageParser.Package pkg = it.next(); 5852 if (pkgNames.contains(pkg.packageName)) { 5853 if (DEBUG_DEXOPT) { 5854 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5855 } 5856 sortedPkgs.add(pkg); 5857 it.remove(); 5858 } 5859 } 5860 // Give priority to system apps. 5861 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5862 PackageParser.Package pkg = it.next(); 5863 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5864 if (DEBUG_DEXOPT) { 5865 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5866 } 5867 sortedPkgs.add(pkg); 5868 it.remove(); 5869 } 5870 } 5871 // Give priority to updated system apps. 5872 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5873 PackageParser.Package pkg = it.next(); 5874 if (pkg.isUpdatedSystemApp()) { 5875 if (DEBUG_DEXOPT) { 5876 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5877 } 5878 sortedPkgs.add(pkg); 5879 it.remove(); 5880 } 5881 } 5882 // Give priority to apps that listen for boot complete. 5883 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5884 pkgNames = getPackageNamesForIntent(intent); 5885 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5886 PackageParser.Package pkg = it.next(); 5887 if (pkgNames.contains(pkg.packageName)) { 5888 if (DEBUG_DEXOPT) { 5889 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5890 } 5891 sortedPkgs.add(pkg); 5892 it.remove(); 5893 } 5894 } 5895 // Filter out packages that aren't recently used. 5896 filterRecentlyUsedApps(pkgs); 5897 // Add all remaining apps. 5898 for (PackageParser.Package pkg : pkgs) { 5899 if (DEBUG_DEXOPT) { 5900 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5901 } 5902 sortedPkgs.add(pkg); 5903 } 5904 5905 // If we want to be lazy, filter everything that wasn't recently used. 5906 if (mLazyDexOpt) { 5907 filterRecentlyUsedApps(sortedPkgs); 5908 } 5909 5910 int i = 0; 5911 int total = sortedPkgs.size(); 5912 File dataDir = Environment.getDataDirectory(); 5913 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5914 if (lowThreshold == 0) { 5915 throw new IllegalStateException("Invalid low memory threshold"); 5916 } 5917 for (PackageParser.Package pkg : sortedPkgs) { 5918 long usableSpace = dataDir.getUsableSpace(); 5919 if (usableSpace < lowThreshold) { 5920 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5921 break; 5922 } 5923 performBootDexOpt(pkg, ++i, total); 5924 } 5925 } 5926 } 5927 5928 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5929 // Filter out packages that aren't recently used. 5930 // 5931 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5932 // should do a full dexopt. 5933 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5934 int total = pkgs.size(); 5935 int skipped = 0; 5936 long now = System.currentTimeMillis(); 5937 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5938 PackageParser.Package pkg = i.next(); 5939 long then = pkg.mLastPackageUsageTimeInMills; 5940 if (then + mDexOptLRUThresholdInMills < now) { 5941 if (DEBUG_DEXOPT) { 5942 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5943 ((then == 0) ? "never" : new Date(then))); 5944 } 5945 i.remove(); 5946 skipped++; 5947 } 5948 } 5949 if (DEBUG_DEXOPT) { 5950 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5951 } 5952 } 5953 } 5954 5955 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5956 List<ResolveInfo> ris = null; 5957 try { 5958 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5959 intent, null, 0, UserHandle.USER_OWNER); 5960 } catch (RemoteException e) { 5961 } 5962 ArraySet<String> pkgNames = new ArraySet<String>(); 5963 if (ris != null) { 5964 for (ResolveInfo ri : ris) { 5965 pkgNames.add(ri.activityInfo.packageName); 5966 } 5967 } 5968 return pkgNames; 5969 } 5970 5971 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5972 if (DEBUG_DEXOPT) { 5973 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5974 } 5975 if (!isFirstBoot()) { 5976 try { 5977 ActivityManagerNative.getDefault().showBootMessage( 5978 mContext.getResources().getString(R.string.android_upgrading_apk, 5979 curr, total), true); 5980 } catch (RemoteException e) { 5981 } 5982 } 5983 PackageParser.Package p = pkg; 5984 synchronized (mInstallLock) { 5985 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5986 false /* force dex */, false /* defer */, true /* include dependencies */); 5987 } 5988 } 5989 5990 @Override 5991 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5992 return performDexOpt(packageName, instructionSet, false); 5993 } 5994 5995 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5996 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5997 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5998 if (!dexopt && !updateUsage) { 5999 // We aren't going to dexopt or update usage, so bail early. 6000 return false; 6001 } 6002 PackageParser.Package p; 6003 final String targetInstructionSet; 6004 synchronized (mPackages) { 6005 p = mPackages.get(packageName); 6006 if (p == null) { 6007 return false; 6008 } 6009 if (updateUsage) { 6010 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6011 } 6012 mPackageUsage.write(false); 6013 if (!dexopt) { 6014 // We aren't going to dexopt, so bail early. 6015 return false; 6016 } 6017 6018 targetInstructionSet = instructionSet != null ? instructionSet : 6019 getPrimaryInstructionSet(p.applicationInfo); 6020 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6021 return false; 6022 } 6023 } 6024 6025 synchronized (mInstallLock) { 6026 final String[] instructionSets = new String[] { targetInstructionSet }; 6027 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6028 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6029 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6030 } 6031 } 6032 6033 public ArraySet<String> getPackagesThatNeedDexOpt() { 6034 ArraySet<String> pkgs = null; 6035 synchronized (mPackages) { 6036 for (PackageParser.Package p : mPackages.values()) { 6037 if (DEBUG_DEXOPT) { 6038 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6039 } 6040 if (!p.mDexOptPerformed.isEmpty()) { 6041 continue; 6042 } 6043 if (pkgs == null) { 6044 pkgs = new ArraySet<String>(); 6045 } 6046 pkgs.add(p.packageName); 6047 } 6048 } 6049 return pkgs; 6050 } 6051 6052 public void shutdown() { 6053 mPackageUsage.write(true); 6054 } 6055 6056 @Override 6057 public void forceDexOpt(String packageName) { 6058 enforceSystemOrRoot("forceDexOpt"); 6059 6060 PackageParser.Package pkg; 6061 synchronized (mPackages) { 6062 pkg = mPackages.get(packageName); 6063 if (pkg == null) { 6064 throw new IllegalArgumentException("Missing package: " + packageName); 6065 } 6066 } 6067 6068 synchronized (mInstallLock) { 6069 final String[] instructionSets = new String[] { 6070 getPrimaryInstructionSet(pkg.applicationInfo) }; 6071 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6072 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6073 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6074 throw new IllegalStateException("Failed to dexopt: " + res); 6075 } 6076 } 6077 } 6078 6079 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6080 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6081 Slog.w(TAG, "Unable to update from " + oldPkg.name 6082 + " to " + newPkg.packageName 6083 + ": old package not in system partition"); 6084 return false; 6085 } else if (mPackages.get(oldPkg.name) != null) { 6086 Slog.w(TAG, "Unable to update from " + oldPkg.name 6087 + " to " + newPkg.packageName 6088 + ": old package still exists"); 6089 return false; 6090 } 6091 return true; 6092 } 6093 6094 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6095 int[] users = sUserManager.getUserIds(); 6096 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6097 if (res < 0) { 6098 return res; 6099 } 6100 for (int user : users) { 6101 if (user != 0) { 6102 res = mInstaller.createUserData(volumeUuid, packageName, 6103 UserHandle.getUid(user, uid), user, seinfo); 6104 if (res < 0) { 6105 return res; 6106 } 6107 } 6108 } 6109 return res; 6110 } 6111 6112 private int removeDataDirsLI(String volumeUuid, String packageName) { 6113 int[] users = sUserManager.getUserIds(); 6114 int res = 0; 6115 for (int user : users) { 6116 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6117 if (resInner < 0) { 6118 res = resInner; 6119 } 6120 } 6121 6122 return res; 6123 } 6124 6125 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6126 int[] users = sUserManager.getUserIds(); 6127 int res = 0; 6128 for (int user : users) { 6129 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6130 if (resInner < 0) { 6131 res = resInner; 6132 } 6133 } 6134 return res; 6135 } 6136 6137 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6138 PackageParser.Package changingLib) { 6139 if (file.path != null) { 6140 usesLibraryFiles.add(file.path); 6141 return; 6142 } 6143 PackageParser.Package p = mPackages.get(file.apk); 6144 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6145 // If we are doing this while in the middle of updating a library apk, 6146 // then we need to make sure to use that new apk for determining the 6147 // dependencies here. (We haven't yet finished committing the new apk 6148 // to the package manager state.) 6149 if (p == null || p.packageName.equals(changingLib.packageName)) { 6150 p = changingLib; 6151 } 6152 } 6153 if (p != null) { 6154 usesLibraryFiles.addAll(p.getAllCodePaths()); 6155 } 6156 } 6157 6158 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6159 PackageParser.Package changingLib) throws PackageManagerException { 6160 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6161 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6162 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6163 for (int i=0; i<N; i++) { 6164 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6165 if (file == null) { 6166 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6167 "Package " + pkg.packageName + " requires unavailable shared library " 6168 + pkg.usesLibraries.get(i) + "; failing!"); 6169 } 6170 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6171 } 6172 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6173 for (int i=0; i<N; i++) { 6174 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6175 if (file == null) { 6176 Slog.w(TAG, "Package " + pkg.packageName 6177 + " desires unavailable shared library " 6178 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6179 } else { 6180 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6181 } 6182 } 6183 N = usesLibraryFiles.size(); 6184 if (N > 0) { 6185 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6186 } else { 6187 pkg.usesLibraryFiles = null; 6188 } 6189 } 6190 } 6191 6192 private static boolean hasString(List<String> list, List<String> which) { 6193 if (list == null) { 6194 return false; 6195 } 6196 for (int i=list.size()-1; i>=0; i--) { 6197 for (int j=which.size()-1; j>=0; j--) { 6198 if (which.get(j).equals(list.get(i))) { 6199 return true; 6200 } 6201 } 6202 } 6203 return false; 6204 } 6205 6206 private void updateAllSharedLibrariesLPw() { 6207 for (PackageParser.Package pkg : mPackages.values()) { 6208 try { 6209 updateSharedLibrariesLPw(pkg, null); 6210 } catch (PackageManagerException e) { 6211 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6212 } 6213 } 6214 } 6215 6216 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6217 PackageParser.Package changingPkg) { 6218 ArrayList<PackageParser.Package> res = null; 6219 for (PackageParser.Package pkg : mPackages.values()) { 6220 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6221 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6222 if (res == null) { 6223 res = new ArrayList<PackageParser.Package>(); 6224 } 6225 res.add(pkg); 6226 try { 6227 updateSharedLibrariesLPw(pkg, changingPkg); 6228 } catch (PackageManagerException e) { 6229 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6230 } 6231 } 6232 } 6233 return res; 6234 } 6235 6236 /** 6237 * Derive the value of the {@code cpuAbiOverride} based on the provided 6238 * value and an optional stored value from the package settings. 6239 */ 6240 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6241 String cpuAbiOverride = null; 6242 6243 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6244 cpuAbiOverride = null; 6245 } else if (abiOverride != null) { 6246 cpuAbiOverride = abiOverride; 6247 } else if (settings != null) { 6248 cpuAbiOverride = settings.cpuAbiOverrideString; 6249 } 6250 6251 return cpuAbiOverride; 6252 } 6253 6254 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6255 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6256 boolean success = false; 6257 try { 6258 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6259 currentTime, user); 6260 success = true; 6261 return res; 6262 } finally { 6263 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6264 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6265 } 6266 } 6267 } 6268 6269 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6270 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6271 final File scanFile = new File(pkg.codePath); 6272 if (pkg.applicationInfo.getCodePath() == null || 6273 pkg.applicationInfo.getResourcePath() == null) { 6274 // Bail out. The resource and code paths haven't been set. 6275 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6276 "Code and resource paths haven't been set correctly"); 6277 } 6278 6279 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6280 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6281 } else { 6282 // Only allow system apps to be flagged as core apps. 6283 pkg.coreApp = false; 6284 } 6285 6286 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6287 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6288 } 6289 6290 if (mCustomResolverComponentName != null && 6291 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6292 setUpCustomResolverActivity(pkg); 6293 } 6294 6295 if (pkg.packageName.equals("android")) { 6296 synchronized (mPackages) { 6297 if (mAndroidApplication != null) { 6298 Slog.w(TAG, "*************************************************"); 6299 Slog.w(TAG, "Core android package being redefined. Skipping."); 6300 Slog.w(TAG, " file=" + scanFile); 6301 Slog.w(TAG, "*************************************************"); 6302 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6303 "Core android package being redefined. Skipping."); 6304 } 6305 6306 // Set up information for our fall-back user intent resolution activity. 6307 mPlatformPackage = pkg; 6308 pkg.mVersionCode = mSdkVersion; 6309 mAndroidApplication = pkg.applicationInfo; 6310 6311 if (!mResolverReplaced) { 6312 mResolveActivity.applicationInfo = mAndroidApplication; 6313 mResolveActivity.name = ResolverActivity.class.getName(); 6314 mResolveActivity.packageName = mAndroidApplication.packageName; 6315 mResolveActivity.processName = "system:ui"; 6316 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6317 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6318 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6319 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6320 mResolveActivity.exported = true; 6321 mResolveActivity.enabled = true; 6322 mResolveInfo.activityInfo = mResolveActivity; 6323 mResolveInfo.priority = 0; 6324 mResolveInfo.preferredOrder = 0; 6325 mResolveInfo.match = 0; 6326 mResolveComponentName = new ComponentName( 6327 mAndroidApplication.packageName, mResolveActivity.name); 6328 } 6329 } 6330 } 6331 6332 if (DEBUG_PACKAGE_SCANNING) { 6333 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6334 Log.d(TAG, "Scanning package " + pkg.packageName); 6335 } 6336 6337 if (mPackages.containsKey(pkg.packageName) 6338 || mSharedLibraries.containsKey(pkg.packageName)) { 6339 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6340 "Application package " + pkg.packageName 6341 + " already installed. Skipping duplicate."); 6342 } 6343 6344 // If we're only installing presumed-existing packages, require that the 6345 // scanned APK is both already known and at the path previously established 6346 // for it. Previously unknown packages we pick up normally, but if we have an 6347 // a priori expectation about this package's install presence, enforce it. 6348 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6349 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6350 if (known != null) { 6351 if (DEBUG_PACKAGE_SCANNING) { 6352 Log.d(TAG, "Examining " + pkg.codePath 6353 + " and requiring known paths " + known.codePathString 6354 + " & " + known.resourcePathString); 6355 } 6356 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6357 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6358 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6359 "Application package " + pkg.packageName 6360 + " found at " + pkg.applicationInfo.getCodePath() 6361 + " but expected at " + known.codePathString + "; ignoring."); 6362 } 6363 } 6364 } 6365 6366 // Initialize package source and resource directories 6367 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6368 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6369 6370 SharedUserSetting suid = null; 6371 PackageSetting pkgSetting = null; 6372 6373 if (!isSystemApp(pkg)) { 6374 // Only system apps can use these features. 6375 pkg.mOriginalPackages = null; 6376 pkg.mRealPackage = null; 6377 pkg.mAdoptPermissions = null; 6378 } 6379 6380 // writer 6381 synchronized (mPackages) { 6382 if (pkg.mSharedUserId != null) { 6383 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6384 if (suid == null) { 6385 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6386 "Creating application package " + pkg.packageName 6387 + " for shared user failed"); 6388 } 6389 if (DEBUG_PACKAGE_SCANNING) { 6390 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6391 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6392 + "): packages=" + suid.packages); 6393 } 6394 } 6395 6396 // Check if we are renaming from an original package name. 6397 PackageSetting origPackage = null; 6398 String realName = null; 6399 if (pkg.mOriginalPackages != null) { 6400 // This package may need to be renamed to a previously 6401 // installed name. Let's check on that... 6402 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6403 if (pkg.mOriginalPackages.contains(renamed)) { 6404 // This package had originally been installed as the 6405 // original name, and we have already taken care of 6406 // transitioning to the new one. Just update the new 6407 // one to continue using the old name. 6408 realName = pkg.mRealPackage; 6409 if (!pkg.packageName.equals(renamed)) { 6410 // Callers into this function may have already taken 6411 // care of renaming the package; only do it here if 6412 // it is not already done. 6413 pkg.setPackageName(renamed); 6414 } 6415 6416 } else { 6417 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6418 if ((origPackage = mSettings.peekPackageLPr( 6419 pkg.mOriginalPackages.get(i))) != null) { 6420 // We do have the package already installed under its 6421 // original name... should we use it? 6422 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6423 // New package is not compatible with original. 6424 origPackage = null; 6425 continue; 6426 } else if (origPackage.sharedUser != null) { 6427 // Make sure uid is compatible between packages. 6428 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6429 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6430 + " to " + pkg.packageName + ": old uid " 6431 + origPackage.sharedUser.name 6432 + " differs from " + pkg.mSharedUserId); 6433 origPackage = null; 6434 continue; 6435 } 6436 } else { 6437 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6438 + pkg.packageName + " to old name " + origPackage.name); 6439 } 6440 break; 6441 } 6442 } 6443 } 6444 } 6445 6446 if (mTransferedPackages.contains(pkg.packageName)) { 6447 Slog.w(TAG, "Package " + pkg.packageName 6448 + " was transferred to another, but its .apk remains"); 6449 } 6450 6451 // Just create the setting, don't add it yet. For already existing packages 6452 // the PkgSetting exists already and doesn't have to be created. 6453 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6454 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6455 pkg.applicationInfo.primaryCpuAbi, 6456 pkg.applicationInfo.secondaryCpuAbi, 6457 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6458 user, false); 6459 if (pkgSetting == null) { 6460 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6461 "Creating application package " + pkg.packageName + " failed"); 6462 } 6463 6464 if (pkgSetting.origPackage != null) { 6465 // If we are first transitioning from an original package, 6466 // fix up the new package's name now. We need to do this after 6467 // looking up the package under its new name, so getPackageLP 6468 // can take care of fiddling things correctly. 6469 pkg.setPackageName(origPackage.name); 6470 6471 // File a report about this. 6472 String msg = "New package " + pkgSetting.realName 6473 + " renamed to replace old package " + pkgSetting.name; 6474 reportSettingsProblem(Log.WARN, msg); 6475 6476 // Make a note of it. 6477 mTransferedPackages.add(origPackage.name); 6478 6479 // No longer need to retain this. 6480 pkgSetting.origPackage = null; 6481 } 6482 6483 if (realName != null) { 6484 // Make a note of it. 6485 mTransferedPackages.add(pkg.packageName); 6486 } 6487 6488 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6489 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6490 } 6491 6492 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6493 // Check all shared libraries and map to their actual file path. 6494 // We only do this here for apps not on a system dir, because those 6495 // are the only ones that can fail an install due to this. We 6496 // will take care of the system apps by updating all of their 6497 // library paths after the scan is done. 6498 updateSharedLibrariesLPw(pkg, null); 6499 } 6500 6501 if (mFoundPolicyFile) { 6502 SELinuxMMAC.assignSeinfoValue(pkg); 6503 } 6504 6505 pkg.applicationInfo.uid = pkgSetting.appId; 6506 pkg.mExtras = pkgSetting; 6507 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6508 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6509 // We just determined the app is signed correctly, so bring 6510 // over the latest parsed certs. 6511 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6512 } else { 6513 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6514 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6515 "Package " + pkg.packageName + " upgrade keys do not match the " 6516 + "previously installed version"); 6517 } else { 6518 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6519 String msg = "System package " + pkg.packageName 6520 + " signature changed; retaining data."; 6521 reportSettingsProblem(Log.WARN, msg); 6522 } 6523 } 6524 } else { 6525 try { 6526 verifySignaturesLP(pkgSetting, pkg); 6527 // We just determined the app is signed correctly, so bring 6528 // over the latest parsed certs. 6529 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6530 } catch (PackageManagerException e) { 6531 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6532 throw e; 6533 } 6534 // The signature has changed, but this package is in the system 6535 // image... let's recover! 6536 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6537 // However... if this package is part of a shared user, but it 6538 // doesn't match the signature of the shared user, let's fail. 6539 // What this means is that you can't change the signatures 6540 // associated with an overall shared user, which doesn't seem all 6541 // that unreasonable. 6542 if (pkgSetting.sharedUser != null) { 6543 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6544 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6545 throw new PackageManagerException( 6546 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6547 "Signature mismatch for shared user : " 6548 + pkgSetting.sharedUser); 6549 } 6550 } 6551 // File a report about this. 6552 String msg = "System package " + pkg.packageName 6553 + " signature changed; retaining data."; 6554 reportSettingsProblem(Log.WARN, msg); 6555 } 6556 } 6557 // Verify that this new package doesn't have any content providers 6558 // that conflict with existing packages. Only do this if the 6559 // package isn't already installed, since we don't want to break 6560 // things that are installed. 6561 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6562 final int N = pkg.providers.size(); 6563 int i; 6564 for (i=0; i<N; i++) { 6565 PackageParser.Provider p = pkg.providers.get(i); 6566 if (p.info.authority != null) { 6567 String names[] = p.info.authority.split(";"); 6568 for (int j = 0; j < names.length; j++) { 6569 if (mProvidersByAuthority.containsKey(names[j])) { 6570 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6571 final String otherPackageName = 6572 ((other != null && other.getComponentName() != null) ? 6573 other.getComponentName().getPackageName() : "?"); 6574 throw new PackageManagerException( 6575 INSTALL_FAILED_CONFLICTING_PROVIDER, 6576 "Can't install because provider name " + names[j] 6577 + " (in package " + pkg.applicationInfo.packageName 6578 + ") is already used by " + otherPackageName); 6579 } 6580 } 6581 } 6582 } 6583 } 6584 6585 if (pkg.mAdoptPermissions != null) { 6586 // This package wants to adopt ownership of permissions from 6587 // another package. 6588 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6589 final String origName = pkg.mAdoptPermissions.get(i); 6590 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6591 if (orig != null) { 6592 if (verifyPackageUpdateLPr(orig, pkg)) { 6593 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6594 + pkg.packageName); 6595 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6596 } 6597 } 6598 } 6599 } 6600 } 6601 6602 final String pkgName = pkg.packageName; 6603 6604 final long scanFileTime = scanFile.lastModified(); 6605 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6606 pkg.applicationInfo.processName = fixProcessName( 6607 pkg.applicationInfo.packageName, 6608 pkg.applicationInfo.processName, 6609 pkg.applicationInfo.uid); 6610 6611 File dataPath; 6612 if (mPlatformPackage == pkg) { 6613 // The system package is special. 6614 dataPath = new File(Environment.getDataDirectory(), "system"); 6615 6616 pkg.applicationInfo.dataDir = dataPath.getPath(); 6617 6618 } else { 6619 // This is a normal package, need to make its data directory. 6620 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6621 UserHandle.USER_OWNER); 6622 6623 boolean uidError = false; 6624 if (dataPath.exists()) { 6625 int currentUid = 0; 6626 try { 6627 StructStat stat = Os.stat(dataPath.getPath()); 6628 currentUid = stat.st_uid; 6629 } catch (ErrnoException e) { 6630 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6631 } 6632 6633 // If we have mismatched owners for the data path, we have a problem. 6634 if (currentUid != pkg.applicationInfo.uid) { 6635 boolean recovered = false; 6636 if (currentUid == 0) { 6637 // The directory somehow became owned by root. Wow. 6638 // This is probably because the system was stopped while 6639 // installd was in the middle of messing with its libs 6640 // directory. Ask installd to fix that. 6641 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6642 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6643 if (ret >= 0) { 6644 recovered = true; 6645 String msg = "Package " + pkg.packageName 6646 + " unexpectedly changed to uid 0; recovered to " + 6647 + pkg.applicationInfo.uid; 6648 reportSettingsProblem(Log.WARN, msg); 6649 } 6650 } 6651 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6652 || (scanFlags&SCAN_BOOTING) != 0)) { 6653 // If this is a system app, we can at least delete its 6654 // current data so the application will still work. 6655 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6656 if (ret >= 0) { 6657 // TODO: Kill the processes first 6658 // Old data gone! 6659 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6660 ? "System package " : "Third party package "; 6661 String msg = prefix + pkg.packageName 6662 + " has changed from uid: " 6663 + currentUid + " to " 6664 + pkg.applicationInfo.uid + "; old data erased"; 6665 reportSettingsProblem(Log.WARN, msg); 6666 recovered = true; 6667 6668 // And now re-install the app. 6669 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6670 pkg.applicationInfo.seinfo); 6671 if (ret == -1) { 6672 // Ack should not happen! 6673 msg = prefix + pkg.packageName 6674 + " could not have data directory re-created after delete."; 6675 reportSettingsProblem(Log.WARN, msg); 6676 throw new PackageManagerException( 6677 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6678 } 6679 } 6680 if (!recovered) { 6681 mHasSystemUidErrors = true; 6682 } 6683 } else if (!recovered) { 6684 // If we allow this install to proceed, we will be broken. 6685 // Abort, abort! 6686 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6687 "scanPackageLI"); 6688 } 6689 if (!recovered) { 6690 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6691 + pkg.applicationInfo.uid + "/fs_" 6692 + currentUid; 6693 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6694 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6695 String msg = "Package " + pkg.packageName 6696 + " has mismatched uid: " 6697 + currentUid + " on disk, " 6698 + pkg.applicationInfo.uid + " in settings"; 6699 // writer 6700 synchronized (mPackages) { 6701 mSettings.mReadMessages.append(msg); 6702 mSettings.mReadMessages.append('\n'); 6703 uidError = true; 6704 if (!pkgSetting.uidError) { 6705 reportSettingsProblem(Log.ERROR, msg); 6706 } 6707 } 6708 } 6709 } 6710 pkg.applicationInfo.dataDir = dataPath.getPath(); 6711 if (mShouldRestoreconData) { 6712 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6713 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6714 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6715 } 6716 } else { 6717 if (DEBUG_PACKAGE_SCANNING) { 6718 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6719 Log.v(TAG, "Want this data dir: " + dataPath); 6720 } 6721 //invoke installer to do the actual installation 6722 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6723 pkg.applicationInfo.seinfo); 6724 if (ret < 0) { 6725 // Error from installer 6726 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6727 "Unable to create data dirs [errorCode=" + ret + "]"); 6728 } 6729 6730 if (dataPath.exists()) { 6731 pkg.applicationInfo.dataDir = dataPath.getPath(); 6732 } else { 6733 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6734 pkg.applicationInfo.dataDir = null; 6735 } 6736 } 6737 6738 pkgSetting.uidError = uidError; 6739 } 6740 6741 final String path = scanFile.getPath(); 6742 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6743 6744 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6745 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6746 6747 // Some system apps still use directory structure for native libraries 6748 // in which case we might end up not detecting abi solely based on apk 6749 // structure. Try to detect abi based on directory structure. 6750 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6751 pkg.applicationInfo.primaryCpuAbi == null) { 6752 setBundledAppAbisAndRoots(pkg, pkgSetting); 6753 setNativeLibraryPaths(pkg); 6754 } 6755 6756 } else { 6757 if ((scanFlags & SCAN_MOVE) != 0) { 6758 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6759 // but we already have this packages package info in the PackageSetting. We just 6760 // use that and derive the native library path based on the new codepath. 6761 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6762 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6763 } 6764 6765 // Set native library paths again. For moves, the path will be updated based on the 6766 // ABIs we've determined above. For non-moves, the path will be updated based on the 6767 // ABIs we determined during compilation, but the path will depend on the final 6768 // package path (after the rename away from the stage path). 6769 setNativeLibraryPaths(pkg); 6770 } 6771 6772 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6773 final int[] userIds = sUserManager.getUserIds(); 6774 synchronized (mInstallLock) { 6775 // Create a native library symlink only if we have native libraries 6776 // and if the native libraries are 32 bit libraries. We do not provide 6777 // this symlink for 64 bit libraries. 6778 if (pkg.applicationInfo.primaryCpuAbi != null && 6779 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6780 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6781 for (int userId : userIds) { 6782 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6783 nativeLibPath, userId) < 0) { 6784 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6785 "Failed linking native library dir (user=" + userId + ")"); 6786 } 6787 } 6788 } 6789 } 6790 6791 // This is a special case for the "system" package, where the ABI is 6792 // dictated by the zygote configuration (and init.rc). We should keep track 6793 // of this ABI so that we can deal with "normal" applications that run under 6794 // the same UID correctly. 6795 if (mPlatformPackage == pkg) { 6796 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6797 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6798 } 6799 6800 // If there's a mismatch between the abi-override in the package setting 6801 // and the abiOverride specified for the install. Warn about this because we 6802 // would've already compiled the app without taking the package setting into 6803 // account. 6804 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6805 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6806 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6807 " for package: " + pkg.packageName); 6808 } 6809 } 6810 6811 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6812 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6813 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6814 6815 // Copy the derived override back to the parsed package, so that we can 6816 // update the package settings accordingly. 6817 pkg.cpuAbiOverride = cpuAbiOverride; 6818 6819 if (DEBUG_ABI_SELECTION) { 6820 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6821 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6822 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6823 } 6824 6825 // Push the derived path down into PackageSettings so we know what to 6826 // clean up at uninstall time. 6827 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6828 6829 if (DEBUG_ABI_SELECTION) { 6830 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6831 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6832 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6833 } 6834 6835 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6836 // We don't do this here during boot because we can do it all 6837 // at once after scanning all existing packages. 6838 // 6839 // We also do this *before* we perform dexopt on this package, so that 6840 // we can avoid redundant dexopts, and also to make sure we've got the 6841 // code and package path correct. 6842 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6843 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6844 } 6845 6846 if ((scanFlags & SCAN_NO_DEX) == 0) { 6847 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6848 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6849 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6850 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6851 } 6852 } 6853 if (mFactoryTest && pkg.requestedPermissions.contains( 6854 android.Manifest.permission.FACTORY_TEST)) { 6855 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6856 } 6857 6858 ArrayList<PackageParser.Package> clientLibPkgs = null; 6859 6860 // writer 6861 synchronized (mPackages) { 6862 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6863 // Only system apps can add new shared libraries. 6864 if (pkg.libraryNames != null) { 6865 for (int i=0; i<pkg.libraryNames.size(); i++) { 6866 String name = pkg.libraryNames.get(i); 6867 boolean allowed = false; 6868 if (pkg.isUpdatedSystemApp()) { 6869 // New library entries can only be added through the 6870 // system image. This is important to get rid of a lot 6871 // of nasty edge cases: for example if we allowed a non- 6872 // system update of the app to add a library, then uninstalling 6873 // the update would make the library go away, and assumptions 6874 // we made such as through app install filtering would now 6875 // have allowed apps on the device which aren't compatible 6876 // with it. Better to just have the restriction here, be 6877 // conservative, and create many fewer cases that can negatively 6878 // impact the user experience. 6879 final PackageSetting sysPs = mSettings 6880 .getDisabledSystemPkgLPr(pkg.packageName); 6881 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6882 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6883 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6884 allowed = true; 6885 allowed = true; 6886 break; 6887 } 6888 } 6889 } 6890 } else { 6891 allowed = true; 6892 } 6893 if (allowed) { 6894 if (!mSharedLibraries.containsKey(name)) { 6895 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6896 } else if (!name.equals(pkg.packageName)) { 6897 Slog.w(TAG, "Package " + pkg.packageName + " library " 6898 + name + " already exists; skipping"); 6899 } 6900 } else { 6901 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6902 + name + " that is not declared on system image; skipping"); 6903 } 6904 } 6905 if ((scanFlags&SCAN_BOOTING) == 0) { 6906 // If we are not booting, we need to update any applications 6907 // that are clients of our shared library. If we are booting, 6908 // this will all be done once the scan is complete. 6909 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6910 } 6911 } 6912 } 6913 } 6914 6915 // We also need to dexopt any apps that are dependent on this library. Note that 6916 // if these fail, we should abort the install since installing the library will 6917 // result in some apps being broken. 6918 if (clientLibPkgs != null) { 6919 if ((scanFlags & SCAN_NO_DEX) == 0) { 6920 for (int i = 0; i < clientLibPkgs.size(); i++) { 6921 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6922 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6923 null /* instruction sets */, forceDex, 6924 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6925 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6926 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6927 "scanPackageLI failed to dexopt clientLibPkgs"); 6928 } 6929 } 6930 } 6931 } 6932 6933 // Also need to kill any apps that are dependent on the library. 6934 if (clientLibPkgs != null) { 6935 for (int i=0; i<clientLibPkgs.size(); i++) { 6936 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6937 killApplication(clientPkg.applicationInfo.packageName, 6938 clientPkg.applicationInfo.uid, "update lib"); 6939 } 6940 } 6941 6942 // Make sure we're not adding any bogus keyset info 6943 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6944 ksms.assertScannedPackageValid(pkg); 6945 6946 // writer 6947 synchronized (mPackages) { 6948 // We don't expect installation to fail beyond this point 6949 6950 // Add the new setting to mSettings 6951 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6952 // Add the new setting to mPackages 6953 mPackages.put(pkg.applicationInfo.packageName, pkg); 6954 // Make sure we don't accidentally delete its data. 6955 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6956 while (iter.hasNext()) { 6957 PackageCleanItem item = iter.next(); 6958 if (pkgName.equals(item.packageName)) { 6959 iter.remove(); 6960 } 6961 } 6962 6963 // Take care of first install / last update times. 6964 if (currentTime != 0) { 6965 if (pkgSetting.firstInstallTime == 0) { 6966 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6967 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6968 pkgSetting.lastUpdateTime = currentTime; 6969 } 6970 } else if (pkgSetting.firstInstallTime == 0) { 6971 // We need *something*. Take time time stamp of the file. 6972 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6973 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6974 if (scanFileTime != pkgSetting.timeStamp) { 6975 // A package on the system image has changed; consider this 6976 // to be an update. 6977 pkgSetting.lastUpdateTime = scanFileTime; 6978 } 6979 } 6980 6981 // Add the package's KeySets to the global KeySetManagerService 6982 ksms.addScannedPackageLPw(pkg); 6983 6984 int N = pkg.providers.size(); 6985 StringBuilder r = null; 6986 int i; 6987 for (i=0; i<N; i++) { 6988 PackageParser.Provider p = pkg.providers.get(i); 6989 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6990 p.info.processName, pkg.applicationInfo.uid); 6991 mProviders.addProvider(p); 6992 p.syncable = p.info.isSyncable; 6993 if (p.info.authority != null) { 6994 String names[] = p.info.authority.split(";"); 6995 p.info.authority = null; 6996 for (int j = 0; j < names.length; j++) { 6997 if (j == 1 && p.syncable) { 6998 // We only want the first authority for a provider to possibly be 6999 // syncable, so if we already added this provider using a different 7000 // authority clear the syncable flag. We copy the provider before 7001 // changing it because the mProviders object contains a reference 7002 // to a provider that we don't want to change. 7003 // Only do this for the second authority since the resulting provider 7004 // object can be the same for all future authorities for this provider. 7005 p = new PackageParser.Provider(p); 7006 p.syncable = false; 7007 } 7008 if (!mProvidersByAuthority.containsKey(names[j])) { 7009 mProvidersByAuthority.put(names[j], p); 7010 if (p.info.authority == null) { 7011 p.info.authority = names[j]; 7012 } else { 7013 p.info.authority = p.info.authority + ";" + names[j]; 7014 } 7015 if (DEBUG_PACKAGE_SCANNING) { 7016 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7017 Log.d(TAG, "Registered content provider: " + names[j] 7018 + ", className = " + p.info.name + ", isSyncable = " 7019 + p.info.isSyncable); 7020 } 7021 } else { 7022 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7023 Slog.w(TAG, "Skipping provider name " + names[j] + 7024 " (in package " + pkg.applicationInfo.packageName + 7025 "): name already used by " 7026 + ((other != null && other.getComponentName() != null) 7027 ? other.getComponentName().getPackageName() : "?")); 7028 } 7029 } 7030 } 7031 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7032 if (r == null) { 7033 r = new StringBuilder(256); 7034 } else { 7035 r.append(' '); 7036 } 7037 r.append(p.info.name); 7038 } 7039 } 7040 if (r != null) { 7041 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7042 } 7043 7044 N = pkg.services.size(); 7045 r = null; 7046 for (i=0; i<N; i++) { 7047 PackageParser.Service s = pkg.services.get(i); 7048 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7049 s.info.processName, pkg.applicationInfo.uid); 7050 mServices.addService(s); 7051 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7052 if (r == null) { 7053 r = new StringBuilder(256); 7054 } else { 7055 r.append(' '); 7056 } 7057 r.append(s.info.name); 7058 } 7059 } 7060 if (r != null) { 7061 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7062 } 7063 7064 N = pkg.receivers.size(); 7065 r = null; 7066 for (i=0; i<N; i++) { 7067 PackageParser.Activity a = pkg.receivers.get(i); 7068 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7069 a.info.processName, pkg.applicationInfo.uid); 7070 mReceivers.addActivity(a, "receiver"); 7071 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7072 if (r == null) { 7073 r = new StringBuilder(256); 7074 } else { 7075 r.append(' '); 7076 } 7077 r.append(a.info.name); 7078 } 7079 } 7080 if (r != null) { 7081 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7082 } 7083 7084 N = pkg.activities.size(); 7085 r = null; 7086 for (i=0; i<N; i++) { 7087 PackageParser.Activity a = pkg.activities.get(i); 7088 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7089 a.info.processName, pkg.applicationInfo.uid); 7090 mActivities.addActivity(a, "activity"); 7091 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7092 if (r == null) { 7093 r = new StringBuilder(256); 7094 } else { 7095 r.append(' '); 7096 } 7097 r.append(a.info.name); 7098 } 7099 } 7100 if (r != null) { 7101 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7102 } 7103 7104 N = pkg.permissionGroups.size(); 7105 r = null; 7106 for (i=0; i<N; i++) { 7107 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7108 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7109 if (cur == null) { 7110 mPermissionGroups.put(pg.info.name, pg); 7111 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7112 if (r == null) { 7113 r = new StringBuilder(256); 7114 } else { 7115 r.append(' '); 7116 } 7117 r.append(pg.info.name); 7118 } 7119 } else { 7120 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7121 + pg.info.packageName + " ignored: original from " 7122 + cur.info.packageName); 7123 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7124 if (r == null) { 7125 r = new StringBuilder(256); 7126 } else { 7127 r.append(' '); 7128 } 7129 r.append("DUP:"); 7130 r.append(pg.info.name); 7131 } 7132 } 7133 } 7134 if (r != null) { 7135 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7136 } 7137 7138 N = pkg.permissions.size(); 7139 r = null; 7140 for (i=0; i<N; i++) { 7141 PackageParser.Permission p = pkg.permissions.get(i); 7142 7143 // Now that permission groups have a special meaning, we ignore permission 7144 // groups for legacy apps to prevent unexpected behavior. In particular, 7145 // permissions for one app being granted to someone just becuase they happen 7146 // to be in a group defined by another app (before this had no implications). 7147 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7148 p.group = mPermissionGroups.get(p.info.group); 7149 // Warn for a permission in an unknown group. 7150 if (p.info.group != null && p.group == null) { 7151 Slog.w(TAG, "Permission " + p.info.name + " from package " 7152 + p.info.packageName + " in an unknown group " + p.info.group); 7153 } 7154 } 7155 7156 ArrayMap<String, BasePermission> permissionMap = 7157 p.tree ? mSettings.mPermissionTrees 7158 : mSettings.mPermissions; 7159 BasePermission bp = permissionMap.get(p.info.name); 7160 7161 // Allow system apps to redefine non-system permissions 7162 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7163 final boolean currentOwnerIsSystem = (bp.perm != null 7164 && isSystemApp(bp.perm.owner)); 7165 if (isSystemApp(p.owner)) { 7166 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7167 // It's a built-in permission and no owner, take ownership now 7168 bp.packageSetting = pkgSetting; 7169 bp.perm = p; 7170 bp.uid = pkg.applicationInfo.uid; 7171 bp.sourcePackage = p.info.packageName; 7172 } else if (!currentOwnerIsSystem) { 7173 String msg = "New decl " + p.owner + " of permission " 7174 + p.info.name + " is system; overriding " + bp.sourcePackage; 7175 reportSettingsProblem(Log.WARN, msg); 7176 bp = null; 7177 } 7178 } 7179 } 7180 7181 if (bp == null) { 7182 bp = new BasePermission(p.info.name, p.info.packageName, 7183 BasePermission.TYPE_NORMAL); 7184 permissionMap.put(p.info.name, bp); 7185 } 7186 7187 if (bp.perm == null) { 7188 if (bp.sourcePackage == null 7189 || bp.sourcePackage.equals(p.info.packageName)) { 7190 BasePermission tree = findPermissionTreeLP(p.info.name); 7191 if (tree == null 7192 || tree.sourcePackage.equals(p.info.packageName)) { 7193 bp.packageSetting = pkgSetting; 7194 bp.perm = p; 7195 bp.uid = pkg.applicationInfo.uid; 7196 bp.sourcePackage = p.info.packageName; 7197 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7198 if (r == null) { 7199 r = new StringBuilder(256); 7200 } else { 7201 r.append(' '); 7202 } 7203 r.append(p.info.name); 7204 } 7205 } else { 7206 Slog.w(TAG, "Permission " + p.info.name + " from package " 7207 + p.info.packageName + " ignored: base tree " 7208 + tree.name + " is from package " 7209 + tree.sourcePackage); 7210 } 7211 } else { 7212 Slog.w(TAG, "Permission " + p.info.name + " from package " 7213 + p.info.packageName + " ignored: original from " 7214 + bp.sourcePackage); 7215 } 7216 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7217 if (r == null) { 7218 r = new StringBuilder(256); 7219 } else { 7220 r.append(' '); 7221 } 7222 r.append("DUP:"); 7223 r.append(p.info.name); 7224 } 7225 if (bp.perm == p) { 7226 bp.protectionLevel = p.info.protectionLevel; 7227 } 7228 } 7229 7230 if (r != null) { 7231 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7232 } 7233 7234 N = pkg.instrumentation.size(); 7235 r = null; 7236 for (i=0; i<N; i++) { 7237 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7238 a.info.packageName = pkg.applicationInfo.packageName; 7239 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7240 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7241 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7242 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7243 a.info.dataDir = pkg.applicationInfo.dataDir; 7244 7245 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7246 // need other information about the application, like the ABI and what not ? 7247 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7248 mInstrumentation.put(a.getComponentName(), a); 7249 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7250 if (r == null) { 7251 r = new StringBuilder(256); 7252 } else { 7253 r.append(' '); 7254 } 7255 r.append(a.info.name); 7256 } 7257 } 7258 if (r != null) { 7259 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7260 } 7261 7262 if (pkg.protectedBroadcasts != null) { 7263 N = pkg.protectedBroadcasts.size(); 7264 for (i=0; i<N; i++) { 7265 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7266 } 7267 } 7268 7269 pkgSetting.setTimeStamp(scanFileTime); 7270 7271 // Create idmap files for pairs of (packages, overlay packages). 7272 // Note: "android", ie framework-res.apk, is handled by native layers. 7273 if (pkg.mOverlayTarget != null) { 7274 // This is an overlay package. 7275 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7276 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7277 mOverlays.put(pkg.mOverlayTarget, 7278 new ArrayMap<String, PackageParser.Package>()); 7279 } 7280 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7281 map.put(pkg.packageName, pkg); 7282 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7283 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7284 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7285 "scanPackageLI failed to createIdmap"); 7286 } 7287 } 7288 } else if (mOverlays.containsKey(pkg.packageName) && 7289 !pkg.packageName.equals("android")) { 7290 // This is a regular package, with one or more known overlay packages. 7291 createIdmapsForPackageLI(pkg); 7292 } 7293 } 7294 7295 return pkg; 7296 } 7297 7298 /** 7299 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7300 * is derived purely on the basis of the contents of {@code scanFile} and 7301 * {@code cpuAbiOverride}. 7302 * 7303 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7304 */ 7305 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7306 String cpuAbiOverride, boolean extractLibs) 7307 throws PackageManagerException { 7308 // TODO: We can probably be smarter about this stuff. For installed apps, 7309 // we can calculate this information at install time once and for all. For 7310 // system apps, we can probably assume that this information doesn't change 7311 // after the first boot scan. As things stand, we do lots of unnecessary work. 7312 7313 // Give ourselves some initial paths; we'll come back for another 7314 // pass once we've determined ABI below. 7315 setNativeLibraryPaths(pkg); 7316 7317 // We would never need to extract libs for forward-locked and external packages, 7318 // since the container service will do it for us. We shouldn't attempt to 7319 // extract libs from system app when it was not updated. 7320 if (pkg.isForwardLocked() || isExternal(pkg) || 7321 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7322 extractLibs = false; 7323 } 7324 7325 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7326 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7327 7328 NativeLibraryHelper.Handle handle = null; 7329 try { 7330 handle = NativeLibraryHelper.Handle.create(scanFile); 7331 // TODO(multiArch): This can be null for apps that didn't go through the 7332 // usual installation process. We can calculate it again, like we 7333 // do during install time. 7334 // 7335 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7336 // unnecessary. 7337 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7338 7339 // Null out the abis so that they can be recalculated. 7340 pkg.applicationInfo.primaryCpuAbi = null; 7341 pkg.applicationInfo.secondaryCpuAbi = null; 7342 if (isMultiArch(pkg.applicationInfo)) { 7343 // Warn if we've set an abiOverride for multi-lib packages.. 7344 // By definition, we need to copy both 32 and 64 bit libraries for 7345 // such packages. 7346 if (pkg.cpuAbiOverride != null 7347 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7348 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7349 } 7350 7351 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7352 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7353 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7354 if (extractLibs) { 7355 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7356 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7357 useIsaSpecificSubdirs); 7358 } else { 7359 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7360 } 7361 } 7362 7363 maybeThrowExceptionForMultiArchCopy( 7364 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7365 7366 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7367 if (extractLibs) { 7368 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7369 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7370 useIsaSpecificSubdirs); 7371 } else { 7372 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7373 } 7374 } 7375 7376 maybeThrowExceptionForMultiArchCopy( 7377 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7378 7379 if (abi64 >= 0) { 7380 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7381 } 7382 7383 if (abi32 >= 0) { 7384 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7385 if (abi64 >= 0) { 7386 pkg.applicationInfo.secondaryCpuAbi = abi; 7387 } else { 7388 pkg.applicationInfo.primaryCpuAbi = abi; 7389 } 7390 } 7391 } else { 7392 String[] abiList = (cpuAbiOverride != null) ? 7393 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7394 7395 // Enable gross and lame hacks for apps that are built with old 7396 // SDK tools. We must scan their APKs for renderscript bitcode and 7397 // not launch them if it's present. Don't bother checking on devices 7398 // that don't have 64 bit support. 7399 boolean needsRenderScriptOverride = false; 7400 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7401 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7402 abiList = Build.SUPPORTED_32_BIT_ABIS; 7403 needsRenderScriptOverride = true; 7404 } 7405 7406 final int copyRet; 7407 if (extractLibs) { 7408 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7409 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7410 } else { 7411 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7412 } 7413 7414 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7415 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7416 "Error unpackaging native libs for app, errorCode=" + copyRet); 7417 } 7418 7419 if (copyRet >= 0) { 7420 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7421 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7422 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7423 } else if (needsRenderScriptOverride) { 7424 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7425 } 7426 } 7427 } catch (IOException ioe) { 7428 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7429 } finally { 7430 IoUtils.closeQuietly(handle); 7431 } 7432 7433 // Now that we've calculated the ABIs and determined if it's an internal app, 7434 // we will go ahead and populate the nativeLibraryPath. 7435 setNativeLibraryPaths(pkg); 7436 } 7437 7438 /** 7439 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7440 * i.e, so that all packages can be run inside a single process if required. 7441 * 7442 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7443 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7444 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7445 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7446 * updating a package that belongs to a shared user. 7447 * 7448 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7449 * adds unnecessary complexity. 7450 */ 7451 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7452 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7453 String requiredInstructionSet = null; 7454 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7455 requiredInstructionSet = VMRuntime.getInstructionSet( 7456 scannedPackage.applicationInfo.primaryCpuAbi); 7457 } 7458 7459 PackageSetting requirer = null; 7460 for (PackageSetting ps : packagesForUser) { 7461 // If packagesForUser contains scannedPackage, we skip it. This will happen 7462 // when scannedPackage is an update of an existing package. Without this check, 7463 // we will never be able to change the ABI of any package belonging to a shared 7464 // user, even if it's compatible with other packages. 7465 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7466 if (ps.primaryCpuAbiString == null) { 7467 continue; 7468 } 7469 7470 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7471 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7472 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7473 // this but there's not much we can do. 7474 String errorMessage = "Instruction set mismatch, " 7475 + ((requirer == null) ? "[caller]" : requirer) 7476 + " requires " + requiredInstructionSet + " whereas " + ps 7477 + " requires " + instructionSet; 7478 Slog.w(TAG, errorMessage); 7479 } 7480 7481 if (requiredInstructionSet == null) { 7482 requiredInstructionSet = instructionSet; 7483 requirer = ps; 7484 } 7485 } 7486 } 7487 7488 if (requiredInstructionSet != null) { 7489 String adjustedAbi; 7490 if (requirer != null) { 7491 // requirer != null implies that either scannedPackage was null or that scannedPackage 7492 // did not require an ABI, in which case we have to adjust scannedPackage to match 7493 // the ABI of the set (which is the same as requirer's ABI) 7494 adjustedAbi = requirer.primaryCpuAbiString; 7495 if (scannedPackage != null) { 7496 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7497 } 7498 } else { 7499 // requirer == null implies that we're updating all ABIs in the set to 7500 // match scannedPackage. 7501 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7502 } 7503 7504 for (PackageSetting ps : packagesForUser) { 7505 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7506 if (ps.primaryCpuAbiString != null) { 7507 continue; 7508 } 7509 7510 ps.primaryCpuAbiString = adjustedAbi; 7511 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7512 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7513 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7514 7515 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7516 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7517 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7518 ps.primaryCpuAbiString = null; 7519 ps.pkg.applicationInfo.primaryCpuAbi = null; 7520 return; 7521 } else { 7522 mInstaller.rmdex(ps.codePathString, 7523 getDexCodeInstructionSet(getPreferredInstructionSet())); 7524 } 7525 } 7526 } 7527 } 7528 } 7529 } 7530 7531 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7532 synchronized (mPackages) { 7533 mResolverReplaced = true; 7534 // Set up information for custom user intent resolution activity. 7535 mResolveActivity.applicationInfo = pkg.applicationInfo; 7536 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7537 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7538 mResolveActivity.processName = pkg.applicationInfo.packageName; 7539 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7540 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7541 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7542 mResolveActivity.theme = 0; 7543 mResolveActivity.exported = true; 7544 mResolveActivity.enabled = true; 7545 mResolveInfo.activityInfo = mResolveActivity; 7546 mResolveInfo.priority = 0; 7547 mResolveInfo.preferredOrder = 0; 7548 mResolveInfo.match = 0; 7549 mResolveComponentName = mCustomResolverComponentName; 7550 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7551 mResolveComponentName); 7552 } 7553 } 7554 7555 private static String calculateBundledApkRoot(final String codePathString) { 7556 final File codePath = new File(codePathString); 7557 final File codeRoot; 7558 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7559 codeRoot = Environment.getRootDirectory(); 7560 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7561 codeRoot = Environment.getOemDirectory(); 7562 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7563 codeRoot = Environment.getVendorDirectory(); 7564 } else { 7565 // Unrecognized code path; take its top real segment as the apk root: 7566 // e.g. /something/app/blah.apk => /something 7567 try { 7568 File f = codePath.getCanonicalFile(); 7569 File parent = f.getParentFile(); // non-null because codePath is a file 7570 File tmp; 7571 while ((tmp = parent.getParentFile()) != null) { 7572 f = parent; 7573 parent = tmp; 7574 } 7575 codeRoot = f; 7576 Slog.w(TAG, "Unrecognized code path " 7577 + codePath + " - using " + codeRoot); 7578 } catch (IOException e) { 7579 // Can't canonicalize the code path -- shenanigans? 7580 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7581 return Environment.getRootDirectory().getPath(); 7582 } 7583 } 7584 return codeRoot.getPath(); 7585 } 7586 7587 /** 7588 * Derive and set the location of native libraries for the given package, 7589 * which varies depending on where and how the package was installed. 7590 */ 7591 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7592 final ApplicationInfo info = pkg.applicationInfo; 7593 final String codePath = pkg.codePath; 7594 final File codeFile = new File(codePath); 7595 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7596 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7597 7598 info.nativeLibraryRootDir = null; 7599 info.nativeLibraryRootRequiresIsa = false; 7600 info.nativeLibraryDir = null; 7601 info.secondaryNativeLibraryDir = null; 7602 7603 if (isApkFile(codeFile)) { 7604 // Monolithic install 7605 if (bundledApp) { 7606 // If "/system/lib64/apkname" exists, assume that is the per-package 7607 // native library directory to use; otherwise use "/system/lib/apkname". 7608 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7609 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7610 getPrimaryInstructionSet(info)); 7611 7612 // This is a bundled system app so choose the path based on the ABI. 7613 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7614 // is just the default path. 7615 final String apkName = deriveCodePathName(codePath); 7616 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7617 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7618 apkName).getAbsolutePath(); 7619 7620 if (info.secondaryCpuAbi != null) { 7621 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7622 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7623 secondaryLibDir, apkName).getAbsolutePath(); 7624 } 7625 } else if (asecApp) { 7626 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7627 .getAbsolutePath(); 7628 } else { 7629 final String apkName = deriveCodePathName(codePath); 7630 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7631 .getAbsolutePath(); 7632 } 7633 7634 info.nativeLibraryRootRequiresIsa = false; 7635 info.nativeLibraryDir = info.nativeLibraryRootDir; 7636 } else { 7637 // Cluster install 7638 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7639 info.nativeLibraryRootRequiresIsa = true; 7640 7641 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7642 getPrimaryInstructionSet(info)).getAbsolutePath(); 7643 7644 if (info.secondaryCpuAbi != null) { 7645 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7646 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7647 } 7648 } 7649 } 7650 7651 /** 7652 * Calculate the abis and roots for a bundled app. These can uniquely 7653 * be determined from the contents of the system partition, i.e whether 7654 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7655 * of this information, and instead assume that the system was built 7656 * sensibly. 7657 */ 7658 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7659 PackageSetting pkgSetting) { 7660 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7661 7662 // If "/system/lib64/apkname" exists, assume that is the per-package 7663 // native library directory to use; otherwise use "/system/lib/apkname". 7664 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7665 setBundledAppAbi(pkg, apkRoot, apkName); 7666 // pkgSetting might be null during rescan following uninstall of updates 7667 // to a bundled app, so accommodate that possibility. The settings in 7668 // that case will be established later from the parsed package. 7669 // 7670 // If the settings aren't null, sync them up with what we've just derived. 7671 // note that apkRoot isn't stored in the package settings. 7672 if (pkgSetting != null) { 7673 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7674 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7675 } 7676 } 7677 7678 /** 7679 * Deduces the ABI of a bundled app and sets the relevant fields on the 7680 * parsed pkg object. 7681 * 7682 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7683 * under which system libraries are installed. 7684 * @param apkName the name of the installed package. 7685 */ 7686 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7687 final File codeFile = new File(pkg.codePath); 7688 7689 final boolean has64BitLibs; 7690 final boolean has32BitLibs; 7691 if (isApkFile(codeFile)) { 7692 // Monolithic install 7693 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7694 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7695 } else { 7696 // Cluster install 7697 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7698 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7699 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7700 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7701 has64BitLibs = (new File(rootDir, isa)).exists(); 7702 } else { 7703 has64BitLibs = false; 7704 } 7705 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7706 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7707 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7708 has32BitLibs = (new File(rootDir, isa)).exists(); 7709 } else { 7710 has32BitLibs = false; 7711 } 7712 } 7713 7714 if (has64BitLibs && !has32BitLibs) { 7715 // The package has 64 bit libs, but not 32 bit libs. Its primary 7716 // ABI should be 64 bit. We can safely assume here that the bundled 7717 // native libraries correspond to the most preferred ABI in the list. 7718 7719 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7720 pkg.applicationInfo.secondaryCpuAbi = null; 7721 } else if (has32BitLibs && !has64BitLibs) { 7722 // The package has 32 bit libs but not 64 bit libs. Its primary 7723 // ABI should be 32 bit. 7724 7725 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7726 pkg.applicationInfo.secondaryCpuAbi = null; 7727 } else if (has32BitLibs && has64BitLibs) { 7728 // The application has both 64 and 32 bit bundled libraries. We check 7729 // here that the app declares multiArch support, and warn if it doesn't. 7730 // 7731 // We will be lenient here and record both ABIs. The primary will be the 7732 // ABI that's higher on the list, i.e, a device that's configured to prefer 7733 // 64 bit apps will see a 64 bit primary ABI, 7734 7735 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7736 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7737 } 7738 7739 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7740 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7741 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7742 } else { 7743 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7744 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7745 } 7746 } else { 7747 pkg.applicationInfo.primaryCpuAbi = null; 7748 pkg.applicationInfo.secondaryCpuAbi = null; 7749 } 7750 } 7751 7752 private void killApplication(String pkgName, int appId, String reason) { 7753 // Request the ActivityManager to kill the process(only for existing packages) 7754 // so that we do not end up in a confused state while the user is still using the older 7755 // version of the application while the new one gets installed. 7756 IActivityManager am = ActivityManagerNative.getDefault(); 7757 if (am != null) { 7758 try { 7759 am.killApplicationWithAppId(pkgName, appId, reason); 7760 } catch (RemoteException e) { 7761 } 7762 } 7763 } 7764 7765 void removePackageLI(PackageSetting ps, boolean chatty) { 7766 if (DEBUG_INSTALL) { 7767 if (chatty) 7768 Log.d(TAG, "Removing package " + ps.name); 7769 } 7770 7771 // writer 7772 synchronized (mPackages) { 7773 mPackages.remove(ps.name); 7774 final PackageParser.Package pkg = ps.pkg; 7775 if (pkg != null) { 7776 cleanPackageDataStructuresLILPw(pkg, chatty); 7777 } 7778 } 7779 } 7780 7781 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7782 if (DEBUG_INSTALL) { 7783 if (chatty) 7784 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7785 } 7786 7787 // writer 7788 synchronized (mPackages) { 7789 mPackages.remove(pkg.applicationInfo.packageName); 7790 cleanPackageDataStructuresLILPw(pkg, chatty); 7791 } 7792 } 7793 7794 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7795 int N = pkg.providers.size(); 7796 StringBuilder r = null; 7797 int i; 7798 for (i=0; i<N; i++) { 7799 PackageParser.Provider p = pkg.providers.get(i); 7800 mProviders.removeProvider(p); 7801 if (p.info.authority == null) { 7802 7803 /* There was another ContentProvider with this authority when 7804 * this app was installed so this authority is null, 7805 * Ignore it as we don't have to unregister the provider. 7806 */ 7807 continue; 7808 } 7809 String names[] = p.info.authority.split(";"); 7810 for (int j = 0; j < names.length; j++) { 7811 if (mProvidersByAuthority.get(names[j]) == p) { 7812 mProvidersByAuthority.remove(names[j]); 7813 if (DEBUG_REMOVE) { 7814 if (chatty) 7815 Log.d(TAG, "Unregistered content provider: " + names[j] 7816 + ", className = " + p.info.name + ", isSyncable = " 7817 + p.info.isSyncable); 7818 } 7819 } 7820 } 7821 if (DEBUG_REMOVE && chatty) { 7822 if (r == null) { 7823 r = new StringBuilder(256); 7824 } else { 7825 r.append(' '); 7826 } 7827 r.append(p.info.name); 7828 } 7829 } 7830 if (r != null) { 7831 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7832 } 7833 7834 N = pkg.services.size(); 7835 r = null; 7836 for (i=0; i<N; i++) { 7837 PackageParser.Service s = pkg.services.get(i); 7838 mServices.removeService(s); 7839 if (chatty) { 7840 if (r == null) { 7841 r = new StringBuilder(256); 7842 } else { 7843 r.append(' '); 7844 } 7845 r.append(s.info.name); 7846 } 7847 } 7848 if (r != null) { 7849 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7850 } 7851 7852 N = pkg.receivers.size(); 7853 r = null; 7854 for (i=0; i<N; i++) { 7855 PackageParser.Activity a = pkg.receivers.get(i); 7856 mReceivers.removeActivity(a, "receiver"); 7857 if (DEBUG_REMOVE && chatty) { 7858 if (r == null) { 7859 r = new StringBuilder(256); 7860 } else { 7861 r.append(' '); 7862 } 7863 r.append(a.info.name); 7864 } 7865 } 7866 if (r != null) { 7867 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7868 } 7869 7870 N = pkg.activities.size(); 7871 r = null; 7872 for (i=0; i<N; i++) { 7873 PackageParser.Activity a = pkg.activities.get(i); 7874 mActivities.removeActivity(a, "activity"); 7875 if (DEBUG_REMOVE && chatty) { 7876 if (r == null) { 7877 r = new StringBuilder(256); 7878 } else { 7879 r.append(' '); 7880 } 7881 r.append(a.info.name); 7882 } 7883 } 7884 if (r != null) { 7885 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7886 } 7887 7888 N = pkg.permissions.size(); 7889 r = null; 7890 for (i=0; i<N; i++) { 7891 PackageParser.Permission p = pkg.permissions.get(i); 7892 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7893 if (bp == null) { 7894 bp = mSettings.mPermissionTrees.get(p.info.name); 7895 } 7896 if (bp != null && bp.perm == p) { 7897 bp.perm = null; 7898 if (DEBUG_REMOVE && chatty) { 7899 if (r == null) { 7900 r = new StringBuilder(256); 7901 } else { 7902 r.append(' '); 7903 } 7904 r.append(p.info.name); 7905 } 7906 } 7907 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7908 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7909 if (appOpPerms != null) { 7910 appOpPerms.remove(pkg.packageName); 7911 } 7912 } 7913 } 7914 if (r != null) { 7915 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7916 } 7917 7918 N = pkg.requestedPermissions.size(); 7919 r = null; 7920 for (i=0; i<N; i++) { 7921 String perm = pkg.requestedPermissions.get(i); 7922 BasePermission bp = mSettings.mPermissions.get(perm); 7923 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7924 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7925 if (appOpPerms != null) { 7926 appOpPerms.remove(pkg.packageName); 7927 if (appOpPerms.isEmpty()) { 7928 mAppOpPermissionPackages.remove(perm); 7929 } 7930 } 7931 } 7932 } 7933 if (r != null) { 7934 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7935 } 7936 7937 N = pkg.instrumentation.size(); 7938 r = null; 7939 for (i=0; i<N; i++) { 7940 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7941 mInstrumentation.remove(a.getComponentName()); 7942 if (DEBUG_REMOVE && chatty) { 7943 if (r == null) { 7944 r = new StringBuilder(256); 7945 } else { 7946 r.append(' '); 7947 } 7948 r.append(a.info.name); 7949 } 7950 } 7951 if (r != null) { 7952 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7953 } 7954 7955 r = null; 7956 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7957 // Only system apps can hold shared libraries. 7958 if (pkg.libraryNames != null) { 7959 for (i=0; i<pkg.libraryNames.size(); i++) { 7960 String name = pkg.libraryNames.get(i); 7961 SharedLibraryEntry cur = mSharedLibraries.get(name); 7962 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7963 mSharedLibraries.remove(name); 7964 if (DEBUG_REMOVE && chatty) { 7965 if (r == null) { 7966 r = new StringBuilder(256); 7967 } else { 7968 r.append(' '); 7969 } 7970 r.append(name); 7971 } 7972 } 7973 } 7974 } 7975 } 7976 if (r != null) { 7977 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7978 } 7979 } 7980 7981 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7982 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7983 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7984 return true; 7985 } 7986 } 7987 return false; 7988 } 7989 7990 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7991 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7992 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7993 7994 private void updatePermissionsLPw(String changingPkg, 7995 PackageParser.Package pkgInfo, int flags) { 7996 // Make sure there are no dangling permission trees. 7997 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7998 while (it.hasNext()) { 7999 final BasePermission bp = it.next(); 8000 if (bp.packageSetting == null) { 8001 // We may not yet have parsed the package, so just see if 8002 // we still know about its settings. 8003 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8004 } 8005 if (bp.packageSetting == null) { 8006 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8007 + " from package " + bp.sourcePackage); 8008 it.remove(); 8009 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8010 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8011 Slog.i(TAG, "Removing old permission tree: " + bp.name 8012 + " from package " + bp.sourcePackage); 8013 flags |= UPDATE_PERMISSIONS_ALL; 8014 it.remove(); 8015 } 8016 } 8017 } 8018 8019 // Make sure all dynamic permissions have been assigned to a package, 8020 // and make sure there are no dangling permissions. 8021 it = mSettings.mPermissions.values().iterator(); 8022 while (it.hasNext()) { 8023 final BasePermission bp = it.next(); 8024 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8025 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8026 + bp.name + " pkg=" + bp.sourcePackage 8027 + " info=" + bp.pendingInfo); 8028 if (bp.packageSetting == null && bp.pendingInfo != null) { 8029 final BasePermission tree = findPermissionTreeLP(bp.name); 8030 if (tree != null && tree.perm != null) { 8031 bp.packageSetting = tree.packageSetting; 8032 bp.perm = new PackageParser.Permission(tree.perm.owner, 8033 new PermissionInfo(bp.pendingInfo)); 8034 bp.perm.info.packageName = tree.perm.info.packageName; 8035 bp.perm.info.name = bp.name; 8036 bp.uid = tree.uid; 8037 } 8038 } 8039 } 8040 if (bp.packageSetting == null) { 8041 // We may not yet have parsed the package, so just see if 8042 // we still know about its settings. 8043 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8044 } 8045 if (bp.packageSetting == null) { 8046 Slog.w(TAG, "Removing dangling permission: " + bp.name 8047 + " from package " + bp.sourcePackage); 8048 it.remove(); 8049 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8050 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8051 Slog.i(TAG, "Removing old permission: " + bp.name 8052 + " from package " + bp.sourcePackage); 8053 flags |= UPDATE_PERMISSIONS_ALL; 8054 it.remove(); 8055 } 8056 } 8057 } 8058 8059 // Now update the permissions for all packages, in particular 8060 // replace the granted permissions of the system packages. 8061 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8062 for (PackageParser.Package pkg : mPackages.values()) { 8063 if (pkg != pkgInfo) { 8064 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8065 changingPkg); 8066 } 8067 } 8068 } 8069 8070 if (pkgInfo != null) { 8071 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8072 } 8073 } 8074 8075 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8076 String packageOfInterest) { 8077 // IMPORTANT: There are two types of permissions: install and runtime. 8078 // Install time permissions are granted when the app is installed to 8079 // all device users and users added in the future. Runtime permissions 8080 // are granted at runtime explicitly to specific users. Normal and signature 8081 // protected permissions are install time permissions. Dangerous permissions 8082 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8083 // otherwise they are runtime permissions. This function does not manage 8084 // runtime permissions except for the case an app targeting Lollipop MR1 8085 // being upgraded to target a newer SDK, in which case dangerous permissions 8086 // are transformed from install time to runtime ones. 8087 8088 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8089 if (ps == null) { 8090 return; 8091 } 8092 8093 PermissionsState permissionsState = ps.getPermissionsState(); 8094 PermissionsState origPermissions = permissionsState; 8095 8096 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8097 8098 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8099 8100 boolean changedInstallPermission = false; 8101 8102 if (replace) { 8103 ps.installPermissionsFixed = false; 8104 if (!ps.isSharedUser()) { 8105 origPermissions = new PermissionsState(permissionsState); 8106 permissionsState.reset(); 8107 } 8108 } 8109 8110 permissionsState.setGlobalGids(mGlobalGids); 8111 8112 final int N = pkg.requestedPermissions.size(); 8113 for (int i=0; i<N; i++) { 8114 final String name = pkg.requestedPermissions.get(i); 8115 final BasePermission bp = mSettings.mPermissions.get(name); 8116 8117 if (DEBUG_INSTALL) { 8118 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8119 } 8120 8121 if (bp == null || bp.packageSetting == null) { 8122 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8123 Slog.w(TAG, "Unknown permission " + name 8124 + " in package " + pkg.packageName); 8125 } 8126 continue; 8127 } 8128 8129 final String perm = bp.name; 8130 boolean allowedSig = false; 8131 int grant = GRANT_DENIED; 8132 8133 // Keep track of app op permissions. 8134 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8135 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8136 if (pkgs == null) { 8137 pkgs = new ArraySet<>(); 8138 mAppOpPermissionPackages.put(bp.name, pkgs); 8139 } 8140 pkgs.add(pkg.packageName); 8141 } 8142 8143 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8144 switch (level) { 8145 case PermissionInfo.PROTECTION_NORMAL: { 8146 // For all apps normal permissions are install time ones. 8147 grant = GRANT_INSTALL; 8148 } break; 8149 8150 case PermissionInfo.PROTECTION_DANGEROUS: { 8151 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8152 // For legacy apps dangerous permissions are install time ones. 8153 grant = GRANT_INSTALL_LEGACY; 8154 } else if (origPermissions.hasInstallPermission(bp.name)) { 8155 // For legacy apps that became modern, install becomes runtime. 8156 grant = GRANT_UPGRADE; 8157 } else { 8158 // For modern apps keep runtime permissions unchanged. 8159 grant = GRANT_RUNTIME; 8160 } 8161 } break; 8162 8163 case PermissionInfo.PROTECTION_SIGNATURE: { 8164 // For all apps signature permissions are install time ones. 8165 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8166 if (allowedSig) { 8167 grant = GRANT_INSTALL; 8168 } 8169 } break; 8170 } 8171 8172 if (DEBUG_INSTALL) { 8173 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8174 } 8175 8176 if (grant != GRANT_DENIED) { 8177 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8178 // If this is an existing, non-system package, then 8179 // we can't add any new permissions to it. 8180 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8181 // Except... if this is a permission that was added 8182 // to the platform (note: need to only do this when 8183 // updating the platform). 8184 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8185 grant = GRANT_DENIED; 8186 } 8187 } 8188 } 8189 8190 switch (grant) { 8191 case GRANT_INSTALL: { 8192 // Revoke this as runtime permission to handle the case of 8193 // a runtime permission being downgraded to an install one. 8194 for (int userId : UserManagerService.getInstance().getUserIds()) { 8195 if (origPermissions.getRuntimePermissionState( 8196 bp.name, userId) != null) { 8197 // Revoke the runtime permission and clear the flags. 8198 origPermissions.revokeRuntimePermission(bp, userId); 8199 origPermissions.updatePermissionFlags(bp, userId, 8200 PackageManager.MASK_PERMISSION_FLAGS, 0); 8201 // If we revoked a permission permission, we have to write. 8202 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8203 changedRuntimePermissionUserIds, userId); 8204 } 8205 } 8206 // Grant an install permission. 8207 if (permissionsState.grantInstallPermission(bp) != 8208 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8209 changedInstallPermission = true; 8210 } 8211 } break; 8212 8213 case GRANT_INSTALL_LEGACY: { 8214 // Grant an install permission. 8215 if (permissionsState.grantInstallPermission(bp) != 8216 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8217 changedInstallPermission = true; 8218 } 8219 } break; 8220 8221 case GRANT_RUNTIME: { 8222 // Grant previously granted runtime permissions. 8223 for (int userId : UserManagerService.getInstance().getUserIds()) { 8224 PermissionState permissionState = origPermissions 8225 .getRuntimePermissionState(bp.name, userId); 8226 final int flags = permissionState != null 8227 ? permissionState.getFlags() : 0; 8228 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8229 if (permissionsState.grantRuntimePermission(bp, userId) == 8230 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8231 // If we cannot put the permission as it was, we have to write. 8232 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8233 changedRuntimePermissionUserIds, userId); 8234 } 8235 } 8236 // Propagate the permission flags. 8237 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8238 } 8239 } break; 8240 8241 case GRANT_UPGRADE: { 8242 // Grant runtime permissions for a previously held install permission. 8243 PermissionState permissionState = origPermissions 8244 .getInstallPermissionState(bp.name); 8245 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8246 8247 if (origPermissions.revokeInstallPermission(bp) 8248 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8249 // We will be transferring the permission flags, so clear them. 8250 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8251 PackageManager.MASK_PERMISSION_FLAGS, 0); 8252 changedInstallPermission = true; 8253 } 8254 8255 // If the permission is not to be promoted to runtime we ignore it and 8256 // also its other flags as they are not applicable to install permissions. 8257 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8258 for (int userId : currentUserIds) { 8259 if (permissionsState.grantRuntimePermission(bp, userId) != 8260 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8261 // Transfer the permission flags. 8262 permissionsState.updatePermissionFlags(bp, userId, 8263 flags, flags); 8264 // If we granted the permission, we have to write. 8265 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8266 changedRuntimePermissionUserIds, userId); 8267 } 8268 } 8269 } 8270 } break; 8271 8272 default: { 8273 if (packageOfInterest == null 8274 || packageOfInterest.equals(pkg.packageName)) { 8275 Slog.w(TAG, "Not granting permission " + perm 8276 + " to package " + pkg.packageName 8277 + " because it was previously installed without"); 8278 } 8279 } break; 8280 } 8281 } else { 8282 if (permissionsState.revokeInstallPermission(bp) != 8283 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8284 // Also drop the permission flags. 8285 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8286 PackageManager.MASK_PERMISSION_FLAGS, 0); 8287 changedInstallPermission = true; 8288 Slog.i(TAG, "Un-granting permission " + perm 8289 + " from package " + pkg.packageName 8290 + " (protectionLevel=" + bp.protectionLevel 8291 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8292 + ")"); 8293 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8294 // Don't print warning for app op permissions, since it is fine for them 8295 // not to be granted, there is a UI for the user to decide. 8296 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8297 Slog.w(TAG, "Not granting permission " + perm 8298 + " to package " + pkg.packageName 8299 + " (protectionLevel=" + bp.protectionLevel 8300 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8301 + ")"); 8302 } 8303 } 8304 } 8305 } 8306 8307 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8308 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8309 // This is the first that we have heard about this package, so the 8310 // permissions we have now selected are fixed until explicitly 8311 // changed. 8312 ps.installPermissionsFixed = true; 8313 } 8314 8315 // Persist the runtime permissions state for users with changes. 8316 for (int userId : changedRuntimePermissionUserIds) { 8317 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8318 } 8319 } 8320 8321 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8322 boolean allowed = false; 8323 final int NP = PackageParser.NEW_PERMISSIONS.length; 8324 for (int ip=0; ip<NP; ip++) { 8325 final PackageParser.NewPermissionInfo npi 8326 = PackageParser.NEW_PERMISSIONS[ip]; 8327 if (npi.name.equals(perm) 8328 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8329 allowed = true; 8330 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8331 + pkg.packageName); 8332 break; 8333 } 8334 } 8335 return allowed; 8336 } 8337 8338 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8339 BasePermission bp, PermissionsState origPermissions) { 8340 boolean allowed; 8341 allowed = (compareSignatures( 8342 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8343 == PackageManager.SIGNATURE_MATCH) 8344 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8345 == PackageManager.SIGNATURE_MATCH); 8346 if (!allowed && (bp.protectionLevel 8347 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8348 if (isSystemApp(pkg)) { 8349 // For updated system applications, a system permission 8350 // is granted only if it had been defined by the original application. 8351 if (pkg.isUpdatedSystemApp()) { 8352 final PackageSetting sysPs = mSettings 8353 .getDisabledSystemPkgLPr(pkg.packageName); 8354 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8355 // If the original was granted this permission, we take 8356 // that grant decision as read and propagate it to the 8357 // update. 8358 if (sysPs.isPrivileged()) { 8359 allowed = true; 8360 } 8361 } else { 8362 // The system apk may have been updated with an older 8363 // version of the one on the data partition, but which 8364 // granted a new system permission that it didn't have 8365 // before. In this case we do want to allow the app to 8366 // now get the new permission if the ancestral apk is 8367 // privileged to get it. 8368 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8369 for (int j=0; 8370 j<sysPs.pkg.requestedPermissions.size(); j++) { 8371 if (perm.equals( 8372 sysPs.pkg.requestedPermissions.get(j))) { 8373 allowed = true; 8374 break; 8375 } 8376 } 8377 } 8378 } 8379 } else { 8380 allowed = isPrivilegedApp(pkg); 8381 } 8382 } 8383 } 8384 if (!allowed && (bp.protectionLevel 8385 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8386 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8387 // If this was a previously normal/dangerous permission that got moved 8388 // to a system permission as part of the runtime permission redesign, then 8389 // we still want to blindly grant it to old apps. 8390 allowed = true; 8391 } 8392 if (!allowed && (bp.protectionLevel 8393 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8394 // For development permissions, a development permission 8395 // is granted only if it was already granted. 8396 allowed = origPermissions.hasInstallPermission(perm); 8397 } 8398 return allowed; 8399 } 8400 8401 final class ActivityIntentResolver 8402 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8403 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8404 boolean defaultOnly, int userId) { 8405 if (!sUserManager.exists(userId)) return null; 8406 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8407 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8408 } 8409 8410 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8411 int userId) { 8412 if (!sUserManager.exists(userId)) return null; 8413 mFlags = flags; 8414 return super.queryIntent(intent, resolvedType, 8415 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8416 } 8417 8418 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8419 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8420 if (!sUserManager.exists(userId)) return null; 8421 if (packageActivities == null) { 8422 return null; 8423 } 8424 mFlags = flags; 8425 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8426 final int N = packageActivities.size(); 8427 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8428 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8429 8430 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8431 for (int i = 0; i < N; ++i) { 8432 intentFilters = packageActivities.get(i).intents; 8433 if (intentFilters != null && intentFilters.size() > 0) { 8434 PackageParser.ActivityIntentInfo[] array = 8435 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8436 intentFilters.toArray(array); 8437 listCut.add(array); 8438 } 8439 } 8440 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8441 } 8442 8443 public final void addActivity(PackageParser.Activity a, String type) { 8444 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8445 mActivities.put(a.getComponentName(), a); 8446 if (DEBUG_SHOW_INFO) 8447 Log.v( 8448 TAG, " " + type + " " + 8449 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8450 if (DEBUG_SHOW_INFO) 8451 Log.v(TAG, " Class=" + a.info.name); 8452 final int NI = a.intents.size(); 8453 for (int j=0; j<NI; j++) { 8454 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8455 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8456 intent.setPriority(0); 8457 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8458 + a.className + " with priority > 0, forcing to 0"); 8459 } 8460 if (DEBUG_SHOW_INFO) { 8461 Log.v(TAG, " IntentFilter:"); 8462 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8463 } 8464 if (!intent.debugCheck()) { 8465 Log.w(TAG, "==> For Activity " + a.info.name); 8466 } 8467 addFilter(intent); 8468 } 8469 } 8470 8471 public final void removeActivity(PackageParser.Activity a, String type) { 8472 mActivities.remove(a.getComponentName()); 8473 if (DEBUG_SHOW_INFO) { 8474 Log.v(TAG, " " + type + " " 8475 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8476 : a.info.name) + ":"); 8477 Log.v(TAG, " Class=" + a.info.name); 8478 } 8479 final int NI = a.intents.size(); 8480 for (int j=0; j<NI; j++) { 8481 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8482 if (DEBUG_SHOW_INFO) { 8483 Log.v(TAG, " IntentFilter:"); 8484 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8485 } 8486 removeFilter(intent); 8487 } 8488 } 8489 8490 @Override 8491 protected boolean allowFilterResult( 8492 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8493 ActivityInfo filterAi = filter.activity.info; 8494 for (int i=dest.size()-1; i>=0; i--) { 8495 ActivityInfo destAi = dest.get(i).activityInfo; 8496 if (destAi.name == filterAi.name 8497 && destAi.packageName == filterAi.packageName) { 8498 return false; 8499 } 8500 } 8501 return true; 8502 } 8503 8504 @Override 8505 protected ActivityIntentInfo[] newArray(int size) { 8506 return new ActivityIntentInfo[size]; 8507 } 8508 8509 @Override 8510 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8511 if (!sUserManager.exists(userId)) return true; 8512 PackageParser.Package p = filter.activity.owner; 8513 if (p != null) { 8514 PackageSetting ps = (PackageSetting)p.mExtras; 8515 if (ps != null) { 8516 // System apps are never considered stopped for purposes of 8517 // filtering, because there may be no way for the user to 8518 // actually re-launch them. 8519 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8520 && ps.getStopped(userId); 8521 } 8522 } 8523 return false; 8524 } 8525 8526 @Override 8527 protected boolean isPackageForFilter(String packageName, 8528 PackageParser.ActivityIntentInfo info) { 8529 return packageName.equals(info.activity.owner.packageName); 8530 } 8531 8532 @Override 8533 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8534 int match, int userId) { 8535 if (!sUserManager.exists(userId)) return null; 8536 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8537 return null; 8538 } 8539 final PackageParser.Activity activity = info.activity; 8540 if (mSafeMode && (activity.info.applicationInfo.flags 8541 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8542 return null; 8543 } 8544 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8545 if (ps == null) { 8546 return null; 8547 } 8548 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8549 ps.readUserState(userId), userId); 8550 if (ai == null) { 8551 return null; 8552 } 8553 final ResolveInfo res = new ResolveInfo(); 8554 res.activityInfo = ai; 8555 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8556 res.filter = info; 8557 } 8558 if (info != null) { 8559 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8560 } 8561 res.priority = info.getPriority(); 8562 res.preferredOrder = activity.owner.mPreferredOrder; 8563 //System.out.println("Result: " + res.activityInfo.className + 8564 // " = " + res.priority); 8565 res.match = match; 8566 res.isDefault = info.hasDefault; 8567 res.labelRes = info.labelRes; 8568 res.nonLocalizedLabel = info.nonLocalizedLabel; 8569 if (userNeedsBadging(userId)) { 8570 res.noResourceId = true; 8571 } else { 8572 res.icon = info.icon; 8573 } 8574 res.iconResourceId = info.icon; 8575 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8576 return res; 8577 } 8578 8579 @Override 8580 protected void sortResults(List<ResolveInfo> results) { 8581 Collections.sort(results, mResolvePrioritySorter); 8582 } 8583 8584 @Override 8585 protected void dumpFilter(PrintWriter out, String prefix, 8586 PackageParser.ActivityIntentInfo filter) { 8587 out.print(prefix); out.print( 8588 Integer.toHexString(System.identityHashCode(filter.activity))); 8589 out.print(' '); 8590 filter.activity.printComponentShortName(out); 8591 out.print(" filter "); 8592 out.println(Integer.toHexString(System.identityHashCode(filter))); 8593 } 8594 8595 @Override 8596 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8597 return filter.activity; 8598 } 8599 8600 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8601 PackageParser.Activity activity = (PackageParser.Activity)label; 8602 out.print(prefix); out.print( 8603 Integer.toHexString(System.identityHashCode(activity))); 8604 out.print(' '); 8605 activity.printComponentShortName(out); 8606 if (count > 1) { 8607 out.print(" ("); out.print(count); out.print(" filters)"); 8608 } 8609 out.println(); 8610 } 8611 8612// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8613// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8614// final List<ResolveInfo> retList = Lists.newArrayList(); 8615// while (i.hasNext()) { 8616// final ResolveInfo resolveInfo = i.next(); 8617// if (isEnabledLP(resolveInfo.activityInfo)) { 8618// retList.add(resolveInfo); 8619// } 8620// } 8621// return retList; 8622// } 8623 8624 // Keys are String (activity class name), values are Activity. 8625 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8626 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8627 private int mFlags; 8628 } 8629 8630 private final class ServiceIntentResolver 8631 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8632 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8633 boolean defaultOnly, int userId) { 8634 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8635 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8636 } 8637 8638 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8639 int userId) { 8640 if (!sUserManager.exists(userId)) return null; 8641 mFlags = flags; 8642 return super.queryIntent(intent, resolvedType, 8643 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8644 } 8645 8646 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8647 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8648 if (!sUserManager.exists(userId)) return null; 8649 if (packageServices == null) { 8650 return null; 8651 } 8652 mFlags = flags; 8653 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8654 final int N = packageServices.size(); 8655 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8656 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8657 8658 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8659 for (int i = 0; i < N; ++i) { 8660 intentFilters = packageServices.get(i).intents; 8661 if (intentFilters != null && intentFilters.size() > 0) { 8662 PackageParser.ServiceIntentInfo[] array = 8663 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8664 intentFilters.toArray(array); 8665 listCut.add(array); 8666 } 8667 } 8668 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8669 } 8670 8671 public final void addService(PackageParser.Service s) { 8672 mServices.put(s.getComponentName(), s); 8673 if (DEBUG_SHOW_INFO) { 8674 Log.v(TAG, " " 8675 + (s.info.nonLocalizedLabel != null 8676 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8677 Log.v(TAG, " Class=" + s.info.name); 8678 } 8679 final int NI = s.intents.size(); 8680 int j; 8681 for (j=0; j<NI; j++) { 8682 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8683 if (DEBUG_SHOW_INFO) { 8684 Log.v(TAG, " IntentFilter:"); 8685 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8686 } 8687 if (!intent.debugCheck()) { 8688 Log.w(TAG, "==> For Service " + s.info.name); 8689 } 8690 addFilter(intent); 8691 } 8692 } 8693 8694 public final void removeService(PackageParser.Service s) { 8695 mServices.remove(s.getComponentName()); 8696 if (DEBUG_SHOW_INFO) { 8697 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8698 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8699 Log.v(TAG, " Class=" + s.info.name); 8700 } 8701 final int NI = s.intents.size(); 8702 int j; 8703 for (j=0; j<NI; j++) { 8704 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8705 if (DEBUG_SHOW_INFO) { 8706 Log.v(TAG, " IntentFilter:"); 8707 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8708 } 8709 removeFilter(intent); 8710 } 8711 } 8712 8713 @Override 8714 protected boolean allowFilterResult( 8715 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8716 ServiceInfo filterSi = filter.service.info; 8717 for (int i=dest.size()-1; i>=0; i--) { 8718 ServiceInfo destAi = dest.get(i).serviceInfo; 8719 if (destAi.name == filterSi.name 8720 && destAi.packageName == filterSi.packageName) { 8721 return false; 8722 } 8723 } 8724 return true; 8725 } 8726 8727 @Override 8728 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8729 return new PackageParser.ServiceIntentInfo[size]; 8730 } 8731 8732 @Override 8733 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8734 if (!sUserManager.exists(userId)) return true; 8735 PackageParser.Package p = filter.service.owner; 8736 if (p != null) { 8737 PackageSetting ps = (PackageSetting)p.mExtras; 8738 if (ps != null) { 8739 // System apps are never considered stopped for purposes of 8740 // filtering, because there may be no way for the user to 8741 // actually re-launch them. 8742 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8743 && ps.getStopped(userId); 8744 } 8745 } 8746 return false; 8747 } 8748 8749 @Override 8750 protected boolean isPackageForFilter(String packageName, 8751 PackageParser.ServiceIntentInfo info) { 8752 return packageName.equals(info.service.owner.packageName); 8753 } 8754 8755 @Override 8756 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8757 int match, int userId) { 8758 if (!sUserManager.exists(userId)) return null; 8759 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8760 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8761 return null; 8762 } 8763 final PackageParser.Service service = info.service; 8764 if (mSafeMode && (service.info.applicationInfo.flags 8765 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8766 return null; 8767 } 8768 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8769 if (ps == null) { 8770 return null; 8771 } 8772 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8773 ps.readUserState(userId), userId); 8774 if (si == null) { 8775 return null; 8776 } 8777 final ResolveInfo res = new ResolveInfo(); 8778 res.serviceInfo = si; 8779 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8780 res.filter = filter; 8781 } 8782 res.priority = info.getPriority(); 8783 res.preferredOrder = service.owner.mPreferredOrder; 8784 res.match = match; 8785 res.isDefault = info.hasDefault; 8786 res.labelRes = info.labelRes; 8787 res.nonLocalizedLabel = info.nonLocalizedLabel; 8788 res.icon = info.icon; 8789 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8790 return res; 8791 } 8792 8793 @Override 8794 protected void sortResults(List<ResolveInfo> results) { 8795 Collections.sort(results, mResolvePrioritySorter); 8796 } 8797 8798 @Override 8799 protected void dumpFilter(PrintWriter out, String prefix, 8800 PackageParser.ServiceIntentInfo filter) { 8801 out.print(prefix); out.print( 8802 Integer.toHexString(System.identityHashCode(filter.service))); 8803 out.print(' '); 8804 filter.service.printComponentShortName(out); 8805 out.print(" filter "); 8806 out.println(Integer.toHexString(System.identityHashCode(filter))); 8807 } 8808 8809 @Override 8810 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8811 return filter.service; 8812 } 8813 8814 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8815 PackageParser.Service service = (PackageParser.Service)label; 8816 out.print(prefix); out.print( 8817 Integer.toHexString(System.identityHashCode(service))); 8818 out.print(' '); 8819 service.printComponentShortName(out); 8820 if (count > 1) { 8821 out.print(" ("); out.print(count); out.print(" filters)"); 8822 } 8823 out.println(); 8824 } 8825 8826// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8827// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8828// final List<ResolveInfo> retList = Lists.newArrayList(); 8829// while (i.hasNext()) { 8830// final ResolveInfo resolveInfo = (ResolveInfo) i; 8831// if (isEnabledLP(resolveInfo.serviceInfo)) { 8832// retList.add(resolveInfo); 8833// } 8834// } 8835// return retList; 8836// } 8837 8838 // Keys are String (activity class name), values are Activity. 8839 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8840 = new ArrayMap<ComponentName, PackageParser.Service>(); 8841 private int mFlags; 8842 }; 8843 8844 private final class ProviderIntentResolver 8845 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8846 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8847 boolean defaultOnly, int userId) { 8848 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8849 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8850 } 8851 8852 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8853 int userId) { 8854 if (!sUserManager.exists(userId)) 8855 return null; 8856 mFlags = flags; 8857 return super.queryIntent(intent, resolvedType, 8858 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8859 } 8860 8861 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8862 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8863 if (!sUserManager.exists(userId)) 8864 return null; 8865 if (packageProviders == null) { 8866 return null; 8867 } 8868 mFlags = flags; 8869 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8870 final int N = packageProviders.size(); 8871 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8872 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8873 8874 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8875 for (int i = 0; i < N; ++i) { 8876 intentFilters = packageProviders.get(i).intents; 8877 if (intentFilters != null && intentFilters.size() > 0) { 8878 PackageParser.ProviderIntentInfo[] array = 8879 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8880 intentFilters.toArray(array); 8881 listCut.add(array); 8882 } 8883 } 8884 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8885 } 8886 8887 public final void addProvider(PackageParser.Provider p) { 8888 if (mProviders.containsKey(p.getComponentName())) { 8889 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8890 return; 8891 } 8892 8893 mProviders.put(p.getComponentName(), p); 8894 if (DEBUG_SHOW_INFO) { 8895 Log.v(TAG, " " 8896 + (p.info.nonLocalizedLabel != null 8897 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8898 Log.v(TAG, " Class=" + p.info.name); 8899 } 8900 final int NI = p.intents.size(); 8901 int j; 8902 for (j = 0; j < NI; j++) { 8903 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8904 if (DEBUG_SHOW_INFO) { 8905 Log.v(TAG, " IntentFilter:"); 8906 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8907 } 8908 if (!intent.debugCheck()) { 8909 Log.w(TAG, "==> For Provider " + p.info.name); 8910 } 8911 addFilter(intent); 8912 } 8913 } 8914 8915 public final void removeProvider(PackageParser.Provider p) { 8916 mProviders.remove(p.getComponentName()); 8917 if (DEBUG_SHOW_INFO) { 8918 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8919 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8920 Log.v(TAG, " Class=" + p.info.name); 8921 } 8922 final int NI = p.intents.size(); 8923 int j; 8924 for (j = 0; j < NI; j++) { 8925 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8926 if (DEBUG_SHOW_INFO) { 8927 Log.v(TAG, " IntentFilter:"); 8928 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8929 } 8930 removeFilter(intent); 8931 } 8932 } 8933 8934 @Override 8935 protected boolean allowFilterResult( 8936 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8937 ProviderInfo filterPi = filter.provider.info; 8938 for (int i = dest.size() - 1; i >= 0; i--) { 8939 ProviderInfo destPi = dest.get(i).providerInfo; 8940 if (destPi.name == filterPi.name 8941 && destPi.packageName == filterPi.packageName) { 8942 return false; 8943 } 8944 } 8945 return true; 8946 } 8947 8948 @Override 8949 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8950 return new PackageParser.ProviderIntentInfo[size]; 8951 } 8952 8953 @Override 8954 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8955 if (!sUserManager.exists(userId)) 8956 return true; 8957 PackageParser.Package p = filter.provider.owner; 8958 if (p != null) { 8959 PackageSetting ps = (PackageSetting) p.mExtras; 8960 if (ps != null) { 8961 // System apps are never considered stopped for purposes of 8962 // filtering, because there may be no way for the user to 8963 // actually re-launch them. 8964 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8965 && ps.getStopped(userId); 8966 } 8967 } 8968 return false; 8969 } 8970 8971 @Override 8972 protected boolean isPackageForFilter(String packageName, 8973 PackageParser.ProviderIntentInfo info) { 8974 return packageName.equals(info.provider.owner.packageName); 8975 } 8976 8977 @Override 8978 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8979 int match, int userId) { 8980 if (!sUserManager.exists(userId)) 8981 return null; 8982 final PackageParser.ProviderIntentInfo info = filter; 8983 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8984 return null; 8985 } 8986 final PackageParser.Provider provider = info.provider; 8987 if (mSafeMode && (provider.info.applicationInfo.flags 8988 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8989 return null; 8990 } 8991 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8992 if (ps == null) { 8993 return null; 8994 } 8995 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8996 ps.readUserState(userId), userId); 8997 if (pi == null) { 8998 return null; 8999 } 9000 final ResolveInfo res = new ResolveInfo(); 9001 res.providerInfo = pi; 9002 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9003 res.filter = filter; 9004 } 9005 res.priority = info.getPriority(); 9006 res.preferredOrder = provider.owner.mPreferredOrder; 9007 res.match = match; 9008 res.isDefault = info.hasDefault; 9009 res.labelRes = info.labelRes; 9010 res.nonLocalizedLabel = info.nonLocalizedLabel; 9011 res.icon = info.icon; 9012 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9013 return res; 9014 } 9015 9016 @Override 9017 protected void sortResults(List<ResolveInfo> results) { 9018 Collections.sort(results, mResolvePrioritySorter); 9019 } 9020 9021 @Override 9022 protected void dumpFilter(PrintWriter out, String prefix, 9023 PackageParser.ProviderIntentInfo filter) { 9024 out.print(prefix); 9025 out.print( 9026 Integer.toHexString(System.identityHashCode(filter.provider))); 9027 out.print(' '); 9028 filter.provider.printComponentShortName(out); 9029 out.print(" filter "); 9030 out.println(Integer.toHexString(System.identityHashCode(filter))); 9031 } 9032 9033 @Override 9034 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9035 return filter.provider; 9036 } 9037 9038 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9039 PackageParser.Provider provider = (PackageParser.Provider)label; 9040 out.print(prefix); out.print( 9041 Integer.toHexString(System.identityHashCode(provider))); 9042 out.print(' '); 9043 provider.printComponentShortName(out); 9044 if (count > 1) { 9045 out.print(" ("); out.print(count); out.print(" filters)"); 9046 } 9047 out.println(); 9048 } 9049 9050 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9051 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9052 private int mFlags; 9053 }; 9054 9055 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9056 new Comparator<ResolveInfo>() { 9057 public int compare(ResolveInfo r1, ResolveInfo r2) { 9058 int v1 = r1.priority; 9059 int v2 = r2.priority; 9060 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9061 if (v1 != v2) { 9062 return (v1 > v2) ? -1 : 1; 9063 } 9064 v1 = r1.preferredOrder; 9065 v2 = r2.preferredOrder; 9066 if (v1 != v2) { 9067 return (v1 > v2) ? -1 : 1; 9068 } 9069 if (r1.isDefault != r2.isDefault) { 9070 return r1.isDefault ? -1 : 1; 9071 } 9072 v1 = r1.match; 9073 v2 = r2.match; 9074 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9075 if (v1 != v2) { 9076 return (v1 > v2) ? -1 : 1; 9077 } 9078 if (r1.system != r2.system) { 9079 return r1.system ? -1 : 1; 9080 } 9081 return 0; 9082 } 9083 }; 9084 9085 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9086 new Comparator<ProviderInfo>() { 9087 public int compare(ProviderInfo p1, ProviderInfo p2) { 9088 final int v1 = p1.initOrder; 9089 final int v2 = p2.initOrder; 9090 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9091 } 9092 }; 9093 9094 final void sendPackageBroadcast(final String action, final String pkg, 9095 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9096 final int[] userIds) { 9097 mHandler.post(new Runnable() { 9098 @Override 9099 public void run() { 9100 try { 9101 final IActivityManager am = ActivityManagerNative.getDefault(); 9102 if (am == null) return; 9103 final int[] resolvedUserIds; 9104 if (userIds == null) { 9105 resolvedUserIds = am.getRunningUserIds(); 9106 } else { 9107 resolvedUserIds = userIds; 9108 } 9109 for (int id : resolvedUserIds) { 9110 final Intent intent = new Intent(action, 9111 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9112 if (extras != null) { 9113 intent.putExtras(extras); 9114 } 9115 if (targetPkg != null) { 9116 intent.setPackage(targetPkg); 9117 } 9118 // Modify the UID when posting to other users 9119 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9120 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9121 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9122 intent.putExtra(Intent.EXTRA_UID, uid); 9123 } 9124 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9125 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9126 if (DEBUG_BROADCASTS) { 9127 RuntimeException here = new RuntimeException("here"); 9128 here.fillInStackTrace(); 9129 Slog.d(TAG, "Sending to user " + id + ": " 9130 + intent.toShortString(false, true, false, false) 9131 + " " + intent.getExtras(), here); 9132 } 9133 am.broadcastIntent(null, intent, null, finishedReceiver, 9134 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9135 null, finishedReceiver != null, false, id); 9136 } 9137 } catch (RemoteException ex) { 9138 } 9139 } 9140 }); 9141 } 9142 9143 /** 9144 * Check if the external storage media is available. This is true if there 9145 * is a mounted external storage medium or if the external storage is 9146 * emulated. 9147 */ 9148 private boolean isExternalMediaAvailable() { 9149 return mMediaMounted || Environment.isExternalStorageEmulated(); 9150 } 9151 9152 @Override 9153 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9154 // writer 9155 synchronized (mPackages) { 9156 if (!isExternalMediaAvailable()) { 9157 // If the external storage is no longer mounted at this point, 9158 // the caller may not have been able to delete all of this 9159 // packages files and can not delete any more. Bail. 9160 return null; 9161 } 9162 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9163 if (lastPackage != null) { 9164 pkgs.remove(lastPackage); 9165 } 9166 if (pkgs.size() > 0) { 9167 return pkgs.get(0); 9168 } 9169 } 9170 return null; 9171 } 9172 9173 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9174 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9175 userId, andCode ? 1 : 0, packageName); 9176 if (mSystemReady) { 9177 msg.sendToTarget(); 9178 } else { 9179 if (mPostSystemReadyMessages == null) { 9180 mPostSystemReadyMessages = new ArrayList<>(); 9181 } 9182 mPostSystemReadyMessages.add(msg); 9183 } 9184 } 9185 9186 void startCleaningPackages() { 9187 // reader 9188 synchronized (mPackages) { 9189 if (!isExternalMediaAvailable()) { 9190 return; 9191 } 9192 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9193 return; 9194 } 9195 } 9196 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9197 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9198 IActivityManager am = ActivityManagerNative.getDefault(); 9199 if (am != null) { 9200 try { 9201 am.startService(null, intent, null, mContext.getOpPackageName(), 9202 UserHandle.USER_OWNER); 9203 } catch (RemoteException e) { 9204 } 9205 } 9206 } 9207 9208 @Override 9209 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9210 int installFlags, String installerPackageName, VerificationParams verificationParams, 9211 String packageAbiOverride) { 9212 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9213 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9214 } 9215 9216 @Override 9217 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9218 int installFlags, String installerPackageName, VerificationParams verificationParams, 9219 String packageAbiOverride, int userId) { 9220 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9221 9222 final int callingUid = Binder.getCallingUid(); 9223 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9224 9225 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9226 try { 9227 if (observer != null) { 9228 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9229 } 9230 } catch (RemoteException re) { 9231 } 9232 return; 9233 } 9234 9235 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9236 installFlags |= PackageManager.INSTALL_FROM_ADB; 9237 9238 } else { 9239 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9240 // about installerPackageName. 9241 9242 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9243 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9244 } 9245 9246 UserHandle user; 9247 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9248 user = UserHandle.ALL; 9249 } else { 9250 user = new UserHandle(userId); 9251 } 9252 9253 // Only system components can circumvent runtime permissions when installing. 9254 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9255 && mContext.checkCallingOrSelfPermission(Manifest.permission 9256 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9257 throw new SecurityException("You need the " 9258 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9259 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9260 } 9261 9262 verificationParams.setInstallerUid(callingUid); 9263 9264 final File originFile = new File(originPath); 9265 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9266 9267 final Message msg = mHandler.obtainMessage(INIT_COPY); 9268 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9269 null, verificationParams, user, packageAbiOverride); 9270 mHandler.sendMessage(msg); 9271 } 9272 9273 void installStage(String packageName, File stagedDir, String stagedCid, 9274 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9275 String installerPackageName, int installerUid, UserHandle user) { 9276 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9277 params.referrerUri, installerUid, null); 9278 verifParams.setInstallerUid(installerUid); 9279 9280 final OriginInfo origin; 9281 if (stagedDir != null) { 9282 origin = OriginInfo.fromStagedFile(stagedDir); 9283 } else { 9284 origin = OriginInfo.fromStagedContainer(stagedCid); 9285 } 9286 9287 final Message msg = mHandler.obtainMessage(INIT_COPY); 9288 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9289 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9290 mHandler.sendMessage(msg); 9291 } 9292 9293 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9294 Bundle extras = new Bundle(1); 9295 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9296 9297 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9298 packageName, extras, null, null, new int[] {userId}); 9299 try { 9300 IActivityManager am = ActivityManagerNative.getDefault(); 9301 final boolean isSystem = 9302 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9303 if (isSystem && am.isUserRunning(userId, false)) { 9304 // The just-installed/enabled app is bundled on the system, so presumed 9305 // to be able to run automatically without needing an explicit launch. 9306 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9307 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9308 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9309 .setPackage(packageName); 9310 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9311 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9312 } 9313 } catch (RemoteException e) { 9314 // shouldn't happen 9315 Slog.w(TAG, "Unable to bootstrap installed package", e); 9316 } 9317 } 9318 9319 @Override 9320 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9321 int userId) { 9322 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9323 PackageSetting pkgSetting; 9324 final int uid = Binder.getCallingUid(); 9325 enforceCrossUserPermission(uid, userId, true, true, 9326 "setApplicationHiddenSetting for user " + userId); 9327 9328 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9329 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9330 return false; 9331 } 9332 9333 long callingId = Binder.clearCallingIdentity(); 9334 try { 9335 boolean sendAdded = false; 9336 boolean sendRemoved = false; 9337 // writer 9338 synchronized (mPackages) { 9339 pkgSetting = mSettings.mPackages.get(packageName); 9340 if (pkgSetting == null) { 9341 return false; 9342 } 9343 if (pkgSetting.getHidden(userId) != hidden) { 9344 pkgSetting.setHidden(hidden, userId); 9345 mSettings.writePackageRestrictionsLPr(userId); 9346 if (hidden) { 9347 sendRemoved = true; 9348 } else { 9349 sendAdded = true; 9350 } 9351 } 9352 } 9353 if (sendAdded) { 9354 sendPackageAddedForUser(packageName, pkgSetting, userId); 9355 return true; 9356 } 9357 if (sendRemoved) { 9358 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9359 "hiding pkg"); 9360 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9361 } 9362 } finally { 9363 Binder.restoreCallingIdentity(callingId); 9364 } 9365 return false; 9366 } 9367 9368 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9369 int userId) { 9370 final PackageRemovedInfo info = new PackageRemovedInfo(); 9371 info.removedPackage = packageName; 9372 info.removedUsers = new int[] {userId}; 9373 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9374 info.sendBroadcast(false, false, false); 9375 } 9376 9377 /** 9378 * Returns true if application is not found or there was an error. Otherwise it returns 9379 * the hidden state of the package for the given user. 9380 */ 9381 @Override 9382 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9383 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9384 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9385 false, "getApplicationHidden for user " + userId); 9386 PackageSetting pkgSetting; 9387 long callingId = Binder.clearCallingIdentity(); 9388 try { 9389 // writer 9390 synchronized (mPackages) { 9391 pkgSetting = mSettings.mPackages.get(packageName); 9392 if (pkgSetting == null) { 9393 return true; 9394 } 9395 return pkgSetting.getHidden(userId); 9396 } 9397 } finally { 9398 Binder.restoreCallingIdentity(callingId); 9399 } 9400 } 9401 9402 /** 9403 * @hide 9404 */ 9405 @Override 9406 public int installExistingPackageAsUser(String packageName, int userId) { 9407 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9408 null); 9409 PackageSetting pkgSetting; 9410 final int uid = Binder.getCallingUid(); 9411 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9412 + userId); 9413 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9414 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9415 } 9416 9417 long callingId = Binder.clearCallingIdentity(); 9418 try { 9419 boolean sendAdded = false; 9420 9421 // writer 9422 synchronized (mPackages) { 9423 pkgSetting = mSettings.mPackages.get(packageName); 9424 if (pkgSetting == null) { 9425 return PackageManager.INSTALL_FAILED_INVALID_URI; 9426 } 9427 if (!pkgSetting.getInstalled(userId)) { 9428 pkgSetting.setInstalled(true, userId); 9429 pkgSetting.setHidden(false, userId); 9430 mSettings.writePackageRestrictionsLPr(userId); 9431 sendAdded = true; 9432 } 9433 } 9434 9435 if (sendAdded) { 9436 sendPackageAddedForUser(packageName, pkgSetting, userId); 9437 } 9438 } finally { 9439 Binder.restoreCallingIdentity(callingId); 9440 } 9441 9442 return PackageManager.INSTALL_SUCCEEDED; 9443 } 9444 9445 boolean isUserRestricted(int userId, String restrictionKey) { 9446 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9447 if (restrictions.getBoolean(restrictionKey, false)) { 9448 Log.w(TAG, "User is restricted: " + restrictionKey); 9449 return true; 9450 } 9451 return false; 9452 } 9453 9454 @Override 9455 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9456 mContext.enforceCallingOrSelfPermission( 9457 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9458 "Only package verification agents can verify applications"); 9459 9460 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9461 final PackageVerificationResponse response = new PackageVerificationResponse( 9462 verificationCode, Binder.getCallingUid()); 9463 msg.arg1 = id; 9464 msg.obj = response; 9465 mHandler.sendMessage(msg); 9466 } 9467 9468 @Override 9469 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9470 long millisecondsToDelay) { 9471 mContext.enforceCallingOrSelfPermission( 9472 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9473 "Only package verification agents can extend verification timeouts"); 9474 9475 final PackageVerificationState state = mPendingVerification.get(id); 9476 final PackageVerificationResponse response = new PackageVerificationResponse( 9477 verificationCodeAtTimeout, Binder.getCallingUid()); 9478 9479 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9480 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9481 } 9482 if (millisecondsToDelay < 0) { 9483 millisecondsToDelay = 0; 9484 } 9485 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9486 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9487 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9488 } 9489 9490 if ((state != null) && !state.timeoutExtended()) { 9491 state.extendTimeout(); 9492 9493 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9494 msg.arg1 = id; 9495 msg.obj = response; 9496 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9497 } 9498 } 9499 9500 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9501 int verificationCode, UserHandle user) { 9502 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9503 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9504 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9505 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9506 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9507 9508 mContext.sendBroadcastAsUser(intent, user, 9509 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9510 } 9511 9512 private ComponentName matchComponentForVerifier(String packageName, 9513 List<ResolveInfo> receivers) { 9514 ActivityInfo targetReceiver = null; 9515 9516 final int NR = receivers.size(); 9517 for (int i = 0; i < NR; i++) { 9518 final ResolveInfo info = receivers.get(i); 9519 if (info.activityInfo == null) { 9520 continue; 9521 } 9522 9523 if (packageName.equals(info.activityInfo.packageName)) { 9524 targetReceiver = info.activityInfo; 9525 break; 9526 } 9527 } 9528 9529 if (targetReceiver == null) { 9530 return null; 9531 } 9532 9533 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9534 } 9535 9536 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9537 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9538 if (pkgInfo.verifiers.length == 0) { 9539 return null; 9540 } 9541 9542 final int N = pkgInfo.verifiers.length; 9543 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9544 for (int i = 0; i < N; i++) { 9545 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9546 9547 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9548 receivers); 9549 if (comp == null) { 9550 continue; 9551 } 9552 9553 final int verifierUid = getUidForVerifier(verifierInfo); 9554 if (verifierUid == -1) { 9555 continue; 9556 } 9557 9558 if (DEBUG_VERIFY) { 9559 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9560 + " with the correct signature"); 9561 } 9562 sufficientVerifiers.add(comp); 9563 verificationState.addSufficientVerifier(verifierUid); 9564 } 9565 9566 return sufficientVerifiers; 9567 } 9568 9569 private int getUidForVerifier(VerifierInfo verifierInfo) { 9570 synchronized (mPackages) { 9571 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9572 if (pkg == null) { 9573 return -1; 9574 } else if (pkg.mSignatures.length != 1) { 9575 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9576 + " has more than one signature; ignoring"); 9577 return -1; 9578 } 9579 9580 /* 9581 * If the public key of the package's signature does not match 9582 * our expected public key, then this is a different package and 9583 * we should skip. 9584 */ 9585 9586 final byte[] expectedPublicKey; 9587 try { 9588 final Signature verifierSig = pkg.mSignatures[0]; 9589 final PublicKey publicKey = verifierSig.getPublicKey(); 9590 expectedPublicKey = publicKey.getEncoded(); 9591 } catch (CertificateException e) { 9592 return -1; 9593 } 9594 9595 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9596 9597 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9598 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9599 + " does not have the expected public key; ignoring"); 9600 return -1; 9601 } 9602 9603 return pkg.applicationInfo.uid; 9604 } 9605 } 9606 9607 @Override 9608 public void finishPackageInstall(int token) { 9609 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9610 9611 if (DEBUG_INSTALL) { 9612 Slog.v(TAG, "BM finishing package install for " + token); 9613 } 9614 9615 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9616 mHandler.sendMessage(msg); 9617 } 9618 9619 /** 9620 * Get the verification agent timeout. 9621 * 9622 * @return verification timeout in milliseconds 9623 */ 9624 private long getVerificationTimeout() { 9625 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9626 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9627 DEFAULT_VERIFICATION_TIMEOUT); 9628 } 9629 9630 /** 9631 * Get the default verification agent response code. 9632 * 9633 * @return default verification response code 9634 */ 9635 private int getDefaultVerificationResponse() { 9636 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9637 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9638 DEFAULT_VERIFICATION_RESPONSE); 9639 } 9640 9641 /** 9642 * Check whether or not package verification has been enabled. 9643 * 9644 * @return true if verification should be performed 9645 */ 9646 private boolean isVerificationEnabled(int userId, int installFlags) { 9647 if (!DEFAULT_VERIFY_ENABLE) { 9648 return false; 9649 } 9650 9651 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9652 9653 // Check if installing from ADB 9654 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9655 // Do not run verification in a test harness environment 9656 if (ActivityManager.isRunningInTestHarness()) { 9657 return false; 9658 } 9659 if (ensureVerifyAppsEnabled) { 9660 return true; 9661 } 9662 // Check if the developer does not want package verification for ADB installs 9663 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9664 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9665 return false; 9666 } 9667 } 9668 9669 if (ensureVerifyAppsEnabled) { 9670 return true; 9671 } 9672 9673 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9674 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9675 } 9676 9677 @Override 9678 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9679 throws RemoteException { 9680 mContext.enforceCallingOrSelfPermission( 9681 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9682 "Only intentfilter verification agents can verify applications"); 9683 9684 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9685 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9686 Binder.getCallingUid(), verificationCode, failedDomains); 9687 msg.arg1 = id; 9688 msg.obj = response; 9689 mHandler.sendMessage(msg); 9690 } 9691 9692 @Override 9693 public int getIntentVerificationStatus(String packageName, int userId) { 9694 synchronized (mPackages) { 9695 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9696 } 9697 } 9698 9699 @Override 9700 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9701 mContext.enforceCallingOrSelfPermission( 9702 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9703 9704 boolean result = false; 9705 synchronized (mPackages) { 9706 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9707 } 9708 if (result) { 9709 scheduleWritePackageRestrictionsLocked(userId); 9710 } 9711 return result; 9712 } 9713 9714 @Override 9715 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9716 synchronized (mPackages) { 9717 return mSettings.getIntentFilterVerificationsLPr(packageName); 9718 } 9719 } 9720 9721 @Override 9722 public List<IntentFilter> getAllIntentFilters(String packageName) { 9723 if (TextUtils.isEmpty(packageName)) { 9724 return Collections.<IntentFilter>emptyList(); 9725 } 9726 synchronized (mPackages) { 9727 PackageParser.Package pkg = mPackages.get(packageName); 9728 if (pkg == null || pkg.activities == null) { 9729 return Collections.<IntentFilter>emptyList(); 9730 } 9731 final int count = pkg.activities.size(); 9732 ArrayList<IntentFilter> result = new ArrayList<>(); 9733 for (int n=0; n<count; n++) { 9734 PackageParser.Activity activity = pkg.activities.get(n); 9735 if (activity.intents != null || activity.intents.size() > 0) { 9736 result.addAll(activity.intents); 9737 } 9738 } 9739 return result; 9740 } 9741 } 9742 9743 @Override 9744 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9745 mContext.enforceCallingOrSelfPermission( 9746 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9747 9748 synchronized (mPackages) { 9749 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9750 if (packageName != null) { 9751 result |= updateIntentVerificationStatus(packageName, 9752 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9753 UserHandle.myUserId()); 9754 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9755 packageName, userId); 9756 } 9757 return result; 9758 } 9759 } 9760 9761 @Override 9762 public String getDefaultBrowserPackageName(int userId) { 9763 synchronized (mPackages) { 9764 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9765 } 9766 } 9767 9768 /** 9769 * Get the "allow unknown sources" setting. 9770 * 9771 * @return the current "allow unknown sources" setting 9772 */ 9773 private int getUnknownSourcesSettings() { 9774 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9775 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9776 -1); 9777 } 9778 9779 @Override 9780 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9781 final int uid = Binder.getCallingUid(); 9782 // writer 9783 synchronized (mPackages) { 9784 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9785 if (targetPackageSetting == null) { 9786 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9787 } 9788 9789 PackageSetting installerPackageSetting; 9790 if (installerPackageName != null) { 9791 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9792 if (installerPackageSetting == null) { 9793 throw new IllegalArgumentException("Unknown installer package: " 9794 + installerPackageName); 9795 } 9796 } else { 9797 installerPackageSetting = null; 9798 } 9799 9800 Signature[] callerSignature; 9801 Object obj = mSettings.getUserIdLPr(uid); 9802 if (obj != null) { 9803 if (obj instanceof SharedUserSetting) { 9804 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9805 } else if (obj instanceof PackageSetting) { 9806 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9807 } else { 9808 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9809 } 9810 } else { 9811 throw new SecurityException("Unknown calling uid " + uid); 9812 } 9813 9814 // Verify: can't set installerPackageName to a package that is 9815 // not signed with the same cert as the caller. 9816 if (installerPackageSetting != null) { 9817 if (compareSignatures(callerSignature, 9818 installerPackageSetting.signatures.mSignatures) 9819 != PackageManager.SIGNATURE_MATCH) { 9820 throw new SecurityException( 9821 "Caller does not have same cert as new installer package " 9822 + installerPackageName); 9823 } 9824 } 9825 9826 // Verify: if target already has an installer package, it must 9827 // be signed with the same cert as the caller. 9828 if (targetPackageSetting.installerPackageName != null) { 9829 PackageSetting setting = mSettings.mPackages.get( 9830 targetPackageSetting.installerPackageName); 9831 // If the currently set package isn't valid, then it's always 9832 // okay to change it. 9833 if (setting != null) { 9834 if (compareSignatures(callerSignature, 9835 setting.signatures.mSignatures) 9836 != PackageManager.SIGNATURE_MATCH) { 9837 throw new SecurityException( 9838 "Caller does not have same cert as old installer package " 9839 + targetPackageSetting.installerPackageName); 9840 } 9841 } 9842 } 9843 9844 // Okay! 9845 targetPackageSetting.installerPackageName = installerPackageName; 9846 scheduleWriteSettingsLocked(); 9847 } 9848 } 9849 9850 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9851 // Queue up an async operation since the package installation may take a little while. 9852 mHandler.post(new Runnable() { 9853 public void run() { 9854 mHandler.removeCallbacks(this); 9855 // Result object to be returned 9856 PackageInstalledInfo res = new PackageInstalledInfo(); 9857 res.returnCode = currentStatus; 9858 res.uid = -1; 9859 res.pkg = null; 9860 res.removedInfo = new PackageRemovedInfo(); 9861 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9862 args.doPreInstall(res.returnCode); 9863 synchronized (mInstallLock) { 9864 installPackageLI(args, res); 9865 } 9866 args.doPostInstall(res.returnCode, res.uid); 9867 } 9868 9869 // A restore should be performed at this point if (a) the install 9870 // succeeded, (b) the operation is not an update, and (c) the new 9871 // package has not opted out of backup participation. 9872 final boolean update = res.removedInfo.removedPackage != null; 9873 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9874 boolean doRestore = !update 9875 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9876 9877 // Set up the post-install work request bookkeeping. This will be used 9878 // and cleaned up by the post-install event handling regardless of whether 9879 // there's a restore pass performed. Token values are >= 1. 9880 int token; 9881 if (mNextInstallToken < 0) mNextInstallToken = 1; 9882 token = mNextInstallToken++; 9883 9884 PostInstallData data = new PostInstallData(args, res); 9885 mRunningInstalls.put(token, data); 9886 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9887 9888 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9889 // Pass responsibility to the Backup Manager. It will perform a 9890 // restore if appropriate, then pass responsibility back to the 9891 // Package Manager to run the post-install observer callbacks 9892 // and broadcasts. 9893 IBackupManager bm = IBackupManager.Stub.asInterface( 9894 ServiceManager.getService(Context.BACKUP_SERVICE)); 9895 if (bm != null) { 9896 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9897 + " to BM for possible restore"); 9898 try { 9899 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9900 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9901 } else { 9902 doRestore = false; 9903 } 9904 } catch (RemoteException e) { 9905 // can't happen; the backup manager is local 9906 } catch (Exception e) { 9907 Slog.e(TAG, "Exception trying to enqueue restore", e); 9908 doRestore = false; 9909 } 9910 } else { 9911 Slog.e(TAG, "Backup Manager not found!"); 9912 doRestore = false; 9913 } 9914 } 9915 9916 if (!doRestore) { 9917 // No restore possible, or the Backup Manager was mysteriously not 9918 // available -- just fire the post-install work request directly. 9919 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9920 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9921 mHandler.sendMessage(msg); 9922 } 9923 } 9924 }); 9925 } 9926 9927 private abstract class HandlerParams { 9928 private static final int MAX_RETRIES = 4; 9929 9930 /** 9931 * Number of times startCopy() has been attempted and had a non-fatal 9932 * error. 9933 */ 9934 private int mRetries = 0; 9935 9936 /** User handle for the user requesting the information or installation. */ 9937 private final UserHandle mUser; 9938 9939 HandlerParams(UserHandle user) { 9940 mUser = user; 9941 } 9942 9943 UserHandle getUser() { 9944 return mUser; 9945 } 9946 9947 final boolean startCopy() { 9948 boolean res; 9949 try { 9950 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9951 9952 if (++mRetries > MAX_RETRIES) { 9953 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9954 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9955 handleServiceError(); 9956 return false; 9957 } else { 9958 handleStartCopy(); 9959 res = true; 9960 } 9961 } catch (RemoteException e) { 9962 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9963 mHandler.sendEmptyMessage(MCS_RECONNECT); 9964 res = false; 9965 } 9966 handleReturnCode(); 9967 return res; 9968 } 9969 9970 final void serviceError() { 9971 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9972 handleServiceError(); 9973 handleReturnCode(); 9974 } 9975 9976 abstract void handleStartCopy() throws RemoteException; 9977 abstract void handleServiceError(); 9978 abstract void handleReturnCode(); 9979 } 9980 9981 class MeasureParams extends HandlerParams { 9982 private final PackageStats mStats; 9983 private boolean mSuccess; 9984 9985 private final IPackageStatsObserver mObserver; 9986 9987 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9988 super(new UserHandle(stats.userHandle)); 9989 mObserver = observer; 9990 mStats = stats; 9991 } 9992 9993 @Override 9994 public String toString() { 9995 return "MeasureParams{" 9996 + Integer.toHexString(System.identityHashCode(this)) 9997 + " " + mStats.packageName + "}"; 9998 } 9999 10000 @Override 10001 void handleStartCopy() throws RemoteException { 10002 synchronized (mInstallLock) { 10003 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10004 } 10005 10006 if (mSuccess) { 10007 final boolean mounted; 10008 if (Environment.isExternalStorageEmulated()) { 10009 mounted = true; 10010 } else { 10011 final String status = Environment.getExternalStorageState(); 10012 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10013 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10014 } 10015 10016 if (mounted) { 10017 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10018 10019 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10020 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10021 10022 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10023 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10024 10025 // Always subtract cache size, since it's a subdirectory 10026 mStats.externalDataSize -= mStats.externalCacheSize; 10027 10028 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10029 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10030 10031 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10032 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10033 } 10034 } 10035 } 10036 10037 @Override 10038 void handleReturnCode() { 10039 if (mObserver != null) { 10040 try { 10041 mObserver.onGetStatsCompleted(mStats, mSuccess); 10042 } catch (RemoteException e) { 10043 Slog.i(TAG, "Observer no longer exists."); 10044 } 10045 } 10046 } 10047 10048 @Override 10049 void handleServiceError() { 10050 Slog.e(TAG, "Could not measure application " + mStats.packageName 10051 + " external storage"); 10052 } 10053 } 10054 10055 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10056 throws RemoteException { 10057 long result = 0; 10058 for (File path : paths) { 10059 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10060 } 10061 return result; 10062 } 10063 10064 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10065 for (File path : paths) { 10066 try { 10067 mcs.clearDirectory(path.getAbsolutePath()); 10068 } catch (RemoteException e) { 10069 } 10070 } 10071 } 10072 10073 static class OriginInfo { 10074 /** 10075 * Location where install is coming from, before it has been 10076 * copied/renamed into place. This could be a single monolithic APK 10077 * file, or a cluster directory. This location may be untrusted. 10078 */ 10079 final File file; 10080 final String cid; 10081 10082 /** 10083 * Flag indicating that {@link #file} or {@link #cid} has already been 10084 * staged, meaning downstream users don't need to defensively copy the 10085 * contents. 10086 */ 10087 final boolean staged; 10088 10089 /** 10090 * Flag indicating that {@link #file} or {@link #cid} is an already 10091 * installed app that is being moved. 10092 */ 10093 final boolean existing; 10094 10095 final String resolvedPath; 10096 final File resolvedFile; 10097 10098 static OriginInfo fromNothing() { 10099 return new OriginInfo(null, null, false, false); 10100 } 10101 10102 static OriginInfo fromUntrustedFile(File file) { 10103 return new OriginInfo(file, null, false, false); 10104 } 10105 10106 static OriginInfo fromExistingFile(File file) { 10107 return new OriginInfo(file, null, false, true); 10108 } 10109 10110 static OriginInfo fromStagedFile(File file) { 10111 return new OriginInfo(file, null, true, false); 10112 } 10113 10114 static OriginInfo fromStagedContainer(String cid) { 10115 return new OriginInfo(null, cid, true, false); 10116 } 10117 10118 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10119 this.file = file; 10120 this.cid = cid; 10121 this.staged = staged; 10122 this.existing = existing; 10123 10124 if (cid != null) { 10125 resolvedPath = PackageHelper.getSdDir(cid); 10126 resolvedFile = new File(resolvedPath); 10127 } else if (file != null) { 10128 resolvedPath = file.getAbsolutePath(); 10129 resolvedFile = file; 10130 } else { 10131 resolvedPath = null; 10132 resolvedFile = null; 10133 } 10134 } 10135 } 10136 10137 class MoveInfo { 10138 final int moveId; 10139 final String fromUuid; 10140 final String toUuid; 10141 final String packageName; 10142 final String dataAppName; 10143 final int appId; 10144 final String seinfo; 10145 10146 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10147 String dataAppName, int appId, String seinfo) { 10148 this.moveId = moveId; 10149 this.fromUuid = fromUuid; 10150 this.toUuid = toUuid; 10151 this.packageName = packageName; 10152 this.dataAppName = dataAppName; 10153 this.appId = appId; 10154 this.seinfo = seinfo; 10155 } 10156 } 10157 10158 class InstallParams extends HandlerParams { 10159 final OriginInfo origin; 10160 final MoveInfo move; 10161 final IPackageInstallObserver2 observer; 10162 int installFlags; 10163 final String installerPackageName; 10164 final String volumeUuid; 10165 final VerificationParams verificationParams; 10166 private InstallArgs mArgs; 10167 private int mRet; 10168 final String packageAbiOverride; 10169 10170 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10171 int installFlags, String installerPackageName, String volumeUuid, 10172 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10173 super(user); 10174 this.origin = origin; 10175 this.move = move; 10176 this.observer = observer; 10177 this.installFlags = installFlags; 10178 this.installerPackageName = installerPackageName; 10179 this.volumeUuid = volumeUuid; 10180 this.verificationParams = verificationParams; 10181 this.packageAbiOverride = packageAbiOverride; 10182 } 10183 10184 @Override 10185 public String toString() { 10186 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10187 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10188 } 10189 10190 public ManifestDigest getManifestDigest() { 10191 if (verificationParams == null) { 10192 return null; 10193 } 10194 return verificationParams.getManifestDigest(); 10195 } 10196 10197 private int installLocationPolicy(PackageInfoLite pkgLite) { 10198 String packageName = pkgLite.packageName; 10199 int installLocation = pkgLite.installLocation; 10200 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10201 // reader 10202 synchronized (mPackages) { 10203 PackageParser.Package pkg = mPackages.get(packageName); 10204 if (pkg != null) { 10205 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10206 // Check for downgrading. 10207 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10208 try { 10209 checkDowngrade(pkg, pkgLite); 10210 } catch (PackageManagerException e) { 10211 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10212 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10213 } 10214 } 10215 // Check for updated system application. 10216 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10217 if (onSd) { 10218 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10219 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10220 } 10221 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10222 } else { 10223 if (onSd) { 10224 // Install flag overrides everything. 10225 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10226 } 10227 // If current upgrade specifies particular preference 10228 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10229 // Application explicitly specified internal. 10230 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10231 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10232 // App explictly prefers external. Let policy decide 10233 } else { 10234 // Prefer previous location 10235 if (isExternal(pkg)) { 10236 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10237 } 10238 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10239 } 10240 } 10241 } else { 10242 // Invalid install. Return error code 10243 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10244 } 10245 } 10246 } 10247 // All the special cases have been taken care of. 10248 // Return result based on recommended install location. 10249 if (onSd) { 10250 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10251 } 10252 return pkgLite.recommendedInstallLocation; 10253 } 10254 10255 /* 10256 * Invoke remote method to get package information and install 10257 * location values. Override install location based on default 10258 * policy if needed and then create install arguments based 10259 * on the install location. 10260 */ 10261 public void handleStartCopy() throws RemoteException { 10262 int ret = PackageManager.INSTALL_SUCCEEDED; 10263 10264 // If we're already staged, we've firmly committed to an install location 10265 if (origin.staged) { 10266 if (origin.file != null) { 10267 installFlags |= PackageManager.INSTALL_INTERNAL; 10268 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10269 } else if (origin.cid != null) { 10270 installFlags |= PackageManager.INSTALL_EXTERNAL; 10271 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10272 } else { 10273 throw new IllegalStateException("Invalid stage location"); 10274 } 10275 } 10276 10277 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10278 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10279 10280 PackageInfoLite pkgLite = null; 10281 10282 if (onInt && onSd) { 10283 // Check if both bits are set. 10284 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10285 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10286 } else { 10287 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10288 packageAbiOverride); 10289 10290 /* 10291 * If we have too little free space, try to free cache 10292 * before giving up. 10293 */ 10294 if (!origin.staged && pkgLite.recommendedInstallLocation 10295 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10296 // TODO: focus freeing disk space on the target device 10297 final StorageManager storage = StorageManager.from(mContext); 10298 final long lowThreshold = storage.getStorageLowBytes( 10299 Environment.getDataDirectory()); 10300 10301 final long sizeBytes = mContainerService.calculateInstalledSize( 10302 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10303 10304 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10305 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10306 installFlags, packageAbiOverride); 10307 } 10308 10309 /* 10310 * The cache free must have deleted the file we 10311 * downloaded to install. 10312 * 10313 * TODO: fix the "freeCache" call to not delete 10314 * the file we care about. 10315 */ 10316 if (pkgLite.recommendedInstallLocation 10317 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10318 pkgLite.recommendedInstallLocation 10319 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10320 } 10321 } 10322 } 10323 10324 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10325 int loc = pkgLite.recommendedInstallLocation; 10326 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10327 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10328 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10329 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10330 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10331 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10332 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10333 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10334 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10335 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10336 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10337 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10338 } else { 10339 // Override with defaults if needed. 10340 loc = installLocationPolicy(pkgLite); 10341 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10342 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10343 } else if (!onSd && !onInt) { 10344 // Override install location with flags 10345 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10346 // Set the flag to install on external media. 10347 installFlags |= PackageManager.INSTALL_EXTERNAL; 10348 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10349 } else { 10350 // Make sure the flag for installing on external 10351 // media is unset 10352 installFlags |= PackageManager.INSTALL_INTERNAL; 10353 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10354 } 10355 } 10356 } 10357 } 10358 10359 final InstallArgs args = createInstallArgs(this); 10360 mArgs = args; 10361 10362 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10363 /* 10364 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10365 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10366 */ 10367 int userIdentifier = getUser().getIdentifier(); 10368 if (userIdentifier == UserHandle.USER_ALL 10369 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10370 userIdentifier = UserHandle.USER_OWNER; 10371 } 10372 10373 /* 10374 * Determine if we have any installed package verifiers. If we 10375 * do, then we'll defer to them to verify the packages. 10376 */ 10377 final int requiredUid = mRequiredVerifierPackage == null ? -1 10378 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10379 if (!origin.existing && requiredUid != -1 10380 && isVerificationEnabled(userIdentifier, installFlags)) { 10381 final Intent verification = new Intent( 10382 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10383 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10384 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10385 PACKAGE_MIME_TYPE); 10386 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10387 10388 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10389 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10390 0 /* TODO: Which userId? */); 10391 10392 if (DEBUG_VERIFY) { 10393 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10394 + verification.toString() + " with " + pkgLite.verifiers.length 10395 + " optional verifiers"); 10396 } 10397 10398 final int verificationId = mPendingVerificationToken++; 10399 10400 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10401 10402 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10403 installerPackageName); 10404 10405 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10406 installFlags); 10407 10408 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10409 pkgLite.packageName); 10410 10411 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10412 pkgLite.versionCode); 10413 10414 if (verificationParams != null) { 10415 if (verificationParams.getVerificationURI() != null) { 10416 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10417 verificationParams.getVerificationURI()); 10418 } 10419 if (verificationParams.getOriginatingURI() != null) { 10420 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10421 verificationParams.getOriginatingURI()); 10422 } 10423 if (verificationParams.getReferrer() != null) { 10424 verification.putExtra(Intent.EXTRA_REFERRER, 10425 verificationParams.getReferrer()); 10426 } 10427 if (verificationParams.getOriginatingUid() >= 0) { 10428 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10429 verificationParams.getOriginatingUid()); 10430 } 10431 if (verificationParams.getInstallerUid() >= 0) { 10432 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10433 verificationParams.getInstallerUid()); 10434 } 10435 } 10436 10437 final PackageVerificationState verificationState = new PackageVerificationState( 10438 requiredUid, args); 10439 10440 mPendingVerification.append(verificationId, verificationState); 10441 10442 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10443 receivers, verificationState); 10444 10445 /* 10446 * If any sufficient verifiers were listed in the package 10447 * manifest, attempt to ask them. 10448 */ 10449 if (sufficientVerifiers != null) { 10450 final int N = sufficientVerifiers.size(); 10451 if (N == 0) { 10452 Slog.i(TAG, "Additional verifiers required, but none installed."); 10453 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10454 } else { 10455 for (int i = 0; i < N; i++) { 10456 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10457 10458 final Intent sufficientIntent = new Intent(verification); 10459 sufficientIntent.setComponent(verifierComponent); 10460 10461 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10462 } 10463 } 10464 } 10465 10466 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10467 mRequiredVerifierPackage, receivers); 10468 if (ret == PackageManager.INSTALL_SUCCEEDED 10469 && mRequiredVerifierPackage != null) { 10470 /* 10471 * Send the intent to the required verification agent, 10472 * but only start the verification timeout after the 10473 * target BroadcastReceivers have run. 10474 */ 10475 verification.setComponent(requiredVerifierComponent); 10476 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10477 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10478 new BroadcastReceiver() { 10479 @Override 10480 public void onReceive(Context context, Intent intent) { 10481 final Message msg = mHandler 10482 .obtainMessage(CHECK_PENDING_VERIFICATION); 10483 msg.arg1 = verificationId; 10484 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10485 } 10486 }, null, 0, null, null); 10487 10488 /* 10489 * We don't want the copy to proceed until verification 10490 * succeeds, so null out this field. 10491 */ 10492 mArgs = null; 10493 } 10494 } else { 10495 /* 10496 * No package verification is enabled, so immediately start 10497 * the remote call to initiate copy using temporary file. 10498 */ 10499 ret = args.copyApk(mContainerService, true); 10500 } 10501 } 10502 10503 mRet = ret; 10504 } 10505 10506 @Override 10507 void handleReturnCode() { 10508 // If mArgs is null, then MCS couldn't be reached. When it 10509 // reconnects, it will try again to install. At that point, this 10510 // will succeed. 10511 if (mArgs != null) { 10512 processPendingInstall(mArgs, mRet); 10513 } 10514 } 10515 10516 @Override 10517 void handleServiceError() { 10518 mArgs = createInstallArgs(this); 10519 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10520 } 10521 10522 public boolean isForwardLocked() { 10523 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10524 } 10525 } 10526 10527 /** 10528 * Used during creation of InstallArgs 10529 * 10530 * @param installFlags package installation flags 10531 * @return true if should be installed on external storage 10532 */ 10533 private static boolean installOnExternalAsec(int installFlags) { 10534 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10535 return false; 10536 } 10537 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10538 return true; 10539 } 10540 return false; 10541 } 10542 10543 /** 10544 * Used during creation of InstallArgs 10545 * 10546 * @param installFlags package installation flags 10547 * @return true if should be installed as forward locked 10548 */ 10549 private static boolean installForwardLocked(int installFlags) { 10550 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10551 } 10552 10553 private InstallArgs createInstallArgs(InstallParams params) { 10554 if (params.move != null) { 10555 return new MoveInstallArgs(params); 10556 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10557 return new AsecInstallArgs(params); 10558 } else { 10559 return new FileInstallArgs(params); 10560 } 10561 } 10562 10563 /** 10564 * Create args that describe an existing installed package. Typically used 10565 * when cleaning up old installs, or used as a move source. 10566 */ 10567 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10568 String resourcePath, String[] instructionSets) { 10569 final boolean isInAsec; 10570 if (installOnExternalAsec(installFlags)) { 10571 /* Apps on SD card are always in ASEC containers. */ 10572 isInAsec = true; 10573 } else if (installForwardLocked(installFlags) 10574 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10575 /* 10576 * Forward-locked apps are only in ASEC containers if they're the 10577 * new style 10578 */ 10579 isInAsec = true; 10580 } else { 10581 isInAsec = false; 10582 } 10583 10584 if (isInAsec) { 10585 return new AsecInstallArgs(codePath, instructionSets, 10586 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10587 } else { 10588 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10589 } 10590 } 10591 10592 static abstract class InstallArgs { 10593 /** @see InstallParams#origin */ 10594 final OriginInfo origin; 10595 /** @see InstallParams#move */ 10596 final MoveInfo move; 10597 10598 final IPackageInstallObserver2 observer; 10599 // Always refers to PackageManager flags only 10600 final int installFlags; 10601 final String installerPackageName; 10602 final String volumeUuid; 10603 final ManifestDigest manifestDigest; 10604 final UserHandle user; 10605 final String abiOverride; 10606 10607 // The list of instruction sets supported by this app. This is currently 10608 // only used during the rmdex() phase to clean up resources. We can get rid of this 10609 // if we move dex files under the common app path. 10610 /* nullable */ String[] instructionSets; 10611 10612 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10613 int installFlags, String installerPackageName, String volumeUuid, 10614 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10615 String abiOverride) { 10616 this.origin = origin; 10617 this.move = move; 10618 this.installFlags = installFlags; 10619 this.observer = observer; 10620 this.installerPackageName = installerPackageName; 10621 this.volumeUuid = volumeUuid; 10622 this.manifestDigest = manifestDigest; 10623 this.user = user; 10624 this.instructionSets = instructionSets; 10625 this.abiOverride = abiOverride; 10626 } 10627 10628 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10629 abstract int doPreInstall(int status); 10630 10631 /** 10632 * Rename package into final resting place. All paths on the given 10633 * scanned package should be updated to reflect the rename. 10634 */ 10635 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10636 abstract int doPostInstall(int status, int uid); 10637 10638 /** @see PackageSettingBase#codePathString */ 10639 abstract String getCodePath(); 10640 /** @see PackageSettingBase#resourcePathString */ 10641 abstract String getResourcePath(); 10642 10643 // Need installer lock especially for dex file removal. 10644 abstract void cleanUpResourcesLI(); 10645 abstract boolean doPostDeleteLI(boolean delete); 10646 10647 /** 10648 * Called before the source arguments are copied. This is used mostly 10649 * for MoveParams when it needs to read the source file to put it in the 10650 * destination. 10651 */ 10652 int doPreCopy() { 10653 return PackageManager.INSTALL_SUCCEEDED; 10654 } 10655 10656 /** 10657 * Called after the source arguments are copied. This is used mostly for 10658 * MoveParams when it needs to read the source file to put it in the 10659 * destination. 10660 * 10661 * @return 10662 */ 10663 int doPostCopy(int uid) { 10664 return PackageManager.INSTALL_SUCCEEDED; 10665 } 10666 10667 protected boolean isFwdLocked() { 10668 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10669 } 10670 10671 protected boolean isExternalAsec() { 10672 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10673 } 10674 10675 UserHandle getUser() { 10676 return user; 10677 } 10678 } 10679 10680 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10681 if (!allCodePaths.isEmpty()) { 10682 if (instructionSets == null) { 10683 throw new IllegalStateException("instructionSet == null"); 10684 } 10685 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10686 for (String codePath : allCodePaths) { 10687 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10688 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10689 if (retCode < 0) { 10690 Slog.w(TAG, "Couldn't remove dex file for package: " 10691 + " at location " + codePath + ", retcode=" + retCode); 10692 // we don't consider this to be a failure of the core package deletion 10693 } 10694 } 10695 } 10696 } 10697 } 10698 10699 /** 10700 * Logic to handle installation of non-ASEC applications, including copying 10701 * and renaming logic. 10702 */ 10703 class FileInstallArgs extends InstallArgs { 10704 private File codeFile; 10705 private File resourceFile; 10706 10707 // Example topology: 10708 // /data/app/com.example/base.apk 10709 // /data/app/com.example/split_foo.apk 10710 // /data/app/com.example/lib/arm/libfoo.so 10711 // /data/app/com.example/lib/arm64/libfoo.so 10712 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10713 10714 /** New install */ 10715 FileInstallArgs(InstallParams params) { 10716 super(params.origin, params.move, params.observer, params.installFlags, 10717 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10718 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10719 if (isFwdLocked()) { 10720 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10721 } 10722 } 10723 10724 /** Existing install */ 10725 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10726 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10727 null); 10728 this.codeFile = (codePath != null) ? new File(codePath) : null; 10729 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10730 } 10731 10732 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10733 if (origin.staged) { 10734 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10735 codeFile = origin.file; 10736 resourceFile = origin.file; 10737 return PackageManager.INSTALL_SUCCEEDED; 10738 } 10739 10740 try { 10741 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10742 codeFile = tempDir; 10743 resourceFile = tempDir; 10744 } catch (IOException e) { 10745 Slog.w(TAG, "Failed to create copy file: " + e); 10746 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10747 } 10748 10749 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10750 @Override 10751 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10752 if (!FileUtils.isValidExtFilename(name)) { 10753 throw new IllegalArgumentException("Invalid filename: " + name); 10754 } 10755 try { 10756 final File file = new File(codeFile, name); 10757 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10758 O_RDWR | O_CREAT, 0644); 10759 Os.chmod(file.getAbsolutePath(), 0644); 10760 return new ParcelFileDescriptor(fd); 10761 } catch (ErrnoException e) { 10762 throw new RemoteException("Failed to open: " + e.getMessage()); 10763 } 10764 } 10765 }; 10766 10767 int ret = PackageManager.INSTALL_SUCCEEDED; 10768 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10769 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10770 Slog.e(TAG, "Failed to copy package"); 10771 return ret; 10772 } 10773 10774 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10775 NativeLibraryHelper.Handle handle = null; 10776 try { 10777 handle = NativeLibraryHelper.Handle.create(codeFile); 10778 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10779 abiOverride); 10780 } catch (IOException e) { 10781 Slog.e(TAG, "Copying native libraries failed", e); 10782 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10783 } finally { 10784 IoUtils.closeQuietly(handle); 10785 } 10786 10787 return ret; 10788 } 10789 10790 int doPreInstall(int status) { 10791 if (status != PackageManager.INSTALL_SUCCEEDED) { 10792 cleanUp(); 10793 } 10794 return status; 10795 } 10796 10797 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10798 if (status != PackageManager.INSTALL_SUCCEEDED) { 10799 cleanUp(); 10800 return false; 10801 } 10802 10803 final File targetDir = codeFile.getParentFile(); 10804 final File beforeCodeFile = codeFile; 10805 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10806 10807 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10808 try { 10809 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10810 } catch (ErrnoException e) { 10811 Slog.w(TAG, "Failed to rename", e); 10812 return false; 10813 } 10814 10815 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10816 Slog.w(TAG, "Failed to restorecon"); 10817 return false; 10818 } 10819 10820 // Reflect the rename internally 10821 codeFile = afterCodeFile; 10822 resourceFile = afterCodeFile; 10823 10824 // Reflect the rename in scanned details 10825 pkg.codePath = afterCodeFile.getAbsolutePath(); 10826 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10827 pkg.baseCodePath); 10828 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10829 pkg.splitCodePaths); 10830 10831 // Reflect the rename in app info 10832 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10833 pkg.applicationInfo.setCodePath(pkg.codePath); 10834 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10835 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10836 pkg.applicationInfo.setResourcePath(pkg.codePath); 10837 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10838 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10839 10840 return true; 10841 } 10842 10843 int doPostInstall(int status, int uid) { 10844 if (status != PackageManager.INSTALL_SUCCEEDED) { 10845 cleanUp(); 10846 } 10847 return status; 10848 } 10849 10850 @Override 10851 String getCodePath() { 10852 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10853 } 10854 10855 @Override 10856 String getResourcePath() { 10857 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10858 } 10859 10860 private boolean cleanUp() { 10861 if (codeFile == null || !codeFile.exists()) { 10862 return false; 10863 } 10864 10865 if (codeFile.isDirectory()) { 10866 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10867 } else { 10868 codeFile.delete(); 10869 } 10870 10871 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10872 resourceFile.delete(); 10873 } 10874 10875 return true; 10876 } 10877 10878 void cleanUpResourcesLI() { 10879 // Try enumerating all code paths before deleting 10880 List<String> allCodePaths = Collections.EMPTY_LIST; 10881 if (codeFile != null && codeFile.exists()) { 10882 try { 10883 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10884 allCodePaths = pkg.getAllCodePaths(); 10885 } catch (PackageParserException e) { 10886 // Ignored; we tried our best 10887 } 10888 } 10889 10890 cleanUp(); 10891 removeDexFiles(allCodePaths, instructionSets); 10892 } 10893 10894 boolean doPostDeleteLI(boolean delete) { 10895 // XXX err, shouldn't we respect the delete flag? 10896 cleanUpResourcesLI(); 10897 return true; 10898 } 10899 } 10900 10901 private boolean isAsecExternal(String cid) { 10902 final String asecPath = PackageHelper.getSdFilesystem(cid); 10903 return !asecPath.startsWith(mAsecInternalPath); 10904 } 10905 10906 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10907 PackageManagerException { 10908 if (copyRet < 0) { 10909 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10910 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10911 throw new PackageManagerException(copyRet, message); 10912 } 10913 } 10914 } 10915 10916 /** 10917 * Extract the MountService "container ID" from the full code path of an 10918 * .apk. 10919 */ 10920 static String cidFromCodePath(String fullCodePath) { 10921 int eidx = fullCodePath.lastIndexOf("/"); 10922 String subStr1 = fullCodePath.substring(0, eidx); 10923 int sidx = subStr1.lastIndexOf("/"); 10924 return subStr1.substring(sidx+1, eidx); 10925 } 10926 10927 /** 10928 * Logic to handle installation of ASEC applications, including copying and 10929 * renaming logic. 10930 */ 10931 class AsecInstallArgs extends InstallArgs { 10932 static final String RES_FILE_NAME = "pkg.apk"; 10933 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10934 10935 String cid; 10936 String packagePath; 10937 String resourcePath; 10938 10939 /** New install */ 10940 AsecInstallArgs(InstallParams params) { 10941 super(params.origin, params.move, params.observer, params.installFlags, 10942 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10943 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10944 } 10945 10946 /** Existing install */ 10947 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10948 boolean isExternal, boolean isForwardLocked) { 10949 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10950 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10951 instructionSets, null); 10952 // Hackily pretend we're still looking at a full code path 10953 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10954 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10955 } 10956 10957 // Extract cid from fullCodePath 10958 int eidx = fullCodePath.lastIndexOf("/"); 10959 String subStr1 = fullCodePath.substring(0, eidx); 10960 int sidx = subStr1.lastIndexOf("/"); 10961 cid = subStr1.substring(sidx+1, eidx); 10962 setMountPath(subStr1); 10963 } 10964 10965 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10966 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10967 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10968 instructionSets, null); 10969 this.cid = cid; 10970 setMountPath(PackageHelper.getSdDir(cid)); 10971 } 10972 10973 void createCopyFile() { 10974 cid = mInstallerService.allocateExternalStageCidLegacy(); 10975 } 10976 10977 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10978 if (origin.staged) { 10979 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10980 cid = origin.cid; 10981 setMountPath(PackageHelper.getSdDir(cid)); 10982 return PackageManager.INSTALL_SUCCEEDED; 10983 } 10984 10985 if (temp) { 10986 createCopyFile(); 10987 } else { 10988 /* 10989 * Pre-emptively destroy the container since it's destroyed if 10990 * copying fails due to it existing anyway. 10991 */ 10992 PackageHelper.destroySdDir(cid); 10993 } 10994 10995 final String newMountPath = imcs.copyPackageToContainer( 10996 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10997 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10998 10999 if (newMountPath != null) { 11000 setMountPath(newMountPath); 11001 return PackageManager.INSTALL_SUCCEEDED; 11002 } else { 11003 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11004 } 11005 } 11006 11007 @Override 11008 String getCodePath() { 11009 return packagePath; 11010 } 11011 11012 @Override 11013 String getResourcePath() { 11014 return resourcePath; 11015 } 11016 11017 int doPreInstall(int status) { 11018 if (status != PackageManager.INSTALL_SUCCEEDED) { 11019 // Destroy container 11020 PackageHelper.destroySdDir(cid); 11021 } else { 11022 boolean mounted = PackageHelper.isContainerMounted(cid); 11023 if (!mounted) { 11024 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11025 Process.SYSTEM_UID); 11026 if (newMountPath != null) { 11027 setMountPath(newMountPath); 11028 } else { 11029 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11030 } 11031 } 11032 } 11033 return status; 11034 } 11035 11036 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11037 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11038 String newMountPath = null; 11039 if (PackageHelper.isContainerMounted(cid)) { 11040 // Unmount the container 11041 if (!PackageHelper.unMountSdDir(cid)) { 11042 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11043 return false; 11044 } 11045 } 11046 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11047 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11048 " which might be stale. Will try to clean up."); 11049 // Clean up the stale container and proceed to recreate. 11050 if (!PackageHelper.destroySdDir(newCacheId)) { 11051 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11052 return false; 11053 } 11054 // Successfully cleaned up stale container. Try to rename again. 11055 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11056 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11057 + " inspite of cleaning it up."); 11058 return false; 11059 } 11060 } 11061 if (!PackageHelper.isContainerMounted(newCacheId)) { 11062 Slog.w(TAG, "Mounting container " + newCacheId); 11063 newMountPath = PackageHelper.mountSdDir(newCacheId, 11064 getEncryptKey(), Process.SYSTEM_UID); 11065 } else { 11066 newMountPath = PackageHelper.getSdDir(newCacheId); 11067 } 11068 if (newMountPath == null) { 11069 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11070 return false; 11071 } 11072 Log.i(TAG, "Succesfully renamed " + cid + 11073 " to " + newCacheId + 11074 " at new path: " + newMountPath); 11075 cid = newCacheId; 11076 11077 final File beforeCodeFile = new File(packagePath); 11078 setMountPath(newMountPath); 11079 final File afterCodeFile = new File(packagePath); 11080 11081 // Reflect the rename in scanned details 11082 pkg.codePath = afterCodeFile.getAbsolutePath(); 11083 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11084 pkg.baseCodePath); 11085 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11086 pkg.splitCodePaths); 11087 11088 // Reflect the rename in app info 11089 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11090 pkg.applicationInfo.setCodePath(pkg.codePath); 11091 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11092 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11093 pkg.applicationInfo.setResourcePath(pkg.codePath); 11094 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11095 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11096 11097 return true; 11098 } 11099 11100 private void setMountPath(String mountPath) { 11101 final File mountFile = new File(mountPath); 11102 11103 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11104 if (monolithicFile.exists()) { 11105 packagePath = monolithicFile.getAbsolutePath(); 11106 if (isFwdLocked()) { 11107 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11108 } else { 11109 resourcePath = packagePath; 11110 } 11111 } else { 11112 packagePath = mountFile.getAbsolutePath(); 11113 resourcePath = packagePath; 11114 } 11115 } 11116 11117 int doPostInstall(int status, int uid) { 11118 if (status != PackageManager.INSTALL_SUCCEEDED) { 11119 cleanUp(); 11120 } else { 11121 final int groupOwner; 11122 final String protectedFile; 11123 if (isFwdLocked()) { 11124 groupOwner = UserHandle.getSharedAppGid(uid); 11125 protectedFile = RES_FILE_NAME; 11126 } else { 11127 groupOwner = -1; 11128 protectedFile = null; 11129 } 11130 11131 if (uid < Process.FIRST_APPLICATION_UID 11132 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11133 Slog.e(TAG, "Failed to finalize " + cid); 11134 PackageHelper.destroySdDir(cid); 11135 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11136 } 11137 11138 boolean mounted = PackageHelper.isContainerMounted(cid); 11139 if (!mounted) { 11140 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11141 } 11142 } 11143 return status; 11144 } 11145 11146 private void cleanUp() { 11147 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11148 11149 // Destroy secure container 11150 PackageHelper.destroySdDir(cid); 11151 } 11152 11153 private List<String> getAllCodePaths() { 11154 final File codeFile = new File(getCodePath()); 11155 if (codeFile != null && codeFile.exists()) { 11156 try { 11157 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11158 return pkg.getAllCodePaths(); 11159 } catch (PackageParserException e) { 11160 // Ignored; we tried our best 11161 } 11162 } 11163 return Collections.EMPTY_LIST; 11164 } 11165 11166 void cleanUpResourcesLI() { 11167 // Enumerate all code paths before deleting 11168 cleanUpResourcesLI(getAllCodePaths()); 11169 } 11170 11171 private void cleanUpResourcesLI(List<String> allCodePaths) { 11172 cleanUp(); 11173 removeDexFiles(allCodePaths, instructionSets); 11174 } 11175 11176 String getPackageName() { 11177 return getAsecPackageName(cid); 11178 } 11179 11180 boolean doPostDeleteLI(boolean delete) { 11181 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11182 final List<String> allCodePaths = getAllCodePaths(); 11183 boolean mounted = PackageHelper.isContainerMounted(cid); 11184 if (mounted) { 11185 // Unmount first 11186 if (PackageHelper.unMountSdDir(cid)) { 11187 mounted = false; 11188 } 11189 } 11190 if (!mounted && delete) { 11191 cleanUpResourcesLI(allCodePaths); 11192 } 11193 return !mounted; 11194 } 11195 11196 @Override 11197 int doPreCopy() { 11198 if (isFwdLocked()) { 11199 if (!PackageHelper.fixSdPermissions(cid, 11200 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11201 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11202 } 11203 } 11204 11205 return PackageManager.INSTALL_SUCCEEDED; 11206 } 11207 11208 @Override 11209 int doPostCopy(int uid) { 11210 if (isFwdLocked()) { 11211 if (uid < Process.FIRST_APPLICATION_UID 11212 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11213 RES_FILE_NAME)) { 11214 Slog.e(TAG, "Failed to finalize " + cid); 11215 PackageHelper.destroySdDir(cid); 11216 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11217 } 11218 } 11219 11220 return PackageManager.INSTALL_SUCCEEDED; 11221 } 11222 } 11223 11224 /** 11225 * Logic to handle movement of existing installed applications. 11226 */ 11227 class MoveInstallArgs extends InstallArgs { 11228 private File codeFile; 11229 private File resourceFile; 11230 11231 /** New install */ 11232 MoveInstallArgs(InstallParams params) { 11233 super(params.origin, params.move, params.observer, params.installFlags, 11234 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11235 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11236 } 11237 11238 int copyApk(IMediaContainerService imcs, boolean temp) { 11239 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11240 + move.fromUuid + " to " + move.toUuid); 11241 synchronized (mInstaller) { 11242 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11243 move.dataAppName, move.appId, move.seinfo) != 0) { 11244 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11245 } 11246 } 11247 11248 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11249 resourceFile = codeFile; 11250 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11251 11252 return PackageManager.INSTALL_SUCCEEDED; 11253 } 11254 11255 int doPreInstall(int status) { 11256 if (status != PackageManager.INSTALL_SUCCEEDED) { 11257 cleanUp(); 11258 } 11259 return status; 11260 } 11261 11262 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11263 if (status != PackageManager.INSTALL_SUCCEEDED) { 11264 cleanUp(); 11265 return false; 11266 } 11267 11268 // Reflect the move in app info 11269 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11270 pkg.applicationInfo.setCodePath(pkg.codePath); 11271 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11272 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11273 pkg.applicationInfo.setResourcePath(pkg.codePath); 11274 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11275 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11276 11277 return true; 11278 } 11279 11280 int doPostInstall(int status, int uid) { 11281 if (status != PackageManager.INSTALL_SUCCEEDED) { 11282 cleanUp(); 11283 } 11284 return status; 11285 } 11286 11287 @Override 11288 String getCodePath() { 11289 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11290 } 11291 11292 @Override 11293 String getResourcePath() { 11294 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11295 } 11296 11297 private boolean cleanUp() { 11298 if (codeFile == null || !codeFile.exists()) { 11299 return false; 11300 } 11301 11302 if (codeFile.isDirectory()) { 11303 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11304 } else { 11305 codeFile.delete(); 11306 } 11307 11308 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11309 resourceFile.delete(); 11310 } 11311 11312 return true; 11313 } 11314 11315 void cleanUpResourcesLI() { 11316 cleanUp(); 11317 } 11318 11319 boolean doPostDeleteLI(boolean delete) { 11320 // XXX err, shouldn't we respect the delete flag? 11321 cleanUpResourcesLI(); 11322 return true; 11323 } 11324 } 11325 11326 static String getAsecPackageName(String packageCid) { 11327 int idx = packageCid.lastIndexOf("-"); 11328 if (idx == -1) { 11329 return packageCid; 11330 } 11331 return packageCid.substring(0, idx); 11332 } 11333 11334 // Utility method used to create code paths based on package name and available index. 11335 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11336 String idxStr = ""; 11337 int idx = 1; 11338 // Fall back to default value of idx=1 if prefix is not 11339 // part of oldCodePath 11340 if (oldCodePath != null) { 11341 String subStr = oldCodePath; 11342 // Drop the suffix right away 11343 if (suffix != null && subStr.endsWith(suffix)) { 11344 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11345 } 11346 // If oldCodePath already contains prefix find out the 11347 // ending index to either increment or decrement. 11348 int sidx = subStr.lastIndexOf(prefix); 11349 if (sidx != -1) { 11350 subStr = subStr.substring(sidx + prefix.length()); 11351 if (subStr != null) { 11352 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11353 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11354 } 11355 try { 11356 idx = Integer.parseInt(subStr); 11357 if (idx <= 1) { 11358 idx++; 11359 } else { 11360 idx--; 11361 } 11362 } catch(NumberFormatException e) { 11363 } 11364 } 11365 } 11366 } 11367 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11368 return prefix + idxStr; 11369 } 11370 11371 private File getNextCodePath(File targetDir, String packageName) { 11372 int suffix = 1; 11373 File result; 11374 do { 11375 result = new File(targetDir, packageName + "-" + suffix); 11376 suffix++; 11377 } while (result.exists()); 11378 return result; 11379 } 11380 11381 // Utility method that returns the relative package path with respect 11382 // to the installation directory. Like say for /data/data/com.test-1.apk 11383 // string com.test-1 is returned. 11384 static String deriveCodePathName(String codePath) { 11385 if (codePath == null) { 11386 return null; 11387 } 11388 final File codeFile = new File(codePath); 11389 final String name = codeFile.getName(); 11390 if (codeFile.isDirectory()) { 11391 return name; 11392 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11393 final int lastDot = name.lastIndexOf('.'); 11394 return name.substring(0, lastDot); 11395 } else { 11396 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11397 return null; 11398 } 11399 } 11400 11401 class PackageInstalledInfo { 11402 String name; 11403 int uid; 11404 // The set of users that originally had this package installed. 11405 int[] origUsers; 11406 // The set of users that now have this package installed. 11407 int[] newUsers; 11408 PackageParser.Package pkg; 11409 int returnCode; 11410 String returnMsg; 11411 PackageRemovedInfo removedInfo; 11412 11413 public void setError(int code, String msg) { 11414 returnCode = code; 11415 returnMsg = msg; 11416 Slog.w(TAG, msg); 11417 } 11418 11419 public void setError(String msg, PackageParserException e) { 11420 returnCode = e.error; 11421 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11422 Slog.w(TAG, msg, e); 11423 } 11424 11425 public void setError(String msg, PackageManagerException e) { 11426 returnCode = e.error; 11427 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11428 Slog.w(TAG, msg, e); 11429 } 11430 11431 // In some error cases we want to convey more info back to the observer 11432 String origPackage; 11433 String origPermission; 11434 } 11435 11436 /* 11437 * Install a non-existing package. 11438 */ 11439 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11440 UserHandle user, String installerPackageName, String volumeUuid, 11441 PackageInstalledInfo res) { 11442 // Remember this for later, in case we need to rollback this install 11443 String pkgName = pkg.packageName; 11444 11445 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11446 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11447 UserHandle.USER_OWNER).exists(); 11448 synchronized(mPackages) { 11449 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11450 // A package with the same name is already installed, though 11451 // it has been renamed to an older name. The package we 11452 // are trying to install should be installed as an update to 11453 // the existing one, but that has not been requested, so bail. 11454 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11455 + " without first uninstalling package running as " 11456 + mSettings.mRenamedPackages.get(pkgName)); 11457 return; 11458 } 11459 if (mPackages.containsKey(pkgName)) { 11460 // Don't allow installation over an existing package with the same name. 11461 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11462 + " without first uninstalling."); 11463 return; 11464 } 11465 } 11466 11467 try { 11468 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11469 System.currentTimeMillis(), user); 11470 11471 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11472 // delete the partially installed application. the data directory will have to be 11473 // restored if it was already existing 11474 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11475 // remove package from internal structures. Note that we want deletePackageX to 11476 // delete the package data and cache directories that it created in 11477 // scanPackageLocked, unless those directories existed before we even tried to 11478 // install. 11479 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11480 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11481 res.removedInfo, true); 11482 } 11483 11484 } catch (PackageManagerException e) { 11485 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11486 } 11487 } 11488 11489 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11490 // Can't rotate keys during boot or if sharedUser. 11491 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11492 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11493 return false; 11494 } 11495 // app is using upgradeKeySets; make sure all are valid 11496 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11497 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11498 for (int i = 0; i < upgradeKeySets.length; i++) { 11499 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11500 Slog.wtf(TAG, "Package " 11501 + (oldPs.name != null ? oldPs.name : "<null>") 11502 + " contains upgrade-key-set reference to unknown key-set: " 11503 + upgradeKeySets[i] 11504 + " reverting to signatures check."); 11505 return false; 11506 } 11507 } 11508 return true; 11509 } 11510 11511 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11512 // Upgrade keysets are being used. Determine if new package has a superset of the 11513 // required keys. 11514 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11515 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11516 for (int i = 0; i < upgradeKeySets.length; i++) { 11517 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11518 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11519 return true; 11520 } 11521 } 11522 return false; 11523 } 11524 11525 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11526 UserHandle user, String installerPackageName, String volumeUuid, 11527 PackageInstalledInfo res) { 11528 final PackageParser.Package oldPackage; 11529 final String pkgName = pkg.packageName; 11530 final int[] allUsers; 11531 final boolean[] perUserInstalled; 11532 final boolean weFroze; 11533 11534 // First find the old package info and check signatures 11535 synchronized(mPackages) { 11536 oldPackage = mPackages.get(pkgName); 11537 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11538 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11539 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11540 if(!checkUpgradeKeySetLP(ps, pkg)) { 11541 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11542 "New package not signed by keys specified by upgrade-keysets: " 11543 + pkgName); 11544 return; 11545 } 11546 } else { 11547 // default to original signature matching 11548 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11549 != PackageManager.SIGNATURE_MATCH) { 11550 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11551 "New package has a different signature: " + pkgName); 11552 return; 11553 } 11554 } 11555 11556 // In case of rollback, remember per-user/profile install state 11557 allUsers = sUserManager.getUserIds(); 11558 perUserInstalled = new boolean[allUsers.length]; 11559 for (int i = 0; i < allUsers.length; i++) { 11560 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11561 } 11562 11563 // Mark the app as frozen to prevent launching during the upgrade 11564 // process, and then kill all running instances 11565 if (!ps.frozen) { 11566 ps.frozen = true; 11567 weFroze = true; 11568 } else { 11569 weFroze = false; 11570 } 11571 } 11572 11573 // Now that we're guarded by frozen state, kill app during upgrade 11574 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11575 11576 try { 11577 boolean sysPkg = (isSystemApp(oldPackage)); 11578 if (sysPkg) { 11579 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11580 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11581 } else { 11582 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11583 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11584 } 11585 } finally { 11586 // Regardless of success or failure of upgrade steps above, always 11587 // unfreeze the package if we froze it 11588 if (weFroze) { 11589 unfreezePackage(pkgName); 11590 } 11591 } 11592 } 11593 11594 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11595 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11596 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11597 String volumeUuid, PackageInstalledInfo res) { 11598 String pkgName = deletedPackage.packageName; 11599 boolean deletedPkg = true; 11600 boolean updatedSettings = false; 11601 11602 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11603 + deletedPackage); 11604 long origUpdateTime; 11605 if (pkg.mExtras != null) { 11606 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11607 } else { 11608 origUpdateTime = 0; 11609 } 11610 11611 // First delete the existing package while retaining the data directory 11612 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11613 res.removedInfo, true)) { 11614 // If the existing package wasn't successfully deleted 11615 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11616 deletedPkg = false; 11617 } else { 11618 // Successfully deleted the old package; proceed with replace. 11619 11620 // If deleted package lived in a container, give users a chance to 11621 // relinquish resources before killing. 11622 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11623 if (DEBUG_INSTALL) { 11624 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11625 } 11626 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11627 final ArrayList<String> pkgList = new ArrayList<String>(1); 11628 pkgList.add(deletedPackage.applicationInfo.packageName); 11629 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11630 } 11631 11632 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11633 try { 11634 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11635 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11636 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11637 perUserInstalled, res, user); 11638 updatedSettings = true; 11639 } catch (PackageManagerException e) { 11640 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11641 } 11642 } 11643 11644 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11645 // remove package from internal structures. Note that we want deletePackageX to 11646 // delete the package data and cache directories that it created in 11647 // scanPackageLocked, unless those directories existed before we even tried to 11648 // install. 11649 if(updatedSettings) { 11650 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11651 deletePackageLI( 11652 pkgName, null, true, allUsers, perUserInstalled, 11653 PackageManager.DELETE_KEEP_DATA, 11654 res.removedInfo, true); 11655 } 11656 // Since we failed to install the new package we need to restore the old 11657 // package that we deleted. 11658 if (deletedPkg) { 11659 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11660 File restoreFile = new File(deletedPackage.codePath); 11661 // Parse old package 11662 boolean oldExternal = isExternal(deletedPackage); 11663 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11664 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11665 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11666 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11667 try { 11668 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11669 } catch (PackageManagerException e) { 11670 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11671 + e.getMessage()); 11672 return; 11673 } 11674 // Restore of old package succeeded. Update permissions. 11675 // writer 11676 synchronized (mPackages) { 11677 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11678 UPDATE_PERMISSIONS_ALL); 11679 // can downgrade to reader 11680 mSettings.writeLPr(); 11681 } 11682 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11683 } 11684 } 11685 } 11686 11687 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11688 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11689 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11690 String volumeUuid, PackageInstalledInfo res) { 11691 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11692 + ", old=" + deletedPackage); 11693 boolean disabledSystem = false; 11694 boolean updatedSettings = false; 11695 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11696 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11697 != 0) { 11698 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11699 } 11700 String packageName = deletedPackage.packageName; 11701 if (packageName == null) { 11702 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11703 "Attempt to delete null packageName."); 11704 return; 11705 } 11706 PackageParser.Package oldPkg; 11707 PackageSetting oldPkgSetting; 11708 // reader 11709 synchronized (mPackages) { 11710 oldPkg = mPackages.get(packageName); 11711 oldPkgSetting = mSettings.mPackages.get(packageName); 11712 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11713 (oldPkgSetting == null)) { 11714 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11715 "Couldn't find package:" + packageName + " information"); 11716 return; 11717 } 11718 } 11719 11720 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11721 res.removedInfo.removedPackage = packageName; 11722 // Remove existing system package 11723 removePackageLI(oldPkgSetting, true); 11724 // writer 11725 synchronized (mPackages) { 11726 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11727 if (!disabledSystem && deletedPackage != null) { 11728 // We didn't need to disable the .apk as a current system package, 11729 // which means we are replacing another update that is already 11730 // installed. We need to make sure to delete the older one's .apk. 11731 res.removedInfo.args = createInstallArgsForExisting(0, 11732 deletedPackage.applicationInfo.getCodePath(), 11733 deletedPackage.applicationInfo.getResourcePath(), 11734 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11735 } else { 11736 res.removedInfo.args = null; 11737 } 11738 } 11739 11740 // Successfully disabled the old package. Now proceed with re-installation 11741 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11742 11743 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11744 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11745 11746 PackageParser.Package newPackage = null; 11747 try { 11748 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11749 if (newPackage.mExtras != null) { 11750 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11751 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11752 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11753 11754 // is the update attempting to change shared user? that isn't going to work... 11755 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11756 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11757 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11758 + " to " + newPkgSetting.sharedUser); 11759 updatedSettings = true; 11760 } 11761 } 11762 11763 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11764 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11765 perUserInstalled, res, user); 11766 updatedSettings = true; 11767 } 11768 11769 } catch (PackageManagerException e) { 11770 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11771 } 11772 11773 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11774 // Re installation failed. Restore old information 11775 // Remove new pkg information 11776 if (newPackage != null) { 11777 removeInstalledPackageLI(newPackage, true); 11778 } 11779 // Add back the old system package 11780 try { 11781 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11782 } catch (PackageManagerException e) { 11783 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11784 } 11785 // Restore the old system information in Settings 11786 synchronized (mPackages) { 11787 if (disabledSystem) { 11788 mSettings.enableSystemPackageLPw(packageName); 11789 } 11790 if (updatedSettings) { 11791 mSettings.setInstallerPackageName(packageName, 11792 oldPkgSetting.installerPackageName); 11793 } 11794 mSettings.writeLPr(); 11795 } 11796 } 11797 } 11798 11799 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11800 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11801 UserHandle user) { 11802 String pkgName = newPackage.packageName; 11803 synchronized (mPackages) { 11804 //write settings. the installStatus will be incomplete at this stage. 11805 //note that the new package setting would have already been 11806 //added to mPackages. It hasn't been persisted yet. 11807 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11808 mSettings.writeLPr(); 11809 } 11810 11811 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11812 11813 synchronized (mPackages) { 11814 updatePermissionsLPw(newPackage.packageName, newPackage, 11815 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11816 ? UPDATE_PERMISSIONS_ALL : 0)); 11817 // For system-bundled packages, we assume that installing an upgraded version 11818 // of the package implies that the user actually wants to run that new code, 11819 // so we enable the package. 11820 PackageSetting ps = mSettings.mPackages.get(pkgName); 11821 if (ps != null) { 11822 if (isSystemApp(newPackage)) { 11823 // NB: implicit assumption that system package upgrades apply to all users 11824 if (DEBUG_INSTALL) { 11825 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11826 } 11827 if (res.origUsers != null) { 11828 for (int userHandle : res.origUsers) { 11829 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11830 userHandle, installerPackageName); 11831 } 11832 } 11833 // Also convey the prior install/uninstall state 11834 if (allUsers != null && perUserInstalled != null) { 11835 for (int i = 0; i < allUsers.length; i++) { 11836 if (DEBUG_INSTALL) { 11837 Slog.d(TAG, " user " + allUsers[i] 11838 + " => " + perUserInstalled[i]); 11839 } 11840 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11841 } 11842 // these install state changes will be persisted in the 11843 // upcoming call to mSettings.writeLPr(). 11844 } 11845 } 11846 // It's implied that when a user requests installation, they want the app to be 11847 // installed and enabled. 11848 int userId = user.getIdentifier(); 11849 if (userId != UserHandle.USER_ALL) { 11850 ps.setInstalled(true, userId); 11851 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11852 } 11853 } 11854 res.name = pkgName; 11855 res.uid = newPackage.applicationInfo.uid; 11856 res.pkg = newPackage; 11857 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11858 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11859 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11860 //to update install status 11861 mSettings.writeLPr(); 11862 } 11863 } 11864 11865 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11866 final int installFlags = args.installFlags; 11867 final String installerPackageName = args.installerPackageName; 11868 final String volumeUuid = args.volumeUuid; 11869 final File tmpPackageFile = new File(args.getCodePath()); 11870 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11871 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11872 || (args.volumeUuid != null)); 11873 boolean replace = false; 11874 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11875 if (args.move != null) { 11876 // moving a complete application; perfom an initial scan on the new install location 11877 scanFlags |= SCAN_INITIAL; 11878 } 11879 // Result object to be returned 11880 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11881 11882 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11883 // Retrieve PackageSettings and parse package 11884 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11885 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11886 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11887 PackageParser pp = new PackageParser(); 11888 pp.setSeparateProcesses(mSeparateProcesses); 11889 pp.setDisplayMetrics(mMetrics); 11890 11891 final PackageParser.Package pkg; 11892 try { 11893 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11894 } catch (PackageParserException e) { 11895 res.setError("Failed parse during installPackageLI", e); 11896 return; 11897 } 11898 11899 // Mark that we have an install time CPU ABI override. 11900 pkg.cpuAbiOverride = args.abiOverride; 11901 11902 String pkgName = res.name = pkg.packageName; 11903 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11904 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11905 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11906 return; 11907 } 11908 } 11909 11910 try { 11911 pp.collectCertificates(pkg, parseFlags); 11912 pp.collectManifestDigest(pkg); 11913 } catch (PackageParserException e) { 11914 res.setError("Failed collect during installPackageLI", e); 11915 return; 11916 } 11917 11918 /* If the installer passed in a manifest digest, compare it now. */ 11919 if (args.manifestDigest != null) { 11920 if (DEBUG_INSTALL) { 11921 final String parsedManifest = pkg.manifestDigest == null ? "null" 11922 : pkg.manifestDigest.toString(); 11923 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11924 + parsedManifest); 11925 } 11926 11927 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11928 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11929 return; 11930 } 11931 } else if (DEBUG_INSTALL) { 11932 final String parsedManifest = pkg.manifestDigest == null 11933 ? "null" : pkg.manifestDigest.toString(); 11934 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11935 } 11936 11937 // Get rid of all references to package scan path via parser. 11938 pp = null; 11939 String oldCodePath = null; 11940 boolean systemApp = false; 11941 synchronized (mPackages) { 11942 // Check if installing already existing package 11943 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11944 String oldName = mSettings.mRenamedPackages.get(pkgName); 11945 if (pkg.mOriginalPackages != null 11946 && pkg.mOriginalPackages.contains(oldName) 11947 && mPackages.containsKey(oldName)) { 11948 // This package is derived from an original package, 11949 // and this device has been updating from that original 11950 // name. We must continue using the original name, so 11951 // rename the new package here. 11952 pkg.setPackageName(oldName); 11953 pkgName = pkg.packageName; 11954 replace = true; 11955 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11956 + oldName + " pkgName=" + pkgName); 11957 } else if (mPackages.containsKey(pkgName)) { 11958 // This package, under its official name, already exists 11959 // on the device; we should replace it. 11960 replace = true; 11961 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11962 } 11963 11964 // Prevent apps opting out from runtime permissions 11965 if (replace) { 11966 PackageParser.Package oldPackage = mPackages.get(pkgName); 11967 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11968 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11969 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11970 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11971 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11972 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11973 + " doesn't support runtime permissions but the old" 11974 + " target SDK " + oldTargetSdk + " does."); 11975 return; 11976 } 11977 } 11978 } 11979 11980 PackageSetting ps = mSettings.mPackages.get(pkgName); 11981 if (ps != null) { 11982 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11983 11984 // Quick sanity check that we're signed correctly if updating; 11985 // we'll check this again later when scanning, but we want to 11986 // bail early here before tripping over redefined permissions. 11987 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11988 if (!checkUpgradeKeySetLP(ps, pkg)) { 11989 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11990 + pkg.packageName + " upgrade keys do not match the " 11991 + "previously installed version"); 11992 return; 11993 } 11994 } else { 11995 try { 11996 verifySignaturesLP(ps, pkg); 11997 } catch (PackageManagerException e) { 11998 res.setError(e.error, e.getMessage()); 11999 return; 12000 } 12001 } 12002 12003 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12004 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12005 systemApp = (ps.pkg.applicationInfo.flags & 12006 ApplicationInfo.FLAG_SYSTEM) != 0; 12007 } 12008 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12009 } 12010 12011 // Check whether the newly-scanned package wants to define an already-defined perm 12012 int N = pkg.permissions.size(); 12013 for (int i = N-1; i >= 0; i--) { 12014 PackageParser.Permission perm = pkg.permissions.get(i); 12015 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12016 if (bp != null) { 12017 // If the defining package is signed with our cert, it's okay. This 12018 // also includes the "updating the same package" case, of course. 12019 // "updating same package" could also involve key-rotation. 12020 final boolean sigsOk; 12021 if (bp.sourcePackage.equals(pkg.packageName) 12022 && (bp.packageSetting instanceof PackageSetting) 12023 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12024 scanFlags))) { 12025 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12026 } else { 12027 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12028 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12029 } 12030 if (!sigsOk) { 12031 // If the owning package is the system itself, we log but allow 12032 // install to proceed; we fail the install on all other permission 12033 // redefinitions. 12034 if (!bp.sourcePackage.equals("android")) { 12035 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12036 + pkg.packageName + " attempting to redeclare permission " 12037 + perm.info.name + " already owned by " + bp.sourcePackage); 12038 res.origPermission = perm.info.name; 12039 res.origPackage = bp.sourcePackage; 12040 return; 12041 } else { 12042 Slog.w(TAG, "Package " + pkg.packageName 12043 + " attempting to redeclare system permission " 12044 + perm.info.name + "; ignoring new declaration"); 12045 pkg.permissions.remove(i); 12046 } 12047 } 12048 } 12049 } 12050 12051 } 12052 12053 if (systemApp && onExternal) { 12054 // Disable updates to system apps on sdcard 12055 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12056 "Cannot install updates to system apps on sdcard"); 12057 return; 12058 } 12059 12060 if (args.move != null) { 12061 // We did an in-place move, so dex is ready to roll 12062 scanFlags |= SCAN_NO_DEX; 12063 scanFlags |= SCAN_MOVE; 12064 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12065 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12066 scanFlags |= SCAN_NO_DEX; 12067 12068 try { 12069 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12070 true /* extract libs */); 12071 } catch (PackageManagerException pme) { 12072 Slog.e(TAG, "Error deriving application ABI", pme); 12073 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12074 return; 12075 } 12076 12077 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12078 int result = mPackageDexOptimizer 12079 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12080 false /* defer */, false /* inclDependencies */); 12081 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12082 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12083 return; 12084 } 12085 } 12086 12087 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12088 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12089 return; 12090 } 12091 12092 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12093 12094 if (replace) { 12095 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12096 installerPackageName, volumeUuid, res); 12097 } else { 12098 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12099 args.user, installerPackageName, volumeUuid, res); 12100 } 12101 synchronized (mPackages) { 12102 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12103 if (ps != null) { 12104 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12105 } 12106 } 12107 } 12108 12109 private void startIntentFilterVerifications(int userId, boolean replacing, 12110 PackageParser.Package pkg) { 12111 if (mIntentFilterVerifierComponent == null) { 12112 Slog.w(TAG, "No IntentFilter verification will not be done as " 12113 + "there is no IntentFilterVerifier available!"); 12114 return; 12115 } 12116 12117 final int verifierUid = getPackageUid( 12118 mIntentFilterVerifierComponent.getPackageName(), 12119 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12120 12121 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12122 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12123 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12124 mHandler.sendMessage(msg); 12125 } 12126 12127 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12128 PackageParser.Package pkg) { 12129 int size = pkg.activities.size(); 12130 if (size == 0) { 12131 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12132 "No activity, so no need to verify any IntentFilter!"); 12133 return; 12134 } 12135 12136 final boolean hasDomainURLs = hasDomainURLs(pkg); 12137 if (!hasDomainURLs) { 12138 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12139 "No domain URLs, so no need to verify any IntentFilter!"); 12140 return; 12141 } 12142 12143 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12144 + " if any IntentFilter from the " + size 12145 + " Activities needs verification ..."); 12146 12147 int count = 0; 12148 final String packageName = pkg.packageName; 12149 12150 synchronized (mPackages) { 12151 // If this is a new install and we see that we've already run verification for this 12152 // package, we have nothing to do: it means the state was restored from backup. 12153 if (!replacing) { 12154 IntentFilterVerificationInfo ivi = 12155 mSettings.getIntentFilterVerificationLPr(packageName); 12156 if (ivi != null) { 12157 if (DEBUG_DOMAIN_VERIFICATION) { 12158 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12159 + ivi.getStatusString()); 12160 } 12161 return; 12162 } 12163 } 12164 12165 // If any filters need to be verified, then all need to be. 12166 boolean needToVerify = false; 12167 for (PackageParser.Activity a : pkg.activities) { 12168 for (ActivityIntentInfo filter : a.intents) { 12169 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12170 if (DEBUG_DOMAIN_VERIFICATION) { 12171 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12172 } 12173 needToVerify = true; 12174 break; 12175 } 12176 } 12177 } 12178 12179 if (needToVerify) { 12180 final int verificationId = mIntentFilterVerificationToken++; 12181 for (PackageParser.Activity a : pkg.activities) { 12182 for (ActivityIntentInfo filter : a.intents) { 12183 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12184 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12185 "Verification needed for IntentFilter:" + filter.toString()); 12186 mIntentFilterVerifier.addOneIntentFilterVerification( 12187 verifierUid, userId, verificationId, filter, packageName); 12188 count++; 12189 } 12190 } 12191 } 12192 } 12193 } 12194 12195 if (count > 0) { 12196 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12197 + " IntentFilter verification" + (count > 1 ? "s" : "") 12198 + " for userId:" + userId); 12199 mIntentFilterVerifier.startVerifications(userId); 12200 } else { 12201 if (DEBUG_DOMAIN_VERIFICATION) { 12202 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12203 } 12204 } 12205 } 12206 12207 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12208 final ComponentName cn = filter.activity.getComponentName(); 12209 final String packageName = cn.getPackageName(); 12210 12211 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12212 packageName); 12213 if (ivi == null) { 12214 return true; 12215 } 12216 int status = ivi.getStatus(); 12217 switch (status) { 12218 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12219 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12220 return true; 12221 12222 default: 12223 // Nothing to do 12224 return false; 12225 } 12226 } 12227 12228 private static boolean isMultiArch(PackageSetting ps) { 12229 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12230 } 12231 12232 private static boolean isMultiArch(ApplicationInfo info) { 12233 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12234 } 12235 12236 private static boolean isExternal(PackageParser.Package pkg) { 12237 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12238 } 12239 12240 private static boolean isExternal(PackageSetting ps) { 12241 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12242 } 12243 12244 private static boolean isExternal(ApplicationInfo info) { 12245 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12246 } 12247 12248 private static boolean isSystemApp(PackageParser.Package pkg) { 12249 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12250 } 12251 12252 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12253 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12254 } 12255 12256 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12257 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12258 } 12259 12260 private static boolean isSystemApp(PackageSetting ps) { 12261 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12262 } 12263 12264 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12265 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12266 } 12267 12268 private int packageFlagsToInstallFlags(PackageSetting ps) { 12269 int installFlags = 0; 12270 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12271 // This existing package was an external ASEC install when we have 12272 // the external flag without a UUID 12273 installFlags |= PackageManager.INSTALL_EXTERNAL; 12274 } 12275 if (ps.isForwardLocked()) { 12276 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12277 } 12278 return installFlags; 12279 } 12280 12281 private void deleteTempPackageFiles() { 12282 final FilenameFilter filter = new FilenameFilter() { 12283 public boolean accept(File dir, String name) { 12284 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12285 } 12286 }; 12287 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12288 file.delete(); 12289 } 12290 } 12291 12292 @Override 12293 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12294 int flags) { 12295 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12296 flags); 12297 } 12298 12299 @Override 12300 public void deletePackage(final String packageName, 12301 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12302 mContext.enforceCallingOrSelfPermission( 12303 android.Manifest.permission.DELETE_PACKAGES, null); 12304 final int uid = Binder.getCallingUid(); 12305 if (UserHandle.getUserId(uid) != userId) { 12306 mContext.enforceCallingPermission( 12307 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12308 "deletePackage for user " + userId); 12309 } 12310 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12311 try { 12312 observer.onPackageDeleted(packageName, 12313 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12314 } catch (RemoteException re) { 12315 } 12316 return; 12317 } 12318 12319 boolean uninstallBlocked = false; 12320 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12321 int[] users = sUserManager.getUserIds(); 12322 for (int i = 0; i < users.length; ++i) { 12323 if (getBlockUninstallForUser(packageName, users[i])) { 12324 uninstallBlocked = true; 12325 break; 12326 } 12327 } 12328 } else { 12329 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12330 } 12331 if (uninstallBlocked) { 12332 try { 12333 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12334 null); 12335 } catch (RemoteException re) { 12336 } 12337 return; 12338 } 12339 12340 if (DEBUG_REMOVE) { 12341 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12342 } 12343 // Queue up an async operation since the package deletion may take a little while. 12344 mHandler.post(new Runnable() { 12345 public void run() { 12346 mHandler.removeCallbacks(this); 12347 final int returnCode = deletePackageX(packageName, userId, flags); 12348 if (observer != null) { 12349 try { 12350 observer.onPackageDeleted(packageName, returnCode, null); 12351 } catch (RemoteException e) { 12352 Log.i(TAG, "Observer no longer exists."); 12353 } //end catch 12354 } //end if 12355 } //end run 12356 }); 12357 } 12358 12359 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12360 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12361 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12362 try { 12363 if (dpm != null) { 12364 if (dpm.isDeviceOwner(packageName)) { 12365 return true; 12366 } 12367 int[] users; 12368 if (userId == UserHandle.USER_ALL) { 12369 users = sUserManager.getUserIds(); 12370 } else { 12371 users = new int[]{userId}; 12372 } 12373 for (int i = 0; i < users.length; ++i) { 12374 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12375 return true; 12376 } 12377 } 12378 } 12379 } catch (RemoteException e) { 12380 } 12381 return false; 12382 } 12383 12384 /** 12385 * This method is an internal method that could be get invoked either 12386 * to delete an installed package or to clean up a failed installation. 12387 * After deleting an installed package, a broadcast is sent to notify any 12388 * listeners that the package has been installed. For cleaning up a failed 12389 * installation, the broadcast is not necessary since the package's 12390 * installation wouldn't have sent the initial broadcast either 12391 * The key steps in deleting a package are 12392 * deleting the package information in internal structures like mPackages, 12393 * deleting the packages base directories through installd 12394 * updating mSettings to reflect current status 12395 * persisting settings for later use 12396 * sending a broadcast if necessary 12397 */ 12398 private int deletePackageX(String packageName, int userId, int flags) { 12399 final PackageRemovedInfo info = new PackageRemovedInfo(); 12400 final boolean res; 12401 12402 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12403 ? UserHandle.ALL : new UserHandle(userId); 12404 12405 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12406 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12407 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12408 } 12409 12410 boolean removedForAllUsers = false; 12411 boolean systemUpdate = false; 12412 12413 // for the uninstall-updates case and restricted profiles, remember the per- 12414 // userhandle installed state 12415 int[] allUsers; 12416 boolean[] perUserInstalled; 12417 synchronized (mPackages) { 12418 PackageSetting ps = mSettings.mPackages.get(packageName); 12419 allUsers = sUserManager.getUserIds(); 12420 perUserInstalled = new boolean[allUsers.length]; 12421 for (int i = 0; i < allUsers.length; i++) { 12422 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12423 } 12424 } 12425 12426 synchronized (mInstallLock) { 12427 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12428 res = deletePackageLI(packageName, removeForUser, 12429 true, allUsers, perUserInstalled, 12430 flags | REMOVE_CHATTY, info, true); 12431 systemUpdate = info.isRemovedPackageSystemUpdate; 12432 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12433 removedForAllUsers = true; 12434 } 12435 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12436 + " removedForAllUsers=" + removedForAllUsers); 12437 } 12438 12439 if (res) { 12440 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12441 12442 // If the removed package was a system update, the old system package 12443 // was re-enabled; we need to broadcast this information 12444 if (systemUpdate) { 12445 Bundle extras = new Bundle(1); 12446 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12447 ? info.removedAppId : info.uid); 12448 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12449 12450 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12451 extras, null, null, null); 12452 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12453 extras, null, null, null); 12454 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12455 null, packageName, null, null); 12456 } 12457 } 12458 // Force a gc here. 12459 Runtime.getRuntime().gc(); 12460 // Delete the resources here after sending the broadcast to let 12461 // other processes clean up before deleting resources. 12462 if (info.args != null) { 12463 synchronized (mInstallLock) { 12464 info.args.doPostDeleteLI(true); 12465 } 12466 } 12467 12468 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12469 } 12470 12471 class PackageRemovedInfo { 12472 String removedPackage; 12473 int uid = -1; 12474 int removedAppId = -1; 12475 int[] removedUsers = null; 12476 boolean isRemovedPackageSystemUpdate = false; 12477 // Clean up resources deleted packages. 12478 InstallArgs args = null; 12479 12480 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12481 Bundle extras = new Bundle(1); 12482 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12483 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12484 if (replacing) { 12485 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12486 } 12487 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12488 if (removedPackage != null) { 12489 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12490 extras, null, null, removedUsers); 12491 if (fullRemove && !replacing) { 12492 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12493 extras, null, null, removedUsers); 12494 } 12495 } 12496 if (removedAppId >= 0) { 12497 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12498 removedUsers); 12499 } 12500 } 12501 } 12502 12503 /* 12504 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12505 * flag is not set, the data directory is removed as well. 12506 * make sure this flag is set for partially installed apps. If not its meaningless to 12507 * delete a partially installed application. 12508 */ 12509 private void removePackageDataLI(PackageSetting ps, 12510 int[] allUserHandles, boolean[] perUserInstalled, 12511 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12512 String packageName = ps.name; 12513 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12514 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12515 // Retrieve object to delete permissions for shared user later on 12516 final PackageSetting deletedPs; 12517 // reader 12518 synchronized (mPackages) { 12519 deletedPs = mSettings.mPackages.get(packageName); 12520 if (outInfo != null) { 12521 outInfo.removedPackage = packageName; 12522 outInfo.removedUsers = deletedPs != null 12523 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12524 : null; 12525 } 12526 } 12527 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12528 removeDataDirsLI(ps.volumeUuid, packageName); 12529 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12530 } 12531 // writer 12532 synchronized (mPackages) { 12533 if (deletedPs != null) { 12534 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12535 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12536 clearDefaultBrowserIfNeeded(packageName); 12537 if (outInfo != null) { 12538 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12539 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12540 } 12541 updatePermissionsLPw(deletedPs.name, null, 0); 12542 if (deletedPs.sharedUser != null) { 12543 // Remove permissions associated with package. Since runtime 12544 // permissions are per user we have to kill the removed package 12545 // or packages running under the shared user of the removed 12546 // package if revoking the permissions requested only by the removed 12547 // package is successful and this causes a change in gids. 12548 for (int userId : UserManagerService.getInstance().getUserIds()) { 12549 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12550 userId); 12551 if (userIdToKill == UserHandle.USER_ALL 12552 || userIdToKill >= UserHandle.USER_OWNER) { 12553 // If gids changed for this user, kill all affected packages. 12554 mHandler.post(new Runnable() { 12555 @Override 12556 public void run() { 12557 // This has to happen with no lock held. 12558 killSettingPackagesForUser(deletedPs, userIdToKill, 12559 KILL_APP_REASON_GIDS_CHANGED); 12560 } 12561 }); 12562 break; 12563 } 12564 } 12565 } 12566 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12567 } 12568 // make sure to preserve per-user disabled state if this removal was just 12569 // a downgrade of a system app to the factory package 12570 if (allUserHandles != null && perUserInstalled != null) { 12571 if (DEBUG_REMOVE) { 12572 Slog.d(TAG, "Propagating install state across downgrade"); 12573 } 12574 for (int i = 0; i < allUserHandles.length; i++) { 12575 if (DEBUG_REMOVE) { 12576 Slog.d(TAG, " user " + allUserHandles[i] 12577 + " => " + perUserInstalled[i]); 12578 } 12579 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12580 } 12581 } 12582 } 12583 // can downgrade to reader 12584 if (writeSettings) { 12585 // Save settings now 12586 mSettings.writeLPr(); 12587 } 12588 } 12589 if (outInfo != null) { 12590 // A user ID was deleted here. Go through all users and remove it 12591 // from KeyStore. 12592 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12593 } 12594 } 12595 12596 static boolean locationIsPrivileged(File path) { 12597 try { 12598 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12599 .getCanonicalPath(); 12600 return path.getCanonicalPath().startsWith(privilegedAppDir); 12601 } catch (IOException e) { 12602 Slog.e(TAG, "Unable to access code path " + path); 12603 } 12604 return false; 12605 } 12606 12607 /* 12608 * Tries to delete system package. 12609 */ 12610 private boolean deleteSystemPackageLI(PackageSetting newPs, 12611 int[] allUserHandles, boolean[] perUserInstalled, 12612 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12613 final boolean applyUserRestrictions 12614 = (allUserHandles != null) && (perUserInstalled != null); 12615 PackageSetting disabledPs = null; 12616 // Confirm if the system package has been updated 12617 // An updated system app can be deleted. This will also have to restore 12618 // the system pkg from system partition 12619 // reader 12620 synchronized (mPackages) { 12621 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12622 } 12623 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12624 + " disabledPs=" + disabledPs); 12625 if (disabledPs == null) { 12626 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12627 return false; 12628 } else if (DEBUG_REMOVE) { 12629 Slog.d(TAG, "Deleting system pkg from data partition"); 12630 } 12631 if (DEBUG_REMOVE) { 12632 if (applyUserRestrictions) { 12633 Slog.d(TAG, "Remembering install states:"); 12634 for (int i = 0; i < allUserHandles.length; i++) { 12635 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12636 } 12637 } 12638 } 12639 // Delete the updated package 12640 outInfo.isRemovedPackageSystemUpdate = true; 12641 if (disabledPs.versionCode < newPs.versionCode) { 12642 // Delete data for downgrades 12643 flags &= ~PackageManager.DELETE_KEEP_DATA; 12644 } else { 12645 // Preserve data by setting flag 12646 flags |= PackageManager.DELETE_KEEP_DATA; 12647 } 12648 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12649 allUserHandles, perUserInstalled, outInfo, writeSettings); 12650 if (!ret) { 12651 return false; 12652 } 12653 // writer 12654 synchronized (mPackages) { 12655 // Reinstate the old system package 12656 mSettings.enableSystemPackageLPw(newPs.name); 12657 // Remove any native libraries from the upgraded package. 12658 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12659 } 12660 // Install the system package 12661 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12662 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12663 if (locationIsPrivileged(disabledPs.codePath)) { 12664 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12665 } 12666 12667 final PackageParser.Package newPkg; 12668 try { 12669 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12670 } catch (PackageManagerException e) { 12671 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12672 return false; 12673 } 12674 12675 // writer 12676 synchronized (mPackages) { 12677 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12678 updatePermissionsLPw(newPkg.packageName, newPkg, 12679 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12680 if (applyUserRestrictions) { 12681 if (DEBUG_REMOVE) { 12682 Slog.d(TAG, "Propagating install state across reinstall"); 12683 } 12684 for (int i = 0; i < allUserHandles.length; i++) { 12685 if (DEBUG_REMOVE) { 12686 Slog.d(TAG, " user " + allUserHandles[i] 12687 + " => " + perUserInstalled[i]); 12688 } 12689 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12690 } 12691 // Regardless of writeSettings we need to ensure that this restriction 12692 // state propagation is persisted 12693 mSettings.writeAllUsersPackageRestrictionsLPr(); 12694 } 12695 // can downgrade to reader here 12696 if (writeSettings) { 12697 mSettings.writeLPr(); 12698 } 12699 } 12700 return true; 12701 } 12702 12703 private boolean deleteInstalledPackageLI(PackageSetting ps, 12704 boolean deleteCodeAndResources, int flags, 12705 int[] allUserHandles, boolean[] perUserInstalled, 12706 PackageRemovedInfo outInfo, boolean writeSettings) { 12707 if (outInfo != null) { 12708 outInfo.uid = ps.appId; 12709 } 12710 12711 // Delete package data from internal structures and also remove data if flag is set 12712 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12713 12714 // Delete application code and resources 12715 if (deleteCodeAndResources && (outInfo != null)) { 12716 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12717 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12718 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12719 } 12720 return true; 12721 } 12722 12723 @Override 12724 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12725 int userId) { 12726 mContext.enforceCallingOrSelfPermission( 12727 android.Manifest.permission.DELETE_PACKAGES, null); 12728 synchronized (mPackages) { 12729 PackageSetting ps = mSettings.mPackages.get(packageName); 12730 if (ps == null) { 12731 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12732 return false; 12733 } 12734 if (!ps.getInstalled(userId)) { 12735 // Can't block uninstall for an app that is not installed or enabled. 12736 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12737 return false; 12738 } 12739 ps.setBlockUninstall(blockUninstall, userId); 12740 mSettings.writePackageRestrictionsLPr(userId); 12741 } 12742 return true; 12743 } 12744 12745 @Override 12746 public boolean getBlockUninstallForUser(String packageName, int userId) { 12747 synchronized (mPackages) { 12748 PackageSetting ps = mSettings.mPackages.get(packageName); 12749 if (ps == null) { 12750 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12751 return false; 12752 } 12753 return ps.getBlockUninstall(userId); 12754 } 12755 } 12756 12757 /* 12758 * This method handles package deletion in general 12759 */ 12760 private boolean deletePackageLI(String packageName, UserHandle user, 12761 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12762 int flags, PackageRemovedInfo outInfo, 12763 boolean writeSettings) { 12764 if (packageName == null) { 12765 Slog.w(TAG, "Attempt to delete null packageName."); 12766 return false; 12767 } 12768 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12769 PackageSetting ps; 12770 boolean dataOnly = false; 12771 int removeUser = -1; 12772 int appId = -1; 12773 synchronized (mPackages) { 12774 ps = mSettings.mPackages.get(packageName); 12775 if (ps == null) { 12776 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12777 return false; 12778 } 12779 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12780 && user.getIdentifier() != UserHandle.USER_ALL) { 12781 // The caller is asking that the package only be deleted for a single 12782 // user. To do this, we just mark its uninstalled state and delete 12783 // its data. If this is a system app, we only allow this to happen if 12784 // they have set the special DELETE_SYSTEM_APP which requests different 12785 // semantics than normal for uninstalling system apps. 12786 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12787 ps.setUserState(user.getIdentifier(), 12788 COMPONENT_ENABLED_STATE_DEFAULT, 12789 false, //installed 12790 true, //stopped 12791 true, //notLaunched 12792 false, //hidden 12793 null, null, null, 12794 false, // blockUninstall 12795 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12796 if (!isSystemApp(ps)) { 12797 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12798 // Other user still have this package installed, so all 12799 // we need to do is clear this user's data and save that 12800 // it is uninstalled. 12801 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12802 removeUser = user.getIdentifier(); 12803 appId = ps.appId; 12804 scheduleWritePackageRestrictionsLocked(removeUser); 12805 } else { 12806 // We need to set it back to 'installed' so the uninstall 12807 // broadcasts will be sent correctly. 12808 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12809 ps.setInstalled(true, user.getIdentifier()); 12810 } 12811 } else { 12812 // This is a system app, so we assume that the 12813 // other users still have this package installed, so all 12814 // we need to do is clear this user's data and save that 12815 // it is uninstalled. 12816 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12817 removeUser = user.getIdentifier(); 12818 appId = ps.appId; 12819 scheduleWritePackageRestrictionsLocked(removeUser); 12820 } 12821 } 12822 } 12823 12824 if (removeUser >= 0) { 12825 // From above, we determined that we are deleting this only 12826 // for a single user. Continue the work here. 12827 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12828 if (outInfo != null) { 12829 outInfo.removedPackage = packageName; 12830 outInfo.removedAppId = appId; 12831 outInfo.removedUsers = new int[] {removeUser}; 12832 } 12833 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12834 removeKeystoreDataIfNeeded(removeUser, appId); 12835 schedulePackageCleaning(packageName, removeUser, false); 12836 synchronized (mPackages) { 12837 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12838 scheduleWritePackageRestrictionsLocked(removeUser); 12839 } 12840 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12841 removeUser); 12842 } 12843 return true; 12844 } 12845 12846 if (dataOnly) { 12847 // Delete application data first 12848 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12849 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12850 return true; 12851 } 12852 12853 boolean ret = false; 12854 if (isSystemApp(ps)) { 12855 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12856 // When an updated system application is deleted we delete the existing resources as well and 12857 // fall back to existing code in system partition 12858 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12859 flags, outInfo, writeSettings); 12860 } else { 12861 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12862 // Kill application pre-emptively especially for apps on sd. 12863 killApplication(packageName, ps.appId, "uninstall pkg"); 12864 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12865 allUserHandles, perUserInstalled, 12866 outInfo, writeSettings); 12867 } 12868 12869 return ret; 12870 } 12871 12872 private final class ClearStorageConnection implements ServiceConnection { 12873 IMediaContainerService mContainerService; 12874 12875 @Override 12876 public void onServiceConnected(ComponentName name, IBinder service) { 12877 synchronized (this) { 12878 mContainerService = IMediaContainerService.Stub.asInterface(service); 12879 notifyAll(); 12880 } 12881 } 12882 12883 @Override 12884 public void onServiceDisconnected(ComponentName name) { 12885 } 12886 } 12887 12888 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12889 final boolean mounted; 12890 if (Environment.isExternalStorageEmulated()) { 12891 mounted = true; 12892 } else { 12893 final String status = Environment.getExternalStorageState(); 12894 12895 mounted = status.equals(Environment.MEDIA_MOUNTED) 12896 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12897 } 12898 12899 if (!mounted) { 12900 return; 12901 } 12902 12903 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12904 int[] users; 12905 if (userId == UserHandle.USER_ALL) { 12906 users = sUserManager.getUserIds(); 12907 } else { 12908 users = new int[] { userId }; 12909 } 12910 final ClearStorageConnection conn = new ClearStorageConnection(); 12911 if (mContext.bindServiceAsUser( 12912 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12913 try { 12914 for (int curUser : users) { 12915 long timeout = SystemClock.uptimeMillis() + 5000; 12916 synchronized (conn) { 12917 long now = SystemClock.uptimeMillis(); 12918 while (conn.mContainerService == null && now < timeout) { 12919 try { 12920 conn.wait(timeout - now); 12921 } catch (InterruptedException e) { 12922 } 12923 } 12924 } 12925 if (conn.mContainerService == null) { 12926 return; 12927 } 12928 12929 final UserEnvironment userEnv = new UserEnvironment(curUser); 12930 clearDirectory(conn.mContainerService, 12931 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12932 if (allData) { 12933 clearDirectory(conn.mContainerService, 12934 userEnv.buildExternalStorageAppDataDirs(packageName)); 12935 clearDirectory(conn.mContainerService, 12936 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12937 } 12938 } 12939 } finally { 12940 mContext.unbindService(conn); 12941 } 12942 } 12943 } 12944 12945 @Override 12946 public void clearApplicationUserData(final String packageName, 12947 final IPackageDataObserver observer, final int userId) { 12948 mContext.enforceCallingOrSelfPermission( 12949 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12950 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12951 // Queue up an async operation since the package deletion may take a little while. 12952 mHandler.post(new Runnable() { 12953 public void run() { 12954 mHandler.removeCallbacks(this); 12955 final boolean succeeded; 12956 synchronized (mInstallLock) { 12957 succeeded = clearApplicationUserDataLI(packageName, userId); 12958 } 12959 clearExternalStorageDataSync(packageName, userId, true); 12960 if (succeeded) { 12961 // invoke DeviceStorageMonitor's update method to clear any notifications 12962 DeviceStorageMonitorInternal 12963 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12964 if (dsm != null) { 12965 dsm.checkMemory(); 12966 } 12967 } 12968 if(observer != null) { 12969 try { 12970 observer.onRemoveCompleted(packageName, succeeded); 12971 } catch (RemoteException e) { 12972 Log.i(TAG, "Observer no longer exists."); 12973 } 12974 } //end if observer 12975 } //end run 12976 }); 12977 } 12978 12979 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12980 if (packageName == null) { 12981 Slog.w(TAG, "Attempt to delete null packageName."); 12982 return false; 12983 } 12984 12985 // Try finding details about the requested package 12986 PackageParser.Package pkg; 12987 synchronized (mPackages) { 12988 pkg = mPackages.get(packageName); 12989 if (pkg == null) { 12990 final PackageSetting ps = mSettings.mPackages.get(packageName); 12991 if (ps != null) { 12992 pkg = ps.pkg; 12993 } 12994 } 12995 12996 if (pkg == null) { 12997 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12998 return false; 12999 } 13000 13001 PackageSetting ps = (PackageSetting) pkg.mExtras; 13002 PermissionsState permissionsState = ps.getPermissionsState(); 13003 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 13004 } 13005 13006 // Always delete data directories for package, even if we found no other 13007 // record of app. This helps users recover from UID mismatches without 13008 // resorting to a full data wipe. 13009 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13010 if (retCode < 0) { 13011 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13012 return false; 13013 } 13014 13015 final int appId = pkg.applicationInfo.uid; 13016 removeKeystoreDataIfNeeded(userId, appId); 13017 13018 // Create a native library symlink only if we have native libraries 13019 // and if the native libraries are 32 bit libraries. We do not provide 13020 // this symlink for 64 bit libraries. 13021 if (pkg.applicationInfo.primaryCpuAbi != null && 13022 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13023 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13024 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13025 nativeLibPath, userId) < 0) { 13026 Slog.w(TAG, "Failed linking native library dir"); 13027 return false; 13028 } 13029 } 13030 13031 return true; 13032 } 13033 13034 13035 /** 13036 * Revokes granted runtime permissions and clears resettable flags 13037 * which are flags that can be set by a user interaction. 13038 * 13039 * @param permissionsState The permission state to reset. 13040 * @param userId The device user for which to do a reset. 13041 */ 13042 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 13043 PermissionsState permissionsState, int userId) { 13044 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 13045 | PackageManager.FLAG_PERMISSION_USER_FIXED 13046 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13047 13048 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 13049 } 13050 13051 /** 13052 * Revokes granted runtime permissions and clears all flags. 13053 * 13054 * @param permissionsState The permission state to reset. 13055 * @param userId The device user for which to do a reset. 13056 */ 13057 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 13058 PermissionsState permissionsState, int userId) { 13059 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 13060 PackageManager.MASK_PERMISSION_FLAGS); 13061 } 13062 13063 /** 13064 * Revokes granted runtime permissions and clears certain flags. 13065 * 13066 * @param permissionsState The permission state to reset. 13067 * @param userId The device user for which to do a reset. 13068 * @param flags The flags that is going to be reset. 13069 */ 13070 private void revokeRuntimePermissionsAndClearFlagsLocked( 13071 PermissionsState permissionsState, final int userId, int flags) { 13072 boolean needsWrite = false; 13073 13074 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 13075 BasePermission bp = mSettings.mPermissions.get(state.getName()); 13076 if (bp != null) { 13077 permissionsState.revokeRuntimePermission(bp, userId); 13078 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 13079 needsWrite = true; 13080 } 13081 } 13082 13083 // Ensure default permissions are never cleared. 13084 mHandler.post(new Runnable() { 13085 @Override 13086 public void run() { 13087 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13088 } 13089 }); 13090 13091 if (needsWrite) { 13092 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13093 } 13094 } 13095 13096 /** 13097 * Remove entries from the keystore daemon. Will only remove it if the 13098 * {@code appId} is valid. 13099 */ 13100 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13101 if (appId < 0) { 13102 return; 13103 } 13104 13105 final KeyStore keyStore = KeyStore.getInstance(); 13106 if (keyStore != null) { 13107 if (userId == UserHandle.USER_ALL) { 13108 for (final int individual : sUserManager.getUserIds()) { 13109 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13110 } 13111 } else { 13112 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13113 } 13114 } else { 13115 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13116 } 13117 } 13118 13119 @Override 13120 public void deleteApplicationCacheFiles(final String packageName, 13121 final IPackageDataObserver observer) { 13122 mContext.enforceCallingOrSelfPermission( 13123 android.Manifest.permission.DELETE_CACHE_FILES, null); 13124 // Queue up an async operation since the package deletion may take a little while. 13125 final int userId = UserHandle.getCallingUserId(); 13126 mHandler.post(new Runnable() { 13127 public void run() { 13128 mHandler.removeCallbacks(this); 13129 final boolean succeded; 13130 synchronized (mInstallLock) { 13131 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13132 } 13133 clearExternalStorageDataSync(packageName, userId, false); 13134 if (observer != null) { 13135 try { 13136 observer.onRemoveCompleted(packageName, succeded); 13137 } catch (RemoteException e) { 13138 Log.i(TAG, "Observer no longer exists."); 13139 } 13140 } //end if observer 13141 } //end run 13142 }); 13143 } 13144 13145 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13146 if (packageName == null) { 13147 Slog.w(TAG, "Attempt to delete null packageName."); 13148 return false; 13149 } 13150 PackageParser.Package p; 13151 synchronized (mPackages) { 13152 p = mPackages.get(packageName); 13153 } 13154 if (p == null) { 13155 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13156 return false; 13157 } 13158 final ApplicationInfo applicationInfo = p.applicationInfo; 13159 if (applicationInfo == null) { 13160 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13161 return false; 13162 } 13163 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13164 if (retCode < 0) { 13165 Slog.w(TAG, "Couldn't remove cache files for package: " 13166 + packageName + " u" + userId); 13167 return false; 13168 } 13169 return true; 13170 } 13171 13172 @Override 13173 public void getPackageSizeInfo(final String packageName, int userHandle, 13174 final IPackageStatsObserver observer) { 13175 mContext.enforceCallingOrSelfPermission( 13176 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13177 if (packageName == null) { 13178 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13179 } 13180 13181 PackageStats stats = new PackageStats(packageName, userHandle); 13182 13183 /* 13184 * Queue up an async operation since the package measurement may take a 13185 * little while. 13186 */ 13187 Message msg = mHandler.obtainMessage(INIT_COPY); 13188 msg.obj = new MeasureParams(stats, observer); 13189 mHandler.sendMessage(msg); 13190 } 13191 13192 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13193 PackageStats pStats) { 13194 if (packageName == null) { 13195 Slog.w(TAG, "Attempt to get size of null packageName."); 13196 return false; 13197 } 13198 PackageParser.Package p; 13199 boolean dataOnly = false; 13200 String libDirRoot = null; 13201 String asecPath = null; 13202 PackageSetting ps = null; 13203 synchronized (mPackages) { 13204 p = mPackages.get(packageName); 13205 ps = mSettings.mPackages.get(packageName); 13206 if(p == null) { 13207 dataOnly = true; 13208 if((ps == null) || (ps.pkg == null)) { 13209 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13210 return false; 13211 } 13212 p = ps.pkg; 13213 } 13214 if (ps != null) { 13215 libDirRoot = ps.legacyNativeLibraryPathString; 13216 } 13217 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13218 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13219 if (secureContainerId != null) { 13220 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13221 } 13222 } 13223 } 13224 String publicSrcDir = null; 13225 if(!dataOnly) { 13226 final ApplicationInfo applicationInfo = p.applicationInfo; 13227 if (applicationInfo == null) { 13228 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13229 return false; 13230 } 13231 if (p.isForwardLocked()) { 13232 publicSrcDir = applicationInfo.getBaseResourcePath(); 13233 } 13234 } 13235 // TODO: extend to measure size of split APKs 13236 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13237 // not just the first level. 13238 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13239 // just the primary. 13240 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13241 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13242 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13243 if (res < 0) { 13244 return false; 13245 } 13246 13247 // Fix-up for forward-locked applications in ASEC containers. 13248 if (!isExternal(p)) { 13249 pStats.codeSize += pStats.externalCodeSize; 13250 pStats.externalCodeSize = 0L; 13251 } 13252 13253 return true; 13254 } 13255 13256 13257 @Override 13258 public void addPackageToPreferred(String packageName) { 13259 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13260 } 13261 13262 @Override 13263 public void removePackageFromPreferred(String packageName) { 13264 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13265 } 13266 13267 @Override 13268 public List<PackageInfo> getPreferredPackages(int flags) { 13269 return new ArrayList<PackageInfo>(); 13270 } 13271 13272 private int getUidTargetSdkVersionLockedLPr(int uid) { 13273 Object obj = mSettings.getUserIdLPr(uid); 13274 if (obj instanceof SharedUserSetting) { 13275 final SharedUserSetting sus = (SharedUserSetting) obj; 13276 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13277 final Iterator<PackageSetting> it = sus.packages.iterator(); 13278 while (it.hasNext()) { 13279 final PackageSetting ps = it.next(); 13280 if (ps.pkg != null) { 13281 int v = ps.pkg.applicationInfo.targetSdkVersion; 13282 if (v < vers) vers = v; 13283 } 13284 } 13285 return vers; 13286 } else if (obj instanceof PackageSetting) { 13287 final PackageSetting ps = (PackageSetting) obj; 13288 if (ps.pkg != null) { 13289 return ps.pkg.applicationInfo.targetSdkVersion; 13290 } 13291 } 13292 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13293 } 13294 13295 @Override 13296 public void addPreferredActivity(IntentFilter filter, int match, 13297 ComponentName[] set, ComponentName activity, int userId) { 13298 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13299 "Adding preferred"); 13300 } 13301 13302 private void addPreferredActivityInternal(IntentFilter filter, int match, 13303 ComponentName[] set, ComponentName activity, boolean always, int userId, 13304 String opname) { 13305 // writer 13306 int callingUid = Binder.getCallingUid(); 13307 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13308 if (filter.countActions() == 0) { 13309 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13310 return; 13311 } 13312 synchronized (mPackages) { 13313 if (mContext.checkCallingOrSelfPermission( 13314 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13315 != PackageManager.PERMISSION_GRANTED) { 13316 if (getUidTargetSdkVersionLockedLPr(callingUid) 13317 < Build.VERSION_CODES.FROYO) { 13318 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13319 + callingUid); 13320 return; 13321 } 13322 mContext.enforceCallingOrSelfPermission( 13323 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13324 } 13325 13326 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13327 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13328 + userId + ":"); 13329 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13330 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13331 scheduleWritePackageRestrictionsLocked(userId); 13332 } 13333 } 13334 13335 @Override 13336 public void replacePreferredActivity(IntentFilter filter, int match, 13337 ComponentName[] set, ComponentName activity, int userId) { 13338 if (filter.countActions() != 1) { 13339 throw new IllegalArgumentException( 13340 "replacePreferredActivity expects filter to have only 1 action."); 13341 } 13342 if (filter.countDataAuthorities() != 0 13343 || filter.countDataPaths() != 0 13344 || filter.countDataSchemes() > 1 13345 || filter.countDataTypes() != 0) { 13346 throw new IllegalArgumentException( 13347 "replacePreferredActivity expects filter to have no data authorities, " + 13348 "paths, or types; and at most one scheme."); 13349 } 13350 13351 final int callingUid = Binder.getCallingUid(); 13352 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13353 synchronized (mPackages) { 13354 if (mContext.checkCallingOrSelfPermission( 13355 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13356 != PackageManager.PERMISSION_GRANTED) { 13357 if (getUidTargetSdkVersionLockedLPr(callingUid) 13358 < Build.VERSION_CODES.FROYO) { 13359 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13360 + Binder.getCallingUid()); 13361 return; 13362 } 13363 mContext.enforceCallingOrSelfPermission( 13364 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13365 } 13366 13367 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13368 if (pir != null) { 13369 // Get all of the existing entries that exactly match this filter. 13370 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13371 if (existing != null && existing.size() == 1) { 13372 PreferredActivity cur = existing.get(0); 13373 if (DEBUG_PREFERRED) { 13374 Slog.i(TAG, "Checking replace of preferred:"); 13375 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13376 if (!cur.mPref.mAlways) { 13377 Slog.i(TAG, " -- CUR; not mAlways!"); 13378 } else { 13379 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13380 Slog.i(TAG, " -- CUR: mSet=" 13381 + Arrays.toString(cur.mPref.mSetComponents)); 13382 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13383 Slog.i(TAG, " -- NEW: mMatch=" 13384 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13385 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13386 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13387 } 13388 } 13389 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13390 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13391 && cur.mPref.sameSet(set)) { 13392 // Setting the preferred activity to what it happens to be already 13393 if (DEBUG_PREFERRED) { 13394 Slog.i(TAG, "Replacing with same preferred activity " 13395 + cur.mPref.mShortComponent + " for user " 13396 + userId + ":"); 13397 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13398 } 13399 return; 13400 } 13401 } 13402 13403 if (existing != null) { 13404 if (DEBUG_PREFERRED) { 13405 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13406 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13407 } 13408 for (int i = 0; i < existing.size(); i++) { 13409 PreferredActivity pa = existing.get(i); 13410 if (DEBUG_PREFERRED) { 13411 Slog.i(TAG, "Removing existing preferred activity " 13412 + pa.mPref.mComponent + ":"); 13413 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13414 } 13415 pir.removeFilter(pa); 13416 } 13417 } 13418 } 13419 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13420 "Replacing preferred"); 13421 } 13422 } 13423 13424 @Override 13425 public void clearPackagePreferredActivities(String packageName) { 13426 final int uid = Binder.getCallingUid(); 13427 // writer 13428 synchronized (mPackages) { 13429 PackageParser.Package pkg = mPackages.get(packageName); 13430 if (pkg == null || pkg.applicationInfo.uid != uid) { 13431 if (mContext.checkCallingOrSelfPermission( 13432 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13433 != PackageManager.PERMISSION_GRANTED) { 13434 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13435 < Build.VERSION_CODES.FROYO) { 13436 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13437 + Binder.getCallingUid()); 13438 return; 13439 } 13440 mContext.enforceCallingOrSelfPermission( 13441 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13442 } 13443 } 13444 13445 int user = UserHandle.getCallingUserId(); 13446 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13447 scheduleWritePackageRestrictionsLocked(user); 13448 } 13449 } 13450 } 13451 13452 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13453 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13454 ArrayList<PreferredActivity> removed = null; 13455 boolean changed = false; 13456 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13457 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13458 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13459 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13460 continue; 13461 } 13462 Iterator<PreferredActivity> it = pir.filterIterator(); 13463 while (it.hasNext()) { 13464 PreferredActivity pa = it.next(); 13465 // Mark entry for removal only if it matches the package name 13466 // and the entry is of type "always". 13467 if (packageName == null || 13468 (pa.mPref.mComponent.getPackageName().equals(packageName) 13469 && pa.mPref.mAlways)) { 13470 if (removed == null) { 13471 removed = new ArrayList<PreferredActivity>(); 13472 } 13473 removed.add(pa); 13474 } 13475 } 13476 if (removed != null) { 13477 for (int j=0; j<removed.size(); j++) { 13478 PreferredActivity pa = removed.get(j); 13479 pir.removeFilter(pa); 13480 } 13481 changed = true; 13482 } 13483 } 13484 return changed; 13485 } 13486 13487 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13488 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13489 if (userId == UserHandle.USER_ALL) { 13490 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13491 sUserManager.getUserIds())) { 13492 for (int oneUserId : sUserManager.getUserIds()) { 13493 scheduleWritePackageRestrictionsLocked(oneUserId); 13494 } 13495 } 13496 } else { 13497 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13498 scheduleWritePackageRestrictionsLocked(userId); 13499 } 13500 } 13501 } 13502 13503 13504 void clearDefaultBrowserIfNeeded(String packageName) { 13505 for (int oneUserId : sUserManager.getUserIds()) { 13506 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13507 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13508 if (packageName.equals(defaultBrowserPackageName)) { 13509 setDefaultBrowserPackageName(null, oneUserId); 13510 } 13511 } 13512 } 13513 13514 @Override 13515 public void resetPreferredActivities(int userId) { 13516 mContext.enforceCallingOrSelfPermission( 13517 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13518 // writer 13519 synchronized (mPackages) { 13520 clearPackagePreferredActivitiesLPw(null, userId); 13521 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13522 applyFactoryDefaultBrowserLPw(userId); 13523 13524 scheduleWritePackageRestrictionsLocked(userId); 13525 } 13526 } 13527 13528 @Override 13529 public int getPreferredActivities(List<IntentFilter> outFilters, 13530 List<ComponentName> outActivities, String packageName) { 13531 13532 int num = 0; 13533 final int userId = UserHandle.getCallingUserId(); 13534 // reader 13535 synchronized (mPackages) { 13536 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13537 if (pir != null) { 13538 final Iterator<PreferredActivity> it = pir.filterIterator(); 13539 while (it.hasNext()) { 13540 final PreferredActivity pa = it.next(); 13541 if (packageName == null 13542 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13543 && pa.mPref.mAlways)) { 13544 if (outFilters != null) { 13545 outFilters.add(new IntentFilter(pa)); 13546 } 13547 if (outActivities != null) { 13548 outActivities.add(pa.mPref.mComponent); 13549 } 13550 } 13551 } 13552 } 13553 } 13554 13555 return num; 13556 } 13557 13558 @Override 13559 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13560 int userId) { 13561 int callingUid = Binder.getCallingUid(); 13562 if (callingUid != Process.SYSTEM_UID) { 13563 throw new SecurityException( 13564 "addPersistentPreferredActivity can only be run by the system"); 13565 } 13566 if (filter.countActions() == 0) { 13567 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13568 return; 13569 } 13570 synchronized (mPackages) { 13571 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13572 " :"); 13573 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13574 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13575 new PersistentPreferredActivity(filter, activity)); 13576 scheduleWritePackageRestrictionsLocked(userId); 13577 } 13578 } 13579 13580 @Override 13581 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13582 int callingUid = Binder.getCallingUid(); 13583 if (callingUid != Process.SYSTEM_UID) { 13584 throw new SecurityException( 13585 "clearPackagePersistentPreferredActivities can only be run by the system"); 13586 } 13587 ArrayList<PersistentPreferredActivity> removed = null; 13588 boolean changed = false; 13589 synchronized (mPackages) { 13590 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13591 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13592 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13593 .valueAt(i); 13594 if (userId != thisUserId) { 13595 continue; 13596 } 13597 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13598 while (it.hasNext()) { 13599 PersistentPreferredActivity ppa = it.next(); 13600 // Mark entry for removal only if it matches the package name. 13601 if (ppa.mComponent.getPackageName().equals(packageName)) { 13602 if (removed == null) { 13603 removed = new ArrayList<PersistentPreferredActivity>(); 13604 } 13605 removed.add(ppa); 13606 } 13607 } 13608 if (removed != null) { 13609 for (int j=0; j<removed.size(); j++) { 13610 PersistentPreferredActivity ppa = removed.get(j); 13611 ppir.removeFilter(ppa); 13612 } 13613 changed = true; 13614 } 13615 } 13616 13617 if (changed) { 13618 scheduleWritePackageRestrictionsLocked(userId); 13619 } 13620 } 13621 } 13622 13623 /** 13624 * Common machinery for picking apart a restored XML blob and passing 13625 * it to a caller-supplied functor to be applied to the running system. 13626 */ 13627 private void restoreFromXml(XmlPullParser parser, int userId, 13628 String expectedStartTag, BlobXmlRestorer functor) 13629 throws IOException, XmlPullParserException { 13630 int type; 13631 while ((type = parser.next()) != XmlPullParser.START_TAG 13632 && type != XmlPullParser.END_DOCUMENT) { 13633 } 13634 if (type != XmlPullParser.START_TAG) { 13635 // oops didn't find a start tag?! 13636 if (DEBUG_BACKUP) { 13637 Slog.e(TAG, "Didn't find start tag during restore"); 13638 } 13639 return; 13640 } 13641 13642 // this is supposed to be TAG_PREFERRED_BACKUP 13643 if (!expectedStartTag.equals(parser.getName())) { 13644 if (DEBUG_BACKUP) { 13645 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13646 } 13647 return; 13648 } 13649 13650 // skip interfering stuff, then we're aligned with the backing implementation 13651 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13652 functor.apply(parser, userId); 13653 } 13654 13655 private interface BlobXmlRestorer { 13656 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13657 } 13658 13659 /** 13660 * Non-Binder method, support for the backup/restore mechanism: write the 13661 * full set of preferred activities in its canonical XML format. Returns the 13662 * XML output as a byte array, or null if there is none. 13663 */ 13664 @Override 13665 public byte[] getPreferredActivityBackup(int userId) { 13666 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13667 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13668 } 13669 13670 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13671 try { 13672 final XmlSerializer serializer = new FastXmlSerializer(); 13673 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13674 serializer.startDocument(null, true); 13675 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13676 13677 synchronized (mPackages) { 13678 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13679 } 13680 13681 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13682 serializer.endDocument(); 13683 serializer.flush(); 13684 } catch (Exception e) { 13685 if (DEBUG_BACKUP) { 13686 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13687 } 13688 return null; 13689 } 13690 13691 return dataStream.toByteArray(); 13692 } 13693 13694 @Override 13695 public void restorePreferredActivities(byte[] backup, int userId) { 13696 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13697 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13698 } 13699 13700 try { 13701 final XmlPullParser parser = Xml.newPullParser(); 13702 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13703 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13704 new BlobXmlRestorer() { 13705 @Override 13706 public void apply(XmlPullParser parser, int userId) 13707 throws XmlPullParserException, IOException { 13708 synchronized (mPackages) { 13709 mSettings.readPreferredActivitiesLPw(parser, userId); 13710 } 13711 } 13712 } ); 13713 } catch (Exception e) { 13714 if (DEBUG_BACKUP) { 13715 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13716 } 13717 } 13718 } 13719 13720 /** 13721 * Non-Binder method, support for the backup/restore mechanism: write the 13722 * default browser (etc) settings in its canonical XML format. Returns the default 13723 * browser XML representation as a byte array, or null if there is none. 13724 */ 13725 @Override 13726 public byte[] getDefaultAppsBackup(int userId) { 13727 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13728 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13729 } 13730 13731 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13732 try { 13733 final XmlSerializer serializer = new FastXmlSerializer(); 13734 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13735 serializer.startDocument(null, true); 13736 serializer.startTag(null, TAG_DEFAULT_APPS); 13737 13738 synchronized (mPackages) { 13739 mSettings.writeDefaultAppsLPr(serializer, userId); 13740 } 13741 13742 serializer.endTag(null, TAG_DEFAULT_APPS); 13743 serializer.endDocument(); 13744 serializer.flush(); 13745 } catch (Exception e) { 13746 if (DEBUG_BACKUP) { 13747 Slog.e(TAG, "Unable to write default apps for backup", e); 13748 } 13749 return null; 13750 } 13751 13752 return dataStream.toByteArray(); 13753 } 13754 13755 @Override 13756 public void restoreDefaultApps(byte[] backup, int userId) { 13757 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13758 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13759 } 13760 13761 try { 13762 final XmlPullParser parser = Xml.newPullParser(); 13763 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13764 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13765 new BlobXmlRestorer() { 13766 @Override 13767 public void apply(XmlPullParser parser, int userId) 13768 throws XmlPullParserException, IOException { 13769 synchronized (mPackages) { 13770 mSettings.readDefaultAppsLPw(parser, userId); 13771 } 13772 } 13773 } ); 13774 } catch (Exception e) { 13775 if (DEBUG_BACKUP) { 13776 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13777 } 13778 } 13779 } 13780 13781 @Override 13782 public byte[] getIntentFilterVerificationBackup(int userId) { 13783 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13784 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13785 } 13786 13787 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13788 try { 13789 final XmlSerializer serializer = new FastXmlSerializer(); 13790 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13791 serializer.startDocument(null, true); 13792 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13793 13794 synchronized (mPackages) { 13795 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13796 } 13797 13798 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13799 serializer.endDocument(); 13800 serializer.flush(); 13801 } catch (Exception e) { 13802 if (DEBUG_BACKUP) { 13803 Slog.e(TAG, "Unable to write default apps for backup", e); 13804 } 13805 return null; 13806 } 13807 13808 return dataStream.toByteArray(); 13809 } 13810 13811 @Override 13812 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13813 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13814 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13815 } 13816 13817 try { 13818 final XmlPullParser parser = Xml.newPullParser(); 13819 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13820 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13821 new BlobXmlRestorer() { 13822 @Override 13823 public void apply(XmlPullParser parser, int userId) 13824 throws XmlPullParserException, IOException { 13825 synchronized (mPackages) { 13826 mSettings.readAllDomainVerificationsLPr(parser, userId); 13827 mSettings.writeLPr(); 13828 } 13829 } 13830 } ); 13831 } catch (Exception e) { 13832 if (DEBUG_BACKUP) { 13833 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13834 } 13835 } 13836 } 13837 13838 @Override 13839 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13840 int sourceUserId, int targetUserId, int flags) { 13841 mContext.enforceCallingOrSelfPermission( 13842 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13843 int callingUid = Binder.getCallingUid(); 13844 enforceOwnerRights(ownerPackage, callingUid); 13845 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13846 if (intentFilter.countActions() == 0) { 13847 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13848 return; 13849 } 13850 synchronized (mPackages) { 13851 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13852 ownerPackage, targetUserId, flags); 13853 CrossProfileIntentResolver resolver = 13854 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13855 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13856 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13857 if (existing != null) { 13858 int size = existing.size(); 13859 for (int i = 0; i < size; i++) { 13860 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13861 return; 13862 } 13863 } 13864 } 13865 resolver.addFilter(newFilter); 13866 scheduleWritePackageRestrictionsLocked(sourceUserId); 13867 } 13868 } 13869 13870 @Override 13871 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13872 mContext.enforceCallingOrSelfPermission( 13873 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13874 int callingUid = Binder.getCallingUid(); 13875 enforceOwnerRights(ownerPackage, callingUid); 13876 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13877 synchronized (mPackages) { 13878 CrossProfileIntentResolver resolver = 13879 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13880 ArraySet<CrossProfileIntentFilter> set = 13881 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13882 for (CrossProfileIntentFilter filter : set) { 13883 if (filter.getOwnerPackage().equals(ownerPackage)) { 13884 resolver.removeFilter(filter); 13885 } 13886 } 13887 scheduleWritePackageRestrictionsLocked(sourceUserId); 13888 } 13889 } 13890 13891 // Enforcing that callingUid is owning pkg on userId 13892 private void enforceOwnerRights(String pkg, int callingUid) { 13893 // The system owns everything. 13894 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13895 return; 13896 } 13897 int callingUserId = UserHandle.getUserId(callingUid); 13898 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13899 if (pi == null) { 13900 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13901 + callingUserId); 13902 } 13903 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13904 throw new SecurityException("Calling uid " + callingUid 13905 + " does not own package " + pkg); 13906 } 13907 } 13908 13909 @Override 13910 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13911 Intent intent = new Intent(Intent.ACTION_MAIN); 13912 intent.addCategory(Intent.CATEGORY_HOME); 13913 13914 final int callingUserId = UserHandle.getCallingUserId(); 13915 List<ResolveInfo> list = queryIntentActivities(intent, null, 13916 PackageManager.GET_META_DATA, callingUserId); 13917 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13918 true, false, false, callingUserId); 13919 13920 allHomeCandidates.clear(); 13921 if (list != null) { 13922 for (ResolveInfo ri : list) { 13923 allHomeCandidates.add(ri); 13924 } 13925 } 13926 return (preferred == null || preferred.activityInfo == null) 13927 ? null 13928 : new ComponentName(preferred.activityInfo.packageName, 13929 preferred.activityInfo.name); 13930 } 13931 13932 @Override 13933 public void setApplicationEnabledSetting(String appPackageName, 13934 int newState, int flags, int userId, String callingPackage) { 13935 if (!sUserManager.exists(userId)) return; 13936 if (callingPackage == null) { 13937 callingPackage = Integer.toString(Binder.getCallingUid()); 13938 } 13939 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13940 } 13941 13942 @Override 13943 public void setComponentEnabledSetting(ComponentName componentName, 13944 int newState, int flags, int userId) { 13945 if (!sUserManager.exists(userId)) return; 13946 setEnabledSetting(componentName.getPackageName(), 13947 componentName.getClassName(), newState, flags, userId, null); 13948 } 13949 13950 private void setEnabledSetting(final String packageName, String className, int newState, 13951 final int flags, int userId, String callingPackage) { 13952 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13953 || newState == COMPONENT_ENABLED_STATE_ENABLED 13954 || newState == COMPONENT_ENABLED_STATE_DISABLED 13955 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13956 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13957 throw new IllegalArgumentException("Invalid new component state: " 13958 + newState); 13959 } 13960 PackageSetting pkgSetting; 13961 final int uid = Binder.getCallingUid(); 13962 final int permission = mContext.checkCallingOrSelfPermission( 13963 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13964 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13965 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13966 boolean sendNow = false; 13967 boolean isApp = (className == null); 13968 String componentName = isApp ? packageName : className; 13969 int packageUid = -1; 13970 ArrayList<String> components; 13971 13972 // writer 13973 synchronized (mPackages) { 13974 pkgSetting = mSettings.mPackages.get(packageName); 13975 if (pkgSetting == null) { 13976 if (className == null) { 13977 throw new IllegalArgumentException( 13978 "Unknown package: " + packageName); 13979 } 13980 throw new IllegalArgumentException( 13981 "Unknown component: " + packageName 13982 + "/" + className); 13983 } 13984 // Allow root and verify that userId is not being specified by a different user 13985 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13986 throw new SecurityException( 13987 "Permission Denial: attempt to change component state from pid=" 13988 + Binder.getCallingPid() 13989 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13990 } 13991 if (className == null) { 13992 // We're dealing with an application/package level state change 13993 if (pkgSetting.getEnabled(userId) == newState) { 13994 // Nothing to do 13995 return; 13996 } 13997 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13998 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13999 // Don't care about who enables an app. 14000 callingPackage = null; 14001 } 14002 pkgSetting.setEnabled(newState, userId, callingPackage); 14003 // pkgSetting.pkg.mSetEnabled = newState; 14004 } else { 14005 // We're dealing with a component level state change 14006 // First, verify that this is a valid class name. 14007 PackageParser.Package pkg = pkgSetting.pkg; 14008 if (pkg == null || !pkg.hasComponentClassName(className)) { 14009 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14010 throw new IllegalArgumentException("Component class " + className 14011 + " does not exist in " + packageName); 14012 } else { 14013 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14014 + className + " does not exist in " + packageName); 14015 } 14016 } 14017 switch (newState) { 14018 case COMPONENT_ENABLED_STATE_ENABLED: 14019 if (!pkgSetting.enableComponentLPw(className, userId)) { 14020 return; 14021 } 14022 break; 14023 case COMPONENT_ENABLED_STATE_DISABLED: 14024 if (!pkgSetting.disableComponentLPw(className, userId)) { 14025 return; 14026 } 14027 break; 14028 case COMPONENT_ENABLED_STATE_DEFAULT: 14029 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14030 return; 14031 } 14032 break; 14033 default: 14034 Slog.e(TAG, "Invalid new component state: " + newState); 14035 return; 14036 } 14037 } 14038 scheduleWritePackageRestrictionsLocked(userId); 14039 components = mPendingBroadcasts.get(userId, packageName); 14040 final boolean newPackage = components == null; 14041 if (newPackage) { 14042 components = new ArrayList<String>(); 14043 } 14044 if (!components.contains(componentName)) { 14045 components.add(componentName); 14046 } 14047 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14048 sendNow = true; 14049 // Purge entry from pending broadcast list if another one exists already 14050 // since we are sending one right away. 14051 mPendingBroadcasts.remove(userId, packageName); 14052 } else { 14053 if (newPackage) { 14054 mPendingBroadcasts.put(userId, packageName, components); 14055 } 14056 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14057 // Schedule a message 14058 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14059 } 14060 } 14061 } 14062 14063 long callingId = Binder.clearCallingIdentity(); 14064 try { 14065 if (sendNow) { 14066 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14067 sendPackageChangedBroadcast(packageName, 14068 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14069 } 14070 } finally { 14071 Binder.restoreCallingIdentity(callingId); 14072 } 14073 } 14074 14075 private void sendPackageChangedBroadcast(String packageName, 14076 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14077 if (DEBUG_INSTALL) 14078 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14079 + componentNames); 14080 Bundle extras = new Bundle(4); 14081 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14082 String nameList[] = new String[componentNames.size()]; 14083 componentNames.toArray(nameList); 14084 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14085 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14086 extras.putInt(Intent.EXTRA_UID, packageUid); 14087 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14088 new int[] {UserHandle.getUserId(packageUid)}); 14089 } 14090 14091 @Override 14092 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14093 if (!sUserManager.exists(userId)) return; 14094 final int uid = Binder.getCallingUid(); 14095 final int permission = mContext.checkCallingOrSelfPermission( 14096 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14097 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14098 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14099 // writer 14100 synchronized (mPackages) { 14101 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14102 allowedByPermission, uid, userId)) { 14103 scheduleWritePackageRestrictionsLocked(userId); 14104 } 14105 } 14106 } 14107 14108 @Override 14109 public String getInstallerPackageName(String packageName) { 14110 // reader 14111 synchronized (mPackages) { 14112 return mSettings.getInstallerPackageNameLPr(packageName); 14113 } 14114 } 14115 14116 @Override 14117 public int getApplicationEnabledSetting(String packageName, int userId) { 14118 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14119 int uid = Binder.getCallingUid(); 14120 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14121 // reader 14122 synchronized (mPackages) { 14123 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14124 } 14125 } 14126 14127 @Override 14128 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14129 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14130 int uid = Binder.getCallingUid(); 14131 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14132 // reader 14133 synchronized (mPackages) { 14134 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14135 } 14136 } 14137 14138 @Override 14139 public void enterSafeMode() { 14140 enforceSystemOrRoot("Only the system can request entering safe mode"); 14141 14142 if (!mSystemReady) { 14143 mSafeMode = true; 14144 } 14145 } 14146 14147 @Override 14148 public void systemReady() { 14149 mSystemReady = true; 14150 14151 // Read the compatibilty setting when the system is ready. 14152 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14153 mContext.getContentResolver(), 14154 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14155 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14156 if (DEBUG_SETTINGS) { 14157 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14158 } 14159 14160 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14161 14162 synchronized (mPackages) { 14163 // Verify that all of the preferred activity components actually 14164 // exist. It is possible for applications to be updated and at 14165 // that point remove a previously declared activity component that 14166 // had been set as a preferred activity. We try to clean this up 14167 // the next time we encounter that preferred activity, but it is 14168 // possible for the user flow to never be able to return to that 14169 // situation so here we do a sanity check to make sure we haven't 14170 // left any junk around. 14171 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14172 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14173 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14174 removed.clear(); 14175 for (PreferredActivity pa : pir.filterSet()) { 14176 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14177 removed.add(pa); 14178 } 14179 } 14180 if (removed.size() > 0) { 14181 for (int r=0; r<removed.size(); r++) { 14182 PreferredActivity pa = removed.get(r); 14183 Slog.w(TAG, "Removing dangling preferred activity: " 14184 + pa.mPref.mComponent); 14185 pir.removeFilter(pa); 14186 } 14187 mSettings.writePackageRestrictionsLPr( 14188 mSettings.mPreferredActivities.keyAt(i)); 14189 } 14190 } 14191 14192 for (int userId : UserManagerService.getInstance().getUserIds()) { 14193 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14194 grantPermissionsUserIds = ArrayUtils.appendInt( 14195 grantPermissionsUserIds, userId); 14196 } 14197 } 14198 } 14199 sUserManager.systemReady(); 14200 14201 // If we upgraded grant all default permissions before kicking off. 14202 for (int userId : grantPermissionsUserIds) { 14203 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14204 } 14205 14206 // Kick off any messages waiting for system ready 14207 if (mPostSystemReadyMessages != null) { 14208 for (Message msg : mPostSystemReadyMessages) { 14209 msg.sendToTarget(); 14210 } 14211 mPostSystemReadyMessages = null; 14212 } 14213 14214 // Watch for external volumes that come and go over time 14215 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14216 storage.registerListener(mStorageListener); 14217 14218 mInstallerService.systemReady(); 14219 mPackageDexOptimizer.systemReady(); 14220 } 14221 14222 @Override 14223 public boolean isSafeMode() { 14224 return mSafeMode; 14225 } 14226 14227 @Override 14228 public boolean hasSystemUidErrors() { 14229 return mHasSystemUidErrors; 14230 } 14231 14232 static String arrayToString(int[] array) { 14233 StringBuffer buf = new StringBuffer(128); 14234 buf.append('['); 14235 if (array != null) { 14236 for (int i=0; i<array.length; i++) { 14237 if (i > 0) buf.append(", "); 14238 buf.append(array[i]); 14239 } 14240 } 14241 buf.append(']'); 14242 return buf.toString(); 14243 } 14244 14245 static class DumpState { 14246 public static final int DUMP_LIBS = 1 << 0; 14247 public static final int DUMP_FEATURES = 1 << 1; 14248 public static final int DUMP_RESOLVERS = 1 << 2; 14249 public static final int DUMP_PERMISSIONS = 1 << 3; 14250 public static final int DUMP_PACKAGES = 1 << 4; 14251 public static final int DUMP_SHARED_USERS = 1 << 5; 14252 public static final int DUMP_MESSAGES = 1 << 6; 14253 public static final int DUMP_PROVIDERS = 1 << 7; 14254 public static final int DUMP_VERIFIERS = 1 << 8; 14255 public static final int DUMP_PREFERRED = 1 << 9; 14256 public static final int DUMP_PREFERRED_XML = 1 << 10; 14257 public static final int DUMP_KEYSETS = 1 << 11; 14258 public static final int DUMP_VERSION = 1 << 12; 14259 public static final int DUMP_INSTALLS = 1 << 13; 14260 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14261 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14262 14263 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14264 14265 private int mTypes; 14266 14267 private int mOptions; 14268 14269 private boolean mTitlePrinted; 14270 14271 private SharedUserSetting mSharedUser; 14272 14273 public boolean isDumping(int type) { 14274 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14275 return true; 14276 } 14277 14278 return (mTypes & type) != 0; 14279 } 14280 14281 public void setDump(int type) { 14282 mTypes |= type; 14283 } 14284 14285 public boolean isOptionEnabled(int option) { 14286 return (mOptions & option) != 0; 14287 } 14288 14289 public void setOptionEnabled(int option) { 14290 mOptions |= option; 14291 } 14292 14293 public boolean onTitlePrinted() { 14294 final boolean printed = mTitlePrinted; 14295 mTitlePrinted = true; 14296 return printed; 14297 } 14298 14299 public boolean getTitlePrinted() { 14300 return mTitlePrinted; 14301 } 14302 14303 public void setTitlePrinted(boolean enabled) { 14304 mTitlePrinted = enabled; 14305 } 14306 14307 public SharedUserSetting getSharedUser() { 14308 return mSharedUser; 14309 } 14310 14311 public void setSharedUser(SharedUserSetting user) { 14312 mSharedUser = user; 14313 } 14314 } 14315 14316 @Override 14317 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14318 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14319 != PackageManager.PERMISSION_GRANTED) { 14320 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14321 + Binder.getCallingPid() 14322 + ", uid=" + Binder.getCallingUid() 14323 + " without permission " 14324 + android.Manifest.permission.DUMP); 14325 return; 14326 } 14327 14328 DumpState dumpState = new DumpState(); 14329 boolean fullPreferred = false; 14330 boolean checkin = false; 14331 14332 String packageName = null; 14333 ArraySet<String> permissionNames = null; 14334 14335 int opti = 0; 14336 while (opti < args.length) { 14337 String opt = args[opti]; 14338 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14339 break; 14340 } 14341 opti++; 14342 14343 if ("-a".equals(opt)) { 14344 // Right now we only know how to print all. 14345 } else if ("-h".equals(opt)) { 14346 pw.println("Package manager dump options:"); 14347 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14348 pw.println(" --checkin: dump for a checkin"); 14349 pw.println(" -f: print details of intent filters"); 14350 pw.println(" -h: print this help"); 14351 pw.println(" cmd may be one of:"); 14352 pw.println(" l[ibraries]: list known shared libraries"); 14353 pw.println(" f[ibraries]: list device features"); 14354 pw.println(" k[eysets]: print known keysets"); 14355 pw.println(" r[esolvers]: dump intent resolvers"); 14356 pw.println(" perm[issions]: dump permissions"); 14357 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14358 pw.println(" pref[erred]: print preferred package settings"); 14359 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14360 pw.println(" prov[iders]: dump content providers"); 14361 pw.println(" p[ackages]: dump installed packages"); 14362 pw.println(" s[hared-users]: dump shared user IDs"); 14363 pw.println(" m[essages]: print collected runtime messages"); 14364 pw.println(" v[erifiers]: print package verifier info"); 14365 pw.println(" version: print database version info"); 14366 pw.println(" write: write current settings now"); 14367 pw.println(" <package.name>: info about given package"); 14368 pw.println(" installs: details about install sessions"); 14369 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14370 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14371 return; 14372 } else if ("--checkin".equals(opt)) { 14373 checkin = true; 14374 } else if ("-f".equals(opt)) { 14375 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14376 } else { 14377 pw.println("Unknown argument: " + opt + "; use -h for help"); 14378 } 14379 } 14380 14381 // Is the caller requesting to dump a particular piece of data? 14382 if (opti < args.length) { 14383 String cmd = args[opti]; 14384 opti++; 14385 // Is this a package name? 14386 if ("android".equals(cmd) || cmd.contains(".")) { 14387 packageName = cmd; 14388 // When dumping a single package, we always dump all of its 14389 // filter information since the amount of data will be reasonable. 14390 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14391 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14392 dumpState.setDump(DumpState.DUMP_LIBS); 14393 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14394 dumpState.setDump(DumpState.DUMP_FEATURES); 14395 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14396 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14397 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14398 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14399 } else if ("permission".equals(cmd)) { 14400 if (opti >= args.length) { 14401 pw.println("Error: permission requires permission name"); 14402 return; 14403 } 14404 permissionNames = new ArraySet<>(); 14405 while (opti < args.length) { 14406 permissionNames.add(args[opti]); 14407 opti++; 14408 } 14409 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14410 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14411 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14412 dumpState.setDump(DumpState.DUMP_PREFERRED); 14413 } else if ("preferred-xml".equals(cmd)) { 14414 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14415 if (opti < args.length && "--full".equals(args[opti])) { 14416 fullPreferred = true; 14417 opti++; 14418 } 14419 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14420 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14421 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14422 dumpState.setDump(DumpState.DUMP_PACKAGES); 14423 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14424 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14425 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14426 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14427 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14428 dumpState.setDump(DumpState.DUMP_MESSAGES); 14429 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14430 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14431 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14432 || "intent-filter-verifiers".equals(cmd)) { 14433 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14434 } else if ("version".equals(cmd)) { 14435 dumpState.setDump(DumpState.DUMP_VERSION); 14436 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14437 dumpState.setDump(DumpState.DUMP_KEYSETS); 14438 } else if ("installs".equals(cmd)) { 14439 dumpState.setDump(DumpState.DUMP_INSTALLS); 14440 } else if ("write".equals(cmd)) { 14441 synchronized (mPackages) { 14442 mSettings.writeLPr(); 14443 pw.println("Settings written."); 14444 return; 14445 } 14446 } 14447 } 14448 14449 if (checkin) { 14450 pw.println("vers,1"); 14451 } 14452 14453 // reader 14454 synchronized (mPackages) { 14455 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14456 if (!checkin) { 14457 if (dumpState.onTitlePrinted()) 14458 pw.println(); 14459 pw.println("Database versions:"); 14460 pw.print(" SDK Version:"); 14461 pw.print(" internal="); 14462 pw.print(mSettings.mInternalSdkPlatform); 14463 pw.print(" external="); 14464 pw.println(mSettings.mExternalSdkPlatform); 14465 pw.print(" DB Version:"); 14466 pw.print(" internal="); 14467 pw.print(mSettings.mInternalDatabaseVersion); 14468 pw.print(" external="); 14469 pw.println(mSettings.mExternalDatabaseVersion); 14470 } 14471 } 14472 14473 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14474 if (!checkin) { 14475 if (dumpState.onTitlePrinted()) 14476 pw.println(); 14477 pw.println("Verifiers:"); 14478 pw.print(" Required: "); 14479 pw.print(mRequiredVerifierPackage); 14480 pw.print(" (uid="); 14481 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14482 pw.println(")"); 14483 } else if (mRequiredVerifierPackage != null) { 14484 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14485 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14486 } 14487 } 14488 14489 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14490 packageName == null) { 14491 if (mIntentFilterVerifierComponent != null) { 14492 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14493 if (!checkin) { 14494 if (dumpState.onTitlePrinted()) 14495 pw.println(); 14496 pw.println("Intent Filter Verifier:"); 14497 pw.print(" Using: "); 14498 pw.print(verifierPackageName); 14499 pw.print(" (uid="); 14500 pw.print(getPackageUid(verifierPackageName, 0)); 14501 pw.println(")"); 14502 } else if (verifierPackageName != null) { 14503 pw.print("ifv,"); pw.print(verifierPackageName); 14504 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14505 } 14506 } else { 14507 pw.println(); 14508 pw.println("No Intent Filter Verifier available!"); 14509 } 14510 } 14511 14512 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14513 boolean printedHeader = false; 14514 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14515 while (it.hasNext()) { 14516 String name = it.next(); 14517 SharedLibraryEntry ent = mSharedLibraries.get(name); 14518 if (!checkin) { 14519 if (!printedHeader) { 14520 if (dumpState.onTitlePrinted()) 14521 pw.println(); 14522 pw.println("Libraries:"); 14523 printedHeader = true; 14524 } 14525 pw.print(" "); 14526 } else { 14527 pw.print("lib,"); 14528 } 14529 pw.print(name); 14530 if (!checkin) { 14531 pw.print(" -> "); 14532 } 14533 if (ent.path != null) { 14534 if (!checkin) { 14535 pw.print("(jar) "); 14536 pw.print(ent.path); 14537 } else { 14538 pw.print(",jar,"); 14539 pw.print(ent.path); 14540 } 14541 } else { 14542 if (!checkin) { 14543 pw.print("(apk) "); 14544 pw.print(ent.apk); 14545 } else { 14546 pw.print(",apk,"); 14547 pw.print(ent.apk); 14548 } 14549 } 14550 pw.println(); 14551 } 14552 } 14553 14554 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14555 if (dumpState.onTitlePrinted()) 14556 pw.println(); 14557 if (!checkin) { 14558 pw.println("Features:"); 14559 } 14560 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14561 while (it.hasNext()) { 14562 String name = it.next(); 14563 if (!checkin) { 14564 pw.print(" "); 14565 } else { 14566 pw.print("feat,"); 14567 } 14568 pw.println(name); 14569 } 14570 } 14571 14572 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14573 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14574 : "Activity Resolver Table:", " ", packageName, 14575 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14576 dumpState.setTitlePrinted(true); 14577 } 14578 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14579 : "Receiver Resolver Table:", " ", packageName, 14580 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14581 dumpState.setTitlePrinted(true); 14582 } 14583 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14584 : "Service Resolver Table:", " ", packageName, 14585 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14586 dumpState.setTitlePrinted(true); 14587 } 14588 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14589 : "Provider Resolver Table:", " ", packageName, 14590 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14591 dumpState.setTitlePrinted(true); 14592 } 14593 } 14594 14595 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14596 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14597 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14598 int user = mSettings.mPreferredActivities.keyAt(i); 14599 if (pir.dump(pw, 14600 dumpState.getTitlePrinted() 14601 ? "\nPreferred Activities User " + user + ":" 14602 : "Preferred Activities User " + user + ":", " ", 14603 packageName, true, false)) { 14604 dumpState.setTitlePrinted(true); 14605 } 14606 } 14607 } 14608 14609 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14610 pw.flush(); 14611 FileOutputStream fout = new FileOutputStream(fd); 14612 BufferedOutputStream str = new BufferedOutputStream(fout); 14613 XmlSerializer serializer = new FastXmlSerializer(); 14614 try { 14615 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14616 serializer.startDocument(null, true); 14617 serializer.setFeature( 14618 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14619 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14620 serializer.endDocument(); 14621 serializer.flush(); 14622 } catch (IllegalArgumentException e) { 14623 pw.println("Failed writing: " + e); 14624 } catch (IllegalStateException e) { 14625 pw.println("Failed writing: " + e); 14626 } catch (IOException e) { 14627 pw.println("Failed writing: " + e); 14628 } 14629 } 14630 14631 if (!checkin 14632 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14633 && packageName == null) { 14634 pw.println(); 14635 int count = mSettings.mPackages.size(); 14636 if (count == 0) { 14637 pw.println("No domain preferred apps!"); 14638 pw.println(); 14639 } else { 14640 final String prefix = " "; 14641 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14642 if (allPackageSettings.size() == 0) { 14643 pw.println("No domain preferred apps!"); 14644 pw.println(); 14645 } else { 14646 pw.println("Domain preferred apps status:"); 14647 pw.println(); 14648 count = 0; 14649 for (PackageSetting ps : allPackageSettings) { 14650 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14651 if (ivi == null || ivi.getPackageName() == null) continue; 14652 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14653 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14654 pw.println(prefix + "Status: " + ivi.getStatusString()); 14655 pw.println(); 14656 count++; 14657 } 14658 if (count == 0) { 14659 pw.println(prefix + "No domain preferred app status!"); 14660 pw.println(); 14661 } 14662 for (int userId : sUserManager.getUserIds()) { 14663 pw.println("Domain preferred apps for User " + userId + ":"); 14664 pw.println(); 14665 count = 0; 14666 for (PackageSetting ps : allPackageSettings) { 14667 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14668 if (ivi == null || ivi.getPackageName() == null) { 14669 continue; 14670 } 14671 final int status = ps.getDomainVerificationStatusForUser(userId); 14672 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14673 continue; 14674 } 14675 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14676 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14677 String statusStr = IntentFilterVerificationInfo. 14678 getStatusStringFromValue(status); 14679 pw.println(prefix + "Status: " + statusStr); 14680 pw.println(); 14681 count++; 14682 } 14683 if (count == 0) { 14684 pw.println(prefix + "No domain preferred apps!"); 14685 pw.println(); 14686 } 14687 } 14688 } 14689 } 14690 } 14691 14692 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14693 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14694 if (packageName == null && permissionNames == null) { 14695 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14696 if (iperm == 0) { 14697 if (dumpState.onTitlePrinted()) 14698 pw.println(); 14699 pw.println("AppOp Permissions:"); 14700 } 14701 pw.print(" AppOp Permission "); 14702 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14703 pw.println(":"); 14704 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14705 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14706 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14707 } 14708 } 14709 } 14710 } 14711 14712 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14713 boolean printedSomething = false; 14714 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14715 if (packageName != null && !packageName.equals(p.info.packageName)) { 14716 continue; 14717 } 14718 if (!printedSomething) { 14719 if (dumpState.onTitlePrinted()) 14720 pw.println(); 14721 pw.println("Registered ContentProviders:"); 14722 printedSomething = true; 14723 } 14724 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14725 pw.print(" "); pw.println(p.toString()); 14726 } 14727 printedSomething = false; 14728 for (Map.Entry<String, PackageParser.Provider> entry : 14729 mProvidersByAuthority.entrySet()) { 14730 PackageParser.Provider p = entry.getValue(); 14731 if (packageName != null && !packageName.equals(p.info.packageName)) { 14732 continue; 14733 } 14734 if (!printedSomething) { 14735 if (dumpState.onTitlePrinted()) 14736 pw.println(); 14737 pw.println("ContentProvider Authorities:"); 14738 printedSomething = true; 14739 } 14740 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14741 pw.print(" "); pw.println(p.toString()); 14742 if (p.info != null && p.info.applicationInfo != null) { 14743 final String appInfo = p.info.applicationInfo.toString(); 14744 pw.print(" applicationInfo="); pw.println(appInfo); 14745 } 14746 } 14747 } 14748 14749 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14750 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14751 } 14752 14753 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14754 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14755 } 14756 14757 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14758 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14759 } 14760 14761 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14762 // XXX should handle packageName != null by dumping only install data that 14763 // the given package is involved with. 14764 if (dumpState.onTitlePrinted()) pw.println(); 14765 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14766 } 14767 14768 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14769 if (dumpState.onTitlePrinted()) pw.println(); 14770 mSettings.dumpReadMessagesLPr(pw, dumpState); 14771 14772 pw.println(); 14773 pw.println("Package warning messages:"); 14774 BufferedReader in = null; 14775 String line = null; 14776 try { 14777 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14778 while ((line = in.readLine()) != null) { 14779 if (line.contains("ignored: updated version")) continue; 14780 pw.println(line); 14781 } 14782 } catch (IOException ignored) { 14783 } finally { 14784 IoUtils.closeQuietly(in); 14785 } 14786 } 14787 14788 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14789 BufferedReader in = null; 14790 String line = null; 14791 try { 14792 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14793 while ((line = in.readLine()) != null) { 14794 if (line.contains("ignored: updated version")) continue; 14795 pw.print("msg,"); 14796 pw.println(line); 14797 } 14798 } catch (IOException ignored) { 14799 } finally { 14800 IoUtils.closeQuietly(in); 14801 } 14802 } 14803 } 14804 } 14805 14806 // ------- apps on sdcard specific code ------- 14807 static final boolean DEBUG_SD_INSTALL = false; 14808 14809 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14810 14811 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14812 14813 private boolean mMediaMounted = false; 14814 14815 static String getEncryptKey() { 14816 try { 14817 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14818 SD_ENCRYPTION_KEYSTORE_NAME); 14819 if (sdEncKey == null) { 14820 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14821 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14822 if (sdEncKey == null) { 14823 Slog.e(TAG, "Failed to create encryption keys"); 14824 return null; 14825 } 14826 } 14827 return sdEncKey; 14828 } catch (NoSuchAlgorithmException nsae) { 14829 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14830 return null; 14831 } catch (IOException ioe) { 14832 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14833 return null; 14834 } 14835 } 14836 14837 /* 14838 * Update media status on PackageManager. 14839 */ 14840 @Override 14841 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14842 int callingUid = Binder.getCallingUid(); 14843 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14844 throw new SecurityException("Media status can only be updated by the system"); 14845 } 14846 // reader; this apparently protects mMediaMounted, but should probably 14847 // be a different lock in that case. 14848 synchronized (mPackages) { 14849 Log.i(TAG, "Updating external media status from " 14850 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14851 + (mediaStatus ? "mounted" : "unmounted")); 14852 if (DEBUG_SD_INSTALL) 14853 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14854 + ", mMediaMounted=" + mMediaMounted); 14855 if (mediaStatus == mMediaMounted) { 14856 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14857 : 0, -1); 14858 mHandler.sendMessage(msg); 14859 return; 14860 } 14861 mMediaMounted = mediaStatus; 14862 } 14863 // Queue up an async operation since the package installation may take a 14864 // little while. 14865 mHandler.post(new Runnable() { 14866 public void run() { 14867 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14868 } 14869 }); 14870 } 14871 14872 /** 14873 * Called by MountService when the initial ASECs to scan are available. 14874 * Should block until all the ASEC containers are finished being scanned. 14875 */ 14876 public void scanAvailableAsecs() { 14877 updateExternalMediaStatusInner(true, false, false); 14878 if (mShouldRestoreconData) { 14879 SELinuxMMAC.setRestoreconDone(); 14880 mShouldRestoreconData = false; 14881 } 14882 } 14883 14884 /* 14885 * Collect information of applications on external media, map them against 14886 * existing containers and update information based on current mount status. 14887 * Please note that we always have to report status if reportStatus has been 14888 * set to true especially when unloading packages. 14889 */ 14890 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14891 boolean externalStorage) { 14892 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14893 int[] uidArr = EmptyArray.INT; 14894 14895 final String[] list = PackageHelper.getSecureContainerList(); 14896 if (ArrayUtils.isEmpty(list)) { 14897 Log.i(TAG, "No secure containers found"); 14898 } else { 14899 // Process list of secure containers and categorize them 14900 // as active or stale based on their package internal state. 14901 14902 // reader 14903 synchronized (mPackages) { 14904 for (String cid : list) { 14905 // Leave stages untouched for now; installer service owns them 14906 if (PackageInstallerService.isStageName(cid)) continue; 14907 14908 if (DEBUG_SD_INSTALL) 14909 Log.i(TAG, "Processing container " + cid); 14910 String pkgName = getAsecPackageName(cid); 14911 if (pkgName == null) { 14912 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14913 continue; 14914 } 14915 if (DEBUG_SD_INSTALL) 14916 Log.i(TAG, "Looking for pkg : " + pkgName); 14917 14918 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14919 if (ps == null) { 14920 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14921 continue; 14922 } 14923 14924 /* 14925 * Skip packages that are not external if we're unmounting 14926 * external storage. 14927 */ 14928 if (externalStorage && !isMounted && !isExternal(ps)) { 14929 continue; 14930 } 14931 14932 final AsecInstallArgs args = new AsecInstallArgs(cid, 14933 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14934 // The package status is changed only if the code path 14935 // matches between settings and the container id. 14936 if (ps.codePathString != null 14937 && ps.codePathString.startsWith(args.getCodePath())) { 14938 if (DEBUG_SD_INSTALL) { 14939 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14940 + " at code path: " + ps.codePathString); 14941 } 14942 14943 // We do have a valid package installed on sdcard 14944 processCids.put(args, ps.codePathString); 14945 final int uid = ps.appId; 14946 if (uid != -1) { 14947 uidArr = ArrayUtils.appendInt(uidArr, uid); 14948 } 14949 } else { 14950 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14951 + ps.codePathString); 14952 } 14953 } 14954 } 14955 14956 Arrays.sort(uidArr); 14957 } 14958 14959 // Process packages with valid entries. 14960 if (isMounted) { 14961 if (DEBUG_SD_INSTALL) 14962 Log.i(TAG, "Loading packages"); 14963 loadMediaPackages(processCids, uidArr); 14964 startCleaningPackages(); 14965 mInstallerService.onSecureContainersAvailable(); 14966 } else { 14967 if (DEBUG_SD_INSTALL) 14968 Log.i(TAG, "Unloading packages"); 14969 unloadMediaPackages(processCids, uidArr, reportStatus); 14970 } 14971 } 14972 14973 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14974 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14975 final int size = infos.size(); 14976 final String[] packageNames = new String[size]; 14977 final int[] packageUids = new int[size]; 14978 for (int i = 0; i < size; i++) { 14979 final ApplicationInfo info = infos.get(i); 14980 packageNames[i] = info.packageName; 14981 packageUids[i] = info.uid; 14982 } 14983 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14984 finishedReceiver); 14985 } 14986 14987 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14988 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14989 sendResourcesChangedBroadcast(mediaStatus, replacing, 14990 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14991 } 14992 14993 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14994 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14995 int size = pkgList.length; 14996 if (size > 0) { 14997 // Send broadcasts here 14998 Bundle extras = new Bundle(); 14999 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15000 if (uidArr != null) { 15001 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15002 } 15003 if (replacing) { 15004 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15005 } 15006 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15007 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15008 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15009 } 15010 } 15011 15012 /* 15013 * Look at potentially valid container ids from processCids If package 15014 * information doesn't match the one on record or package scanning fails, 15015 * the cid is added to list of removeCids. We currently don't delete stale 15016 * containers. 15017 */ 15018 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15019 ArrayList<String> pkgList = new ArrayList<String>(); 15020 Set<AsecInstallArgs> keys = processCids.keySet(); 15021 15022 for (AsecInstallArgs args : keys) { 15023 String codePath = processCids.get(args); 15024 if (DEBUG_SD_INSTALL) 15025 Log.i(TAG, "Loading container : " + args.cid); 15026 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15027 try { 15028 // Make sure there are no container errors first. 15029 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15030 Slog.e(TAG, "Failed to mount cid : " + args.cid 15031 + " when installing from sdcard"); 15032 continue; 15033 } 15034 // Check code path here. 15035 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15036 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15037 + " does not match one in settings " + codePath); 15038 continue; 15039 } 15040 // Parse package 15041 int parseFlags = mDefParseFlags; 15042 if (args.isExternalAsec()) { 15043 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15044 } 15045 if (args.isFwdLocked()) { 15046 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15047 } 15048 15049 synchronized (mInstallLock) { 15050 PackageParser.Package pkg = null; 15051 try { 15052 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15053 } catch (PackageManagerException e) { 15054 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15055 } 15056 // Scan the package 15057 if (pkg != null) { 15058 /* 15059 * TODO why is the lock being held? doPostInstall is 15060 * called in other places without the lock. This needs 15061 * to be straightened out. 15062 */ 15063 // writer 15064 synchronized (mPackages) { 15065 retCode = PackageManager.INSTALL_SUCCEEDED; 15066 pkgList.add(pkg.packageName); 15067 // Post process args 15068 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15069 pkg.applicationInfo.uid); 15070 } 15071 } else { 15072 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15073 } 15074 } 15075 15076 } finally { 15077 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15078 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15079 } 15080 } 15081 } 15082 // writer 15083 synchronized (mPackages) { 15084 // If the platform SDK has changed since the last time we booted, 15085 // we need to re-grant app permission to catch any new ones that 15086 // appear. This is really a hack, and means that apps can in some 15087 // cases get permissions that the user didn't initially explicitly 15088 // allow... it would be nice to have some better way to handle 15089 // this situation. 15090 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15091 if (regrantPermissions) 15092 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15093 + mSdkVersion + "; regranting permissions for external storage"); 15094 mSettings.mExternalSdkPlatform = mSdkVersion; 15095 15096 // Make sure group IDs have been assigned, and any permission 15097 // changes in other apps are accounted for 15098 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15099 | (regrantPermissions 15100 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15101 : 0)); 15102 15103 mSettings.updateExternalDatabaseVersion(); 15104 15105 // can downgrade to reader 15106 // Persist settings 15107 mSettings.writeLPr(); 15108 } 15109 // Send a broadcast to let everyone know we are done processing 15110 if (pkgList.size() > 0) { 15111 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15112 } 15113 } 15114 15115 /* 15116 * Utility method to unload a list of specified containers 15117 */ 15118 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15119 // Just unmount all valid containers. 15120 for (AsecInstallArgs arg : cidArgs) { 15121 synchronized (mInstallLock) { 15122 arg.doPostDeleteLI(false); 15123 } 15124 } 15125 } 15126 15127 /* 15128 * Unload packages mounted on external media. This involves deleting package 15129 * data from internal structures, sending broadcasts about diabled packages, 15130 * gc'ing to free up references, unmounting all secure containers 15131 * corresponding to packages on external media, and posting a 15132 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15133 * that we always have to post this message if status has been requested no 15134 * matter what. 15135 */ 15136 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15137 final boolean reportStatus) { 15138 if (DEBUG_SD_INSTALL) 15139 Log.i(TAG, "unloading media packages"); 15140 ArrayList<String> pkgList = new ArrayList<String>(); 15141 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15142 final Set<AsecInstallArgs> keys = processCids.keySet(); 15143 for (AsecInstallArgs args : keys) { 15144 String pkgName = args.getPackageName(); 15145 if (DEBUG_SD_INSTALL) 15146 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15147 // Delete package internally 15148 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15149 synchronized (mInstallLock) { 15150 boolean res = deletePackageLI(pkgName, null, false, null, null, 15151 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15152 if (res) { 15153 pkgList.add(pkgName); 15154 } else { 15155 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15156 failedList.add(args); 15157 } 15158 } 15159 } 15160 15161 // reader 15162 synchronized (mPackages) { 15163 // We didn't update the settings after removing each package; 15164 // write them now for all packages. 15165 mSettings.writeLPr(); 15166 } 15167 15168 // We have to absolutely send UPDATED_MEDIA_STATUS only 15169 // after confirming that all the receivers processed the ordered 15170 // broadcast when packages get disabled, force a gc to clean things up. 15171 // and unload all the containers. 15172 if (pkgList.size() > 0) { 15173 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15174 new IIntentReceiver.Stub() { 15175 public void performReceive(Intent intent, int resultCode, String data, 15176 Bundle extras, boolean ordered, boolean sticky, 15177 int sendingUser) throws RemoteException { 15178 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15179 reportStatus ? 1 : 0, 1, keys); 15180 mHandler.sendMessage(msg); 15181 } 15182 }); 15183 } else { 15184 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15185 keys); 15186 mHandler.sendMessage(msg); 15187 } 15188 } 15189 15190 private void loadPrivatePackages(VolumeInfo vol) { 15191 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15192 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15193 synchronized (mInstallLock) { 15194 synchronized (mPackages) { 15195 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15196 for (PackageSetting ps : packages) { 15197 final PackageParser.Package pkg; 15198 try { 15199 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15200 loaded.add(pkg.applicationInfo); 15201 } catch (PackageManagerException e) { 15202 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15203 } 15204 } 15205 15206 // TODO: regrant any permissions that changed based since original install 15207 15208 mSettings.writeLPr(); 15209 } 15210 } 15211 15212 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15213 sendResourcesChangedBroadcast(true, false, loaded, null); 15214 } 15215 15216 private void unloadPrivatePackages(VolumeInfo vol) { 15217 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15218 synchronized (mInstallLock) { 15219 synchronized (mPackages) { 15220 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15221 for (PackageSetting ps : packages) { 15222 if (ps.pkg == null) continue; 15223 15224 final ApplicationInfo info = ps.pkg.applicationInfo; 15225 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15226 if (deletePackageLI(ps.name, null, false, null, null, 15227 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15228 unloaded.add(info); 15229 } else { 15230 Slog.w(TAG, "Failed to unload " + ps.codePath); 15231 } 15232 } 15233 15234 mSettings.writeLPr(); 15235 } 15236 } 15237 15238 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15239 sendResourcesChangedBroadcast(false, false, unloaded, null); 15240 } 15241 15242 private void unfreezePackage(String packageName) { 15243 synchronized (mPackages) { 15244 final PackageSetting ps = mSettings.mPackages.get(packageName); 15245 if (ps != null) { 15246 ps.frozen = false; 15247 } 15248 } 15249 } 15250 15251 @Override 15252 public int movePackage(final String packageName, final String volumeUuid) { 15253 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15254 15255 final int moveId = mNextMoveId.getAndIncrement(); 15256 try { 15257 movePackageInternal(packageName, volumeUuid, moveId); 15258 } catch (PackageManagerException e) { 15259 Slog.w(TAG, "Failed to move " + packageName, e); 15260 mMoveCallbacks.notifyStatusChanged(moveId, 15261 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15262 } 15263 return moveId; 15264 } 15265 15266 private void movePackageInternal(final String packageName, final String volumeUuid, 15267 final int moveId) throws PackageManagerException { 15268 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15269 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15270 final PackageManager pm = mContext.getPackageManager(); 15271 15272 final boolean currentAsec; 15273 final String currentVolumeUuid; 15274 final File codeFile; 15275 final String installerPackageName; 15276 final String packageAbiOverride; 15277 final int appId; 15278 final String seinfo; 15279 final String label; 15280 15281 // reader 15282 synchronized (mPackages) { 15283 final PackageParser.Package pkg = mPackages.get(packageName); 15284 final PackageSetting ps = mSettings.mPackages.get(packageName); 15285 if (pkg == null || ps == null) { 15286 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15287 } 15288 15289 if (pkg.applicationInfo.isSystemApp()) { 15290 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15291 "Cannot move system application"); 15292 } 15293 15294 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15295 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15296 "Package already moved to " + volumeUuid); 15297 } 15298 15299 final File probe = new File(pkg.codePath); 15300 final File probeOat = new File(probe, "oat"); 15301 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15302 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15303 "Move only supported for modern cluster style installs"); 15304 } 15305 15306 if (ps.frozen) { 15307 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15308 "Failed to move already frozen package"); 15309 } 15310 ps.frozen = true; 15311 15312 currentAsec = pkg.applicationInfo.isForwardLocked() 15313 || pkg.applicationInfo.isExternalAsec(); 15314 currentVolumeUuid = ps.volumeUuid; 15315 codeFile = new File(pkg.codePath); 15316 installerPackageName = ps.installerPackageName; 15317 packageAbiOverride = ps.cpuAbiOverrideString; 15318 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15319 seinfo = pkg.applicationInfo.seinfo; 15320 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15321 } 15322 15323 // Now that we're guarded by frozen state, kill app during move 15324 killApplication(packageName, appId, "move pkg"); 15325 15326 final Bundle extras = new Bundle(); 15327 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15328 extras.putString(Intent.EXTRA_TITLE, label); 15329 mMoveCallbacks.notifyCreated(moveId, extras); 15330 15331 int installFlags; 15332 final boolean moveCompleteApp; 15333 final File measurePath; 15334 15335 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15336 installFlags = INSTALL_INTERNAL; 15337 moveCompleteApp = !currentAsec; 15338 measurePath = Environment.getDataAppDirectory(volumeUuid); 15339 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15340 installFlags = INSTALL_EXTERNAL; 15341 moveCompleteApp = false; 15342 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15343 } else { 15344 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15345 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15346 || !volume.isMountedWritable()) { 15347 unfreezePackage(packageName); 15348 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15349 "Move location not mounted private volume"); 15350 } 15351 15352 Preconditions.checkState(!currentAsec); 15353 15354 installFlags = INSTALL_INTERNAL; 15355 moveCompleteApp = true; 15356 measurePath = Environment.getDataAppDirectory(volumeUuid); 15357 } 15358 15359 final PackageStats stats = new PackageStats(null, -1); 15360 synchronized (mInstaller) { 15361 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15362 unfreezePackage(packageName); 15363 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15364 "Failed to measure package size"); 15365 } 15366 } 15367 15368 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15369 + stats.dataSize); 15370 15371 final long startFreeBytes = measurePath.getFreeSpace(); 15372 final long sizeBytes; 15373 if (moveCompleteApp) { 15374 sizeBytes = stats.codeSize + stats.dataSize; 15375 } else { 15376 sizeBytes = stats.codeSize; 15377 } 15378 15379 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15380 unfreezePackage(packageName); 15381 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15382 "Not enough free space to move"); 15383 } 15384 15385 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15386 15387 final CountDownLatch installedLatch = new CountDownLatch(1); 15388 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15389 @Override 15390 public void onUserActionRequired(Intent intent) throws RemoteException { 15391 throw new IllegalStateException(); 15392 } 15393 15394 @Override 15395 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15396 Bundle extras) throws RemoteException { 15397 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15398 + PackageManager.installStatusToString(returnCode, msg)); 15399 15400 installedLatch.countDown(); 15401 15402 // Regardless of success or failure of the move operation, 15403 // always unfreeze the package 15404 unfreezePackage(packageName); 15405 15406 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15407 switch (status) { 15408 case PackageInstaller.STATUS_SUCCESS: 15409 mMoveCallbacks.notifyStatusChanged(moveId, 15410 PackageManager.MOVE_SUCCEEDED); 15411 break; 15412 case PackageInstaller.STATUS_FAILURE_STORAGE: 15413 mMoveCallbacks.notifyStatusChanged(moveId, 15414 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15415 break; 15416 default: 15417 mMoveCallbacks.notifyStatusChanged(moveId, 15418 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15419 break; 15420 } 15421 } 15422 }; 15423 15424 final MoveInfo move; 15425 if (moveCompleteApp) { 15426 // Kick off a thread to report progress estimates 15427 new Thread() { 15428 @Override 15429 public void run() { 15430 while (true) { 15431 try { 15432 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15433 break; 15434 } 15435 } catch (InterruptedException ignored) { 15436 } 15437 15438 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15439 final int progress = 10 + (int) MathUtils.constrain( 15440 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15441 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15442 } 15443 } 15444 }.start(); 15445 15446 final String dataAppName = codeFile.getName(); 15447 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15448 dataAppName, appId, seinfo); 15449 } else { 15450 move = null; 15451 } 15452 15453 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15454 15455 final Message msg = mHandler.obtainMessage(INIT_COPY); 15456 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15457 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15458 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15459 mHandler.sendMessage(msg); 15460 } 15461 15462 @Override 15463 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15464 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15465 15466 final int realMoveId = mNextMoveId.getAndIncrement(); 15467 final Bundle extras = new Bundle(); 15468 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15469 mMoveCallbacks.notifyCreated(realMoveId, extras); 15470 15471 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15472 @Override 15473 public void onCreated(int moveId, Bundle extras) { 15474 // Ignored 15475 } 15476 15477 @Override 15478 public void onStatusChanged(int moveId, int status, long estMillis) { 15479 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15480 } 15481 }; 15482 15483 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15484 storage.setPrimaryStorageUuid(volumeUuid, callback); 15485 return realMoveId; 15486 } 15487 15488 @Override 15489 public int getMoveStatus(int moveId) { 15490 mContext.enforceCallingOrSelfPermission( 15491 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15492 return mMoveCallbacks.mLastStatus.get(moveId); 15493 } 15494 15495 @Override 15496 public void registerMoveCallback(IPackageMoveObserver callback) { 15497 mContext.enforceCallingOrSelfPermission( 15498 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15499 mMoveCallbacks.register(callback); 15500 } 15501 15502 @Override 15503 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15504 mContext.enforceCallingOrSelfPermission( 15505 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15506 mMoveCallbacks.unregister(callback); 15507 } 15508 15509 @Override 15510 public boolean setInstallLocation(int loc) { 15511 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15512 null); 15513 if (getInstallLocation() == loc) { 15514 return true; 15515 } 15516 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15517 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15518 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15519 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15520 return true; 15521 } 15522 return false; 15523 } 15524 15525 @Override 15526 public int getInstallLocation() { 15527 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15528 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15529 PackageHelper.APP_INSTALL_AUTO); 15530 } 15531 15532 /** Called by UserManagerService */ 15533 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15534 mDirtyUsers.remove(userHandle); 15535 mSettings.removeUserLPw(userHandle); 15536 mPendingBroadcasts.remove(userHandle); 15537 if (mInstaller != null) { 15538 // Technically, we shouldn't be doing this with the package lock 15539 // held. However, this is very rare, and there is already so much 15540 // other disk I/O going on, that we'll let it slide for now. 15541 final StorageManager storage = StorageManager.from(mContext); 15542 final List<VolumeInfo> vols = storage.getVolumes(); 15543 for (VolumeInfo vol : vols) { 15544 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15545 final String volumeUuid = vol.getFsUuid(); 15546 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15547 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15548 } 15549 } 15550 } 15551 mUserNeedsBadging.delete(userHandle); 15552 removeUnusedPackagesLILPw(userManager, userHandle); 15553 } 15554 15555 /** 15556 * We're removing userHandle and would like to remove any downloaded packages 15557 * that are no longer in use by any other user. 15558 * @param userHandle the user being removed 15559 */ 15560 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15561 final boolean DEBUG_CLEAN_APKS = false; 15562 int [] users = userManager.getUserIdsLPr(); 15563 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15564 while (psit.hasNext()) { 15565 PackageSetting ps = psit.next(); 15566 if (ps.pkg == null) { 15567 continue; 15568 } 15569 final String packageName = ps.pkg.packageName; 15570 // Skip over if system app 15571 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15572 continue; 15573 } 15574 if (DEBUG_CLEAN_APKS) { 15575 Slog.i(TAG, "Checking package " + packageName); 15576 } 15577 boolean keep = false; 15578 for (int i = 0; i < users.length; i++) { 15579 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15580 keep = true; 15581 if (DEBUG_CLEAN_APKS) { 15582 Slog.i(TAG, " Keeping package " + packageName + " for user " 15583 + users[i]); 15584 } 15585 break; 15586 } 15587 } 15588 if (!keep) { 15589 if (DEBUG_CLEAN_APKS) { 15590 Slog.i(TAG, " Removing package " + packageName); 15591 } 15592 mHandler.post(new Runnable() { 15593 public void run() { 15594 deletePackageX(packageName, userHandle, 0); 15595 } //end run 15596 }); 15597 } 15598 } 15599 } 15600 15601 /** Called by UserManagerService */ 15602 void createNewUserLILPw(int userHandle, File path) { 15603 if (mInstaller != null) { 15604 mInstaller.createUserConfig(userHandle); 15605 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15606 applyFactoryDefaultBrowserLPw(userHandle); 15607 } 15608 } 15609 15610 void newUserCreatedLILPw(final int userHandle) { 15611 // We cannot grant the default permissions with a lock held as 15612 // we query providers from other components for default handlers 15613 // such as enabled IMEs, etc. 15614 mHandler.post(new Runnable() { 15615 @Override 15616 public void run() { 15617 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15618 } 15619 }); 15620 } 15621 15622 @Override 15623 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15624 mContext.enforceCallingOrSelfPermission( 15625 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15626 "Only package verification agents can read the verifier device identity"); 15627 15628 synchronized (mPackages) { 15629 return mSettings.getVerifierDeviceIdentityLPw(); 15630 } 15631 } 15632 15633 @Override 15634 public void setPermissionEnforced(String permission, boolean enforced) { 15635 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15636 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15637 synchronized (mPackages) { 15638 if (mSettings.mReadExternalStorageEnforced == null 15639 || mSettings.mReadExternalStorageEnforced != enforced) { 15640 mSettings.mReadExternalStorageEnforced = enforced; 15641 mSettings.writeLPr(); 15642 } 15643 } 15644 // kill any non-foreground processes so we restart them and 15645 // grant/revoke the GID. 15646 final IActivityManager am = ActivityManagerNative.getDefault(); 15647 if (am != null) { 15648 final long token = Binder.clearCallingIdentity(); 15649 try { 15650 am.killProcessesBelowForeground("setPermissionEnforcement"); 15651 } catch (RemoteException e) { 15652 } finally { 15653 Binder.restoreCallingIdentity(token); 15654 } 15655 } 15656 } else { 15657 throw new IllegalArgumentException("No selective enforcement for " + permission); 15658 } 15659 } 15660 15661 @Override 15662 @Deprecated 15663 public boolean isPermissionEnforced(String permission) { 15664 return true; 15665 } 15666 15667 @Override 15668 public boolean isStorageLow() { 15669 final long token = Binder.clearCallingIdentity(); 15670 try { 15671 final DeviceStorageMonitorInternal 15672 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15673 if (dsm != null) { 15674 return dsm.isMemoryLow(); 15675 } else { 15676 return false; 15677 } 15678 } finally { 15679 Binder.restoreCallingIdentity(token); 15680 } 15681 } 15682 15683 @Override 15684 public IPackageInstaller getPackageInstaller() { 15685 return mInstallerService; 15686 } 15687 15688 private boolean userNeedsBadging(int userId) { 15689 int index = mUserNeedsBadging.indexOfKey(userId); 15690 if (index < 0) { 15691 final UserInfo userInfo; 15692 final long token = Binder.clearCallingIdentity(); 15693 try { 15694 userInfo = sUserManager.getUserInfo(userId); 15695 } finally { 15696 Binder.restoreCallingIdentity(token); 15697 } 15698 final boolean b; 15699 if (userInfo != null && userInfo.isManagedProfile()) { 15700 b = true; 15701 } else { 15702 b = false; 15703 } 15704 mUserNeedsBadging.put(userId, b); 15705 return b; 15706 } 15707 return mUserNeedsBadging.valueAt(index); 15708 } 15709 15710 @Override 15711 public KeySet getKeySetByAlias(String packageName, String alias) { 15712 if (packageName == null || alias == null) { 15713 return null; 15714 } 15715 synchronized(mPackages) { 15716 final PackageParser.Package pkg = mPackages.get(packageName); 15717 if (pkg == null) { 15718 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15719 throw new IllegalArgumentException("Unknown package: " + packageName); 15720 } 15721 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15722 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15723 } 15724 } 15725 15726 @Override 15727 public KeySet getSigningKeySet(String packageName) { 15728 if (packageName == null) { 15729 return null; 15730 } 15731 synchronized(mPackages) { 15732 final PackageParser.Package pkg = mPackages.get(packageName); 15733 if (pkg == null) { 15734 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15735 throw new IllegalArgumentException("Unknown package: " + packageName); 15736 } 15737 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15738 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15739 throw new SecurityException("May not access signing KeySet of other apps."); 15740 } 15741 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15742 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15743 } 15744 } 15745 15746 @Override 15747 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15748 if (packageName == null || ks == null) { 15749 return false; 15750 } 15751 synchronized(mPackages) { 15752 final PackageParser.Package pkg = mPackages.get(packageName); 15753 if (pkg == null) { 15754 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15755 throw new IllegalArgumentException("Unknown package: " + packageName); 15756 } 15757 IBinder ksh = ks.getToken(); 15758 if (ksh instanceof KeySetHandle) { 15759 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15760 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15761 } 15762 return false; 15763 } 15764 } 15765 15766 @Override 15767 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15768 if (packageName == null || ks == null) { 15769 return false; 15770 } 15771 synchronized(mPackages) { 15772 final PackageParser.Package pkg = mPackages.get(packageName); 15773 if (pkg == null) { 15774 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15775 throw new IllegalArgumentException("Unknown package: " + packageName); 15776 } 15777 IBinder ksh = ks.getToken(); 15778 if (ksh instanceof KeySetHandle) { 15779 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15780 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15781 } 15782 return false; 15783 } 15784 } 15785 15786 public void getUsageStatsIfNoPackageUsageInfo() { 15787 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15788 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15789 if (usm == null) { 15790 throw new IllegalStateException("UsageStatsManager must be initialized"); 15791 } 15792 long now = System.currentTimeMillis(); 15793 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15794 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15795 String packageName = entry.getKey(); 15796 PackageParser.Package pkg = mPackages.get(packageName); 15797 if (pkg == null) { 15798 continue; 15799 } 15800 UsageStats usage = entry.getValue(); 15801 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15802 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15803 } 15804 } 15805 } 15806 15807 /** 15808 * Check and throw if the given before/after packages would be considered a 15809 * downgrade. 15810 */ 15811 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15812 throws PackageManagerException { 15813 if (after.versionCode < before.mVersionCode) { 15814 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15815 "Update version code " + after.versionCode + " is older than current " 15816 + before.mVersionCode); 15817 } else if (after.versionCode == before.mVersionCode) { 15818 if (after.baseRevisionCode < before.baseRevisionCode) { 15819 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15820 "Update base revision code " + after.baseRevisionCode 15821 + " is older than current " + before.baseRevisionCode); 15822 } 15823 15824 if (!ArrayUtils.isEmpty(after.splitNames)) { 15825 for (int i = 0; i < after.splitNames.length; i++) { 15826 final String splitName = after.splitNames[i]; 15827 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15828 if (j != -1) { 15829 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15830 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15831 "Update split " + splitName + " revision code " 15832 + after.splitRevisionCodes[i] + " is older than current " 15833 + before.splitRevisionCodes[j]); 15834 } 15835 } 15836 } 15837 } 15838 } 15839 } 15840 15841 private static class MoveCallbacks extends Handler { 15842 private static final int MSG_CREATED = 1; 15843 private static final int MSG_STATUS_CHANGED = 2; 15844 15845 private final RemoteCallbackList<IPackageMoveObserver> 15846 mCallbacks = new RemoteCallbackList<>(); 15847 15848 private final SparseIntArray mLastStatus = new SparseIntArray(); 15849 15850 public MoveCallbacks(Looper looper) { 15851 super(looper); 15852 } 15853 15854 public void register(IPackageMoveObserver callback) { 15855 mCallbacks.register(callback); 15856 } 15857 15858 public void unregister(IPackageMoveObserver callback) { 15859 mCallbacks.unregister(callback); 15860 } 15861 15862 @Override 15863 public void handleMessage(Message msg) { 15864 final SomeArgs args = (SomeArgs) msg.obj; 15865 final int n = mCallbacks.beginBroadcast(); 15866 for (int i = 0; i < n; i++) { 15867 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15868 try { 15869 invokeCallback(callback, msg.what, args); 15870 } catch (RemoteException ignored) { 15871 } 15872 } 15873 mCallbacks.finishBroadcast(); 15874 args.recycle(); 15875 } 15876 15877 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15878 throws RemoteException { 15879 switch (what) { 15880 case MSG_CREATED: { 15881 callback.onCreated(args.argi1, (Bundle) args.arg2); 15882 break; 15883 } 15884 case MSG_STATUS_CHANGED: { 15885 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15886 break; 15887 } 15888 } 15889 } 15890 15891 private void notifyCreated(int moveId, Bundle extras) { 15892 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15893 15894 final SomeArgs args = SomeArgs.obtain(); 15895 args.argi1 = moveId; 15896 args.arg2 = extras; 15897 obtainMessage(MSG_CREATED, args).sendToTarget(); 15898 } 15899 15900 private void notifyStatusChanged(int moveId, int status) { 15901 notifyStatusChanged(moveId, status, -1); 15902 } 15903 15904 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15905 Slog.v(TAG, "Move " + moveId + " status " + status); 15906 15907 final SomeArgs args = SomeArgs.obtain(); 15908 args.argi1 = moveId; 15909 args.argi2 = status; 15910 args.arg3 = estMillis; 15911 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15912 15913 synchronized (mLastStatus) { 15914 mLastStatus.put(moveId, status); 15915 } 15916 } 15917 } 15918 15919 private final class OnPermissionChangeListeners extends Handler { 15920 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15921 15922 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15923 new RemoteCallbackList<>(); 15924 15925 public OnPermissionChangeListeners(Looper looper) { 15926 super(looper); 15927 } 15928 15929 @Override 15930 public void handleMessage(Message msg) { 15931 switch (msg.what) { 15932 case MSG_ON_PERMISSIONS_CHANGED: { 15933 final int uid = msg.arg1; 15934 handleOnPermissionsChanged(uid); 15935 } break; 15936 } 15937 } 15938 15939 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15940 mPermissionListeners.register(listener); 15941 15942 } 15943 15944 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15945 mPermissionListeners.unregister(listener); 15946 } 15947 15948 public void onPermissionsChanged(int uid) { 15949 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15950 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15951 } 15952 } 15953 15954 private void handleOnPermissionsChanged(int uid) { 15955 final int count = mPermissionListeners.beginBroadcast(); 15956 try { 15957 for (int i = 0; i < count; i++) { 15958 IOnPermissionsChangeListener callback = mPermissionListeners 15959 .getBroadcastItem(i); 15960 try { 15961 callback.onPermissionsChanged(uid); 15962 } catch (RemoteException e) { 15963 Log.e(TAG, "Permission listener is dead", e); 15964 } 15965 } 15966 } finally { 15967 mPermissionListeners.finishBroadcast(); 15968 } 15969 } 15970 } 15971 15972 private class PackageManagerInternalImpl extends PackageManagerInternal { 15973 @Override 15974 public void setLocationPackagesProvider(PackagesProvider provider) { 15975 synchronized (mPackages) { 15976 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15977 } 15978 } 15979 15980 @Override 15981 public void setImePackagesProvider(PackagesProvider provider) { 15982 synchronized (mPackages) { 15983 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15984 } 15985 } 15986 15987 @Override 15988 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15989 synchronized (mPackages) { 15990 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15991 } 15992 } 15993 15994 @Override 15995 public void setSmsAppPackagesProvider(PackagesProvider provider) { 15996 synchronized (mPackages) { 15997 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 15998 } 15999 } 16000 16001 @Override 16002 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16003 synchronized (mPackages) { 16004 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16005 } 16006 } 16007 16008 @Override 16009 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16010 synchronized (mPackages) { 16011 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16012 } 16013 } 16014 16015 @Override 16016 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16017 synchronized (mPackages) { 16018 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16019 packageName, userId); 16020 } 16021 } 16022 16023 @Override 16024 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16025 synchronized (mPackages) { 16026 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16027 packageName, userId); 16028 } 16029 } 16030 } 16031 16032 @Override 16033 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16034 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16035 synchronized (mPackages) { 16036 final long identity = Binder.clearCallingIdentity(); 16037 try { 16038 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16039 packageNames, userId); 16040 } finally { 16041 Binder.restoreCallingIdentity(identity); 16042 } 16043 } 16044 } 16045 16046 private static void enforceSystemOrPhoneCaller(String tag) { 16047 int callingUid = Binder.getCallingUid(); 16048 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16049 throw new SecurityException( 16050 "Cannot call " + tag + " from UID " + callingUid); 16051 } 16052 } 16053} 16054