PackageManagerService.java revision 413020a6ca6e7d4eb7e61e3fe7d7a4c570a605db
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.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.PACKAGE_INFO_GID; 59import static android.os.Process.SYSTEM_UID; 60import static android.system.OsConstants.O_CREAT; 61import static android.system.OsConstants.O_RDWR; 62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 66import static com.android.internal.util.ArrayUtils.appendInt; 67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 72 73import android.Manifest; 74import android.app.ActivityManager; 75import android.app.ActivityManagerNative; 76import android.app.AppGlobals; 77import android.app.IActivityManager; 78import android.app.admin.IDevicePolicyManager; 79import android.app.backup.IBackupManager; 80import android.app.usage.UsageStats; 81import android.app.usage.UsageStatsManager; 82import android.content.BroadcastReceiver; 83import android.content.ComponentName; 84import android.content.Context; 85import android.content.IIntentReceiver; 86import android.content.Intent; 87import android.content.IntentFilter; 88import android.content.IntentSender; 89import android.content.IntentSender.SendIntentException; 90import android.content.ServiceConnection; 91import android.content.pm.ActivityInfo; 92import android.content.pm.ApplicationInfo; 93import android.content.pm.FeatureInfo; 94import android.content.pm.IOnPermissionsChangeListener; 95import android.content.pm.IPackageDataObserver; 96import android.content.pm.IPackageDeleteObserver; 97import android.content.pm.IPackageDeleteObserver2; 98import android.content.pm.IPackageInstallObserver2; 99import android.content.pm.IPackageInstaller; 100import android.content.pm.IPackageManager; 101import android.content.pm.IPackageMoveObserver; 102import android.content.pm.IPackageStatsObserver; 103import android.content.pm.IPackagesProvider; 104import android.content.pm.InstrumentationInfo; 105import android.content.pm.IntentFilterVerificationInfo; 106import android.content.pm.KeySet; 107import android.content.pm.ManifestDigest; 108import android.content.pm.PackageCleanItem; 109import android.content.pm.PackageInfo; 110import android.content.pm.PackageInfoLite; 111import android.content.pm.PackageInstaller; 112import android.content.pm.PackageManager; 113import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 114import android.content.pm.PackageManagerInternal; 115import android.content.pm.PackageParser; 116import android.content.pm.PackageParser.ActivityIntentInfo; 117import android.content.pm.PackageParser.PackageLite; 118import android.content.pm.PackageParser.PackageParserException; 119import android.content.pm.PackageStats; 120import android.content.pm.PackageUserState; 121import android.content.pm.ParceledListSlice; 122import android.content.pm.PermissionGroupInfo; 123import android.content.pm.PermissionInfo; 124import android.content.pm.ProviderInfo; 125import android.content.pm.ResolveInfo; 126import android.content.pm.ServiceInfo; 127import android.content.pm.Signature; 128import android.content.pm.UserInfo; 129import android.content.pm.VerificationParams; 130import android.content.pm.VerifierDeviceIdentity; 131import android.content.pm.VerifierInfo; 132import android.content.res.Resources; 133import android.hardware.display.DisplayManager; 134import android.net.Uri; 135import android.os.Binder; 136import android.os.Build; 137import android.os.Bundle; 138import android.os.Debug; 139import android.os.Environment; 140import android.os.Environment.UserEnvironment; 141import android.os.FileUtils; 142import android.os.Handler; 143import android.os.IBinder; 144import android.os.Looper; 145import android.os.Message; 146import android.os.Parcel; 147import android.os.ParcelFileDescriptor; 148import android.os.Process; 149import android.os.RemoteCallbackList; 150import android.os.RemoteException; 151import android.os.SELinux; 152import android.os.ServiceManager; 153import android.os.SystemClock; 154import android.os.SystemProperties; 155import android.os.UserHandle; 156import android.os.UserManager; 157import android.os.storage.IMountService; 158import android.os.storage.StorageEventListener; 159import android.os.storage.StorageManager; 160import android.os.storage.VolumeInfo; 161import android.os.storage.VolumeRecord; 162import android.security.KeyStore; 163import android.security.SystemKeyStore; 164import android.system.ErrnoException; 165import android.system.Os; 166import android.system.StructStat; 167import android.text.TextUtils; 168import android.text.format.DateUtils; 169import android.util.ArrayMap; 170import android.util.ArraySet; 171import android.util.AtomicFile; 172import android.util.DisplayMetrics; 173import android.util.EventLog; 174import android.util.ExceptionUtils; 175import android.util.Log; 176import android.util.LogPrinter; 177import android.util.MathUtils; 178import android.util.PrintStreamPrinter; 179import android.util.Slog; 180import android.util.SparseArray; 181import android.util.SparseBooleanArray; 182import android.util.SparseIntArray; 183import android.util.Xml; 184import android.view.Display; 185 186import dalvik.system.DexFile; 187import dalvik.system.VMRuntime; 188 189import libcore.io.IoUtils; 190import libcore.util.EmptyArray; 191 192import com.android.internal.R; 193import com.android.internal.app.IMediaContainerService; 194import com.android.internal.app.ResolverActivity; 195import com.android.internal.content.NativeLibraryHelper; 196import com.android.internal.content.PackageHelper; 197import com.android.internal.os.IParcelFileDescriptorFactory; 198import com.android.internal.os.SomeArgs; 199import com.android.internal.util.ArrayUtils; 200import com.android.internal.util.FastPrintWriter; 201import com.android.internal.util.FastXmlSerializer; 202import com.android.internal.util.IndentingPrintWriter; 203import com.android.internal.util.Preconditions; 204import com.android.server.EventLogTags; 205import com.android.server.FgThread; 206import com.android.server.IntentResolver; 207import com.android.server.LocalServices; 208import com.android.server.ServiceThread; 209import com.android.server.SystemConfig; 210import com.android.server.Watchdog; 211import com.android.server.pm.Settings.DatabaseVersion; 212import com.android.server.pm.PermissionsState.PermissionState; 213import com.android.server.storage.DeviceStorageMonitorInternal; 214 215import org.xmlpull.v1.XmlPullParser; 216import org.xmlpull.v1.XmlPullParserException; 217import org.xmlpull.v1.XmlSerializer; 218 219import java.io.BufferedInputStream; 220import java.io.BufferedOutputStream; 221import java.io.BufferedReader; 222import java.io.ByteArrayInputStream; 223import java.io.ByteArrayOutputStream; 224import java.io.File; 225import java.io.FileDescriptor; 226import java.io.FileNotFoundException; 227import java.io.FileOutputStream; 228import java.io.FileReader; 229import java.io.FilenameFilter; 230import java.io.IOException; 231import java.io.InputStream; 232import java.io.PrintWriter; 233import java.nio.charset.StandardCharsets; 234import java.security.NoSuchAlgorithmException; 235import java.security.PublicKey; 236import java.security.cert.CertificateEncodingException; 237import java.security.cert.CertificateException; 238import java.text.SimpleDateFormat; 239import java.util.ArrayList; 240import java.util.Arrays; 241import java.util.Collection; 242import java.util.Collections; 243import java.util.Comparator; 244import java.util.Date; 245import java.util.Iterator; 246import java.util.List; 247import java.util.Map; 248import java.util.Objects; 249import java.util.Set; 250import java.util.concurrent.CountDownLatch; 251import java.util.concurrent.TimeUnit; 252import java.util.concurrent.atomic.AtomicBoolean; 253import java.util.concurrent.atomic.AtomicInteger; 254import java.util.concurrent.atomic.AtomicLong; 255 256/** 257 * Keep track of all those .apks everywhere. 258 * 259 * This is very central to the platform's security; please run the unit 260 * tests whenever making modifications here: 261 * 262mmm frameworks/base/tests/AndroidTests 263adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 264adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 265 * 266 * {@hide} 267 */ 268public class PackageManagerService extends IPackageManager.Stub { 269 static final String TAG = "PackageManager"; 270 static final boolean DEBUG_SETTINGS = false; 271 static final boolean DEBUG_PREFERRED = false; 272 static final boolean DEBUG_UPGRADE = false; 273 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 274 private static final boolean DEBUG_BACKUP = true; 275 private static final boolean DEBUG_INSTALL = false; 276 private static final boolean DEBUG_REMOVE = false; 277 private static final boolean DEBUG_BROADCASTS = false; 278 private static final boolean DEBUG_SHOW_INFO = false; 279 private static final boolean DEBUG_PACKAGE_INFO = false; 280 private static final boolean DEBUG_INTENT_MATCHING = false; 281 private static final boolean DEBUG_PACKAGE_SCANNING = false; 282 private static final boolean DEBUG_VERIFY = false; 283 private static final boolean DEBUG_DEXOPT = false; 284 private static final boolean DEBUG_ABI_SELECTION = false; 285 286 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 287 288 private static final int RADIO_UID = Process.PHONE_UID; 289 private static final int LOG_UID = Process.LOG_UID; 290 private static final int NFC_UID = Process.NFC_UID; 291 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 292 private static final int SHELL_UID = Process.SHELL_UID; 293 294 // Cap the size of permission trees that 3rd party apps can define 295 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 296 297 // Suffix used during package installation when copying/moving 298 // package apks to install directory. 299 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 300 301 static final int SCAN_NO_DEX = 1<<1; 302 static final int SCAN_FORCE_DEX = 1<<2; 303 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 304 static final int SCAN_NEW_INSTALL = 1<<4; 305 static final int SCAN_NO_PATHS = 1<<5; 306 static final int SCAN_UPDATE_TIME = 1<<6; 307 static final int SCAN_DEFER_DEX = 1<<7; 308 static final int SCAN_BOOTING = 1<<8; 309 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 310 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 311 static final int SCAN_REQUIRE_KNOWN = 1<<12; 312 static final int SCAN_MOVE = 1<<13; 313 static final int SCAN_INITIAL = 1<<14; 314 315 static final int REMOVE_CHATTY = 1<<16; 316 317 private static final int[] EMPTY_INT_ARRAY = new int[0]; 318 319 /** 320 * Timeout (in milliseconds) after which the watchdog should declare that 321 * our handler thread is wedged. The usual default for such things is one 322 * minute but we sometimes do very lengthy I/O operations on this thread, 323 * such as installing multi-gigabyte applications, so ours needs to be longer. 324 */ 325 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 326 327 /** 328 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 329 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 330 * settings entry if available, otherwise we use the hardcoded default. If it's been 331 * more than this long since the last fstrim, we force one during the boot sequence. 332 * 333 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 334 * one gets run at the next available charging+idle time. This final mandatory 335 * no-fstrim check kicks in only of the other scheduling criteria is never met. 336 */ 337 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 338 339 /** 340 * Whether verification is enabled by default. 341 */ 342 private static final boolean DEFAULT_VERIFY_ENABLE = true; 343 344 /** 345 * The default maximum time to wait for the verification agent to return in 346 * milliseconds. 347 */ 348 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 349 350 /** 351 * The default response for package verification timeout. 352 * 353 * This can be either PackageManager.VERIFICATION_ALLOW or 354 * PackageManager.VERIFICATION_REJECT. 355 */ 356 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 357 358 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 359 360 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 361 DEFAULT_CONTAINER_PACKAGE, 362 "com.android.defcontainer.DefaultContainerService"); 363 364 private static final String KILL_APP_REASON_GIDS_CHANGED = 365 "permission grant or revoke changed gids"; 366 367 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 368 "permissions revoked"; 369 370 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 371 372 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 373 374 /** Permission grant: not grant the permission. */ 375 private static final int GRANT_DENIED = 1; 376 377 /** Permission grant: grant the permission as an install permission. */ 378 private static final int GRANT_INSTALL = 2; 379 380 /** Permission grant: grant the permission as an install permission for a legacy app. */ 381 private static final int GRANT_INSTALL_LEGACY = 3; 382 383 /** Permission grant: grant the permission as a runtime one. */ 384 private static final int GRANT_RUNTIME = 4; 385 386 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 387 private static final int GRANT_UPGRADE = 5; 388 389 final ServiceThread mHandlerThread; 390 391 final PackageHandler mHandler; 392 393 /** 394 * Messages for {@link #mHandler} that need to wait for system ready before 395 * being dispatched. 396 */ 397 private ArrayList<Message> mPostSystemReadyMessages; 398 399 final int mSdkVersion = Build.VERSION.SDK_INT; 400 401 final Context mContext; 402 final boolean mFactoryTest; 403 final boolean mOnlyCore; 404 final boolean mLazyDexOpt; 405 final long mDexOptLRUThresholdInMills; 406 final DisplayMetrics mMetrics; 407 final int mDefParseFlags; 408 final String[] mSeparateProcesses; 409 final boolean mIsUpgrade; 410 411 // This is where all application persistent data goes. 412 final File mAppDataDir; 413 414 // This is where all application persistent data goes for secondary users. 415 final File mUserAppDataDir; 416 417 /** The location for ASEC container files on internal storage. */ 418 final String mAsecInternalPath; 419 420 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 421 // LOCK HELD. Can be called with mInstallLock held. 422 final Installer mInstaller; 423 424 /** Directory where installed third-party apps stored */ 425 final File mAppInstallDir; 426 427 /** 428 * Directory to which applications installed internally have their 429 * 32 bit native libraries copied. 430 */ 431 private File mAppLib32InstallDir; 432 433 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 434 // apps. 435 final File mDrmAppPrivateInstallDir; 436 437 // ---------------------------------------------------------------- 438 439 // Lock for state used when installing and doing other long running 440 // operations. Methods that must be called with this lock held have 441 // the suffix "LI". 442 final Object mInstallLock = new Object(); 443 444 // ---------------------------------------------------------------- 445 446 // Keys are String (package name), values are Package. This also serves 447 // as the lock for the global state. Methods that must be called with 448 // this lock held have the prefix "LP". 449 final ArrayMap<String, PackageParser.Package> mPackages = 450 new ArrayMap<String, PackageParser.Package>(); 451 452 // Tracks available target package names -> overlay package paths. 453 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 454 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 455 456 final Settings mSettings; 457 boolean mRestoredSettings; 458 459 // System configuration read by SystemConfig. 460 final int[] mGlobalGids; 461 final SparseArray<ArraySet<String>> mSystemPermissions; 462 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 463 464 // If mac_permissions.xml was found for seinfo labeling. 465 boolean mFoundPolicyFile; 466 467 // If a recursive restorecon of /data/data/<pkg> is needed. 468 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 469 470 public static final class SharedLibraryEntry { 471 public final String path; 472 public final String apk; 473 474 SharedLibraryEntry(String _path, String _apk) { 475 path = _path; 476 apk = _apk; 477 } 478 } 479 480 // Currently known shared libraries. 481 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 482 new ArrayMap<String, SharedLibraryEntry>(); 483 484 // All available activities, for your resolving pleasure. 485 final ActivityIntentResolver mActivities = 486 new ActivityIntentResolver(); 487 488 // All available receivers, for your resolving pleasure. 489 final ActivityIntentResolver mReceivers = 490 new ActivityIntentResolver(); 491 492 // All available services, for your resolving pleasure. 493 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 494 495 // All available providers, for your resolving pleasure. 496 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 497 498 // Mapping from provider base names (first directory in content URI codePath) 499 // to the provider information. 500 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 501 new ArrayMap<String, PackageParser.Provider>(); 502 503 // Mapping from instrumentation class names to info about them. 504 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 505 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 506 507 // Mapping from permission names to info about them. 508 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 509 new ArrayMap<String, PackageParser.PermissionGroup>(); 510 511 // Packages whose data we have transfered into another package, thus 512 // should no longer exist. 513 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 514 515 // Broadcast actions that are only available to the system. 516 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 517 518 /** List of packages waiting for verification. */ 519 final SparseArray<PackageVerificationState> mPendingVerification 520 = new SparseArray<PackageVerificationState>(); 521 522 /** Set of packages associated with each app op permission. */ 523 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 524 525 final PackageInstallerService mInstallerService; 526 527 private final PackageDexOptimizer mPackageDexOptimizer; 528 529 private AtomicInteger mNextMoveId = new AtomicInteger(); 530 private final MoveCallbacks mMoveCallbacks; 531 532 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 533 534 // Cache of users who need badging. 535 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 536 537 /** Token for keys in mPendingVerification. */ 538 private int mPendingVerificationToken = 0; 539 540 volatile boolean mSystemReady; 541 volatile boolean mSafeMode; 542 volatile boolean mHasSystemUidErrors; 543 544 ApplicationInfo mAndroidApplication; 545 final ActivityInfo mResolveActivity = new ActivityInfo(); 546 final ResolveInfo mResolveInfo = new ResolveInfo(); 547 ComponentName mResolveComponentName; 548 PackageParser.Package mPlatformPackage; 549 ComponentName mCustomResolverComponentName; 550 551 boolean mResolverReplaced = false; 552 553 private final ComponentName mIntentFilterVerifierComponent; 554 private int mIntentFilterVerificationToken = 0; 555 556 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 557 = new SparseArray<IntentFilterVerificationState>(); 558 559 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 560 new DefaultPermissionGrantPolicy(this); 561 562 private static class IFVerificationParams { 563 PackageParser.Package pkg; 564 boolean replacing; 565 int userId; 566 int verifierUid; 567 568 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 569 int _userId, int _verifierUid) { 570 pkg = _pkg; 571 replacing = _replacing; 572 userId = _userId; 573 replacing = _replacing; 574 verifierUid = _verifierUid; 575 } 576 } 577 578 private interface IntentFilterVerifier<T extends IntentFilter> { 579 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 580 T filter, String packageName); 581 void startVerifications(int userId); 582 void receiveVerificationResponse(int verificationId); 583 } 584 585 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 586 private Context mContext; 587 private ComponentName mIntentFilterVerifierComponent; 588 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 589 590 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 591 mContext = context; 592 mIntentFilterVerifierComponent = verifierComponent; 593 } 594 595 private String getDefaultScheme() { 596 return IntentFilter.SCHEME_HTTPS; 597 } 598 599 @Override 600 public void startVerifications(int userId) { 601 // Launch verifications requests 602 int count = mCurrentIntentFilterVerifications.size(); 603 for (int n=0; n<count; n++) { 604 int verificationId = mCurrentIntentFilterVerifications.get(n); 605 final IntentFilterVerificationState ivs = 606 mIntentFilterVerificationStates.get(verificationId); 607 608 String packageName = ivs.getPackageName(); 609 610 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 611 final int filterCount = filters.size(); 612 ArraySet<String> domainsSet = new ArraySet<>(); 613 for (int m=0; m<filterCount; m++) { 614 PackageParser.ActivityIntentInfo filter = filters.get(m); 615 domainsSet.addAll(filter.getHostsList()); 616 } 617 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 618 synchronized (mPackages) { 619 if (mSettings.createIntentFilterVerificationIfNeededLPw( 620 packageName, domainsList) != null) { 621 scheduleWriteSettingsLocked(); 622 } 623 } 624 sendVerificationRequest(userId, verificationId, ivs); 625 } 626 mCurrentIntentFilterVerifications.clear(); 627 } 628 629 private void sendVerificationRequest(int userId, int verificationId, 630 IntentFilterVerificationState ivs) { 631 632 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 633 verificationIntent.putExtra( 634 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 635 verificationId); 636 verificationIntent.putExtra( 637 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 638 getDefaultScheme()); 639 verificationIntent.putExtra( 640 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 641 ivs.getHostsString()); 642 verificationIntent.putExtra( 643 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 644 ivs.getPackageName()); 645 verificationIntent.setComponent(mIntentFilterVerifierComponent); 646 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 647 648 UserHandle user = new UserHandle(userId); 649 mContext.sendBroadcastAsUser(verificationIntent, user); 650 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 651 "Sending IntentFilter verification broadcast"); 652 } 653 654 public void receiveVerificationResponse(int verificationId) { 655 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 656 657 final boolean verified = ivs.isVerified(); 658 659 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 660 final int count = filters.size(); 661 if (DEBUG_DOMAIN_VERIFICATION) { 662 Slog.i(TAG, "Received verification response " + verificationId 663 + " for " + count + " filters, verified=" + verified); 664 } 665 for (int n=0; n<count; n++) { 666 PackageParser.ActivityIntentInfo filter = filters.get(n); 667 filter.setVerified(verified); 668 669 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 670 + " verified with result:" + verified + " and hosts:" 671 + ivs.getHostsString()); 672 } 673 674 mIntentFilterVerificationStates.remove(verificationId); 675 676 final String packageName = ivs.getPackageName(); 677 IntentFilterVerificationInfo ivi = null; 678 679 synchronized (mPackages) { 680 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 681 } 682 if (ivi == null) { 683 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 684 + verificationId + " packageName:" + packageName); 685 return; 686 } 687 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 688 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 689 690 synchronized (mPackages) { 691 if (verified) { 692 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 693 } else { 694 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 695 } 696 scheduleWriteSettingsLocked(); 697 698 final int userId = ivs.getUserId(); 699 if (userId != UserHandle.USER_ALL) { 700 final int userStatus = 701 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 702 703 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 704 boolean needUpdate = false; 705 706 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 707 // already been set by the User thru the Disambiguation dialog 708 switch (userStatus) { 709 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 710 if (verified) { 711 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 712 } else { 713 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 714 } 715 needUpdate = true; 716 break; 717 718 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 719 if (verified) { 720 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 721 needUpdate = true; 722 } 723 break; 724 725 default: 726 // Nothing to do 727 } 728 729 if (needUpdate) { 730 mSettings.updateIntentFilterVerificationStatusLPw( 731 packageName, updatedStatus, userId); 732 scheduleWritePackageRestrictionsLocked(userId); 733 } 734 } 735 } 736 } 737 738 @Override 739 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 740 ActivityIntentInfo filter, String packageName) { 741 if (!hasValidDomains(filter)) { 742 return false; 743 } 744 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 745 if (ivs == null) { 746 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 747 packageName); 748 } 749 if (DEBUG_DOMAIN_VERIFICATION) { 750 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 751 } 752 ivs.addFilter(filter); 753 return true; 754 } 755 756 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 757 int userId, int verificationId, String packageName) { 758 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 759 verifierUid, userId, packageName); 760 ivs.setPendingState(); 761 synchronized (mPackages) { 762 mIntentFilterVerificationStates.append(verificationId, ivs); 763 mCurrentIntentFilterVerifications.add(verificationId); 764 } 765 return ivs; 766 } 767 } 768 769 private static boolean hasValidDomains(ActivityIntentInfo filter) { 770 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 771 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 772 if (!hasHTTPorHTTPS) { 773 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 774 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 775 return false; 776 } 777 return true; 778 } 779 780 private IntentFilterVerifier mIntentFilterVerifier; 781 782 // Set of pending broadcasts for aggregating enable/disable of components. 783 static class PendingPackageBroadcasts { 784 // for each user id, a map of <package name -> components within that package> 785 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 786 787 public PendingPackageBroadcasts() { 788 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 789 } 790 791 public ArrayList<String> get(int userId, String packageName) { 792 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 793 return packages.get(packageName); 794 } 795 796 public void put(int userId, String packageName, ArrayList<String> components) { 797 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 798 packages.put(packageName, components); 799 } 800 801 public void remove(int userId, String packageName) { 802 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 803 if (packages != null) { 804 packages.remove(packageName); 805 } 806 } 807 808 public void remove(int userId) { 809 mUidMap.remove(userId); 810 } 811 812 public int userIdCount() { 813 return mUidMap.size(); 814 } 815 816 public int userIdAt(int n) { 817 return mUidMap.keyAt(n); 818 } 819 820 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 821 return mUidMap.get(userId); 822 } 823 824 public int size() { 825 // total number of pending broadcast entries across all userIds 826 int num = 0; 827 for (int i = 0; i< mUidMap.size(); i++) { 828 num += mUidMap.valueAt(i).size(); 829 } 830 return num; 831 } 832 833 public void clear() { 834 mUidMap.clear(); 835 } 836 837 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 838 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 839 if (map == null) { 840 map = new ArrayMap<String, ArrayList<String>>(); 841 mUidMap.put(userId, map); 842 } 843 return map; 844 } 845 } 846 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 847 848 // Service Connection to remote media container service to copy 849 // package uri's from external media onto secure containers 850 // or internal storage. 851 private IMediaContainerService mContainerService = null; 852 853 static final int SEND_PENDING_BROADCAST = 1; 854 static final int MCS_BOUND = 3; 855 static final int END_COPY = 4; 856 static final int INIT_COPY = 5; 857 static final int MCS_UNBIND = 6; 858 static final int START_CLEANING_PACKAGE = 7; 859 static final int FIND_INSTALL_LOC = 8; 860 static final int POST_INSTALL = 9; 861 static final int MCS_RECONNECT = 10; 862 static final int MCS_GIVE_UP = 11; 863 static final int UPDATED_MEDIA_STATUS = 12; 864 static final int WRITE_SETTINGS = 13; 865 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 866 static final int PACKAGE_VERIFIED = 15; 867 static final int CHECK_PENDING_VERIFICATION = 16; 868 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 869 static final int INTENT_FILTER_VERIFIED = 18; 870 871 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 872 873 // Delay time in millisecs 874 static final int BROADCAST_DELAY = 10 * 1000; 875 876 static UserManagerService sUserManager; 877 878 // Stores a list of users whose package restrictions file needs to be updated 879 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 880 881 final private DefaultContainerConnection mDefContainerConn = 882 new DefaultContainerConnection(); 883 class DefaultContainerConnection implements ServiceConnection { 884 public void onServiceConnected(ComponentName name, IBinder service) { 885 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 886 IMediaContainerService imcs = 887 IMediaContainerService.Stub.asInterface(service); 888 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 889 } 890 891 public void onServiceDisconnected(ComponentName name) { 892 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 893 } 894 } 895 896 // Recordkeeping of restore-after-install operations that are currently in flight 897 // between the Package Manager and the Backup Manager 898 class PostInstallData { 899 public InstallArgs args; 900 public PackageInstalledInfo res; 901 902 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 903 args = _a; 904 res = _r; 905 } 906 } 907 908 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 909 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 910 911 // XML tags for backup/restore of various bits of state 912 private static final String TAG_PREFERRED_BACKUP = "pa"; 913 private static final String TAG_DEFAULT_APPS = "da"; 914 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 915 916 private final String mRequiredVerifierPackage; 917 918 private final PackageUsage mPackageUsage = new PackageUsage(); 919 920 private class PackageUsage { 921 private static final int WRITE_INTERVAL 922 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 923 924 private final Object mFileLock = new Object(); 925 private final AtomicLong mLastWritten = new AtomicLong(0); 926 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 927 928 private boolean mIsHistoricalPackageUsageAvailable = true; 929 930 boolean isHistoricalPackageUsageAvailable() { 931 return mIsHistoricalPackageUsageAvailable; 932 } 933 934 void write(boolean force) { 935 if (force) { 936 writeInternal(); 937 return; 938 } 939 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 940 && !DEBUG_DEXOPT) { 941 return; 942 } 943 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 944 new Thread("PackageUsage_DiskWriter") { 945 @Override 946 public void run() { 947 try { 948 writeInternal(); 949 } finally { 950 mBackgroundWriteRunning.set(false); 951 } 952 } 953 }.start(); 954 } 955 } 956 957 private void writeInternal() { 958 synchronized (mPackages) { 959 synchronized (mFileLock) { 960 AtomicFile file = getFile(); 961 FileOutputStream f = null; 962 try { 963 f = file.startWrite(); 964 BufferedOutputStream out = new BufferedOutputStream(f); 965 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 966 StringBuilder sb = new StringBuilder(); 967 for (PackageParser.Package pkg : mPackages.values()) { 968 if (pkg.mLastPackageUsageTimeInMills == 0) { 969 continue; 970 } 971 sb.setLength(0); 972 sb.append(pkg.packageName); 973 sb.append(' '); 974 sb.append((long)pkg.mLastPackageUsageTimeInMills); 975 sb.append('\n'); 976 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 977 } 978 out.flush(); 979 file.finishWrite(f); 980 } catch (IOException e) { 981 if (f != null) { 982 file.failWrite(f); 983 } 984 Log.e(TAG, "Failed to write package usage times", e); 985 } 986 } 987 } 988 mLastWritten.set(SystemClock.elapsedRealtime()); 989 } 990 991 void readLP() { 992 synchronized (mFileLock) { 993 AtomicFile file = getFile(); 994 BufferedInputStream in = null; 995 try { 996 in = new BufferedInputStream(file.openRead()); 997 StringBuffer sb = new StringBuffer(); 998 while (true) { 999 String packageName = readToken(in, sb, ' '); 1000 if (packageName == null) { 1001 break; 1002 } 1003 String timeInMillisString = readToken(in, sb, '\n'); 1004 if (timeInMillisString == null) { 1005 throw new IOException("Failed to find last usage time for package " 1006 + packageName); 1007 } 1008 PackageParser.Package pkg = mPackages.get(packageName); 1009 if (pkg == null) { 1010 continue; 1011 } 1012 long timeInMillis; 1013 try { 1014 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1015 } catch (NumberFormatException e) { 1016 throw new IOException("Failed to parse " + timeInMillisString 1017 + " as a long.", e); 1018 } 1019 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1020 } 1021 } catch (FileNotFoundException expected) { 1022 mIsHistoricalPackageUsageAvailable = false; 1023 } catch (IOException e) { 1024 Log.w(TAG, "Failed to read package usage times", e); 1025 } finally { 1026 IoUtils.closeQuietly(in); 1027 } 1028 } 1029 mLastWritten.set(SystemClock.elapsedRealtime()); 1030 } 1031 1032 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1033 throws IOException { 1034 sb.setLength(0); 1035 while (true) { 1036 int ch = in.read(); 1037 if (ch == -1) { 1038 if (sb.length() == 0) { 1039 return null; 1040 } 1041 throw new IOException("Unexpected EOF"); 1042 } 1043 if (ch == endOfToken) { 1044 return sb.toString(); 1045 } 1046 sb.append((char)ch); 1047 } 1048 } 1049 1050 private AtomicFile getFile() { 1051 File dataDir = Environment.getDataDirectory(); 1052 File systemDir = new File(dataDir, "system"); 1053 File fname = new File(systemDir, "package-usage.list"); 1054 return new AtomicFile(fname); 1055 } 1056 } 1057 1058 class PackageHandler extends Handler { 1059 private boolean mBound = false; 1060 final ArrayList<HandlerParams> mPendingInstalls = 1061 new ArrayList<HandlerParams>(); 1062 1063 private boolean connectToService() { 1064 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1065 " DefaultContainerService"); 1066 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1067 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1068 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1069 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1070 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1071 mBound = true; 1072 return true; 1073 } 1074 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1075 return false; 1076 } 1077 1078 private void disconnectService() { 1079 mContainerService = null; 1080 mBound = false; 1081 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1082 mContext.unbindService(mDefContainerConn); 1083 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1084 } 1085 1086 PackageHandler(Looper looper) { 1087 super(looper); 1088 } 1089 1090 public void handleMessage(Message msg) { 1091 try { 1092 doHandleMessage(msg); 1093 } finally { 1094 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1095 } 1096 } 1097 1098 void doHandleMessage(Message msg) { 1099 switch (msg.what) { 1100 case INIT_COPY: { 1101 HandlerParams params = (HandlerParams) msg.obj; 1102 int idx = mPendingInstalls.size(); 1103 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1104 // If a bind was already initiated we dont really 1105 // need to do anything. The pending install 1106 // will be processed later on. 1107 if (!mBound) { 1108 // If this is the only one pending we might 1109 // have to bind to the service again. 1110 if (!connectToService()) { 1111 Slog.e(TAG, "Failed to bind to media container service"); 1112 params.serviceError(); 1113 return; 1114 } else { 1115 // Once we bind to the service, the first 1116 // pending request will be processed. 1117 mPendingInstalls.add(idx, params); 1118 } 1119 } else { 1120 mPendingInstalls.add(idx, params); 1121 // Already bound to the service. Just make 1122 // sure we trigger off processing the first request. 1123 if (idx == 0) { 1124 mHandler.sendEmptyMessage(MCS_BOUND); 1125 } 1126 } 1127 break; 1128 } 1129 case MCS_BOUND: { 1130 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1131 if (msg.obj != null) { 1132 mContainerService = (IMediaContainerService) msg.obj; 1133 } 1134 if (mContainerService == null) { 1135 if (!mBound) { 1136 // Something seriously wrong since we are not bound and we are not 1137 // waiting for connection. Bail out. 1138 Slog.e(TAG, "Cannot bind to media container service"); 1139 for (HandlerParams params : mPendingInstalls) { 1140 // Indicate service bind error 1141 params.serviceError(); 1142 } 1143 mPendingInstalls.clear(); 1144 } else { 1145 Slog.w(TAG, "Waiting to connect to media container service"); 1146 } 1147 } else if (mPendingInstalls.size() > 0) { 1148 HandlerParams params = mPendingInstalls.get(0); 1149 if (params != null) { 1150 if (params.startCopy()) { 1151 // We are done... look for more work or to 1152 // go idle. 1153 if (DEBUG_SD_INSTALL) Log.i(TAG, 1154 "Checking for more work or unbind..."); 1155 // Delete pending install 1156 if (mPendingInstalls.size() > 0) { 1157 mPendingInstalls.remove(0); 1158 } 1159 if (mPendingInstalls.size() == 0) { 1160 if (mBound) { 1161 if (DEBUG_SD_INSTALL) Log.i(TAG, 1162 "Posting delayed MCS_UNBIND"); 1163 removeMessages(MCS_UNBIND); 1164 Message ubmsg = obtainMessage(MCS_UNBIND); 1165 // Unbind after a little delay, to avoid 1166 // continual thrashing. 1167 sendMessageDelayed(ubmsg, 10000); 1168 } 1169 } else { 1170 // There are more pending requests in queue. 1171 // Just post MCS_BOUND message to trigger processing 1172 // of next pending install. 1173 if (DEBUG_SD_INSTALL) Log.i(TAG, 1174 "Posting MCS_BOUND for next work"); 1175 mHandler.sendEmptyMessage(MCS_BOUND); 1176 } 1177 } 1178 } 1179 } else { 1180 // Should never happen ideally. 1181 Slog.w(TAG, "Empty queue"); 1182 } 1183 break; 1184 } 1185 case MCS_RECONNECT: { 1186 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1187 if (mPendingInstalls.size() > 0) { 1188 if (mBound) { 1189 disconnectService(); 1190 } 1191 if (!connectToService()) { 1192 Slog.e(TAG, "Failed to bind to media container service"); 1193 for (HandlerParams params : mPendingInstalls) { 1194 // Indicate service bind error 1195 params.serviceError(); 1196 } 1197 mPendingInstalls.clear(); 1198 } 1199 } 1200 break; 1201 } 1202 case MCS_UNBIND: { 1203 // If there is no actual work left, then time to unbind. 1204 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1205 1206 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1207 if (mBound) { 1208 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1209 1210 disconnectService(); 1211 } 1212 } else if (mPendingInstalls.size() > 0) { 1213 // There are more pending requests in queue. 1214 // Just post MCS_BOUND message to trigger processing 1215 // of next pending install. 1216 mHandler.sendEmptyMessage(MCS_BOUND); 1217 } 1218 1219 break; 1220 } 1221 case MCS_GIVE_UP: { 1222 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1223 mPendingInstalls.remove(0); 1224 break; 1225 } 1226 case SEND_PENDING_BROADCAST: { 1227 String packages[]; 1228 ArrayList<String> components[]; 1229 int size = 0; 1230 int uids[]; 1231 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1232 synchronized (mPackages) { 1233 if (mPendingBroadcasts == null) { 1234 return; 1235 } 1236 size = mPendingBroadcasts.size(); 1237 if (size <= 0) { 1238 // Nothing to be done. Just return 1239 return; 1240 } 1241 packages = new String[size]; 1242 components = new ArrayList[size]; 1243 uids = new int[size]; 1244 int i = 0; // filling out the above arrays 1245 1246 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1247 int packageUserId = mPendingBroadcasts.userIdAt(n); 1248 Iterator<Map.Entry<String, ArrayList<String>>> it 1249 = mPendingBroadcasts.packagesForUserId(packageUserId) 1250 .entrySet().iterator(); 1251 while (it.hasNext() && i < size) { 1252 Map.Entry<String, ArrayList<String>> ent = it.next(); 1253 packages[i] = ent.getKey(); 1254 components[i] = ent.getValue(); 1255 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1256 uids[i] = (ps != null) 1257 ? UserHandle.getUid(packageUserId, ps.appId) 1258 : -1; 1259 i++; 1260 } 1261 } 1262 size = i; 1263 mPendingBroadcasts.clear(); 1264 } 1265 // Send broadcasts 1266 for (int i = 0; i < size; i++) { 1267 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1268 } 1269 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1270 break; 1271 } 1272 case START_CLEANING_PACKAGE: { 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1274 final String packageName = (String)msg.obj; 1275 final int userId = msg.arg1; 1276 final boolean andCode = msg.arg2 != 0; 1277 synchronized (mPackages) { 1278 if (userId == UserHandle.USER_ALL) { 1279 int[] users = sUserManager.getUserIds(); 1280 for (int user : users) { 1281 mSettings.addPackageToCleanLPw( 1282 new PackageCleanItem(user, packageName, andCode)); 1283 } 1284 } else { 1285 mSettings.addPackageToCleanLPw( 1286 new PackageCleanItem(userId, packageName, andCode)); 1287 } 1288 } 1289 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1290 startCleaningPackages(); 1291 } break; 1292 case POST_INSTALL: { 1293 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1294 PostInstallData data = mRunningInstalls.get(msg.arg1); 1295 mRunningInstalls.delete(msg.arg1); 1296 boolean deleteOld = false; 1297 1298 if (data != null) { 1299 InstallArgs args = data.args; 1300 PackageInstalledInfo res = data.res; 1301 1302 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1303 res.removedInfo.sendBroadcast(false, true, false); 1304 Bundle extras = new Bundle(1); 1305 extras.putInt(Intent.EXTRA_UID, res.uid); 1306 1307 // Now that we successfully installed the package, grant runtime 1308 // permissions if requested before broadcasting the install. 1309 if ((args.installFlags 1310 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1311 grantRequestedRuntimePermissions(res.pkg, 1312 args.user.getIdentifier()); 1313 } 1314 1315 // Determine the set of users who are adding this 1316 // package for the first time vs. those who are seeing 1317 // an update. 1318 int[] firstUsers; 1319 int[] updateUsers = new int[0]; 1320 if (res.origUsers == null || res.origUsers.length == 0) { 1321 firstUsers = res.newUsers; 1322 } else { 1323 firstUsers = new int[0]; 1324 for (int i=0; i<res.newUsers.length; i++) { 1325 int user = res.newUsers[i]; 1326 boolean isNew = true; 1327 for (int j=0; j<res.origUsers.length; j++) { 1328 if (res.origUsers[j] == user) { 1329 isNew = false; 1330 break; 1331 } 1332 } 1333 if (isNew) { 1334 int[] newFirst = new int[firstUsers.length+1]; 1335 System.arraycopy(firstUsers, 0, newFirst, 0, 1336 firstUsers.length); 1337 newFirst[firstUsers.length] = user; 1338 firstUsers = newFirst; 1339 } else { 1340 int[] newUpdate = new int[updateUsers.length+1]; 1341 System.arraycopy(updateUsers, 0, newUpdate, 0, 1342 updateUsers.length); 1343 newUpdate[updateUsers.length] = user; 1344 updateUsers = newUpdate; 1345 } 1346 } 1347 } 1348 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1349 res.pkg.applicationInfo.packageName, 1350 extras, null, null, firstUsers); 1351 final boolean update = res.removedInfo.removedPackage != null; 1352 if (update) { 1353 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1354 } 1355 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1356 res.pkg.applicationInfo.packageName, 1357 extras, null, null, updateUsers); 1358 if (update) { 1359 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1360 res.pkg.applicationInfo.packageName, 1361 extras, null, null, updateUsers); 1362 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1363 null, null, 1364 res.pkg.applicationInfo.packageName, null, updateUsers); 1365 1366 // treat asec-hosted packages like removable media on upgrade 1367 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1368 if (DEBUG_INSTALL) { 1369 Slog.i(TAG, "upgrading pkg " + res.pkg 1370 + " is ASEC-hosted -> AVAILABLE"); 1371 } 1372 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1373 ArrayList<String> pkgList = new ArrayList<String>(1); 1374 pkgList.add(res.pkg.applicationInfo.packageName); 1375 sendResourcesChangedBroadcast(true, true, 1376 pkgList,uidArray, null); 1377 } 1378 } 1379 if (res.removedInfo.args != null) { 1380 // Remove the replaced package's older resources safely now 1381 deleteOld = true; 1382 } 1383 1384 // Log current value of "unknown sources" setting 1385 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1386 getUnknownSourcesSettings()); 1387 } 1388 // Force a gc to clear up things 1389 Runtime.getRuntime().gc(); 1390 // We delete after a gc for applications on sdcard. 1391 if (deleteOld) { 1392 synchronized (mInstallLock) { 1393 res.removedInfo.args.doPostDeleteLI(true); 1394 } 1395 } 1396 if (args.observer != null) { 1397 try { 1398 Bundle extras = extrasForInstallResult(res); 1399 args.observer.onPackageInstalled(res.name, res.returnCode, 1400 res.returnMsg, extras); 1401 } catch (RemoteException e) { 1402 Slog.i(TAG, "Observer no longer exists."); 1403 } 1404 } 1405 } else { 1406 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1407 } 1408 } break; 1409 case UPDATED_MEDIA_STATUS: { 1410 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1411 boolean reportStatus = msg.arg1 == 1; 1412 boolean doGc = msg.arg2 == 1; 1413 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1414 if (doGc) { 1415 // Force a gc to clear up stale containers. 1416 Runtime.getRuntime().gc(); 1417 } 1418 if (msg.obj != null) { 1419 @SuppressWarnings("unchecked") 1420 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1421 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1422 // Unload containers 1423 unloadAllContainers(args); 1424 } 1425 if (reportStatus) { 1426 try { 1427 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1428 PackageHelper.getMountService().finishMediaUpdate(); 1429 } catch (RemoteException e) { 1430 Log.e(TAG, "MountService not running?"); 1431 } 1432 } 1433 } break; 1434 case WRITE_SETTINGS: { 1435 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1436 synchronized (mPackages) { 1437 removeMessages(WRITE_SETTINGS); 1438 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1439 mSettings.writeLPr(); 1440 mDirtyUsers.clear(); 1441 } 1442 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1443 } break; 1444 case WRITE_PACKAGE_RESTRICTIONS: { 1445 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1446 synchronized (mPackages) { 1447 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1448 for (int userId : mDirtyUsers) { 1449 mSettings.writePackageRestrictionsLPr(userId); 1450 } 1451 mDirtyUsers.clear(); 1452 } 1453 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1454 } break; 1455 case CHECK_PENDING_VERIFICATION: { 1456 final int verificationId = msg.arg1; 1457 final PackageVerificationState state = mPendingVerification.get(verificationId); 1458 1459 if ((state != null) && !state.timeoutExtended()) { 1460 final InstallArgs args = state.getInstallArgs(); 1461 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1462 1463 Slog.i(TAG, "Verification timed out for " + originUri); 1464 mPendingVerification.remove(verificationId); 1465 1466 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1467 1468 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1469 Slog.i(TAG, "Continuing with installation of " + originUri); 1470 state.setVerifierResponse(Binder.getCallingUid(), 1471 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1472 broadcastPackageVerified(verificationId, originUri, 1473 PackageManager.VERIFICATION_ALLOW, 1474 state.getInstallArgs().getUser()); 1475 try { 1476 ret = args.copyApk(mContainerService, true); 1477 } catch (RemoteException e) { 1478 Slog.e(TAG, "Could not contact the ContainerService"); 1479 } 1480 } else { 1481 broadcastPackageVerified(verificationId, originUri, 1482 PackageManager.VERIFICATION_REJECT, 1483 state.getInstallArgs().getUser()); 1484 } 1485 1486 processPendingInstall(args, ret); 1487 mHandler.sendEmptyMessage(MCS_UNBIND); 1488 } 1489 break; 1490 } 1491 case PACKAGE_VERIFIED: { 1492 final int verificationId = msg.arg1; 1493 1494 final PackageVerificationState state = mPendingVerification.get(verificationId); 1495 if (state == null) { 1496 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1497 break; 1498 } 1499 1500 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1501 1502 state.setVerifierResponse(response.callerUid, response.code); 1503 1504 if (state.isVerificationComplete()) { 1505 mPendingVerification.remove(verificationId); 1506 1507 final InstallArgs args = state.getInstallArgs(); 1508 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1509 1510 int ret; 1511 if (state.isInstallAllowed()) { 1512 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1513 broadcastPackageVerified(verificationId, originUri, 1514 response.code, state.getInstallArgs().getUser()); 1515 try { 1516 ret = args.copyApk(mContainerService, true); 1517 } catch (RemoteException e) { 1518 Slog.e(TAG, "Could not contact the ContainerService"); 1519 } 1520 } else { 1521 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1522 } 1523 1524 processPendingInstall(args, ret); 1525 1526 mHandler.sendEmptyMessage(MCS_UNBIND); 1527 } 1528 1529 break; 1530 } 1531 case START_INTENT_FILTER_VERIFICATIONS: { 1532 IFVerificationParams params = (IFVerificationParams) msg.obj; 1533 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1534 params.replacing, params.pkg); 1535 break; 1536 } 1537 case INTENT_FILTER_VERIFIED: { 1538 final int verificationId = msg.arg1; 1539 1540 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1541 verificationId); 1542 if (state == null) { 1543 Slog.w(TAG, "Invalid IntentFilter verification token " 1544 + verificationId + " received"); 1545 break; 1546 } 1547 1548 final int userId = state.getUserId(); 1549 1550 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1551 "Processing IntentFilter verification with token:" 1552 + verificationId + " and userId:" + userId); 1553 1554 final IntentFilterVerificationResponse response = 1555 (IntentFilterVerificationResponse) msg.obj; 1556 1557 state.setVerifierResponse(response.callerUid, response.code); 1558 1559 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1560 "IntentFilter verification with token:" + verificationId 1561 + " and userId:" + userId 1562 + " is settings verifier response with response code:" 1563 + response.code); 1564 1565 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1566 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1567 + response.getFailedDomainsString()); 1568 } 1569 1570 if (state.isVerificationComplete()) { 1571 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1572 } else { 1573 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1574 "IntentFilter verification with token:" + verificationId 1575 + " was not said to be complete"); 1576 } 1577 1578 break; 1579 } 1580 } 1581 } 1582 } 1583 1584 private StorageEventListener mStorageListener = new StorageEventListener() { 1585 @Override 1586 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1587 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1588 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1589 // TODO: ensure that private directories exist for all active users 1590 // TODO: remove user data whose serial number doesn't match 1591 loadPrivatePackages(vol); 1592 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1593 unloadPrivatePackages(vol); 1594 } 1595 } 1596 1597 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1598 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1599 updateExternalMediaStatus(true, false); 1600 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1601 updateExternalMediaStatus(false, false); 1602 } 1603 } 1604 } 1605 1606 @Override 1607 public void onVolumeForgotten(String fsUuid) { 1608 // TODO: remove all packages hosted on this uuid 1609 } 1610 }; 1611 1612 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1613 if (userId >= UserHandle.USER_OWNER) { 1614 grantRequestedRuntimePermissionsForUser(pkg, userId); 1615 } else if (userId == UserHandle.USER_ALL) { 1616 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1617 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1618 } 1619 } 1620 1621 // We could have touched GID membership, so flush out packages.list 1622 synchronized (mPackages) { 1623 mSettings.writePackageListLPr(); 1624 } 1625 } 1626 1627 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1628 SettingBase sb = (SettingBase) pkg.mExtras; 1629 if (sb == null) { 1630 return; 1631 } 1632 1633 PermissionsState permissionsState = sb.getPermissionsState(); 1634 1635 for (String permission : pkg.requestedPermissions) { 1636 BasePermission bp = mSettings.mPermissions.get(permission); 1637 if (bp != null && bp.isRuntime()) { 1638 permissionsState.grantRuntimePermission(bp, userId); 1639 } 1640 } 1641 } 1642 1643 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1644 Bundle extras = null; 1645 switch (res.returnCode) { 1646 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1647 extras = new Bundle(); 1648 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1649 res.origPermission); 1650 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1651 res.origPackage); 1652 break; 1653 } 1654 case PackageManager.INSTALL_SUCCEEDED: { 1655 extras = new Bundle(); 1656 extras.putBoolean(Intent.EXTRA_REPLACING, 1657 res.removedInfo != null && res.removedInfo.removedPackage != null); 1658 break; 1659 } 1660 } 1661 return extras; 1662 } 1663 1664 void scheduleWriteSettingsLocked() { 1665 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1666 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1667 } 1668 } 1669 1670 void scheduleWritePackageRestrictionsLocked(int userId) { 1671 if (!sUserManager.exists(userId)) return; 1672 mDirtyUsers.add(userId); 1673 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1674 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1675 } 1676 } 1677 1678 public static PackageManagerService main(Context context, Installer installer, 1679 boolean factoryTest, boolean onlyCore) { 1680 PackageManagerService m = new PackageManagerService(context, installer, 1681 factoryTest, onlyCore); 1682 ServiceManager.addService("package", m); 1683 return m; 1684 } 1685 1686 static String[] splitString(String str, char sep) { 1687 int count = 1; 1688 int i = 0; 1689 while ((i=str.indexOf(sep, i)) >= 0) { 1690 count++; 1691 i++; 1692 } 1693 1694 String[] res = new String[count]; 1695 i=0; 1696 count = 0; 1697 int lastI=0; 1698 while ((i=str.indexOf(sep, i)) >= 0) { 1699 res[count] = str.substring(lastI, i); 1700 count++; 1701 i++; 1702 lastI = i; 1703 } 1704 res[count] = str.substring(lastI, str.length()); 1705 return res; 1706 } 1707 1708 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1709 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1710 Context.DISPLAY_SERVICE); 1711 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1712 } 1713 1714 public PackageManagerService(Context context, Installer installer, 1715 boolean factoryTest, boolean onlyCore) { 1716 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1717 SystemClock.uptimeMillis()); 1718 1719 if (mSdkVersion <= 0) { 1720 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1721 } 1722 1723 mContext = context; 1724 mFactoryTest = factoryTest; 1725 mOnlyCore = onlyCore; 1726 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1727 mMetrics = new DisplayMetrics(); 1728 mSettings = new Settings(mPackages); 1729 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1730 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1731 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1732 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1733 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1734 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1735 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1736 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1737 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1738 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1739 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1740 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1741 1742 // TODO: add a property to control this? 1743 long dexOptLRUThresholdInMinutes; 1744 if (mLazyDexOpt) { 1745 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1746 } else { 1747 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1748 } 1749 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1750 1751 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1752 if (separateProcesses != null && separateProcesses.length() > 0) { 1753 if ("*".equals(separateProcesses)) { 1754 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1755 mSeparateProcesses = null; 1756 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1757 } else { 1758 mDefParseFlags = 0; 1759 mSeparateProcesses = separateProcesses.split(","); 1760 Slog.w(TAG, "Running with debug.separate_processes: " 1761 + separateProcesses); 1762 } 1763 } else { 1764 mDefParseFlags = 0; 1765 mSeparateProcesses = null; 1766 } 1767 1768 mInstaller = installer; 1769 mPackageDexOptimizer = new PackageDexOptimizer(this); 1770 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1771 1772 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1773 FgThread.get().getLooper()); 1774 1775 getDefaultDisplayMetrics(context, mMetrics); 1776 1777 SystemConfig systemConfig = SystemConfig.getInstance(); 1778 mGlobalGids = systemConfig.getGlobalGids(); 1779 mSystemPermissions = systemConfig.getSystemPermissions(); 1780 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1781 1782 synchronized (mInstallLock) { 1783 // writer 1784 synchronized (mPackages) { 1785 mHandlerThread = new ServiceThread(TAG, 1786 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1787 mHandlerThread.start(); 1788 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1789 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1790 1791 File dataDir = Environment.getDataDirectory(); 1792 mAppDataDir = new File(dataDir, "data"); 1793 mAppInstallDir = new File(dataDir, "app"); 1794 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1795 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1796 mUserAppDataDir = new File(dataDir, "user"); 1797 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1798 1799 sUserManager = new UserManagerService(context, this, 1800 mInstallLock, mPackages); 1801 1802 // Propagate permission configuration in to package manager. 1803 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1804 = systemConfig.getPermissions(); 1805 for (int i=0; i<permConfig.size(); i++) { 1806 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1807 BasePermission bp = mSettings.mPermissions.get(perm.name); 1808 if (bp == null) { 1809 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1810 mSettings.mPermissions.put(perm.name, bp); 1811 } 1812 if (perm.gids != null) { 1813 bp.setGids(perm.gids, perm.perUser); 1814 } 1815 } 1816 1817 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1818 for (int i=0; i<libConfig.size(); i++) { 1819 mSharedLibraries.put(libConfig.keyAt(i), 1820 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1821 } 1822 1823 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1824 1825 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1826 mSdkVersion, mOnlyCore); 1827 1828 String customResolverActivity = Resources.getSystem().getString( 1829 R.string.config_customResolverActivity); 1830 if (TextUtils.isEmpty(customResolverActivity)) { 1831 customResolverActivity = null; 1832 } else { 1833 mCustomResolverComponentName = ComponentName.unflattenFromString( 1834 customResolverActivity); 1835 } 1836 1837 long startTime = SystemClock.uptimeMillis(); 1838 1839 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1840 startTime); 1841 1842 // Set flag to monitor and not change apk file paths when 1843 // scanning install directories. 1844 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1845 1846 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1847 1848 /** 1849 * Add everything in the in the boot class path to the 1850 * list of process files because dexopt will have been run 1851 * if necessary during zygote startup. 1852 */ 1853 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1854 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1855 1856 if (bootClassPath != null) { 1857 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1858 for (String element : bootClassPathElements) { 1859 alreadyDexOpted.add(element); 1860 } 1861 } else { 1862 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1863 } 1864 1865 if (systemServerClassPath != null) { 1866 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1867 for (String element : systemServerClassPathElements) { 1868 alreadyDexOpted.add(element); 1869 } 1870 } else { 1871 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1872 } 1873 1874 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1875 final String[] dexCodeInstructionSets = 1876 getDexCodeInstructionSets( 1877 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1878 1879 /** 1880 * Ensure all external libraries have had dexopt run on them. 1881 */ 1882 if (mSharedLibraries.size() > 0) { 1883 // NOTE: For now, we're compiling these system "shared libraries" 1884 // (and framework jars) into all available architectures. It's possible 1885 // to compile them only when we come across an app that uses them (there's 1886 // already logic for that in scanPackageLI) but that adds some complexity. 1887 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1888 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1889 final String lib = libEntry.path; 1890 if (lib == null) { 1891 continue; 1892 } 1893 1894 try { 1895 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1896 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1897 alreadyDexOpted.add(lib); 1898 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1899 } 1900 } catch (FileNotFoundException e) { 1901 Slog.w(TAG, "Library not found: " + lib); 1902 } catch (IOException e) { 1903 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1904 + e.getMessage()); 1905 } 1906 } 1907 } 1908 } 1909 1910 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1911 1912 // Gross hack for now: we know this file doesn't contain any 1913 // code, so don't dexopt it to avoid the resulting log spew. 1914 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1915 1916 // Gross hack for now: we know this file is only part of 1917 // the boot class path for art, so don't dexopt it to 1918 // avoid the resulting log spew. 1919 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1920 1921 /** 1922 * There are a number of commands implemented in Java, which 1923 * we currently need to do the dexopt on so that they can be 1924 * run from a non-root shell. 1925 */ 1926 String[] frameworkFiles = frameworkDir.list(); 1927 if (frameworkFiles != null) { 1928 // TODO: We could compile these only for the most preferred ABI. We should 1929 // first double check that the dex files for these commands are not referenced 1930 // by other system apps. 1931 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1932 for (int i=0; i<frameworkFiles.length; i++) { 1933 File libPath = new File(frameworkDir, frameworkFiles[i]); 1934 String path = libPath.getPath(); 1935 // Skip the file if we already did it. 1936 if (alreadyDexOpted.contains(path)) { 1937 continue; 1938 } 1939 // Skip the file if it is not a type we want to dexopt. 1940 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1941 continue; 1942 } 1943 try { 1944 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1945 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1946 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1947 } 1948 } catch (FileNotFoundException e) { 1949 Slog.w(TAG, "Jar not found: " + path); 1950 } catch (IOException e) { 1951 Slog.w(TAG, "Exception reading jar: " + path, e); 1952 } 1953 } 1954 } 1955 } 1956 1957 // Collect vendor overlay packages. 1958 // (Do this before scanning any apps.) 1959 // For security and version matching reason, only consider 1960 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1961 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1962 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1963 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1964 1965 // Find base frameworks (resource packages without code). 1966 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1967 | PackageParser.PARSE_IS_SYSTEM_DIR 1968 | PackageParser.PARSE_IS_PRIVILEGED, 1969 scanFlags | SCAN_NO_DEX, 0); 1970 1971 // Collected privileged system packages. 1972 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1973 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1974 | PackageParser.PARSE_IS_SYSTEM_DIR 1975 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1976 1977 // Collect ordinary system packages. 1978 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1979 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1980 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1981 1982 // Collect all vendor packages. 1983 File vendorAppDir = new File("/vendor/app"); 1984 try { 1985 vendorAppDir = vendorAppDir.getCanonicalFile(); 1986 } catch (IOException e) { 1987 // failed to look up canonical path, continue with original one 1988 } 1989 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1990 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1991 1992 // Collect all OEM packages. 1993 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1994 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1995 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1996 1997 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1998 mInstaller.moveFiles(); 1999 2000 // Prune any system packages that no longer exist. 2001 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2002 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2003 if (!mOnlyCore) { 2004 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2005 while (psit.hasNext()) { 2006 PackageSetting ps = psit.next(); 2007 2008 /* 2009 * If this is not a system app, it can't be a 2010 * disable system app. 2011 */ 2012 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2013 continue; 2014 } 2015 2016 /* 2017 * If the package is scanned, it's not erased. 2018 */ 2019 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2020 if (scannedPkg != null) { 2021 /* 2022 * If the system app is both scanned and in the 2023 * disabled packages list, then it must have been 2024 * added via OTA. Remove it from the currently 2025 * scanned package so the previously user-installed 2026 * application can be scanned. 2027 */ 2028 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2029 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2030 + ps.name + "; removing system app. Last known codePath=" 2031 + ps.codePathString + ", installStatus=" + ps.installStatus 2032 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2033 + scannedPkg.mVersionCode); 2034 removePackageLI(ps, true); 2035 expectingBetter.put(ps.name, ps.codePath); 2036 } 2037 2038 continue; 2039 } 2040 2041 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2042 psit.remove(); 2043 logCriticalInfo(Log.WARN, "System package " + ps.name 2044 + " no longer exists; wiping its data"); 2045 removeDataDirsLI(null, ps.name); 2046 } else { 2047 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2048 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2049 possiblyDeletedUpdatedSystemApps.add(ps.name); 2050 } 2051 } 2052 } 2053 } 2054 2055 //look for any incomplete package installations 2056 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2057 //clean up list 2058 for(int i = 0; i < deletePkgsList.size(); i++) { 2059 //clean up here 2060 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2061 } 2062 //delete tmp files 2063 deleteTempPackageFiles(); 2064 2065 // Remove any shared userIDs that have no associated packages 2066 mSettings.pruneSharedUsersLPw(); 2067 2068 if (!mOnlyCore) { 2069 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2070 SystemClock.uptimeMillis()); 2071 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2072 2073 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2074 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2075 2076 /** 2077 * Remove disable package settings for any updated system 2078 * apps that were removed via an OTA. If they're not a 2079 * previously-updated app, remove them completely. 2080 * Otherwise, just revoke their system-level permissions. 2081 */ 2082 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2083 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2084 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2085 2086 String msg; 2087 if (deletedPkg == null) { 2088 msg = "Updated system package " + deletedAppName 2089 + " no longer exists; wiping its data"; 2090 removeDataDirsLI(null, deletedAppName); 2091 } else { 2092 msg = "Updated system app + " + deletedAppName 2093 + " no longer present; removing system privileges for " 2094 + deletedAppName; 2095 2096 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2097 2098 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2099 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2100 } 2101 logCriticalInfo(Log.WARN, msg); 2102 } 2103 2104 /** 2105 * Make sure all system apps that we expected to appear on 2106 * the userdata partition actually showed up. If they never 2107 * appeared, crawl back and revive the system version. 2108 */ 2109 for (int i = 0; i < expectingBetter.size(); i++) { 2110 final String packageName = expectingBetter.keyAt(i); 2111 if (!mPackages.containsKey(packageName)) { 2112 final File scanFile = expectingBetter.valueAt(i); 2113 2114 logCriticalInfo(Log.WARN, "Expected better " + packageName 2115 + " but never showed up; reverting to system"); 2116 2117 final int reparseFlags; 2118 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2119 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2120 | PackageParser.PARSE_IS_SYSTEM_DIR 2121 | PackageParser.PARSE_IS_PRIVILEGED; 2122 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2123 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2124 | PackageParser.PARSE_IS_SYSTEM_DIR; 2125 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2126 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2127 | PackageParser.PARSE_IS_SYSTEM_DIR; 2128 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2129 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2130 | PackageParser.PARSE_IS_SYSTEM_DIR; 2131 } else { 2132 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2133 continue; 2134 } 2135 2136 mSettings.enableSystemPackageLPw(packageName); 2137 2138 try { 2139 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2140 } catch (PackageManagerException e) { 2141 Slog.e(TAG, "Failed to parse original system package: " 2142 + e.getMessage()); 2143 } 2144 } 2145 } 2146 } 2147 2148 // Now that we know all of the shared libraries, update all clients to have 2149 // the correct library paths. 2150 updateAllSharedLibrariesLPw(); 2151 2152 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2153 // NOTE: We ignore potential failures here during a system scan (like 2154 // the rest of the commands above) because there's precious little we 2155 // can do about it. A settings error is reported, though. 2156 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2157 false /* force dexopt */, false /* defer dexopt */); 2158 } 2159 2160 // Now that we know all the packages we are keeping, 2161 // read and update their last usage times. 2162 mPackageUsage.readLP(); 2163 2164 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2165 SystemClock.uptimeMillis()); 2166 Slog.i(TAG, "Time to scan packages: " 2167 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2168 + " seconds"); 2169 2170 // If the platform SDK has changed since the last time we booted, 2171 // we need to re-grant app permission to catch any new ones that 2172 // appear. This is really a hack, and means that apps can in some 2173 // cases get permissions that the user didn't initially explicitly 2174 // allow... it would be nice to have some better way to handle 2175 // this situation. 2176 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2177 != mSdkVersion; 2178 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2179 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2180 + "; regranting permissions for internal storage"); 2181 mSettings.mInternalSdkPlatform = mSdkVersion; 2182 2183 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2184 | (regrantPermissions 2185 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2186 : 0)); 2187 2188 // If this is the first boot, and it is a normal boot, then 2189 // we need to initialize the default preferred apps. 2190 if (!mRestoredSettings && !onlyCore) { 2191 mSettings.readDefaultPreferredAppsLPw(this, 0); 2192 } 2193 2194 // If this is first boot after an OTA, and a normal boot, then 2195 // we need to clear code cache directories. 2196 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2197 if (mIsUpgrade && !onlyCore) { 2198 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2199 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2200 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2201 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2202 } 2203 mSettings.mFingerprint = Build.FINGERPRINT; 2204 } 2205 2206 primeDomainVerificationsLPw(); 2207 checkDefaultBrowser(); 2208 2209 // All the changes are done during package scanning. 2210 mSettings.updateInternalDatabaseVersion(); 2211 2212 // can downgrade to reader 2213 mSettings.writeLPr(); 2214 2215 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2216 SystemClock.uptimeMillis()); 2217 2218 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2219 2220 mInstallerService = new PackageInstallerService(context, this); 2221 2222 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2223 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2224 mIntentFilterVerifierComponent); 2225 2226 } // synchronized (mPackages) 2227 } // synchronized (mInstallLock) 2228 2229 // Now after opening every single application zip, make sure they 2230 // are all flushed. Not really needed, but keeps things nice and 2231 // tidy. 2232 Runtime.getRuntime().gc(); 2233 2234 // Expose private service for system components to use. 2235 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2236 } 2237 2238 @Override 2239 public boolean isFirstBoot() { 2240 return !mRestoredSettings; 2241 } 2242 2243 @Override 2244 public boolean isOnlyCoreApps() { 2245 return mOnlyCore; 2246 } 2247 2248 @Override 2249 public boolean isUpgrade() { 2250 return mIsUpgrade; 2251 } 2252 2253 private String getRequiredVerifierLPr() { 2254 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2255 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2256 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2257 2258 String requiredVerifier = null; 2259 2260 final int N = receivers.size(); 2261 for (int i = 0; i < N; i++) { 2262 final ResolveInfo info = receivers.get(i); 2263 2264 if (info.activityInfo == null) { 2265 continue; 2266 } 2267 2268 final String packageName = info.activityInfo.packageName; 2269 2270 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2271 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2272 continue; 2273 } 2274 2275 if (requiredVerifier != null) { 2276 throw new RuntimeException("There can be only one required verifier"); 2277 } 2278 2279 requiredVerifier = packageName; 2280 } 2281 2282 return requiredVerifier; 2283 } 2284 2285 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2286 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2287 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2288 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2289 2290 ComponentName verifierComponentName = null; 2291 2292 int priority = -1000; 2293 final int N = receivers.size(); 2294 for (int i = 0; i < N; i++) { 2295 final ResolveInfo info = receivers.get(i); 2296 2297 if (info.activityInfo == null) { 2298 continue; 2299 } 2300 2301 final String packageName = info.activityInfo.packageName; 2302 2303 final PackageSetting ps = mSettings.mPackages.get(packageName); 2304 if (ps == null) { 2305 continue; 2306 } 2307 2308 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2309 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2310 continue; 2311 } 2312 2313 // Select the IntentFilterVerifier with the highest priority 2314 if (priority < info.priority) { 2315 priority = info.priority; 2316 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2317 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2318 + verifierComponentName + " with priority: " + info.priority); 2319 } 2320 } 2321 2322 return verifierComponentName; 2323 } 2324 2325 private void primeDomainVerificationsLPw() { 2326 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2327 boolean updated = false; 2328 ArraySet<String> allHostsSet = new ArraySet<>(); 2329 for (PackageParser.Package pkg : mPackages.values()) { 2330 final String packageName = pkg.packageName; 2331 if (!hasDomainURLs(pkg)) { 2332 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2333 "package with no domain URLs: " + packageName); 2334 continue; 2335 } 2336 if (!pkg.isSystemApp()) { 2337 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2338 "No priming domain verifications for a non system package : " + 2339 packageName); 2340 continue; 2341 } 2342 for (PackageParser.Activity a : pkg.activities) { 2343 for (ActivityIntentInfo filter : a.intents) { 2344 if (hasValidDomains(filter)) { 2345 allHostsSet.addAll(filter.getHostsList()); 2346 } 2347 } 2348 } 2349 if (allHostsSet.size() == 0) { 2350 allHostsSet.add("*"); 2351 } 2352 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2353 IntentFilterVerificationInfo ivi = 2354 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2355 if (ivi != null) { 2356 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2357 "Priming domain verifications for package: " + packageName + 2358 " with hosts:" + ivi.getDomainsString()); 2359 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2360 updated = true; 2361 } 2362 else { 2363 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2364 "No priming domain verifications for package: " + packageName); 2365 } 2366 allHostsSet.clear(); 2367 } 2368 if (updated) { 2369 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2370 "Will need to write primed domain verifications"); 2371 } 2372 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2373 } 2374 2375 private void checkDefaultBrowser() { 2376 final int myUserId = UserHandle.myUserId(); 2377 final String packageName = getDefaultBrowserPackageName(myUserId); 2378 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2379 if (info == null) { 2380 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2381 setDefaultBrowserPackageName(null, myUserId); 2382 } 2383 } 2384 2385 @Override 2386 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2387 throws RemoteException { 2388 try { 2389 return super.onTransact(code, data, reply, flags); 2390 } catch (RuntimeException e) { 2391 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2392 Slog.wtf(TAG, "Package Manager Crash", e); 2393 } 2394 throw e; 2395 } 2396 } 2397 2398 void cleanupInstallFailedPackage(PackageSetting ps) { 2399 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2400 2401 removeDataDirsLI(ps.volumeUuid, ps.name); 2402 if (ps.codePath != null) { 2403 if (ps.codePath.isDirectory()) { 2404 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2405 } else { 2406 ps.codePath.delete(); 2407 } 2408 } 2409 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2410 if (ps.resourcePath.isDirectory()) { 2411 FileUtils.deleteContents(ps.resourcePath); 2412 } 2413 ps.resourcePath.delete(); 2414 } 2415 mSettings.removePackageLPw(ps.name); 2416 } 2417 2418 static int[] appendInts(int[] cur, int[] add) { 2419 if (add == null) return cur; 2420 if (cur == null) return add; 2421 final int N = add.length; 2422 for (int i=0; i<N; i++) { 2423 cur = appendInt(cur, add[i]); 2424 } 2425 return cur; 2426 } 2427 2428 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2429 if (!sUserManager.exists(userId)) return null; 2430 final PackageSetting ps = (PackageSetting) p.mExtras; 2431 if (ps == null) { 2432 return null; 2433 } 2434 2435 final PermissionsState permissionsState = ps.getPermissionsState(); 2436 2437 final int[] gids = permissionsState.computeGids(userId); 2438 final Set<String> permissions = permissionsState.getPermissions(userId); 2439 final PackageUserState state = ps.readUserState(userId); 2440 2441 return PackageParser.generatePackageInfo(p, gids, flags, 2442 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2443 } 2444 2445 @Override 2446 public boolean isPackageFrozen(String packageName) { 2447 synchronized (mPackages) { 2448 final PackageSetting ps = mSettings.mPackages.get(packageName); 2449 if (ps != null) { 2450 return ps.frozen; 2451 } 2452 } 2453 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2454 return true; 2455 } 2456 2457 @Override 2458 public boolean isPackageAvailable(String packageName, int userId) { 2459 if (!sUserManager.exists(userId)) return false; 2460 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2461 synchronized (mPackages) { 2462 PackageParser.Package p = mPackages.get(packageName); 2463 if (p != null) { 2464 final PackageSetting ps = (PackageSetting) p.mExtras; 2465 if (ps != null) { 2466 final PackageUserState state = ps.readUserState(userId); 2467 if (state != null) { 2468 return PackageParser.isAvailable(state); 2469 } 2470 } 2471 } 2472 } 2473 return false; 2474 } 2475 2476 @Override 2477 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2478 if (!sUserManager.exists(userId)) return null; 2479 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2480 // reader 2481 synchronized (mPackages) { 2482 PackageParser.Package p = mPackages.get(packageName); 2483 if (DEBUG_PACKAGE_INFO) 2484 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2485 if (p != null) { 2486 return generatePackageInfo(p, flags, userId); 2487 } 2488 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2489 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2490 } 2491 } 2492 return null; 2493 } 2494 2495 @Override 2496 public String[] currentToCanonicalPackageNames(String[] names) { 2497 String[] out = new String[names.length]; 2498 // reader 2499 synchronized (mPackages) { 2500 for (int i=names.length-1; i>=0; i--) { 2501 PackageSetting ps = mSettings.mPackages.get(names[i]); 2502 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2503 } 2504 } 2505 return out; 2506 } 2507 2508 @Override 2509 public String[] canonicalToCurrentPackageNames(String[] names) { 2510 String[] out = new String[names.length]; 2511 // reader 2512 synchronized (mPackages) { 2513 for (int i=names.length-1; i>=0; i--) { 2514 String cur = mSettings.mRenamedPackages.get(names[i]); 2515 out[i] = cur != null ? cur : names[i]; 2516 } 2517 } 2518 return out; 2519 } 2520 2521 @Override 2522 public int getPackageUid(String packageName, int userId) { 2523 if (!sUserManager.exists(userId)) return -1; 2524 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2525 2526 // reader 2527 synchronized (mPackages) { 2528 PackageParser.Package p = mPackages.get(packageName); 2529 if(p != null) { 2530 return UserHandle.getUid(userId, p.applicationInfo.uid); 2531 } 2532 PackageSetting ps = mSettings.mPackages.get(packageName); 2533 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2534 return -1; 2535 } 2536 p = ps.pkg; 2537 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2538 } 2539 } 2540 2541 @Override 2542 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2543 if (!sUserManager.exists(userId)) { 2544 return null; 2545 } 2546 2547 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2548 "getPackageGids"); 2549 2550 // reader 2551 synchronized (mPackages) { 2552 PackageParser.Package p = mPackages.get(packageName); 2553 if (DEBUG_PACKAGE_INFO) { 2554 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2555 } 2556 if (p != null) { 2557 PackageSetting ps = (PackageSetting) p.mExtras; 2558 return ps.getPermissionsState().computeGids(userId); 2559 } 2560 } 2561 2562 return null; 2563 } 2564 2565 static PermissionInfo generatePermissionInfo( 2566 BasePermission bp, int flags) { 2567 if (bp.perm != null) { 2568 return PackageParser.generatePermissionInfo(bp.perm, flags); 2569 } 2570 PermissionInfo pi = new PermissionInfo(); 2571 pi.name = bp.name; 2572 pi.packageName = bp.sourcePackage; 2573 pi.nonLocalizedLabel = bp.name; 2574 pi.protectionLevel = bp.protectionLevel; 2575 return pi; 2576 } 2577 2578 @Override 2579 public PermissionInfo getPermissionInfo(String name, int flags) { 2580 // reader 2581 synchronized (mPackages) { 2582 final BasePermission p = mSettings.mPermissions.get(name); 2583 if (p != null) { 2584 return generatePermissionInfo(p, flags); 2585 } 2586 return null; 2587 } 2588 } 2589 2590 @Override 2591 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2592 // reader 2593 synchronized (mPackages) { 2594 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2595 for (BasePermission p : mSettings.mPermissions.values()) { 2596 if (group == null) { 2597 if (p.perm == null || p.perm.info.group == null) { 2598 out.add(generatePermissionInfo(p, flags)); 2599 } 2600 } else { 2601 if (p.perm != null && group.equals(p.perm.info.group)) { 2602 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2603 } 2604 } 2605 } 2606 2607 if (out.size() > 0) { 2608 return out; 2609 } 2610 return mPermissionGroups.containsKey(group) ? out : null; 2611 } 2612 } 2613 2614 @Override 2615 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2616 // reader 2617 synchronized (mPackages) { 2618 return PackageParser.generatePermissionGroupInfo( 2619 mPermissionGroups.get(name), flags); 2620 } 2621 } 2622 2623 @Override 2624 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2625 // reader 2626 synchronized (mPackages) { 2627 final int N = mPermissionGroups.size(); 2628 ArrayList<PermissionGroupInfo> out 2629 = new ArrayList<PermissionGroupInfo>(N); 2630 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2631 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2632 } 2633 return out; 2634 } 2635 } 2636 2637 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2638 int userId) { 2639 if (!sUserManager.exists(userId)) return null; 2640 PackageSetting ps = mSettings.mPackages.get(packageName); 2641 if (ps != null) { 2642 if (ps.pkg == null) { 2643 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2644 flags, userId); 2645 if (pInfo != null) { 2646 return pInfo.applicationInfo; 2647 } 2648 return null; 2649 } 2650 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2651 ps.readUserState(userId), userId); 2652 } 2653 return null; 2654 } 2655 2656 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2657 int userId) { 2658 if (!sUserManager.exists(userId)) return null; 2659 PackageSetting ps = mSettings.mPackages.get(packageName); 2660 if (ps != null) { 2661 PackageParser.Package pkg = ps.pkg; 2662 if (pkg == null) { 2663 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2664 return null; 2665 } 2666 // Only data remains, so we aren't worried about code paths 2667 pkg = new PackageParser.Package(packageName); 2668 pkg.applicationInfo.packageName = packageName; 2669 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2670 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2671 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2672 packageName, userId).getAbsolutePath(); 2673 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2674 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2675 } 2676 return generatePackageInfo(pkg, flags, userId); 2677 } 2678 return null; 2679 } 2680 2681 @Override 2682 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2683 if (!sUserManager.exists(userId)) return null; 2684 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2685 // writer 2686 synchronized (mPackages) { 2687 PackageParser.Package p = mPackages.get(packageName); 2688 if (DEBUG_PACKAGE_INFO) Log.v( 2689 TAG, "getApplicationInfo " + packageName 2690 + ": " + p); 2691 if (p != null) { 2692 PackageSetting ps = mSettings.mPackages.get(packageName); 2693 if (ps == null) return null; 2694 // Note: isEnabledLP() does not apply here - always return info 2695 return PackageParser.generateApplicationInfo( 2696 p, flags, ps.readUserState(userId), userId); 2697 } 2698 if ("android".equals(packageName)||"system".equals(packageName)) { 2699 return mAndroidApplication; 2700 } 2701 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2702 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2703 } 2704 } 2705 return null; 2706 } 2707 2708 @Override 2709 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2710 final IPackageDataObserver observer) { 2711 mContext.enforceCallingOrSelfPermission( 2712 android.Manifest.permission.CLEAR_APP_CACHE, null); 2713 // Queue up an async operation since clearing cache may take a little while. 2714 mHandler.post(new Runnable() { 2715 public void run() { 2716 mHandler.removeCallbacks(this); 2717 int retCode = -1; 2718 synchronized (mInstallLock) { 2719 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2720 if (retCode < 0) { 2721 Slog.w(TAG, "Couldn't clear application caches"); 2722 } 2723 } 2724 if (observer != null) { 2725 try { 2726 observer.onRemoveCompleted(null, (retCode >= 0)); 2727 } catch (RemoteException e) { 2728 Slog.w(TAG, "RemoveException when invoking call back"); 2729 } 2730 } 2731 } 2732 }); 2733 } 2734 2735 @Override 2736 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2737 final IntentSender pi) { 2738 mContext.enforceCallingOrSelfPermission( 2739 android.Manifest.permission.CLEAR_APP_CACHE, null); 2740 // Queue up an async operation since clearing cache may take a little while. 2741 mHandler.post(new Runnable() { 2742 public void run() { 2743 mHandler.removeCallbacks(this); 2744 int retCode = -1; 2745 synchronized (mInstallLock) { 2746 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2747 if (retCode < 0) { 2748 Slog.w(TAG, "Couldn't clear application caches"); 2749 } 2750 } 2751 if(pi != null) { 2752 try { 2753 // Callback via pending intent 2754 int code = (retCode >= 0) ? 1 : 0; 2755 pi.sendIntent(null, code, null, 2756 null, null); 2757 } catch (SendIntentException e1) { 2758 Slog.i(TAG, "Failed to send pending intent"); 2759 } 2760 } 2761 } 2762 }); 2763 } 2764 2765 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2766 synchronized (mInstallLock) { 2767 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2768 throw new IOException("Failed to free enough space"); 2769 } 2770 } 2771 } 2772 2773 @Override 2774 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2775 if (!sUserManager.exists(userId)) return null; 2776 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2777 synchronized (mPackages) { 2778 PackageParser.Activity a = mActivities.mActivities.get(component); 2779 2780 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2781 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2782 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2783 if (ps == null) return null; 2784 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2785 userId); 2786 } 2787 if (mResolveComponentName.equals(component)) { 2788 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2789 new PackageUserState(), userId); 2790 } 2791 } 2792 return null; 2793 } 2794 2795 @Override 2796 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2797 String resolvedType) { 2798 synchronized (mPackages) { 2799 PackageParser.Activity a = mActivities.mActivities.get(component); 2800 if (a == null) { 2801 return false; 2802 } 2803 for (int i=0; i<a.intents.size(); i++) { 2804 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2805 intent.getData(), intent.getCategories(), TAG) >= 0) { 2806 return true; 2807 } 2808 } 2809 return false; 2810 } 2811 } 2812 2813 @Override 2814 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2815 if (!sUserManager.exists(userId)) return null; 2816 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2817 synchronized (mPackages) { 2818 PackageParser.Activity a = mReceivers.mActivities.get(component); 2819 if (DEBUG_PACKAGE_INFO) Log.v( 2820 TAG, "getReceiverInfo " + component + ": " + a); 2821 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2822 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2823 if (ps == null) return null; 2824 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2825 userId); 2826 } 2827 } 2828 return null; 2829 } 2830 2831 @Override 2832 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2833 if (!sUserManager.exists(userId)) return null; 2834 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2835 synchronized (mPackages) { 2836 PackageParser.Service s = mServices.mServices.get(component); 2837 if (DEBUG_PACKAGE_INFO) Log.v( 2838 TAG, "getServiceInfo " + component + ": " + s); 2839 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2840 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2841 if (ps == null) return null; 2842 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2843 userId); 2844 } 2845 } 2846 return null; 2847 } 2848 2849 @Override 2850 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2851 if (!sUserManager.exists(userId)) return null; 2852 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2853 synchronized (mPackages) { 2854 PackageParser.Provider p = mProviders.mProviders.get(component); 2855 if (DEBUG_PACKAGE_INFO) Log.v( 2856 TAG, "getProviderInfo " + component + ": " + p); 2857 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2858 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2859 if (ps == null) return null; 2860 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2861 userId); 2862 } 2863 } 2864 return null; 2865 } 2866 2867 @Override 2868 public String[] getSystemSharedLibraryNames() { 2869 Set<String> libSet; 2870 synchronized (mPackages) { 2871 libSet = mSharedLibraries.keySet(); 2872 int size = libSet.size(); 2873 if (size > 0) { 2874 String[] libs = new String[size]; 2875 libSet.toArray(libs); 2876 return libs; 2877 } 2878 } 2879 return null; 2880 } 2881 2882 /** 2883 * @hide 2884 */ 2885 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2886 synchronized (mPackages) { 2887 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2888 if (lib != null && lib.apk != null) { 2889 return mPackages.get(lib.apk); 2890 } 2891 } 2892 return null; 2893 } 2894 2895 @Override 2896 public FeatureInfo[] getSystemAvailableFeatures() { 2897 Collection<FeatureInfo> featSet; 2898 synchronized (mPackages) { 2899 featSet = mAvailableFeatures.values(); 2900 int size = featSet.size(); 2901 if (size > 0) { 2902 FeatureInfo[] features = new FeatureInfo[size+1]; 2903 featSet.toArray(features); 2904 FeatureInfo fi = new FeatureInfo(); 2905 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2906 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2907 features[size] = fi; 2908 return features; 2909 } 2910 } 2911 return null; 2912 } 2913 2914 @Override 2915 public boolean hasSystemFeature(String name) { 2916 synchronized (mPackages) { 2917 return mAvailableFeatures.containsKey(name); 2918 } 2919 } 2920 2921 private void checkValidCaller(int uid, int userId) { 2922 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2923 return; 2924 2925 throw new SecurityException("Caller uid=" + uid 2926 + " is not privileged to communicate with user=" + userId); 2927 } 2928 2929 @Override 2930 public int checkPermission(String permName, String pkgName, int userId) { 2931 if (!sUserManager.exists(userId)) { 2932 return PackageManager.PERMISSION_DENIED; 2933 } 2934 2935 synchronized (mPackages) { 2936 final PackageParser.Package p = mPackages.get(pkgName); 2937 if (p != null && p.mExtras != null) { 2938 final PackageSetting ps = (PackageSetting) p.mExtras; 2939 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2940 return PackageManager.PERMISSION_GRANTED; 2941 } 2942 } 2943 } 2944 2945 return PackageManager.PERMISSION_DENIED; 2946 } 2947 2948 @Override 2949 public int checkUidPermission(String permName, int uid) { 2950 final int userId = UserHandle.getUserId(uid); 2951 2952 if (!sUserManager.exists(userId)) { 2953 return PackageManager.PERMISSION_DENIED; 2954 } 2955 2956 synchronized (mPackages) { 2957 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2958 if (obj != null) { 2959 final SettingBase ps = (SettingBase) obj; 2960 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2961 return PackageManager.PERMISSION_GRANTED; 2962 } 2963 } else { 2964 ArraySet<String> perms = mSystemPermissions.get(uid); 2965 if (perms != null && perms.contains(permName)) { 2966 return PackageManager.PERMISSION_GRANTED; 2967 } 2968 } 2969 } 2970 2971 return PackageManager.PERMISSION_DENIED; 2972 } 2973 2974 /** 2975 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2976 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2977 * @param checkShell TODO(yamasani): 2978 * @param message the message to log on security exception 2979 */ 2980 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2981 boolean checkShell, String message) { 2982 if (userId < 0) { 2983 throw new IllegalArgumentException("Invalid userId " + userId); 2984 } 2985 if (checkShell) { 2986 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2987 } 2988 if (userId == UserHandle.getUserId(callingUid)) return; 2989 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2990 if (requireFullPermission) { 2991 mContext.enforceCallingOrSelfPermission( 2992 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2993 } else { 2994 try { 2995 mContext.enforceCallingOrSelfPermission( 2996 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2997 } catch (SecurityException se) { 2998 mContext.enforceCallingOrSelfPermission( 2999 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3000 } 3001 } 3002 } 3003 } 3004 3005 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3006 if (callingUid == Process.SHELL_UID) { 3007 if (userHandle >= 0 3008 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3009 throw new SecurityException("Shell does not have permission to access user " 3010 + userHandle); 3011 } else if (userHandle < 0) { 3012 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3013 + Debug.getCallers(3)); 3014 } 3015 } 3016 } 3017 3018 private BasePermission findPermissionTreeLP(String permName) { 3019 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3020 if (permName.startsWith(bp.name) && 3021 permName.length() > bp.name.length() && 3022 permName.charAt(bp.name.length()) == '.') { 3023 return bp; 3024 } 3025 } 3026 return null; 3027 } 3028 3029 private BasePermission checkPermissionTreeLP(String permName) { 3030 if (permName != null) { 3031 BasePermission bp = findPermissionTreeLP(permName); 3032 if (bp != null) { 3033 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3034 return bp; 3035 } 3036 throw new SecurityException("Calling uid " 3037 + Binder.getCallingUid() 3038 + " is not allowed to add to permission tree " 3039 + bp.name + " owned by uid " + bp.uid); 3040 } 3041 } 3042 throw new SecurityException("No permission tree found for " + permName); 3043 } 3044 3045 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3046 if (s1 == null) { 3047 return s2 == null; 3048 } 3049 if (s2 == null) { 3050 return false; 3051 } 3052 if (s1.getClass() != s2.getClass()) { 3053 return false; 3054 } 3055 return s1.equals(s2); 3056 } 3057 3058 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3059 if (pi1.icon != pi2.icon) return false; 3060 if (pi1.logo != pi2.logo) return false; 3061 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3062 if (!compareStrings(pi1.name, pi2.name)) return false; 3063 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3064 // We'll take care of setting this one. 3065 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3066 // These are not currently stored in settings. 3067 //if (!compareStrings(pi1.group, pi2.group)) return false; 3068 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3069 //if (pi1.labelRes != pi2.labelRes) return false; 3070 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3071 return true; 3072 } 3073 3074 int permissionInfoFootprint(PermissionInfo info) { 3075 int size = info.name.length(); 3076 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3077 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3078 return size; 3079 } 3080 3081 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3082 int size = 0; 3083 for (BasePermission perm : mSettings.mPermissions.values()) { 3084 if (perm.uid == tree.uid) { 3085 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3086 } 3087 } 3088 return size; 3089 } 3090 3091 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3092 // We calculate the max size of permissions defined by this uid and throw 3093 // if that plus the size of 'info' would exceed our stated maximum. 3094 if (tree.uid != Process.SYSTEM_UID) { 3095 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3096 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3097 throw new SecurityException("Permission tree size cap exceeded"); 3098 } 3099 } 3100 } 3101 3102 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3103 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3104 throw new SecurityException("Label must be specified in permission"); 3105 } 3106 BasePermission tree = checkPermissionTreeLP(info.name); 3107 BasePermission bp = mSettings.mPermissions.get(info.name); 3108 boolean added = bp == null; 3109 boolean changed = true; 3110 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3111 if (added) { 3112 enforcePermissionCapLocked(info, tree); 3113 bp = new BasePermission(info.name, tree.sourcePackage, 3114 BasePermission.TYPE_DYNAMIC); 3115 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3116 throw new SecurityException( 3117 "Not allowed to modify non-dynamic permission " 3118 + info.name); 3119 } else { 3120 if (bp.protectionLevel == fixedLevel 3121 && bp.perm.owner.equals(tree.perm.owner) 3122 && bp.uid == tree.uid 3123 && comparePermissionInfos(bp.perm.info, info)) { 3124 changed = false; 3125 } 3126 } 3127 bp.protectionLevel = fixedLevel; 3128 info = new PermissionInfo(info); 3129 info.protectionLevel = fixedLevel; 3130 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3131 bp.perm.info.packageName = tree.perm.info.packageName; 3132 bp.uid = tree.uid; 3133 if (added) { 3134 mSettings.mPermissions.put(info.name, bp); 3135 } 3136 if (changed) { 3137 if (!async) { 3138 mSettings.writeLPr(); 3139 } else { 3140 scheduleWriteSettingsLocked(); 3141 } 3142 } 3143 return added; 3144 } 3145 3146 @Override 3147 public boolean addPermission(PermissionInfo info) { 3148 synchronized (mPackages) { 3149 return addPermissionLocked(info, false); 3150 } 3151 } 3152 3153 @Override 3154 public boolean addPermissionAsync(PermissionInfo info) { 3155 synchronized (mPackages) { 3156 return addPermissionLocked(info, true); 3157 } 3158 } 3159 3160 @Override 3161 public void removePermission(String name) { 3162 synchronized (mPackages) { 3163 checkPermissionTreeLP(name); 3164 BasePermission bp = mSettings.mPermissions.get(name); 3165 if (bp != null) { 3166 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3167 throw new SecurityException( 3168 "Not allowed to modify non-dynamic permission " 3169 + name); 3170 } 3171 mSettings.mPermissions.remove(name); 3172 mSettings.writeLPr(); 3173 } 3174 } 3175 } 3176 3177 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3178 BasePermission bp) { 3179 int index = pkg.requestedPermissions.indexOf(bp.name); 3180 if (index == -1) { 3181 throw new SecurityException("Package " + pkg.packageName 3182 + " has not requested permission " + bp.name); 3183 } 3184 if (!bp.isRuntime()) { 3185 throw new SecurityException("Permission " + bp.name 3186 + " is not a changeable permission type"); 3187 } 3188 } 3189 3190 @Override 3191 public void grantRuntimePermission(String packageName, String name, final int userId) { 3192 if (!sUserManager.exists(userId)) { 3193 Log.e(TAG, "No such user:" + userId); 3194 return; 3195 } 3196 3197 mContext.enforceCallingOrSelfPermission( 3198 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3199 "grantRuntimePermission"); 3200 3201 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3202 "grantRuntimePermission"); 3203 3204 final SettingBase sb; 3205 3206 synchronized (mPackages) { 3207 final PackageParser.Package pkg = mPackages.get(packageName); 3208 if (pkg == null) { 3209 throw new IllegalArgumentException("Unknown package: " + packageName); 3210 } 3211 3212 final BasePermission bp = mSettings.mPermissions.get(name); 3213 if (bp == null) { 3214 throw new IllegalArgumentException("Unknown permission: " + name); 3215 } 3216 3217 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3218 3219 sb = (SettingBase) pkg.mExtras; 3220 if (sb == null) { 3221 throw new IllegalArgumentException("Unknown package: " + packageName); 3222 } 3223 3224 final PermissionsState permissionsState = sb.getPermissionsState(); 3225 3226 final int flags = permissionsState.getPermissionFlags(name, userId); 3227 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3228 throw new SecurityException("Cannot grant system fixed permission: " 3229 + name + " for package: " + packageName); 3230 } 3231 3232 final int result = permissionsState.grantRuntimePermission(bp, userId); 3233 switch (result) { 3234 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3235 return; 3236 } 3237 3238 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3239 mHandler.post(new Runnable() { 3240 @Override 3241 public void run() { 3242 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3243 } 3244 }); 3245 } break; 3246 } 3247 3248 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3249 3250 // Not critical if that is lost - app has to request again. 3251 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3252 } 3253 } 3254 3255 @Override 3256 public void revokeRuntimePermission(String packageName, String name, int userId) { 3257 if (!sUserManager.exists(userId)) { 3258 Log.e(TAG, "No such user:" + userId); 3259 return; 3260 } 3261 3262 mContext.enforceCallingOrSelfPermission( 3263 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3264 "revokeRuntimePermission"); 3265 3266 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3267 "revokeRuntimePermission"); 3268 3269 final SettingBase sb; 3270 3271 synchronized (mPackages) { 3272 final PackageParser.Package pkg = mPackages.get(packageName); 3273 if (pkg == null) { 3274 throw new IllegalArgumentException("Unknown package: " + packageName); 3275 } 3276 3277 final BasePermission bp = mSettings.mPermissions.get(name); 3278 if (bp == null) { 3279 throw new IllegalArgumentException("Unknown permission: " + name); 3280 } 3281 3282 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3283 3284 sb = (SettingBase) pkg.mExtras; 3285 if (sb == null) { 3286 throw new IllegalArgumentException("Unknown package: " + packageName); 3287 } 3288 3289 final PermissionsState permissionsState = sb.getPermissionsState(); 3290 3291 final int flags = permissionsState.getPermissionFlags(name, userId); 3292 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3293 throw new SecurityException("Cannot revoke system fixed permission: " 3294 + name + " for package: " + packageName); 3295 } 3296 3297 if (permissionsState.revokeRuntimePermission(bp, userId) == 3298 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3299 return; 3300 } 3301 3302 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3303 3304 // Critical, after this call app should never have the permission. 3305 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3306 } 3307 3308 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3309 } 3310 3311 @Override 3312 public int getPermissionFlags(String name, String packageName, int userId) { 3313 if (!sUserManager.exists(userId)) { 3314 return 0; 3315 } 3316 3317 mContext.enforceCallingOrSelfPermission( 3318 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3319 "getPermissionFlags"); 3320 3321 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3322 "getPermissionFlags"); 3323 3324 synchronized (mPackages) { 3325 final PackageParser.Package pkg = mPackages.get(packageName); 3326 if (pkg == null) { 3327 throw new IllegalArgumentException("Unknown package: " + packageName); 3328 } 3329 3330 final BasePermission bp = mSettings.mPermissions.get(name); 3331 if (bp == null) { 3332 throw new IllegalArgumentException("Unknown permission: " + name); 3333 } 3334 3335 SettingBase sb = (SettingBase) pkg.mExtras; 3336 if (sb == null) { 3337 throw new IllegalArgumentException("Unknown package: " + packageName); 3338 } 3339 3340 PermissionsState permissionsState = sb.getPermissionsState(); 3341 return permissionsState.getPermissionFlags(name, userId); 3342 } 3343 } 3344 3345 @Override 3346 public void updatePermissionFlags(String name, String packageName, int flagMask, 3347 int flagValues, int userId) { 3348 if (!sUserManager.exists(userId)) { 3349 return; 3350 } 3351 3352 mContext.enforceCallingOrSelfPermission( 3353 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3354 "updatePermissionFlags"); 3355 3356 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3357 "updatePermissionFlags"); 3358 3359 // Only the system can change system fixed flags. 3360 if (getCallingUid() != Process.SYSTEM_UID) { 3361 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3362 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3363 } 3364 3365 synchronized (mPackages) { 3366 final PackageParser.Package pkg = mPackages.get(packageName); 3367 if (pkg == null) { 3368 throw new IllegalArgumentException("Unknown package: " + packageName); 3369 } 3370 3371 final BasePermission bp = mSettings.mPermissions.get(name); 3372 if (bp == null) { 3373 throw new IllegalArgumentException("Unknown permission: " + name); 3374 } 3375 3376 SettingBase sb = (SettingBase) pkg.mExtras; 3377 if (sb == null) { 3378 throw new IllegalArgumentException("Unknown package: " + packageName); 3379 } 3380 3381 PermissionsState permissionsState = sb.getPermissionsState(); 3382 3383 // Only the package manager can change flags for system component permissions. 3384 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3385 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3386 return; 3387 } 3388 3389 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3390 3391 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3392 // Install and runtime permissions are stored in different places, 3393 // so figure out what permission changed and persist the change. 3394 if (permissionsState.getInstallPermissionState(name) != null) { 3395 scheduleWriteSettingsLocked(); 3396 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3397 || hadState) { 3398 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3399 } 3400 } 3401 } 3402 } 3403 3404 /** 3405 * Update the permission flags for all packages and runtime permissions of a user in order 3406 * to allow device or profile owner to remove POLICY_FIXED. 3407 */ 3408 @Override 3409 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3410 if (!sUserManager.exists(userId)) { 3411 return; 3412 } 3413 3414 mContext.enforceCallingOrSelfPermission( 3415 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3416 "updatePermissionFlagsForAllApps"); 3417 3418 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3419 "updatePermissionFlagsForAllApps"); 3420 3421 // Only the system can change system fixed flags. 3422 if (getCallingUid() != Process.SYSTEM_UID) { 3423 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3424 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3425 } 3426 3427 synchronized (mPackages) { 3428 boolean changed = false; 3429 final int packageCount = mPackages.size(); 3430 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3431 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3432 SettingBase sb = (SettingBase) pkg.mExtras; 3433 if (sb == null) { 3434 continue; 3435 } 3436 PermissionsState permissionsState = sb.getPermissionsState(); 3437 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3438 userId, flagMask, flagValues); 3439 } 3440 if (changed) { 3441 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3442 } 3443 } 3444 } 3445 3446 @Override 3447 public boolean shouldShowRequestPermissionRationale(String permissionName, 3448 String packageName, int userId) { 3449 if (UserHandle.getCallingUserId() != userId) { 3450 mContext.enforceCallingPermission( 3451 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3452 "canShowRequestPermissionRationale for user " + userId); 3453 } 3454 3455 final int uid = getPackageUid(packageName, userId); 3456 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3457 return false; 3458 } 3459 3460 if (checkPermission(permissionName, packageName, userId) 3461 == PackageManager.PERMISSION_GRANTED) { 3462 return false; 3463 } 3464 3465 final int flags; 3466 3467 final long identity = Binder.clearCallingIdentity(); 3468 try { 3469 flags = getPermissionFlags(permissionName, 3470 packageName, userId); 3471 } finally { 3472 Binder.restoreCallingIdentity(identity); 3473 } 3474 3475 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3476 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3477 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3478 3479 if ((flags & fixedFlags) != 0) { 3480 return false; 3481 } 3482 3483 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3484 } 3485 3486 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3487 BasePermission bp = mSettings.mPermissions.get(permission); 3488 if (bp == null) { 3489 throw new SecurityException("Missing " + permission + " permission"); 3490 } 3491 3492 SettingBase sb = (SettingBase) pkg.mExtras; 3493 PermissionsState permissionsState = sb.getPermissionsState(); 3494 3495 if (permissionsState.grantInstallPermission(bp) != 3496 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3497 scheduleWriteSettingsLocked(); 3498 } 3499 } 3500 3501 @Override 3502 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3503 mContext.enforceCallingOrSelfPermission( 3504 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3505 "addOnPermissionsChangeListener"); 3506 3507 synchronized (mPackages) { 3508 mOnPermissionChangeListeners.addListenerLocked(listener); 3509 } 3510 } 3511 3512 @Override 3513 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3514 synchronized (mPackages) { 3515 mOnPermissionChangeListeners.removeListenerLocked(listener); 3516 } 3517 } 3518 3519 @Override 3520 public boolean isProtectedBroadcast(String actionName) { 3521 synchronized (mPackages) { 3522 return mProtectedBroadcasts.contains(actionName); 3523 } 3524 } 3525 3526 @Override 3527 public int checkSignatures(String pkg1, String pkg2) { 3528 synchronized (mPackages) { 3529 final PackageParser.Package p1 = mPackages.get(pkg1); 3530 final PackageParser.Package p2 = mPackages.get(pkg2); 3531 if (p1 == null || p1.mExtras == null 3532 || p2 == null || p2.mExtras == null) { 3533 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3534 } 3535 return compareSignatures(p1.mSignatures, p2.mSignatures); 3536 } 3537 } 3538 3539 @Override 3540 public int checkUidSignatures(int uid1, int uid2) { 3541 // Map to base uids. 3542 uid1 = UserHandle.getAppId(uid1); 3543 uid2 = UserHandle.getAppId(uid2); 3544 // reader 3545 synchronized (mPackages) { 3546 Signature[] s1; 3547 Signature[] s2; 3548 Object obj = mSettings.getUserIdLPr(uid1); 3549 if (obj != null) { 3550 if (obj instanceof SharedUserSetting) { 3551 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3552 } else if (obj instanceof PackageSetting) { 3553 s1 = ((PackageSetting)obj).signatures.mSignatures; 3554 } else { 3555 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3556 } 3557 } else { 3558 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3559 } 3560 obj = mSettings.getUserIdLPr(uid2); 3561 if (obj != null) { 3562 if (obj instanceof SharedUserSetting) { 3563 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3564 } else if (obj instanceof PackageSetting) { 3565 s2 = ((PackageSetting)obj).signatures.mSignatures; 3566 } else { 3567 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3568 } 3569 } else { 3570 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3571 } 3572 return compareSignatures(s1, s2); 3573 } 3574 } 3575 3576 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3577 final long identity = Binder.clearCallingIdentity(); 3578 try { 3579 if (sb instanceof SharedUserSetting) { 3580 SharedUserSetting sus = (SharedUserSetting) sb; 3581 final int packageCount = sus.packages.size(); 3582 for (int i = 0; i < packageCount; i++) { 3583 PackageSetting susPs = sus.packages.valueAt(i); 3584 if (userId == UserHandle.USER_ALL) { 3585 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3586 } else { 3587 final int uid = UserHandle.getUid(userId, susPs.appId); 3588 killUid(uid, reason); 3589 } 3590 } 3591 } else if (sb instanceof PackageSetting) { 3592 PackageSetting ps = (PackageSetting) sb; 3593 if (userId == UserHandle.USER_ALL) { 3594 killApplication(ps.pkg.packageName, ps.appId, reason); 3595 } else { 3596 final int uid = UserHandle.getUid(userId, ps.appId); 3597 killUid(uid, reason); 3598 } 3599 } 3600 } finally { 3601 Binder.restoreCallingIdentity(identity); 3602 } 3603 } 3604 3605 private static void killUid(int uid, String reason) { 3606 IActivityManager am = ActivityManagerNative.getDefault(); 3607 if (am != null) { 3608 try { 3609 am.killUid(uid, reason); 3610 } catch (RemoteException e) { 3611 /* ignore - same process */ 3612 } 3613 } 3614 } 3615 3616 /** 3617 * Compares two sets of signatures. Returns: 3618 * <br /> 3619 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3620 * <br /> 3621 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3622 * <br /> 3623 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3624 * <br /> 3625 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3626 * <br /> 3627 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3628 */ 3629 static int compareSignatures(Signature[] s1, Signature[] s2) { 3630 if (s1 == null) { 3631 return s2 == null 3632 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3633 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3634 } 3635 3636 if (s2 == null) { 3637 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3638 } 3639 3640 if (s1.length != s2.length) { 3641 return PackageManager.SIGNATURE_NO_MATCH; 3642 } 3643 3644 // Since both signature sets are of size 1, we can compare without HashSets. 3645 if (s1.length == 1) { 3646 return s1[0].equals(s2[0]) ? 3647 PackageManager.SIGNATURE_MATCH : 3648 PackageManager.SIGNATURE_NO_MATCH; 3649 } 3650 3651 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3652 for (Signature sig : s1) { 3653 set1.add(sig); 3654 } 3655 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3656 for (Signature sig : s2) { 3657 set2.add(sig); 3658 } 3659 // Make sure s2 contains all signatures in s1. 3660 if (set1.equals(set2)) { 3661 return PackageManager.SIGNATURE_MATCH; 3662 } 3663 return PackageManager.SIGNATURE_NO_MATCH; 3664 } 3665 3666 /** 3667 * If the database version for this type of package (internal storage or 3668 * external storage) is less than the version where package signatures 3669 * were updated, return true. 3670 */ 3671 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3672 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3673 DatabaseVersion.SIGNATURE_END_ENTITY)) 3674 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3675 DatabaseVersion.SIGNATURE_END_ENTITY)); 3676 } 3677 3678 /** 3679 * Used for backward compatibility to make sure any packages with 3680 * certificate chains get upgraded to the new style. {@code existingSigs} 3681 * will be in the old format (since they were stored on disk from before the 3682 * system upgrade) and {@code scannedSigs} will be in the newer format. 3683 */ 3684 private int compareSignaturesCompat(PackageSignatures existingSigs, 3685 PackageParser.Package scannedPkg) { 3686 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3687 return PackageManager.SIGNATURE_NO_MATCH; 3688 } 3689 3690 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3691 for (Signature sig : existingSigs.mSignatures) { 3692 existingSet.add(sig); 3693 } 3694 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3695 for (Signature sig : scannedPkg.mSignatures) { 3696 try { 3697 Signature[] chainSignatures = sig.getChainSignatures(); 3698 for (Signature chainSig : chainSignatures) { 3699 scannedCompatSet.add(chainSig); 3700 } 3701 } catch (CertificateEncodingException e) { 3702 scannedCompatSet.add(sig); 3703 } 3704 } 3705 /* 3706 * Make sure the expanded scanned set contains all signatures in the 3707 * existing one. 3708 */ 3709 if (scannedCompatSet.equals(existingSet)) { 3710 // Migrate the old signatures to the new scheme. 3711 existingSigs.assignSignatures(scannedPkg.mSignatures); 3712 // The new KeySets will be re-added later in the scanning process. 3713 synchronized (mPackages) { 3714 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3715 } 3716 return PackageManager.SIGNATURE_MATCH; 3717 } 3718 return PackageManager.SIGNATURE_NO_MATCH; 3719 } 3720 3721 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3722 if (isExternal(scannedPkg)) { 3723 return mSettings.isExternalDatabaseVersionOlderThan( 3724 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3725 } else { 3726 return mSettings.isInternalDatabaseVersionOlderThan( 3727 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3728 } 3729 } 3730 3731 private int compareSignaturesRecover(PackageSignatures existingSigs, 3732 PackageParser.Package scannedPkg) { 3733 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3734 return PackageManager.SIGNATURE_NO_MATCH; 3735 } 3736 3737 String msg = null; 3738 try { 3739 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3740 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3741 + scannedPkg.packageName); 3742 return PackageManager.SIGNATURE_MATCH; 3743 } 3744 } catch (CertificateException e) { 3745 msg = e.getMessage(); 3746 } 3747 3748 logCriticalInfo(Log.INFO, 3749 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3750 return PackageManager.SIGNATURE_NO_MATCH; 3751 } 3752 3753 @Override 3754 public String[] getPackagesForUid(int uid) { 3755 uid = UserHandle.getAppId(uid); 3756 // reader 3757 synchronized (mPackages) { 3758 Object obj = mSettings.getUserIdLPr(uid); 3759 if (obj instanceof SharedUserSetting) { 3760 final SharedUserSetting sus = (SharedUserSetting) obj; 3761 final int N = sus.packages.size(); 3762 final String[] res = new String[N]; 3763 final Iterator<PackageSetting> it = sus.packages.iterator(); 3764 int i = 0; 3765 while (it.hasNext()) { 3766 res[i++] = it.next().name; 3767 } 3768 return res; 3769 } else if (obj instanceof PackageSetting) { 3770 final PackageSetting ps = (PackageSetting) obj; 3771 return new String[] { ps.name }; 3772 } 3773 } 3774 return null; 3775 } 3776 3777 @Override 3778 public String getNameForUid(int uid) { 3779 // reader 3780 synchronized (mPackages) { 3781 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3782 if (obj instanceof SharedUserSetting) { 3783 final SharedUserSetting sus = (SharedUserSetting) obj; 3784 return sus.name + ":" + sus.userId; 3785 } else if (obj instanceof PackageSetting) { 3786 final PackageSetting ps = (PackageSetting) obj; 3787 return ps.name; 3788 } 3789 } 3790 return null; 3791 } 3792 3793 @Override 3794 public int getUidForSharedUser(String sharedUserName) { 3795 if(sharedUserName == null) { 3796 return -1; 3797 } 3798 // reader 3799 synchronized (mPackages) { 3800 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3801 if (suid == null) { 3802 return -1; 3803 } 3804 return suid.userId; 3805 } 3806 } 3807 3808 @Override 3809 public int getFlagsForUid(int uid) { 3810 synchronized (mPackages) { 3811 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3812 if (obj instanceof SharedUserSetting) { 3813 final SharedUserSetting sus = (SharedUserSetting) obj; 3814 return sus.pkgFlags; 3815 } else if (obj instanceof PackageSetting) { 3816 final PackageSetting ps = (PackageSetting) obj; 3817 return ps.pkgFlags; 3818 } 3819 } 3820 return 0; 3821 } 3822 3823 @Override 3824 public int getPrivateFlagsForUid(int uid) { 3825 synchronized (mPackages) { 3826 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3827 if (obj instanceof SharedUserSetting) { 3828 final SharedUserSetting sus = (SharedUserSetting) obj; 3829 return sus.pkgPrivateFlags; 3830 } else if (obj instanceof PackageSetting) { 3831 final PackageSetting ps = (PackageSetting) obj; 3832 return ps.pkgPrivateFlags; 3833 } 3834 } 3835 return 0; 3836 } 3837 3838 @Override 3839 public boolean isUidPrivileged(int uid) { 3840 uid = UserHandle.getAppId(uid); 3841 // reader 3842 synchronized (mPackages) { 3843 Object obj = mSettings.getUserIdLPr(uid); 3844 if (obj instanceof SharedUserSetting) { 3845 final SharedUserSetting sus = (SharedUserSetting) obj; 3846 final Iterator<PackageSetting> it = sus.packages.iterator(); 3847 while (it.hasNext()) { 3848 if (it.next().isPrivileged()) { 3849 return true; 3850 } 3851 } 3852 } else if (obj instanceof PackageSetting) { 3853 final PackageSetting ps = (PackageSetting) obj; 3854 return ps.isPrivileged(); 3855 } 3856 } 3857 return false; 3858 } 3859 3860 @Override 3861 public String[] getAppOpPermissionPackages(String permissionName) { 3862 synchronized (mPackages) { 3863 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3864 if (pkgs == null) { 3865 return null; 3866 } 3867 return pkgs.toArray(new String[pkgs.size()]); 3868 } 3869 } 3870 3871 @Override 3872 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3873 int flags, int userId) { 3874 if (!sUserManager.exists(userId)) return null; 3875 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3876 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3877 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3878 } 3879 3880 @Override 3881 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3882 IntentFilter filter, int match, ComponentName activity) { 3883 final int userId = UserHandle.getCallingUserId(); 3884 if (DEBUG_PREFERRED) { 3885 Log.v(TAG, "setLastChosenActivity intent=" + intent 3886 + " resolvedType=" + resolvedType 3887 + " flags=" + flags 3888 + " filter=" + filter 3889 + " match=" + match 3890 + " activity=" + activity); 3891 filter.dump(new PrintStreamPrinter(System.out), " "); 3892 } 3893 intent.setComponent(null); 3894 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3895 // Find any earlier preferred or last chosen entries and nuke them 3896 findPreferredActivity(intent, resolvedType, 3897 flags, query, 0, false, true, false, userId); 3898 // Add the new activity as the last chosen for this filter 3899 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3900 "Setting last chosen"); 3901 } 3902 3903 @Override 3904 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3905 final int userId = UserHandle.getCallingUserId(); 3906 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3907 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3908 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3909 false, false, false, userId); 3910 } 3911 3912 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3913 int flags, List<ResolveInfo> query, int userId) { 3914 if (query != null) { 3915 final int N = query.size(); 3916 if (N == 1) { 3917 return query.get(0); 3918 } else if (N > 1) { 3919 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3920 // If there is more than one activity with the same priority, 3921 // then let the user decide between them. 3922 ResolveInfo r0 = query.get(0); 3923 ResolveInfo r1 = query.get(1); 3924 if (DEBUG_INTENT_MATCHING || debug) { 3925 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3926 + r1.activityInfo.name + "=" + r1.priority); 3927 } 3928 // If the first activity has a higher priority, or a different 3929 // default, then it is always desireable to pick it. 3930 if (r0.priority != r1.priority 3931 || r0.preferredOrder != r1.preferredOrder 3932 || r0.isDefault != r1.isDefault) { 3933 return query.get(0); 3934 } 3935 // If we have saved a preference for a preferred activity for 3936 // this Intent, use that. 3937 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3938 flags, query, r0.priority, true, false, debug, userId); 3939 if (ri != null) { 3940 return ri; 3941 } 3942 if (userId != 0) { 3943 ri = new ResolveInfo(mResolveInfo); 3944 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3945 ri.activityInfo.applicationInfo = new ApplicationInfo( 3946 ri.activityInfo.applicationInfo); 3947 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3948 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3949 return ri; 3950 } 3951 return mResolveInfo; 3952 } 3953 } 3954 return null; 3955 } 3956 3957 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3958 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3959 final int N = query.size(); 3960 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3961 .get(userId); 3962 // Get the list of persistent preferred activities that handle the intent 3963 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3964 List<PersistentPreferredActivity> pprefs = ppir != null 3965 ? ppir.queryIntent(intent, resolvedType, 3966 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3967 : null; 3968 if (pprefs != null && pprefs.size() > 0) { 3969 final int M = pprefs.size(); 3970 for (int i=0; i<M; i++) { 3971 final PersistentPreferredActivity ppa = pprefs.get(i); 3972 if (DEBUG_PREFERRED || debug) { 3973 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3974 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3975 + "\n component=" + ppa.mComponent); 3976 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3977 } 3978 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3979 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3980 if (DEBUG_PREFERRED || debug) { 3981 Slog.v(TAG, "Found persistent preferred activity:"); 3982 if (ai != null) { 3983 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3984 } else { 3985 Slog.v(TAG, " null"); 3986 } 3987 } 3988 if (ai == null) { 3989 // This previously registered persistent preferred activity 3990 // component is no longer known. Ignore it and do NOT remove it. 3991 continue; 3992 } 3993 for (int j=0; j<N; j++) { 3994 final ResolveInfo ri = query.get(j); 3995 if (!ri.activityInfo.applicationInfo.packageName 3996 .equals(ai.applicationInfo.packageName)) { 3997 continue; 3998 } 3999 if (!ri.activityInfo.name.equals(ai.name)) { 4000 continue; 4001 } 4002 // Found a persistent preference that can handle the intent. 4003 if (DEBUG_PREFERRED || debug) { 4004 Slog.v(TAG, "Returning persistent preferred activity: " + 4005 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4006 } 4007 return ri; 4008 } 4009 } 4010 } 4011 return null; 4012 } 4013 4014 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4015 List<ResolveInfo> query, int priority, boolean always, 4016 boolean removeMatches, boolean debug, int userId) { 4017 if (!sUserManager.exists(userId)) return null; 4018 // writer 4019 synchronized (mPackages) { 4020 if (intent.getSelector() != null) { 4021 intent = intent.getSelector(); 4022 } 4023 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4024 4025 // Try to find a matching persistent preferred activity. 4026 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4027 debug, userId); 4028 4029 // If a persistent preferred activity matched, use it. 4030 if (pri != null) { 4031 return pri; 4032 } 4033 4034 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4035 // Get the list of preferred activities that handle the intent 4036 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4037 List<PreferredActivity> prefs = pir != null 4038 ? pir.queryIntent(intent, resolvedType, 4039 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4040 : null; 4041 if (prefs != null && prefs.size() > 0) { 4042 boolean changed = false; 4043 try { 4044 // First figure out how good the original match set is. 4045 // We will only allow preferred activities that came 4046 // from the same match quality. 4047 int match = 0; 4048 4049 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4050 4051 final int N = query.size(); 4052 for (int j=0; j<N; j++) { 4053 final ResolveInfo ri = query.get(j); 4054 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4055 + ": 0x" + Integer.toHexString(match)); 4056 if (ri.match > match) { 4057 match = ri.match; 4058 } 4059 } 4060 4061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4062 + Integer.toHexString(match)); 4063 4064 match &= IntentFilter.MATCH_CATEGORY_MASK; 4065 final int M = prefs.size(); 4066 for (int i=0; i<M; i++) { 4067 final PreferredActivity pa = prefs.get(i); 4068 if (DEBUG_PREFERRED || debug) { 4069 Slog.v(TAG, "Checking PreferredActivity ds=" 4070 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4071 + "\n component=" + pa.mPref.mComponent); 4072 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4073 } 4074 if (pa.mPref.mMatch != match) { 4075 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4076 + Integer.toHexString(pa.mPref.mMatch)); 4077 continue; 4078 } 4079 // If it's not an "always" type preferred activity and that's what we're 4080 // looking for, skip it. 4081 if (always && !pa.mPref.mAlways) { 4082 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4083 continue; 4084 } 4085 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4086 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4087 if (DEBUG_PREFERRED || debug) { 4088 Slog.v(TAG, "Found preferred activity:"); 4089 if (ai != null) { 4090 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4091 } else { 4092 Slog.v(TAG, " null"); 4093 } 4094 } 4095 if (ai == null) { 4096 // This previously registered preferred activity 4097 // component is no longer known. Most likely an update 4098 // to the app was installed and in the new version this 4099 // component no longer exists. Clean it up by removing 4100 // it from the preferred activities list, and skip it. 4101 Slog.w(TAG, "Removing dangling preferred activity: " 4102 + pa.mPref.mComponent); 4103 pir.removeFilter(pa); 4104 changed = true; 4105 continue; 4106 } 4107 for (int j=0; j<N; j++) { 4108 final ResolveInfo ri = query.get(j); 4109 if (!ri.activityInfo.applicationInfo.packageName 4110 .equals(ai.applicationInfo.packageName)) { 4111 continue; 4112 } 4113 if (!ri.activityInfo.name.equals(ai.name)) { 4114 continue; 4115 } 4116 4117 if (removeMatches) { 4118 pir.removeFilter(pa); 4119 changed = true; 4120 if (DEBUG_PREFERRED) { 4121 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4122 } 4123 break; 4124 } 4125 4126 // Okay we found a previously set preferred or last chosen app. 4127 // If the result set is different from when this 4128 // was created, we need to clear it and re-ask the 4129 // user their preference, if we're looking for an "always" type entry. 4130 if (always && !pa.mPref.sameSet(query)) { 4131 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4132 + intent + " type " + resolvedType); 4133 if (DEBUG_PREFERRED) { 4134 Slog.v(TAG, "Removing preferred activity since set changed " 4135 + pa.mPref.mComponent); 4136 } 4137 pir.removeFilter(pa); 4138 // Re-add the filter as a "last chosen" entry (!always) 4139 PreferredActivity lastChosen = new PreferredActivity( 4140 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4141 pir.addFilter(lastChosen); 4142 changed = true; 4143 return null; 4144 } 4145 4146 // Yay! Either the set matched or we're looking for the last chosen 4147 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4148 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4149 return ri; 4150 } 4151 } 4152 } finally { 4153 if (changed) { 4154 if (DEBUG_PREFERRED) { 4155 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4156 } 4157 scheduleWritePackageRestrictionsLocked(userId); 4158 } 4159 } 4160 } 4161 } 4162 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4163 return null; 4164 } 4165 4166 /* 4167 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4168 */ 4169 @Override 4170 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4171 int targetUserId) { 4172 mContext.enforceCallingOrSelfPermission( 4173 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4174 List<CrossProfileIntentFilter> matches = 4175 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4176 if (matches != null) { 4177 int size = matches.size(); 4178 for (int i = 0; i < size; i++) { 4179 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4180 } 4181 } 4182 if (hasWebURI(intent)) { 4183 // cross-profile app linking works only towards the parent. 4184 final UserInfo parent = getProfileParent(sourceUserId); 4185 synchronized(mPackages) { 4186 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4187 parent.id) != null; 4188 } 4189 } 4190 return false; 4191 } 4192 4193 private UserInfo getProfileParent(int userId) { 4194 final long identity = Binder.clearCallingIdentity(); 4195 try { 4196 return sUserManager.getProfileParent(userId); 4197 } finally { 4198 Binder.restoreCallingIdentity(identity); 4199 } 4200 } 4201 4202 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4203 String resolvedType, int userId) { 4204 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4205 if (resolver != null) { 4206 return resolver.queryIntent(intent, resolvedType, false, userId); 4207 } 4208 return null; 4209 } 4210 4211 @Override 4212 public List<ResolveInfo> queryIntentActivities(Intent intent, 4213 String resolvedType, int flags, int userId) { 4214 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4215 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4216 ComponentName comp = intent.getComponent(); 4217 if (comp == null) { 4218 if (intent.getSelector() != null) { 4219 intent = intent.getSelector(); 4220 comp = intent.getComponent(); 4221 } 4222 } 4223 4224 if (comp != null) { 4225 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4226 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4227 if (ai != null) { 4228 final ResolveInfo ri = new ResolveInfo(); 4229 ri.activityInfo = ai; 4230 list.add(ri); 4231 } 4232 return list; 4233 } 4234 4235 // reader 4236 synchronized (mPackages) { 4237 final String pkgName = intent.getPackage(); 4238 if (pkgName == null) { 4239 List<CrossProfileIntentFilter> matchingFilters = 4240 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4241 // Check for results that need to skip the current profile. 4242 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4243 resolvedType, flags, userId); 4244 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4245 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4246 result.add(xpResolveInfo); 4247 return filterIfNotPrimaryUser(result, userId); 4248 } 4249 4250 // Check for results in the current profile. 4251 List<ResolveInfo> result = mActivities.queryIntent( 4252 intent, resolvedType, flags, userId); 4253 4254 // Check for cross profile results. 4255 xpResolveInfo = queryCrossProfileIntents( 4256 matchingFilters, intent, resolvedType, flags, userId); 4257 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4258 result.add(xpResolveInfo); 4259 Collections.sort(result, mResolvePrioritySorter); 4260 } 4261 result = filterIfNotPrimaryUser(result, userId); 4262 if (hasWebURI(intent)) { 4263 CrossProfileDomainInfo xpDomainInfo = null; 4264 final UserInfo parent = getProfileParent(userId); 4265 if (parent != null) { 4266 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4267 flags, userId, parent.id); 4268 } 4269 if (xpDomainInfo != null) { 4270 if (xpResolveInfo != null) { 4271 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4272 // in the result. 4273 result.remove(xpResolveInfo); 4274 } 4275 if (result.size() == 0) { 4276 result.add(xpDomainInfo.resolveInfo); 4277 return result; 4278 } 4279 } else if (result.size() <= 1) { 4280 return result; 4281 } 4282 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4283 xpDomainInfo); 4284 Collections.sort(result, mResolvePrioritySorter); 4285 } 4286 return result; 4287 } 4288 final PackageParser.Package pkg = mPackages.get(pkgName); 4289 if (pkg != null) { 4290 return filterIfNotPrimaryUser( 4291 mActivities.queryIntentForPackage( 4292 intent, resolvedType, flags, pkg.activities, userId), 4293 userId); 4294 } 4295 return new ArrayList<ResolveInfo>(); 4296 } 4297 } 4298 4299 private static class CrossProfileDomainInfo { 4300 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4301 ResolveInfo resolveInfo; 4302 /* Best domain verification status of the activities found in the other profile */ 4303 int bestDomainVerificationStatus; 4304 } 4305 4306 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4307 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4308 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING, 4309 sourceUserId)) { 4310 return null; 4311 } 4312 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4313 resolvedType, flags, parentUserId); 4314 4315 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4316 return null; 4317 } 4318 CrossProfileDomainInfo result = null; 4319 int size = resultTargetUser.size(); 4320 for (int i = 0; i < size; i++) { 4321 ResolveInfo riTargetUser = resultTargetUser.get(i); 4322 // Intent filter verification is only for filters that specify a host. So don't return 4323 // those that handle all web uris. 4324 if (riTargetUser.handleAllWebDataURI) { 4325 continue; 4326 } 4327 String packageName = riTargetUser.activityInfo.packageName; 4328 PackageSetting ps = mSettings.mPackages.get(packageName); 4329 if (ps == null) { 4330 continue; 4331 } 4332 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4333 if (result == null) { 4334 result = new CrossProfileDomainInfo(); 4335 result.resolveInfo = 4336 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4337 result.bestDomainVerificationStatus = status; 4338 } else { 4339 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4340 result.bestDomainVerificationStatus); 4341 } 4342 } 4343 return result; 4344 } 4345 4346 /** 4347 * Verification statuses are ordered from the worse to the best, except for 4348 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4349 */ 4350 private int bestDomainVerificationStatus(int status1, int status2) { 4351 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4352 return status2; 4353 } 4354 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4355 return status1; 4356 } 4357 return (int) MathUtils.max(status1, status2); 4358 } 4359 4360 private boolean isUserEnabled(int userId) { 4361 long callingId = Binder.clearCallingIdentity(); 4362 try { 4363 UserInfo userInfo = sUserManager.getUserInfo(userId); 4364 return userInfo != null && userInfo.isEnabled(); 4365 } finally { 4366 Binder.restoreCallingIdentity(callingId); 4367 } 4368 } 4369 4370 /** 4371 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4372 * 4373 * @return filtered list 4374 */ 4375 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4376 if (userId == UserHandle.USER_OWNER) { 4377 return resolveInfos; 4378 } 4379 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4380 ResolveInfo info = resolveInfos.get(i); 4381 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4382 resolveInfos.remove(i); 4383 } 4384 } 4385 return resolveInfos; 4386 } 4387 4388 private static boolean hasWebURI(Intent intent) { 4389 if (intent.getData() == null) { 4390 return false; 4391 } 4392 final String scheme = intent.getScheme(); 4393 if (TextUtils.isEmpty(scheme)) { 4394 return false; 4395 } 4396 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4397 } 4398 4399 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4400 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4401 if (DEBUG_PREFERRED) { 4402 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4403 candidates.size()); 4404 } 4405 4406 final int userId = UserHandle.getCallingUserId(); 4407 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4408 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4409 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4410 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4411 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4412 4413 synchronized (mPackages) { 4414 final int count = candidates.size(); 4415 // First, try to use the domain prefered App. Partition the candidates into four lists: 4416 // one for the final results, one for the "do not use ever", one for "undefined status" 4417 // and finally one for "Browser App type". 4418 for (int n=0; n<count; n++) { 4419 ResolveInfo info = candidates.get(n); 4420 String packageName = info.activityInfo.packageName; 4421 PackageSetting ps = mSettings.mPackages.get(packageName); 4422 if (ps != null) { 4423 // Add to the special match all list (Browser use case) 4424 if (info.handleAllWebDataURI) { 4425 matchAllList.add(info); 4426 continue; 4427 } 4428 // Try to get the status from User settings first 4429 int status = getDomainVerificationStatusLPr(ps, userId); 4430 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4431 alwaysList.add(info); 4432 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4433 neverList.add(info); 4434 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4435 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4436 undefinedList.add(info); 4437 } 4438 } 4439 } 4440 // First try to add the "always" resolution for the current user if there is any 4441 if (alwaysList.size() > 0) { 4442 result.addAll(alwaysList); 4443 // if there is an "always" for the parent user, add it. 4444 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4445 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4446 result.add(xpDomainInfo.resolveInfo); 4447 } else { 4448 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4449 result.addAll(undefinedList); 4450 if (xpDomainInfo != null && ( 4451 xpDomainInfo.bestDomainVerificationStatus 4452 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4453 || xpDomainInfo.bestDomainVerificationStatus 4454 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4455 result.add(xpDomainInfo.resolveInfo); 4456 } 4457 // Also add Browsers (all of them or only the default one) 4458 if ((flags & MATCH_ALL) != 0) { 4459 result.addAll(matchAllList); 4460 } else { 4461 // Try to add the Default Browser if we can 4462 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4463 UserHandle.myUserId()); 4464 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4465 boolean defaultBrowserFound = false; 4466 final int browserCount = matchAllList.size(); 4467 for (int n=0; n<browserCount; n++) { 4468 ResolveInfo browser = matchAllList.get(n); 4469 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4470 result.add(browser); 4471 defaultBrowserFound = true; 4472 break; 4473 } 4474 } 4475 if (!defaultBrowserFound) { 4476 result.addAll(matchAllList); 4477 } 4478 } else { 4479 result.addAll(matchAllList); 4480 } 4481 } 4482 4483 // If there is nothing selected, add all candidates and remove the ones that the User 4484 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4485 if (result.size() == 0) { 4486 result.addAll(candidates); 4487 result.removeAll(neverList); 4488 } 4489 } 4490 } 4491 if (DEBUG_PREFERRED) { 4492 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4493 result.size()); 4494 } 4495 return result; 4496 } 4497 4498 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4499 int status = ps.getDomainVerificationStatusForUser(userId); 4500 // if none available, get the master status 4501 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4502 if (ps.getIntentFilterVerificationInfo() != null) { 4503 status = ps.getIntentFilterVerificationInfo().getStatus(); 4504 } 4505 } 4506 return status; 4507 } 4508 4509 private ResolveInfo querySkipCurrentProfileIntents( 4510 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4511 int flags, int sourceUserId) { 4512 if (matchingFilters != null) { 4513 int size = matchingFilters.size(); 4514 for (int i = 0; i < size; i ++) { 4515 CrossProfileIntentFilter filter = matchingFilters.get(i); 4516 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4517 // Checking if there are activities in the target user that can handle the 4518 // intent. 4519 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4520 flags, sourceUserId); 4521 if (resolveInfo != null) { 4522 return resolveInfo; 4523 } 4524 } 4525 } 4526 } 4527 return null; 4528 } 4529 4530 // Return matching ResolveInfo if any for skip current profile intent filters. 4531 private ResolveInfo queryCrossProfileIntents( 4532 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4533 int flags, int sourceUserId) { 4534 if (matchingFilters != null) { 4535 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4536 // match the same intent. For performance reasons, it is better not to 4537 // run queryIntent twice for the same userId 4538 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4539 int size = matchingFilters.size(); 4540 for (int i = 0; i < size; i++) { 4541 CrossProfileIntentFilter filter = matchingFilters.get(i); 4542 int targetUserId = filter.getTargetUserId(); 4543 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4544 && !alreadyTriedUserIds.get(targetUserId)) { 4545 // Checking if there are activities in the target user that can handle the 4546 // intent. 4547 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4548 flags, sourceUserId); 4549 if (resolveInfo != null) return resolveInfo; 4550 alreadyTriedUserIds.put(targetUserId, true); 4551 } 4552 } 4553 } 4554 return null; 4555 } 4556 4557 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4558 String resolvedType, int flags, int sourceUserId) { 4559 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4560 resolvedType, flags, filter.getTargetUserId()); 4561 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4562 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4563 } 4564 return null; 4565 } 4566 4567 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4568 int sourceUserId, int targetUserId) { 4569 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4570 String className; 4571 if (targetUserId == UserHandle.USER_OWNER) { 4572 className = FORWARD_INTENT_TO_USER_OWNER; 4573 } else { 4574 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4575 } 4576 ComponentName forwardingActivityComponentName = new ComponentName( 4577 mAndroidApplication.packageName, className); 4578 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4579 sourceUserId); 4580 if (targetUserId == UserHandle.USER_OWNER) { 4581 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4582 forwardingResolveInfo.noResourceId = true; 4583 } 4584 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4585 forwardingResolveInfo.priority = 0; 4586 forwardingResolveInfo.preferredOrder = 0; 4587 forwardingResolveInfo.match = 0; 4588 forwardingResolveInfo.isDefault = true; 4589 forwardingResolveInfo.filter = filter; 4590 forwardingResolveInfo.targetUserId = targetUserId; 4591 return forwardingResolveInfo; 4592 } 4593 4594 @Override 4595 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4596 Intent[] specifics, String[] specificTypes, Intent intent, 4597 String resolvedType, int flags, int userId) { 4598 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4599 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4600 false, "query intent activity options"); 4601 final String resultsAction = intent.getAction(); 4602 4603 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4604 | PackageManager.GET_RESOLVED_FILTER, userId); 4605 4606 if (DEBUG_INTENT_MATCHING) { 4607 Log.v(TAG, "Query " + intent + ": " + results); 4608 } 4609 4610 int specificsPos = 0; 4611 int N; 4612 4613 // todo: note that the algorithm used here is O(N^2). This 4614 // isn't a problem in our current environment, but if we start running 4615 // into situations where we have more than 5 or 10 matches then this 4616 // should probably be changed to something smarter... 4617 4618 // First we go through and resolve each of the specific items 4619 // that were supplied, taking care of removing any corresponding 4620 // duplicate items in the generic resolve list. 4621 if (specifics != null) { 4622 for (int i=0; i<specifics.length; i++) { 4623 final Intent sintent = specifics[i]; 4624 if (sintent == null) { 4625 continue; 4626 } 4627 4628 if (DEBUG_INTENT_MATCHING) { 4629 Log.v(TAG, "Specific #" + i + ": " + sintent); 4630 } 4631 4632 String action = sintent.getAction(); 4633 if (resultsAction != null && resultsAction.equals(action)) { 4634 // If this action was explicitly requested, then don't 4635 // remove things that have it. 4636 action = null; 4637 } 4638 4639 ResolveInfo ri = null; 4640 ActivityInfo ai = null; 4641 4642 ComponentName comp = sintent.getComponent(); 4643 if (comp == null) { 4644 ri = resolveIntent( 4645 sintent, 4646 specificTypes != null ? specificTypes[i] : null, 4647 flags, userId); 4648 if (ri == null) { 4649 continue; 4650 } 4651 if (ri == mResolveInfo) { 4652 // ACK! Must do something better with this. 4653 } 4654 ai = ri.activityInfo; 4655 comp = new ComponentName(ai.applicationInfo.packageName, 4656 ai.name); 4657 } else { 4658 ai = getActivityInfo(comp, flags, userId); 4659 if (ai == null) { 4660 continue; 4661 } 4662 } 4663 4664 // Look for any generic query activities that are duplicates 4665 // of this specific one, and remove them from the results. 4666 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4667 N = results.size(); 4668 int j; 4669 for (j=specificsPos; j<N; j++) { 4670 ResolveInfo sri = results.get(j); 4671 if ((sri.activityInfo.name.equals(comp.getClassName()) 4672 && sri.activityInfo.applicationInfo.packageName.equals( 4673 comp.getPackageName())) 4674 || (action != null && sri.filter.matchAction(action))) { 4675 results.remove(j); 4676 if (DEBUG_INTENT_MATCHING) Log.v( 4677 TAG, "Removing duplicate item from " + j 4678 + " due to specific " + specificsPos); 4679 if (ri == null) { 4680 ri = sri; 4681 } 4682 j--; 4683 N--; 4684 } 4685 } 4686 4687 // Add this specific item to its proper place. 4688 if (ri == null) { 4689 ri = new ResolveInfo(); 4690 ri.activityInfo = ai; 4691 } 4692 results.add(specificsPos, ri); 4693 ri.specificIndex = i; 4694 specificsPos++; 4695 } 4696 } 4697 4698 // Now we go through the remaining generic results and remove any 4699 // duplicate actions that are found here. 4700 N = results.size(); 4701 for (int i=specificsPos; i<N-1; i++) { 4702 final ResolveInfo rii = results.get(i); 4703 if (rii.filter == null) { 4704 continue; 4705 } 4706 4707 // Iterate over all of the actions of this result's intent 4708 // filter... typically this should be just one. 4709 final Iterator<String> it = rii.filter.actionsIterator(); 4710 if (it == null) { 4711 continue; 4712 } 4713 while (it.hasNext()) { 4714 final String action = it.next(); 4715 if (resultsAction != null && resultsAction.equals(action)) { 4716 // If this action was explicitly requested, then don't 4717 // remove things that have it. 4718 continue; 4719 } 4720 for (int j=i+1; j<N; j++) { 4721 final ResolveInfo rij = results.get(j); 4722 if (rij.filter != null && rij.filter.hasAction(action)) { 4723 results.remove(j); 4724 if (DEBUG_INTENT_MATCHING) Log.v( 4725 TAG, "Removing duplicate item from " + j 4726 + " due to action " + action + " at " + i); 4727 j--; 4728 N--; 4729 } 4730 } 4731 } 4732 4733 // If the caller didn't request filter information, drop it now 4734 // so we don't have to marshall/unmarshall it. 4735 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4736 rii.filter = null; 4737 } 4738 } 4739 4740 // Filter out the caller activity if so requested. 4741 if (caller != null) { 4742 N = results.size(); 4743 for (int i=0; i<N; i++) { 4744 ActivityInfo ainfo = results.get(i).activityInfo; 4745 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4746 && caller.getClassName().equals(ainfo.name)) { 4747 results.remove(i); 4748 break; 4749 } 4750 } 4751 } 4752 4753 // If the caller didn't request filter information, 4754 // drop them now so we don't have to 4755 // marshall/unmarshall it. 4756 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4757 N = results.size(); 4758 for (int i=0; i<N; i++) { 4759 results.get(i).filter = null; 4760 } 4761 } 4762 4763 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4764 return results; 4765 } 4766 4767 @Override 4768 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4769 int userId) { 4770 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4771 ComponentName comp = intent.getComponent(); 4772 if (comp == null) { 4773 if (intent.getSelector() != null) { 4774 intent = intent.getSelector(); 4775 comp = intent.getComponent(); 4776 } 4777 } 4778 if (comp != null) { 4779 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4780 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4781 if (ai != null) { 4782 ResolveInfo ri = new ResolveInfo(); 4783 ri.activityInfo = ai; 4784 list.add(ri); 4785 } 4786 return list; 4787 } 4788 4789 // reader 4790 synchronized (mPackages) { 4791 String pkgName = intent.getPackage(); 4792 if (pkgName == null) { 4793 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4794 } 4795 final PackageParser.Package pkg = mPackages.get(pkgName); 4796 if (pkg != null) { 4797 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4798 userId); 4799 } 4800 return null; 4801 } 4802 } 4803 4804 @Override 4805 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4806 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4807 if (!sUserManager.exists(userId)) return null; 4808 if (query != null) { 4809 if (query.size() >= 1) { 4810 // If there is more than one service with the same priority, 4811 // just arbitrarily pick the first one. 4812 return query.get(0); 4813 } 4814 } 4815 return null; 4816 } 4817 4818 @Override 4819 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4820 int userId) { 4821 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4822 ComponentName comp = intent.getComponent(); 4823 if (comp == null) { 4824 if (intent.getSelector() != null) { 4825 intent = intent.getSelector(); 4826 comp = intent.getComponent(); 4827 } 4828 } 4829 if (comp != null) { 4830 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4831 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4832 if (si != null) { 4833 final ResolveInfo ri = new ResolveInfo(); 4834 ri.serviceInfo = si; 4835 list.add(ri); 4836 } 4837 return list; 4838 } 4839 4840 // reader 4841 synchronized (mPackages) { 4842 String pkgName = intent.getPackage(); 4843 if (pkgName == null) { 4844 return mServices.queryIntent(intent, resolvedType, flags, userId); 4845 } 4846 final PackageParser.Package pkg = mPackages.get(pkgName); 4847 if (pkg != null) { 4848 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4849 userId); 4850 } 4851 return null; 4852 } 4853 } 4854 4855 @Override 4856 public List<ResolveInfo> queryIntentContentProviders( 4857 Intent intent, String resolvedType, int flags, int userId) { 4858 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4859 ComponentName comp = intent.getComponent(); 4860 if (comp == null) { 4861 if (intent.getSelector() != null) { 4862 intent = intent.getSelector(); 4863 comp = intent.getComponent(); 4864 } 4865 } 4866 if (comp != null) { 4867 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4868 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4869 if (pi != null) { 4870 final ResolveInfo ri = new ResolveInfo(); 4871 ri.providerInfo = pi; 4872 list.add(ri); 4873 } 4874 return list; 4875 } 4876 4877 // reader 4878 synchronized (mPackages) { 4879 String pkgName = intent.getPackage(); 4880 if (pkgName == null) { 4881 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4882 } 4883 final PackageParser.Package pkg = mPackages.get(pkgName); 4884 if (pkg != null) { 4885 return mProviders.queryIntentForPackage( 4886 intent, resolvedType, flags, pkg.providers, userId); 4887 } 4888 return null; 4889 } 4890 } 4891 4892 @Override 4893 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4894 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4895 4896 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4897 4898 // writer 4899 synchronized (mPackages) { 4900 ArrayList<PackageInfo> list; 4901 if (listUninstalled) { 4902 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4903 for (PackageSetting ps : mSettings.mPackages.values()) { 4904 PackageInfo pi; 4905 if (ps.pkg != null) { 4906 pi = generatePackageInfo(ps.pkg, flags, userId); 4907 } else { 4908 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4909 } 4910 if (pi != null) { 4911 list.add(pi); 4912 } 4913 } 4914 } else { 4915 list = new ArrayList<PackageInfo>(mPackages.size()); 4916 for (PackageParser.Package p : mPackages.values()) { 4917 PackageInfo pi = generatePackageInfo(p, flags, userId); 4918 if (pi != null) { 4919 list.add(pi); 4920 } 4921 } 4922 } 4923 4924 return new ParceledListSlice<PackageInfo>(list); 4925 } 4926 } 4927 4928 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4929 String[] permissions, boolean[] tmp, int flags, int userId) { 4930 int numMatch = 0; 4931 final PermissionsState permissionsState = ps.getPermissionsState(); 4932 for (int i=0; i<permissions.length; i++) { 4933 final String permission = permissions[i]; 4934 if (permissionsState.hasPermission(permission, userId)) { 4935 tmp[i] = true; 4936 numMatch++; 4937 } else { 4938 tmp[i] = false; 4939 } 4940 } 4941 if (numMatch == 0) { 4942 return; 4943 } 4944 PackageInfo pi; 4945 if (ps.pkg != null) { 4946 pi = generatePackageInfo(ps.pkg, flags, userId); 4947 } else { 4948 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4949 } 4950 // The above might return null in cases of uninstalled apps or install-state 4951 // skew across users/profiles. 4952 if (pi != null) { 4953 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4954 if (numMatch == permissions.length) { 4955 pi.requestedPermissions = permissions; 4956 } else { 4957 pi.requestedPermissions = new String[numMatch]; 4958 numMatch = 0; 4959 for (int i=0; i<permissions.length; i++) { 4960 if (tmp[i]) { 4961 pi.requestedPermissions[numMatch] = permissions[i]; 4962 numMatch++; 4963 } 4964 } 4965 } 4966 } 4967 list.add(pi); 4968 } 4969 } 4970 4971 @Override 4972 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4973 String[] permissions, int flags, int userId) { 4974 if (!sUserManager.exists(userId)) return null; 4975 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4976 4977 // writer 4978 synchronized (mPackages) { 4979 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4980 boolean[] tmpBools = new boolean[permissions.length]; 4981 if (listUninstalled) { 4982 for (PackageSetting ps : mSettings.mPackages.values()) { 4983 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4984 } 4985 } else { 4986 for (PackageParser.Package pkg : mPackages.values()) { 4987 PackageSetting ps = (PackageSetting)pkg.mExtras; 4988 if (ps != null) { 4989 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4990 userId); 4991 } 4992 } 4993 } 4994 4995 return new ParceledListSlice<PackageInfo>(list); 4996 } 4997 } 4998 4999 @Override 5000 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5001 if (!sUserManager.exists(userId)) return null; 5002 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5003 5004 // writer 5005 synchronized (mPackages) { 5006 ArrayList<ApplicationInfo> list; 5007 if (listUninstalled) { 5008 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5009 for (PackageSetting ps : mSettings.mPackages.values()) { 5010 ApplicationInfo ai; 5011 if (ps.pkg != null) { 5012 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5013 ps.readUserState(userId), userId); 5014 } else { 5015 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5016 } 5017 if (ai != null) { 5018 list.add(ai); 5019 } 5020 } 5021 } else { 5022 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5023 for (PackageParser.Package p : mPackages.values()) { 5024 if (p.mExtras != null) { 5025 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5026 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5027 if (ai != null) { 5028 list.add(ai); 5029 } 5030 } 5031 } 5032 } 5033 5034 return new ParceledListSlice<ApplicationInfo>(list); 5035 } 5036 } 5037 5038 public List<ApplicationInfo> getPersistentApplications(int flags) { 5039 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5040 5041 // reader 5042 synchronized (mPackages) { 5043 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5044 final int userId = UserHandle.getCallingUserId(); 5045 while (i.hasNext()) { 5046 final PackageParser.Package p = i.next(); 5047 if (p.applicationInfo != null 5048 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5049 && (!mSafeMode || isSystemApp(p))) { 5050 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5051 if (ps != null) { 5052 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5053 ps.readUserState(userId), userId); 5054 if (ai != null) { 5055 finalList.add(ai); 5056 } 5057 } 5058 } 5059 } 5060 } 5061 5062 return finalList; 5063 } 5064 5065 @Override 5066 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5067 if (!sUserManager.exists(userId)) return null; 5068 // reader 5069 synchronized (mPackages) { 5070 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5071 PackageSetting ps = provider != null 5072 ? mSettings.mPackages.get(provider.owner.packageName) 5073 : null; 5074 return ps != null 5075 && mSettings.isEnabledLPr(provider.info, flags, userId) 5076 && (!mSafeMode || (provider.info.applicationInfo.flags 5077 &ApplicationInfo.FLAG_SYSTEM) != 0) 5078 ? PackageParser.generateProviderInfo(provider, flags, 5079 ps.readUserState(userId), userId) 5080 : null; 5081 } 5082 } 5083 5084 /** 5085 * @deprecated 5086 */ 5087 @Deprecated 5088 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5089 // reader 5090 synchronized (mPackages) { 5091 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5092 .entrySet().iterator(); 5093 final int userId = UserHandle.getCallingUserId(); 5094 while (i.hasNext()) { 5095 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5096 PackageParser.Provider p = entry.getValue(); 5097 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5098 5099 if (ps != null && p.syncable 5100 && (!mSafeMode || (p.info.applicationInfo.flags 5101 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5102 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5103 ps.readUserState(userId), userId); 5104 if (info != null) { 5105 outNames.add(entry.getKey()); 5106 outInfo.add(info); 5107 } 5108 } 5109 } 5110 } 5111 } 5112 5113 @Override 5114 public List<ProviderInfo> queryContentProviders(String processName, 5115 int uid, int flags) { 5116 ArrayList<ProviderInfo> finalList = null; 5117 // reader 5118 synchronized (mPackages) { 5119 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5120 final int userId = processName != null ? 5121 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5122 while (i.hasNext()) { 5123 final PackageParser.Provider p = i.next(); 5124 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5125 if (ps != null && p.info.authority != null 5126 && (processName == null 5127 || (p.info.processName.equals(processName) 5128 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5129 && mSettings.isEnabledLPr(p.info, flags, userId) 5130 && (!mSafeMode 5131 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5132 if (finalList == null) { 5133 finalList = new ArrayList<ProviderInfo>(3); 5134 } 5135 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5136 ps.readUserState(userId), userId); 5137 if (info != null) { 5138 finalList.add(info); 5139 } 5140 } 5141 } 5142 } 5143 5144 if (finalList != null) { 5145 Collections.sort(finalList, mProviderInitOrderSorter); 5146 } 5147 5148 return finalList; 5149 } 5150 5151 @Override 5152 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5153 int flags) { 5154 // reader 5155 synchronized (mPackages) { 5156 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5157 return PackageParser.generateInstrumentationInfo(i, flags); 5158 } 5159 } 5160 5161 @Override 5162 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5163 int flags) { 5164 ArrayList<InstrumentationInfo> finalList = 5165 new ArrayList<InstrumentationInfo>(); 5166 5167 // reader 5168 synchronized (mPackages) { 5169 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5170 while (i.hasNext()) { 5171 final PackageParser.Instrumentation p = i.next(); 5172 if (targetPackage == null 5173 || targetPackage.equals(p.info.targetPackage)) { 5174 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5175 flags); 5176 if (ii != null) { 5177 finalList.add(ii); 5178 } 5179 } 5180 } 5181 } 5182 5183 return finalList; 5184 } 5185 5186 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5187 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5188 if (overlays == null) { 5189 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5190 return; 5191 } 5192 for (PackageParser.Package opkg : overlays.values()) { 5193 // Not much to do if idmap fails: we already logged the error 5194 // and we certainly don't want to abort installation of pkg simply 5195 // because an overlay didn't fit properly. For these reasons, 5196 // ignore the return value of createIdmapForPackagePairLI. 5197 createIdmapForPackagePairLI(pkg, opkg); 5198 } 5199 } 5200 5201 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5202 PackageParser.Package opkg) { 5203 if (!opkg.mTrustedOverlay) { 5204 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5205 opkg.baseCodePath + ": overlay not trusted"); 5206 return false; 5207 } 5208 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5209 if (overlaySet == null) { 5210 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5211 opkg.baseCodePath + " but target package has no known overlays"); 5212 return false; 5213 } 5214 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5215 // TODO: generate idmap for split APKs 5216 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5217 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5218 + opkg.baseCodePath); 5219 return false; 5220 } 5221 PackageParser.Package[] overlayArray = 5222 overlaySet.values().toArray(new PackageParser.Package[0]); 5223 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5224 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5225 return p1.mOverlayPriority - p2.mOverlayPriority; 5226 } 5227 }; 5228 Arrays.sort(overlayArray, cmp); 5229 5230 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5231 int i = 0; 5232 for (PackageParser.Package p : overlayArray) { 5233 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5234 } 5235 return true; 5236 } 5237 5238 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5239 final File[] files = dir.listFiles(); 5240 if (ArrayUtils.isEmpty(files)) { 5241 Log.d(TAG, "No files in app dir " + dir); 5242 return; 5243 } 5244 5245 if (DEBUG_PACKAGE_SCANNING) { 5246 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5247 + " flags=0x" + Integer.toHexString(parseFlags)); 5248 } 5249 5250 for (File file : files) { 5251 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5252 && !PackageInstallerService.isStageName(file.getName()); 5253 if (!isPackage) { 5254 // Ignore entries which are not packages 5255 continue; 5256 } 5257 try { 5258 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5259 scanFlags, currentTime, null); 5260 } catch (PackageManagerException e) { 5261 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5262 5263 // Delete invalid userdata apps 5264 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5265 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5266 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5267 if (file.isDirectory()) { 5268 mInstaller.rmPackageDir(file.getAbsolutePath()); 5269 } else { 5270 file.delete(); 5271 } 5272 } 5273 } 5274 } 5275 } 5276 5277 private static File getSettingsProblemFile() { 5278 File dataDir = Environment.getDataDirectory(); 5279 File systemDir = new File(dataDir, "system"); 5280 File fname = new File(systemDir, "uiderrors.txt"); 5281 return fname; 5282 } 5283 5284 static void reportSettingsProblem(int priority, String msg) { 5285 logCriticalInfo(priority, msg); 5286 } 5287 5288 static void logCriticalInfo(int priority, String msg) { 5289 Slog.println(priority, TAG, msg); 5290 EventLogTags.writePmCriticalInfo(msg); 5291 try { 5292 File fname = getSettingsProblemFile(); 5293 FileOutputStream out = new FileOutputStream(fname, true); 5294 PrintWriter pw = new FastPrintWriter(out); 5295 SimpleDateFormat formatter = new SimpleDateFormat(); 5296 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5297 pw.println(dateString + ": " + msg); 5298 pw.close(); 5299 FileUtils.setPermissions( 5300 fname.toString(), 5301 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5302 -1, -1); 5303 } catch (java.io.IOException e) { 5304 } 5305 } 5306 5307 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5308 PackageParser.Package pkg, File srcFile, int parseFlags) 5309 throws PackageManagerException { 5310 if (ps != null 5311 && ps.codePath.equals(srcFile) 5312 && ps.timeStamp == srcFile.lastModified() 5313 && !isCompatSignatureUpdateNeeded(pkg) 5314 && !isRecoverSignatureUpdateNeeded(pkg)) { 5315 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5316 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5317 ArraySet<PublicKey> signingKs; 5318 synchronized (mPackages) { 5319 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5320 } 5321 if (ps.signatures.mSignatures != null 5322 && ps.signatures.mSignatures.length != 0 5323 && signingKs != null) { 5324 // Optimization: reuse the existing cached certificates 5325 // if the package appears to be unchanged. 5326 pkg.mSignatures = ps.signatures.mSignatures; 5327 pkg.mSigningKeys = signingKs; 5328 return; 5329 } 5330 5331 Slog.w(TAG, "PackageSetting for " + ps.name 5332 + " is missing signatures. Collecting certs again to recover them."); 5333 } else { 5334 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5335 } 5336 5337 try { 5338 pp.collectCertificates(pkg, parseFlags); 5339 pp.collectManifestDigest(pkg); 5340 } catch (PackageParserException e) { 5341 throw PackageManagerException.from(e); 5342 } 5343 } 5344 5345 /* 5346 * Scan a package and return the newly parsed package. 5347 * Returns null in case of errors and the error code is stored in mLastScanError 5348 */ 5349 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5350 long currentTime, UserHandle user) throws PackageManagerException { 5351 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5352 parseFlags |= mDefParseFlags; 5353 PackageParser pp = new PackageParser(); 5354 pp.setSeparateProcesses(mSeparateProcesses); 5355 pp.setOnlyCoreApps(mOnlyCore); 5356 pp.setDisplayMetrics(mMetrics); 5357 5358 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5359 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5360 } 5361 5362 final PackageParser.Package pkg; 5363 try { 5364 pkg = pp.parsePackage(scanFile, parseFlags); 5365 } catch (PackageParserException e) { 5366 throw PackageManagerException.from(e); 5367 } 5368 5369 PackageSetting ps = null; 5370 PackageSetting updatedPkg; 5371 // reader 5372 synchronized (mPackages) { 5373 // Look to see if we already know about this package. 5374 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5375 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5376 // This package has been renamed to its original name. Let's 5377 // use that. 5378 ps = mSettings.peekPackageLPr(oldName); 5379 } 5380 // If there was no original package, see one for the real package name. 5381 if (ps == null) { 5382 ps = mSettings.peekPackageLPr(pkg.packageName); 5383 } 5384 // Check to see if this package could be hiding/updating a system 5385 // package. Must look for it either under the original or real 5386 // package name depending on our state. 5387 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5388 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5389 } 5390 boolean updatedPkgBetter = false; 5391 // First check if this is a system package that may involve an update 5392 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5393 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5394 // it needs to drop FLAG_PRIVILEGED. 5395 if (locationIsPrivileged(scanFile)) { 5396 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5397 } else { 5398 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5399 } 5400 5401 if (ps != null && !ps.codePath.equals(scanFile)) { 5402 // The path has changed from what was last scanned... check the 5403 // version of the new path against what we have stored to determine 5404 // what to do. 5405 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5406 if (pkg.mVersionCode <= ps.versionCode) { 5407 // The system package has been updated and the code path does not match 5408 // Ignore entry. Skip it. 5409 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5410 + " ignored: updated version " + ps.versionCode 5411 + " better than this " + pkg.mVersionCode); 5412 if (!updatedPkg.codePath.equals(scanFile)) { 5413 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5414 + ps.name + " changing from " + updatedPkg.codePathString 5415 + " to " + scanFile); 5416 updatedPkg.codePath = scanFile; 5417 updatedPkg.codePathString = scanFile.toString(); 5418 updatedPkg.resourcePath = scanFile; 5419 updatedPkg.resourcePathString = scanFile.toString(); 5420 } 5421 updatedPkg.pkg = pkg; 5422 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5423 } else { 5424 // The current app on the system partition is better than 5425 // what we have updated to on the data partition; switch 5426 // back to the system partition version. 5427 // At this point, its safely assumed that package installation for 5428 // apps in system partition will go through. If not there won't be a working 5429 // version of the app 5430 // writer 5431 synchronized (mPackages) { 5432 // Just remove the loaded entries from package lists. 5433 mPackages.remove(ps.name); 5434 } 5435 5436 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5437 + " reverting from " + ps.codePathString 5438 + ": new version " + pkg.mVersionCode 5439 + " better than installed " + ps.versionCode); 5440 5441 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5442 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5443 synchronized (mInstallLock) { 5444 args.cleanUpResourcesLI(); 5445 } 5446 synchronized (mPackages) { 5447 mSettings.enableSystemPackageLPw(ps.name); 5448 } 5449 updatedPkgBetter = true; 5450 } 5451 } 5452 } 5453 5454 if (updatedPkg != null) { 5455 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5456 // initially 5457 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5458 5459 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5460 // flag set initially 5461 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5462 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5463 } 5464 } 5465 5466 // Verify certificates against what was last scanned 5467 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5468 5469 /* 5470 * A new system app appeared, but we already had a non-system one of the 5471 * same name installed earlier. 5472 */ 5473 boolean shouldHideSystemApp = false; 5474 if (updatedPkg == null && ps != null 5475 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5476 /* 5477 * Check to make sure the signatures match first. If they don't, 5478 * wipe the installed application and its data. 5479 */ 5480 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5481 != PackageManager.SIGNATURE_MATCH) { 5482 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5483 + " signatures don't match existing userdata copy; removing"); 5484 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5485 ps = null; 5486 } else { 5487 /* 5488 * If the newly-added system app is an older version than the 5489 * already installed version, hide it. It will be scanned later 5490 * and re-added like an update. 5491 */ 5492 if (pkg.mVersionCode <= ps.versionCode) { 5493 shouldHideSystemApp = true; 5494 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5495 + " but new version " + pkg.mVersionCode + " better than installed " 5496 + ps.versionCode + "; hiding system"); 5497 } else { 5498 /* 5499 * The newly found system app is a newer version that the 5500 * one previously installed. Simply remove the 5501 * already-installed application and replace it with our own 5502 * while keeping the application data. 5503 */ 5504 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5505 + " reverting from " + ps.codePathString + ": new version " 5506 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5507 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5508 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5509 synchronized (mInstallLock) { 5510 args.cleanUpResourcesLI(); 5511 } 5512 } 5513 } 5514 } 5515 5516 // The apk is forward locked (not public) if its code and resources 5517 // are kept in different files. (except for app in either system or 5518 // vendor path). 5519 // TODO grab this value from PackageSettings 5520 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5521 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5522 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5523 } 5524 } 5525 5526 // TODO: extend to support forward-locked splits 5527 String resourcePath = null; 5528 String baseResourcePath = null; 5529 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5530 if (ps != null && ps.resourcePathString != null) { 5531 resourcePath = ps.resourcePathString; 5532 baseResourcePath = ps.resourcePathString; 5533 } else { 5534 // Should not happen at all. Just log an error. 5535 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5536 } 5537 } else { 5538 resourcePath = pkg.codePath; 5539 baseResourcePath = pkg.baseCodePath; 5540 } 5541 5542 // Set application objects path explicitly. 5543 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5544 pkg.applicationInfo.setCodePath(pkg.codePath); 5545 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5546 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5547 pkg.applicationInfo.setResourcePath(resourcePath); 5548 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5549 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5550 5551 // Note that we invoke the following method only if we are about to unpack an application 5552 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5553 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5554 5555 /* 5556 * If the system app should be overridden by a previously installed 5557 * data, hide the system app now and let the /data/app scan pick it up 5558 * again. 5559 */ 5560 if (shouldHideSystemApp) { 5561 synchronized (mPackages) { 5562 /* 5563 * We have to grant systems permissions before we hide, because 5564 * grantPermissions will assume the package update is trying to 5565 * expand its permissions. 5566 */ 5567 grantPermissionsLPw(pkg, true, pkg.packageName); 5568 mSettings.disableSystemPackageLPw(pkg.packageName); 5569 } 5570 } 5571 5572 return scannedPkg; 5573 } 5574 5575 private static String fixProcessName(String defProcessName, 5576 String processName, int uid) { 5577 if (processName == null) { 5578 return defProcessName; 5579 } 5580 return processName; 5581 } 5582 5583 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5584 throws PackageManagerException { 5585 if (pkgSetting.signatures.mSignatures != null) { 5586 // Already existing package. Make sure signatures match 5587 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5588 == PackageManager.SIGNATURE_MATCH; 5589 if (!match) { 5590 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5591 == PackageManager.SIGNATURE_MATCH; 5592 } 5593 if (!match) { 5594 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5595 == PackageManager.SIGNATURE_MATCH; 5596 } 5597 if (!match) { 5598 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5599 + pkg.packageName + " signatures do not match the " 5600 + "previously installed version; ignoring!"); 5601 } 5602 } 5603 5604 // Check for shared user signatures 5605 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5606 // Already existing package. Make sure signatures match 5607 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5608 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5609 if (!match) { 5610 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5611 == PackageManager.SIGNATURE_MATCH; 5612 } 5613 if (!match) { 5614 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5615 == PackageManager.SIGNATURE_MATCH; 5616 } 5617 if (!match) { 5618 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5619 "Package " + pkg.packageName 5620 + " has no signatures that match those in shared user " 5621 + pkgSetting.sharedUser.name + "; ignoring!"); 5622 } 5623 } 5624 } 5625 5626 /** 5627 * Enforces that only the system UID or root's UID can call a method exposed 5628 * via Binder. 5629 * 5630 * @param message used as message if SecurityException is thrown 5631 * @throws SecurityException if the caller is not system or root 5632 */ 5633 private static final void enforceSystemOrRoot(String message) { 5634 final int uid = Binder.getCallingUid(); 5635 if (uid != Process.SYSTEM_UID && uid != 0) { 5636 throw new SecurityException(message); 5637 } 5638 } 5639 5640 @Override 5641 public void performBootDexOpt() { 5642 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5643 5644 // Before everything else, see whether we need to fstrim. 5645 try { 5646 IMountService ms = PackageHelper.getMountService(); 5647 if (ms != null) { 5648 final boolean isUpgrade = isUpgrade(); 5649 boolean doTrim = isUpgrade; 5650 if (doTrim) { 5651 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5652 } else { 5653 final long interval = android.provider.Settings.Global.getLong( 5654 mContext.getContentResolver(), 5655 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5656 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5657 if (interval > 0) { 5658 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5659 if (timeSinceLast > interval) { 5660 doTrim = true; 5661 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5662 + "; running immediately"); 5663 } 5664 } 5665 } 5666 if (doTrim) { 5667 if (!isFirstBoot()) { 5668 try { 5669 ActivityManagerNative.getDefault().showBootMessage( 5670 mContext.getResources().getString( 5671 R.string.android_upgrading_fstrim), true); 5672 } catch (RemoteException e) { 5673 } 5674 } 5675 ms.runMaintenance(); 5676 } 5677 } else { 5678 Slog.e(TAG, "Mount service unavailable!"); 5679 } 5680 } catch (RemoteException e) { 5681 // Can't happen; MountService is local 5682 } 5683 5684 final ArraySet<PackageParser.Package> pkgs; 5685 synchronized (mPackages) { 5686 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5687 } 5688 5689 if (pkgs != null) { 5690 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5691 // in case the device runs out of space. 5692 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5693 // Give priority to core apps. 5694 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5695 PackageParser.Package pkg = it.next(); 5696 if (pkg.coreApp) { 5697 if (DEBUG_DEXOPT) { 5698 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5699 } 5700 sortedPkgs.add(pkg); 5701 it.remove(); 5702 } 5703 } 5704 // Give priority to system apps that listen for pre boot complete. 5705 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5706 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5707 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5708 PackageParser.Package pkg = it.next(); 5709 if (pkgNames.contains(pkg.packageName)) { 5710 if (DEBUG_DEXOPT) { 5711 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5712 } 5713 sortedPkgs.add(pkg); 5714 it.remove(); 5715 } 5716 } 5717 // Give priority to system apps. 5718 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5719 PackageParser.Package pkg = it.next(); 5720 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5721 if (DEBUG_DEXOPT) { 5722 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5723 } 5724 sortedPkgs.add(pkg); 5725 it.remove(); 5726 } 5727 } 5728 // Give priority to updated system apps. 5729 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5730 PackageParser.Package pkg = it.next(); 5731 if (pkg.isUpdatedSystemApp()) { 5732 if (DEBUG_DEXOPT) { 5733 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5734 } 5735 sortedPkgs.add(pkg); 5736 it.remove(); 5737 } 5738 } 5739 // Give priority to apps that listen for boot complete. 5740 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5741 pkgNames = getPackageNamesForIntent(intent); 5742 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5743 PackageParser.Package pkg = it.next(); 5744 if (pkgNames.contains(pkg.packageName)) { 5745 if (DEBUG_DEXOPT) { 5746 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5747 } 5748 sortedPkgs.add(pkg); 5749 it.remove(); 5750 } 5751 } 5752 // Filter out packages that aren't recently used. 5753 filterRecentlyUsedApps(pkgs); 5754 // Add all remaining apps. 5755 for (PackageParser.Package pkg : pkgs) { 5756 if (DEBUG_DEXOPT) { 5757 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5758 } 5759 sortedPkgs.add(pkg); 5760 } 5761 5762 // If we want to be lazy, filter everything that wasn't recently used. 5763 if (mLazyDexOpt) { 5764 filterRecentlyUsedApps(sortedPkgs); 5765 } 5766 5767 int i = 0; 5768 int total = sortedPkgs.size(); 5769 File dataDir = Environment.getDataDirectory(); 5770 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5771 if (lowThreshold == 0) { 5772 throw new IllegalStateException("Invalid low memory threshold"); 5773 } 5774 for (PackageParser.Package pkg : sortedPkgs) { 5775 long usableSpace = dataDir.getUsableSpace(); 5776 if (usableSpace < lowThreshold) { 5777 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5778 break; 5779 } 5780 performBootDexOpt(pkg, ++i, total); 5781 } 5782 } 5783 } 5784 5785 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5786 // Filter out packages that aren't recently used. 5787 // 5788 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5789 // should do a full dexopt. 5790 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5791 int total = pkgs.size(); 5792 int skipped = 0; 5793 long now = System.currentTimeMillis(); 5794 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5795 PackageParser.Package pkg = i.next(); 5796 long then = pkg.mLastPackageUsageTimeInMills; 5797 if (then + mDexOptLRUThresholdInMills < now) { 5798 if (DEBUG_DEXOPT) { 5799 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5800 ((then == 0) ? "never" : new Date(then))); 5801 } 5802 i.remove(); 5803 skipped++; 5804 } 5805 } 5806 if (DEBUG_DEXOPT) { 5807 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5808 } 5809 } 5810 } 5811 5812 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5813 List<ResolveInfo> ris = null; 5814 try { 5815 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5816 intent, null, 0, UserHandle.USER_OWNER); 5817 } catch (RemoteException e) { 5818 } 5819 ArraySet<String> pkgNames = new ArraySet<String>(); 5820 if (ris != null) { 5821 for (ResolveInfo ri : ris) { 5822 pkgNames.add(ri.activityInfo.packageName); 5823 } 5824 } 5825 return pkgNames; 5826 } 5827 5828 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5829 if (DEBUG_DEXOPT) { 5830 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5831 } 5832 if (!isFirstBoot()) { 5833 try { 5834 ActivityManagerNative.getDefault().showBootMessage( 5835 mContext.getResources().getString(R.string.android_upgrading_apk, 5836 curr, total), true); 5837 } catch (RemoteException e) { 5838 } 5839 } 5840 PackageParser.Package p = pkg; 5841 synchronized (mInstallLock) { 5842 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5843 false /* force dex */, false /* defer */, true /* include dependencies */); 5844 } 5845 } 5846 5847 @Override 5848 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5849 return performDexOpt(packageName, instructionSet, false); 5850 } 5851 5852 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5853 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5854 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5855 if (!dexopt && !updateUsage) { 5856 // We aren't going to dexopt or update usage, so bail early. 5857 return false; 5858 } 5859 PackageParser.Package p; 5860 final String targetInstructionSet; 5861 synchronized (mPackages) { 5862 p = mPackages.get(packageName); 5863 if (p == null) { 5864 return false; 5865 } 5866 if (updateUsage) { 5867 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5868 } 5869 mPackageUsage.write(false); 5870 if (!dexopt) { 5871 // We aren't going to dexopt, so bail early. 5872 return false; 5873 } 5874 5875 targetInstructionSet = instructionSet != null ? instructionSet : 5876 getPrimaryInstructionSet(p.applicationInfo); 5877 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5878 return false; 5879 } 5880 } 5881 5882 synchronized (mInstallLock) { 5883 final String[] instructionSets = new String[] { targetInstructionSet }; 5884 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5885 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5886 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5887 } 5888 } 5889 5890 public ArraySet<String> getPackagesThatNeedDexOpt() { 5891 ArraySet<String> pkgs = null; 5892 synchronized (mPackages) { 5893 for (PackageParser.Package p : mPackages.values()) { 5894 if (DEBUG_DEXOPT) { 5895 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5896 } 5897 if (!p.mDexOptPerformed.isEmpty()) { 5898 continue; 5899 } 5900 if (pkgs == null) { 5901 pkgs = new ArraySet<String>(); 5902 } 5903 pkgs.add(p.packageName); 5904 } 5905 } 5906 return pkgs; 5907 } 5908 5909 public void shutdown() { 5910 mPackageUsage.write(true); 5911 } 5912 5913 @Override 5914 public void forceDexOpt(String packageName) { 5915 enforceSystemOrRoot("forceDexOpt"); 5916 5917 PackageParser.Package pkg; 5918 synchronized (mPackages) { 5919 pkg = mPackages.get(packageName); 5920 if (pkg == null) { 5921 throw new IllegalArgumentException("Missing package: " + packageName); 5922 } 5923 } 5924 5925 synchronized (mInstallLock) { 5926 final String[] instructionSets = new String[] { 5927 getPrimaryInstructionSet(pkg.applicationInfo) }; 5928 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5929 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5930 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5931 throw new IllegalStateException("Failed to dexopt: " + res); 5932 } 5933 } 5934 } 5935 5936 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5937 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5938 Slog.w(TAG, "Unable to update from " + oldPkg.name 5939 + " to " + newPkg.packageName 5940 + ": old package not in system partition"); 5941 return false; 5942 } else if (mPackages.get(oldPkg.name) != null) { 5943 Slog.w(TAG, "Unable to update from " + oldPkg.name 5944 + " to " + newPkg.packageName 5945 + ": old package still exists"); 5946 return false; 5947 } 5948 return true; 5949 } 5950 5951 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5952 int[] users = sUserManager.getUserIds(); 5953 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5954 if (res < 0) { 5955 return res; 5956 } 5957 for (int user : users) { 5958 if (user != 0) { 5959 res = mInstaller.createUserData(volumeUuid, packageName, 5960 UserHandle.getUid(user, uid), user, seinfo); 5961 if (res < 0) { 5962 return res; 5963 } 5964 } 5965 } 5966 return res; 5967 } 5968 5969 private int removeDataDirsLI(String volumeUuid, String packageName) { 5970 int[] users = sUserManager.getUserIds(); 5971 int res = 0; 5972 for (int user : users) { 5973 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5974 if (resInner < 0) { 5975 res = resInner; 5976 } 5977 } 5978 5979 return res; 5980 } 5981 5982 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5983 int[] users = sUserManager.getUserIds(); 5984 int res = 0; 5985 for (int user : users) { 5986 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5987 if (resInner < 0) { 5988 res = resInner; 5989 } 5990 } 5991 return res; 5992 } 5993 5994 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5995 PackageParser.Package changingLib) { 5996 if (file.path != null) { 5997 usesLibraryFiles.add(file.path); 5998 return; 5999 } 6000 PackageParser.Package p = mPackages.get(file.apk); 6001 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6002 // If we are doing this while in the middle of updating a library apk, 6003 // then we need to make sure to use that new apk for determining the 6004 // dependencies here. (We haven't yet finished committing the new apk 6005 // to the package manager state.) 6006 if (p == null || p.packageName.equals(changingLib.packageName)) { 6007 p = changingLib; 6008 } 6009 } 6010 if (p != null) { 6011 usesLibraryFiles.addAll(p.getAllCodePaths()); 6012 } 6013 } 6014 6015 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6016 PackageParser.Package changingLib) throws PackageManagerException { 6017 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6018 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6019 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6020 for (int i=0; i<N; i++) { 6021 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6022 if (file == null) { 6023 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6024 "Package " + pkg.packageName + " requires unavailable shared library " 6025 + pkg.usesLibraries.get(i) + "; failing!"); 6026 } 6027 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6028 } 6029 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6030 for (int i=0; i<N; i++) { 6031 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6032 if (file == null) { 6033 Slog.w(TAG, "Package " + pkg.packageName 6034 + " desires unavailable shared library " 6035 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6036 } else { 6037 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6038 } 6039 } 6040 N = usesLibraryFiles.size(); 6041 if (N > 0) { 6042 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6043 } else { 6044 pkg.usesLibraryFiles = null; 6045 } 6046 } 6047 } 6048 6049 private static boolean hasString(List<String> list, List<String> which) { 6050 if (list == null) { 6051 return false; 6052 } 6053 for (int i=list.size()-1; i>=0; i--) { 6054 for (int j=which.size()-1; j>=0; j--) { 6055 if (which.get(j).equals(list.get(i))) { 6056 return true; 6057 } 6058 } 6059 } 6060 return false; 6061 } 6062 6063 private void updateAllSharedLibrariesLPw() { 6064 for (PackageParser.Package pkg : mPackages.values()) { 6065 try { 6066 updateSharedLibrariesLPw(pkg, null); 6067 } catch (PackageManagerException e) { 6068 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6069 } 6070 } 6071 } 6072 6073 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6074 PackageParser.Package changingPkg) { 6075 ArrayList<PackageParser.Package> res = null; 6076 for (PackageParser.Package pkg : mPackages.values()) { 6077 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6078 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6079 if (res == null) { 6080 res = new ArrayList<PackageParser.Package>(); 6081 } 6082 res.add(pkg); 6083 try { 6084 updateSharedLibrariesLPw(pkg, changingPkg); 6085 } catch (PackageManagerException e) { 6086 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6087 } 6088 } 6089 } 6090 return res; 6091 } 6092 6093 /** 6094 * Derive the value of the {@code cpuAbiOverride} based on the provided 6095 * value and an optional stored value from the package settings. 6096 */ 6097 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6098 String cpuAbiOverride = null; 6099 6100 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6101 cpuAbiOverride = null; 6102 } else if (abiOverride != null) { 6103 cpuAbiOverride = abiOverride; 6104 } else if (settings != null) { 6105 cpuAbiOverride = settings.cpuAbiOverrideString; 6106 } 6107 6108 return cpuAbiOverride; 6109 } 6110 6111 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6112 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6113 boolean success = false; 6114 try { 6115 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6116 currentTime, user); 6117 success = true; 6118 return res; 6119 } finally { 6120 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6121 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6122 } 6123 } 6124 } 6125 6126 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6127 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6128 final File scanFile = new File(pkg.codePath); 6129 if (pkg.applicationInfo.getCodePath() == null || 6130 pkg.applicationInfo.getResourcePath() == null) { 6131 // Bail out. The resource and code paths haven't been set. 6132 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6133 "Code and resource paths haven't been set correctly"); 6134 } 6135 6136 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6137 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6138 } else { 6139 // Only allow system apps to be flagged as core apps. 6140 pkg.coreApp = false; 6141 } 6142 6143 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6144 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6145 } 6146 6147 if (mCustomResolverComponentName != null && 6148 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6149 setUpCustomResolverActivity(pkg); 6150 } 6151 6152 if (pkg.packageName.equals("android")) { 6153 synchronized (mPackages) { 6154 if (mAndroidApplication != null) { 6155 Slog.w(TAG, "*************************************************"); 6156 Slog.w(TAG, "Core android package being redefined. Skipping."); 6157 Slog.w(TAG, " file=" + scanFile); 6158 Slog.w(TAG, "*************************************************"); 6159 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6160 "Core android package being redefined. Skipping."); 6161 } 6162 6163 // Set up information for our fall-back user intent resolution activity. 6164 mPlatformPackage = pkg; 6165 pkg.mVersionCode = mSdkVersion; 6166 mAndroidApplication = pkg.applicationInfo; 6167 6168 if (!mResolverReplaced) { 6169 mResolveActivity.applicationInfo = mAndroidApplication; 6170 mResolveActivity.name = ResolverActivity.class.getName(); 6171 mResolveActivity.packageName = mAndroidApplication.packageName; 6172 mResolveActivity.processName = "system:ui"; 6173 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6174 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6175 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6176 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6177 mResolveActivity.exported = true; 6178 mResolveActivity.enabled = true; 6179 mResolveInfo.activityInfo = mResolveActivity; 6180 mResolveInfo.priority = 0; 6181 mResolveInfo.preferredOrder = 0; 6182 mResolveInfo.match = 0; 6183 mResolveComponentName = new ComponentName( 6184 mAndroidApplication.packageName, mResolveActivity.name); 6185 } 6186 } 6187 } 6188 6189 if (DEBUG_PACKAGE_SCANNING) { 6190 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6191 Log.d(TAG, "Scanning package " + pkg.packageName); 6192 } 6193 6194 if (mPackages.containsKey(pkg.packageName) 6195 || mSharedLibraries.containsKey(pkg.packageName)) { 6196 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6197 "Application package " + pkg.packageName 6198 + " already installed. Skipping duplicate."); 6199 } 6200 6201 // If we're only installing presumed-existing packages, require that the 6202 // scanned APK is both already known and at the path previously established 6203 // for it. Previously unknown packages we pick up normally, but if we have an 6204 // a priori expectation about this package's install presence, enforce it. 6205 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6206 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6207 if (known != null) { 6208 if (DEBUG_PACKAGE_SCANNING) { 6209 Log.d(TAG, "Examining " + pkg.codePath 6210 + " and requiring known paths " + known.codePathString 6211 + " & " + known.resourcePathString); 6212 } 6213 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6214 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6215 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6216 "Application package " + pkg.packageName 6217 + " found at " + pkg.applicationInfo.getCodePath() 6218 + " but expected at " + known.codePathString + "; ignoring."); 6219 } 6220 } 6221 } 6222 6223 // Initialize package source and resource directories 6224 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6225 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6226 6227 SharedUserSetting suid = null; 6228 PackageSetting pkgSetting = null; 6229 6230 if (!isSystemApp(pkg)) { 6231 // Only system apps can use these features. 6232 pkg.mOriginalPackages = null; 6233 pkg.mRealPackage = null; 6234 pkg.mAdoptPermissions = null; 6235 } 6236 6237 // writer 6238 synchronized (mPackages) { 6239 if (pkg.mSharedUserId != null) { 6240 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6241 if (suid == null) { 6242 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6243 "Creating application package " + pkg.packageName 6244 + " for shared user failed"); 6245 } 6246 if (DEBUG_PACKAGE_SCANNING) { 6247 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6248 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6249 + "): packages=" + suid.packages); 6250 } 6251 } 6252 6253 // Check if we are renaming from an original package name. 6254 PackageSetting origPackage = null; 6255 String realName = null; 6256 if (pkg.mOriginalPackages != null) { 6257 // This package may need to be renamed to a previously 6258 // installed name. Let's check on that... 6259 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6260 if (pkg.mOriginalPackages.contains(renamed)) { 6261 // This package had originally been installed as the 6262 // original name, and we have already taken care of 6263 // transitioning to the new one. Just update the new 6264 // one to continue using the old name. 6265 realName = pkg.mRealPackage; 6266 if (!pkg.packageName.equals(renamed)) { 6267 // Callers into this function may have already taken 6268 // care of renaming the package; only do it here if 6269 // it is not already done. 6270 pkg.setPackageName(renamed); 6271 } 6272 6273 } else { 6274 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6275 if ((origPackage = mSettings.peekPackageLPr( 6276 pkg.mOriginalPackages.get(i))) != null) { 6277 // We do have the package already installed under its 6278 // original name... should we use it? 6279 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6280 // New package is not compatible with original. 6281 origPackage = null; 6282 continue; 6283 } else if (origPackage.sharedUser != null) { 6284 // Make sure uid is compatible between packages. 6285 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6286 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6287 + " to " + pkg.packageName + ": old uid " 6288 + origPackage.sharedUser.name 6289 + " differs from " + pkg.mSharedUserId); 6290 origPackage = null; 6291 continue; 6292 } 6293 } else { 6294 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6295 + pkg.packageName + " to old name " + origPackage.name); 6296 } 6297 break; 6298 } 6299 } 6300 } 6301 } 6302 6303 if (mTransferedPackages.contains(pkg.packageName)) { 6304 Slog.w(TAG, "Package " + pkg.packageName 6305 + " was transferred to another, but its .apk remains"); 6306 } 6307 6308 // Just create the setting, don't add it yet. For already existing packages 6309 // the PkgSetting exists already and doesn't have to be created. 6310 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6311 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6312 pkg.applicationInfo.primaryCpuAbi, 6313 pkg.applicationInfo.secondaryCpuAbi, 6314 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6315 user, false); 6316 if (pkgSetting == null) { 6317 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6318 "Creating application package " + pkg.packageName + " failed"); 6319 } 6320 6321 if (pkgSetting.origPackage != null) { 6322 // If we are first transitioning from an original package, 6323 // fix up the new package's name now. We need to do this after 6324 // looking up the package under its new name, so getPackageLP 6325 // can take care of fiddling things correctly. 6326 pkg.setPackageName(origPackage.name); 6327 6328 // File a report about this. 6329 String msg = "New package " + pkgSetting.realName 6330 + " renamed to replace old package " + pkgSetting.name; 6331 reportSettingsProblem(Log.WARN, msg); 6332 6333 // Make a note of it. 6334 mTransferedPackages.add(origPackage.name); 6335 6336 // No longer need to retain this. 6337 pkgSetting.origPackage = null; 6338 } 6339 6340 if (realName != null) { 6341 // Make a note of it. 6342 mTransferedPackages.add(pkg.packageName); 6343 } 6344 6345 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6346 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6347 } 6348 6349 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6350 // Check all shared libraries and map to their actual file path. 6351 // We only do this here for apps not on a system dir, because those 6352 // are the only ones that can fail an install due to this. We 6353 // will take care of the system apps by updating all of their 6354 // library paths after the scan is done. 6355 updateSharedLibrariesLPw(pkg, null); 6356 } 6357 6358 if (mFoundPolicyFile) { 6359 SELinuxMMAC.assignSeinfoValue(pkg); 6360 } 6361 6362 pkg.applicationInfo.uid = pkgSetting.appId; 6363 pkg.mExtras = pkgSetting; 6364 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6365 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6366 // We just determined the app is signed correctly, so bring 6367 // over the latest parsed certs. 6368 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6369 } else { 6370 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6371 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6372 "Package " + pkg.packageName + " upgrade keys do not match the " 6373 + "previously installed version"); 6374 } else { 6375 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6376 String msg = "System package " + pkg.packageName 6377 + " signature changed; retaining data."; 6378 reportSettingsProblem(Log.WARN, msg); 6379 } 6380 } 6381 } else { 6382 try { 6383 verifySignaturesLP(pkgSetting, pkg); 6384 // We just determined the app is signed correctly, so bring 6385 // over the latest parsed certs. 6386 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6387 } catch (PackageManagerException e) { 6388 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6389 throw e; 6390 } 6391 // The signature has changed, but this package is in the system 6392 // image... let's recover! 6393 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6394 // However... if this package is part of a shared user, but it 6395 // doesn't match the signature of the shared user, let's fail. 6396 // What this means is that you can't change the signatures 6397 // associated with an overall shared user, which doesn't seem all 6398 // that unreasonable. 6399 if (pkgSetting.sharedUser != null) { 6400 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6401 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6402 throw new PackageManagerException( 6403 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6404 "Signature mismatch for shared user : " 6405 + pkgSetting.sharedUser); 6406 } 6407 } 6408 // File a report about this. 6409 String msg = "System package " + pkg.packageName 6410 + " signature changed; retaining data."; 6411 reportSettingsProblem(Log.WARN, msg); 6412 } 6413 } 6414 // Verify that this new package doesn't have any content providers 6415 // that conflict with existing packages. Only do this if the 6416 // package isn't already installed, since we don't want to break 6417 // things that are installed. 6418 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6419 final int N = pkg.providers.size(); 6420 int i; 6421 for (i=0; i<N; i++) { 6422 PackageParser.Provider p = pkg.providers.get(i); 6423 if (p.info.authority != null) { 6424 String names[] = p.info.authority.split(";"); 6425 for (int j = 0; j < names.length; j++) { 6426 if (mProvidersByAuthority.containsKey(names[j])) { 6427 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6428 final String otherPackageName = 6429 ((other != null && other.getComponentName() != null) ? 6430 other.getComponentName().getPackageName() : "?"); 6431 throw new PackageManagerException( 6432 INSTALL_FAILED_CONFLICTING_PROVIDER, 6433 "Can't install because provider name " + names[j] 6434 + " (in package " + pkg.applicationInfo.packageName 6435 + ") is already used by " + otherPackageName); 6436 } 6437 } 6438 } 6439 } 6440 } 6441 6442 if (pkg.mAdoptPermissions != null) { 6443 // This package wants to adopt ownership of permissions from 6444 // another package. 6445 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6446 final String origName = pkg.mAdoptPermissions.get(i); 6447 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6448 if (orig != null) { 6449 if (verifyPackageUpdateLPr(orig, pkg)) { 6450 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6451 + pkg.packageName); 6452 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6453 } 6454 } 6455 } 6456 } 6457 } 6458 6459 final String pkgName = pkg.packageName; 6460 6461 final long scanFileTime = scanFile.lastModified(); 6462 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6463 pkg.applicationInfo.processName = fixProcessName( 6464 pkg.applicationInfo.packageName, 6465 pkg.applicationInfo.processName, 6466 pkg.applicationInfo.uid); 6467 6468 File dataPath; 6469 if (mPlatformPackage == pkg) { 6470 // The system package is special. 6471 dataPath = new File(Environment.getDataDirectory(), "system"); 6472 6473 pkg.applicationInfo.dataDir = dataPath.getPath(); 6474 6475 } else { 6476 // This is a normal package, need to make its data directory. 6477 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6478 UserHandle.USER_OWNER); 6479 6480 boolean uidError = false; 6481 if (dataPath.exists()) { 6482 int currentUid = 0; 6483 try { 6484 StructStat stat = Os.stat(dataPath.getPath()); 6485 currentUid = stat.st_uid; 6486 } catch (ErrnoException e) { 6487 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6488 } 6489 6490 // If we have mismatched owners for the data path, we have a problem. 6491 if (currentUid != pkg.applicationInfo.uid) { 6492 boolean recovered = false; 6493 if (currentUid == 0) { 6494 // The directory somehow became owned by root. Wow. 6495 // This is probably because the system was stopped while 6496 // installd was in the middle of messing with its libs 6497 // directory. Ask installd to fix that. 6498 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6499 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6500 if (ret >= 0) { 6501 recovered = true; 6502 String msg = "Package " + pkg.packageName 6503 + " unexpectedly changed to uid 0; recovered to " + 6504 + pkg.applicationInfo.uid; 6505 reportSettingsProblem(Log.WARN, msg); 6506 } 6507 } 6508 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6509 || (scanFlags&SCAN_BOOTING) != 0)) { 6510 // If this is a system app, we can at least delete its 6511 // current data so the application will still work. 6512 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6513 if (ret >= 0) { 6514 // TODO: Kill the processes first 6515 // Old data gone! 6516 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6517 ? "System package " : "Third party package "; 6518 String msg = prefix + pkg.packageName 6519 + " has changed from uid: " 6520 + currentUid + " to " 6521 + pkg.applicationInfo.uid + "; old data erased"; 6522 reportSettingsProblem(Log.WARN, msg); 6523 recovered = true; 6524 6525 // And now re-install the app. 6526 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6527 pkg.applicationInfo.seinfo); 6528 if (ret == -1) { 6529 // Ack should not happen! 6530 msg = prefix + pkg.packageName 6531 + " could not have data directory re-created after delete."; 6532 reportSettingsProblem(Log.WARN, msg); 6533 throw new PackageManagerException( 6534 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6535 } 6536 } 6537 if (!recovered) { 6538 mHasSystemUidErrors = true; 6539 } 6540 } else if (!recovered) { 6541 // If we allow this install to proceed, we will be broken. 6542 // Abort, abort! 6543 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6544 "scanPackageLI"); 6545 } 6546 if (!recovered) { 6547 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6548 + pkg.applicationInfo.uid + "/fs_" 6549 + currentUid; 6550 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6551 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6552 String msg = "Package " + pkg.packageName 6553 + " has mismatched uid: " 6554 + currentUid + " on disk, " 6555 + pkg.applicationInfo.uid + " in settings"; 6556 // writer 6557 synchronized (mPackages) { 6558 mSettings.mReadMessages.append(msg); 6559 mSettings.mReadMessages.append('\n'); 6560 uidError = true; 6561 if (!pkgSetting.uidError) { 6562 reportSettingsProblem(Log.ERROR, msg); 6563 } 6564 } 6565 } 6566 } 6567 pkg.applicationInfo.dataDir = dataPath.getPath(); 6568 if (mShouldRestoreconData) { 6569 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6570 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6571 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6572 } 6573 } else { 6574 if (DEBUG_PACKAGE_SCANNING) { 6575 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6576 Log.v(TAG, "Want this data dir: " + dataPath); 6577 } 6578 //invoke installer to do the actual installation 6579 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6580 pkg.applicationInfo.seinfo); 6581 if (ret < 0) { 6582 // Error from installer 6583 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6584 "Unable to create data dirs [errorCode=" + ret + "]"); 6585 } 6586 6587 if (dataPath.exists()) { 6588 pkg.applicationInfo.dataDir = dataPath.getPath(); 6589 } else { 6590 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6591 pkg.applicationInfo.dataDir = null; 6592 } 6593 } 6594 6595 pkgSetting.uidError = uidError; 6596 } 6597 6598 final String path = scanFile.getPath(); 6599 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6600 6601 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6602 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6603 6604 // Some system apps still use directory structure for native libraries 6605 // in which case we might end up not detecting abi solely based on apk 6606 // structure. Try to detect abi based on directory structure. 6607 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6608 pkg.applicationInfo.primaryCpuAbi == null) { 6609 setBundledAppAbisAndRoots(pkg, pkgSetting); 6610 setNativeLibraryPaths(pkg); 6611 } 6612 6613 } else { 6614 if ((scanFlags & SCAN_MOVE) != 0) { 6615 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6616 // but we already have this packages package info in the PackageSetting. We just 6617 // use that and derive the native library path based on the new codepath. 6618 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6619 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6620 } 6621 6622 // Set native library paths again. For moves, the path will be updated based on the 6623 // ABIs we've determined above. For non-moves, the path will be updated based on the 6624 // ABIs we determined during compilation, but the path will depend on the final 6625 // package path (after the rename away from the stage path). 6626 setNativeLibraryPaths(pkg); 6627 } 6628 6629 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6630 final int[] userIds = sUserManager.getUserIds(); 6631 synchronized (mInstallLock) { 6632 // Create a native library symlink only if we have native libraries 6633 // and if the native libraries are 32 bit libraries. We do not provide 6634 // this symlink for 64 bit libraries. 6635 if (pkg.applicationInfo.primaryCpuAbi != null && 6636 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6637 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6638 for (int userId : userIds) { 6639 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6640 nativeLibPath, userId) < 0) { 6641 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6642 "Failed linking native library dir (user=" + userId + ")"); 6643 } 6644 } 6645 } 6646 } 6647 6648 // This is a special case for the "system" package, where the ABI is 6649 // dictated by the zygote configuration (and init.rc). We should keep track 6650 // of this ABI so that we can deal with "normal" applications that run under 6651 // the same UID correctly. 6652 if (mPlatformPackage == pkg) { 6653 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6654 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6655 } 6656 6657 // If there's a mismatch between the abi-override in the package setting 6658 // and the abiOverride specified for the install. Warn about this because we 6659 // would've already compiled the app without taking the package setting into 6660 // account. 6661 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6662 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6663 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6664 " for package: " + pkg.packageName); 6665 } 6666 } 6667 6668 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6669 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6670 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6671 6672 // Copy the derived override back to the parsed package, so that we can 6673 // update the package settings accordingly. 6674 pkg.cpuAbiOverride = cpuAbiOverride; 6675 6676 if (DEBUG_ABI_SELECTION) { 6677 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6678 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6679 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6680 } 6681 6682 // Push the derived path down into PackageSettings so we know what to 6683 // clean up at uninstall time. 6684 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6685 6686 if (DEBUG_ABI_SELECTION) { 6687 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6688 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6689 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6690 } 6691 6692 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6693 // We don't do this here during boot because we can do it all 6694 // at once after scanning all existing packages. 6695 // 6696 // We also do this *before* we perform dexopt on this package, so that 6697 // we can avoid redundant dexopts, and also to make sure we've got the 6698 // code and package path correct. 6699 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6700 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6701 } 6702 6703 if ((scanFlags & SCAN_NO_DEX) == 0) { 6704 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6705 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6706 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6707 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6708 } 6709 } 6710 if (mFactoryTest && pkg.requestedPermissions.contains( 6711 android.Manifest.permission.FACTORY_TEST)) { 6712 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6713 } 6714 6715 ArrayList<PackageParser.Package> clientLibPkgs = null; 6716 6717 // writer 6718 synchronized (mPackages) { 6719 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6720 // Only system apps can add new shared libraries. 6721 if (pkg.libraryNames != null) { 6722 for (int i=0; i<pkg.libraryNames.size(); i++) { 6723 String name = pkg.libraryNames.get(i); 6724 boolean allowed = false; 6725 if (pkg.isUpdatedSystemApp()) { 6726 // New library entries can only be added through the 6727 // system image. This is important to get rid of a lot 6728 // of nasty edge cases: for example if we allowed a non- 6729 // system update of the app to add a library, then uninstalling 6730 // the update would make the library go away, and assumptions 6731 // we made such as through app install filtering would now 6732 // have allowed apps on the device which aren't compatible 6733 // with it. Better to just have the restriction here, be 6734 // conservative, and create many fewer cases that can negatively 6735 // impact the user experience. 6736 final PackageSetting sysPs = mSettings 6737 .getDisabledSystemPkgLPr(pkg.packageName); 6738 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6739 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6740 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6741 allowed = true; 6742 allowed = true; 6743 break; 6744 } 6745 } 6746 } 6747 } else { 6748 allowed = true; 6749 } 6750 if (allowed) { 6751 if (!mSharedLibraries.containsKey(name)) { 6752 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6753 } else if (!name.equals(pkg.packageName)) { 6754 Slog.w(TAG, "Package " + pkg.packageName + " library " 6755 + name + " already exists; skipping"); 6756 } 6757 } else { 6758 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6759 + name + " that is not declared on system image; skipping"); 6760 } 6761 } 6762 if ((scanFlags&SCAN_BOOTING) == 0) { 6763 // If we are not booting, we need to update any applications 6764 // that are clients of our shared library. If we are booting, 6765 // this will all be done once the scan is complete. 6766 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6767 } 6768 } 6769 } 6770 } 6771 6772 // We also need to dexopt any apps that are dependent on this library. Note that 6773 // if these fail, we should abort the install since installing the library will 6774 // result in some apps being broken. 6775 if (clientLibPkgs != null) { 6776 if ((scanFlags & SCAN_NO_DEX) == 0) { 6777 for (int i = 0; i < clientLibPkgs.size(); i++) { 6778 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6779 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6780 null /* instruction sets */, forceDex, 6781 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6782 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6783 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6784 "scanPackageLI failed to dexopt clientLibPkgs"); 6785 } 6786 } 6787 } 6788 } 6789 6790 // Also need to kill any apps that are dependent on the library. 6791 if (clientLibPkgs != null) { 6792 for (int i=0; i<clientLibPkgs.size(); i++) { 6793 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6794 killApplication(clientPkg.applicationInfo.packageName, 6795 clientPkg.applicationInfo.uid, "update lib"); 6796 } 6797 } 6798 6799 // Make sure we're not adding any bogus keyset info 6800 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6801 ksms.assertScannedPackageValid(pkg); 6802 6803 // writer 6804 synchronized (mPackages) { 6805 // We don't expect installation to fail beyond this point 6806 6807 // Add the new setting to mSettings 6808 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6809 // Add the new setting to mPackages 6810 mPackages.put(pkg.applicationInfo.packageName, pkg); 6811 // Make sure we don't accidentally delete its data. 6812 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6813 while (iter.hasNext()) { 6814 PackageCleanItem item = iter.next(); 6815 if (pkgName.equals(item.packageName)) { 6816 iter.remove(); 6817 } 6818 } 6819 6820 // Take care of first install / last update times. 6821 if (currentTime != 0) { 6822 if (pkgSetting.firstInstallTime == 0) { 6823 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6824 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6825 pkgSetting.lastUpdateTime = currentTime; 6826 } 6827 } else if (pkgSetting.firstInstallTime == 0) { 6828 // We need *something*. Take time time stamp of the file. 6829 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6830 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6831 if (scanFileTime != pkgSetting.timeStamp) { 6832 // A package on the system image has changed; consider this 6833 // to be an update. 6834 pkgSetting.lastUpdateTime = scanFileTime; 6835 } 6836 } 6837 6838 // Add the package's KeySets to the global KeySetManagerService 6839 ksms.addScannedPackageLPw(pkg); 6840 6841 int N = pkg.providers.size(); 6842 StringBuilder r = null; 6843 int i; 6844 for (i=0; i<N; i++) { 6845 PackageParser.Provider p = pkg.providers.get(i); 6846 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6847 p.info.processName, pkg.applicationInfo.uid); 6848 mProviders.addProvider(p); 6849 p.syncable = p.info.isSyncable; 6850 if (p.info.authority != null) { 6851 String names[] = p.info.authority.split(";"); 6852 p.info.authority = null; 6853 for (int j = 0; j < names.length; j++) { 6854 if (j == 1 && p.syncable) { 6855 // We only want the first authority for a provider to possibly be 6856 // syncable, so if we already added this provider using a different 6857 // authority clear the syncable flag. We copy the provider before 6858 // changing it because the mProviders object contains a reference 6859 // to a provider that we don't want to change. 6860 // Only do this for the second authority since the resulting provider 6861 // object can be the same for all future authorities for this provider. 6862 p = new PackageParser.Provider(p); 6863 p.syncable = false; 6864 } 6865 if (!mProvidersByAuthority.containsKey(names[j])) { 6866 mProvidersByAuthority.put(names[j], p); 6867 if (p.info.authority == null) { 6868 p.info.authority = names[j]; 6869 } else { 6870 p.info.authority = p.info.authority + ";" + names[j]; 6871 } 6872 if (DEBUG_PACKAGE_SCANNING) { 6873 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6874 Log.d(TAG, "Registered content provider: " + names[j] 6875 + ", className = " + p.info.name + ", isSyncable = " 6876 + p.info.isSyncable); 6877 } 6878 } else { 6879 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6880 Slog.w(TAG, "Skipping provider name " + names[j] + 6881 " (in package " + pkg.applicationInfo.packageName + 6882 "): name already used by " 6883 + ((other != null && other.getComponentName() != null) 6884 ? other.getComponentName().getPackageName() : "?")); 6885 } 6886 } 6887 } 6888 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6889 if (r == null) { 6890 r = new StringBuilder(256); 6891 } else { 6892 r.append(' '); 6893 } 6894 r.append(p.info.name); 6895 } 6896 } 6897 if (r != null) { 6898 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6899 } 6900 6901 N = pkg.services.size(); 6902 r = null; 6903 for (i=0; i<N; i++) { 6904 PackageParser.Service s = pkg.services.get(i); 6905 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6906 s.info.processName, pkg.applicationInfo.uid); 6907 mServices.addService(s); 6908 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6909 if (r == null) { 6910 r = new StringBuilder(256); 6911 } else { 6912 r.append(' '); 6913 } 6914 r.append(s.info.name); 6915 } 6916 } 6917 if (r != null) { 6918 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6919 } 6920 6921 N = pkg.receivers.size(); 6922 r = null; 6923 for (i=0; i<N; i++) { 6924 PackageParser.Activity a = pkg.receivers.get(i); 6925 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6926 a.info.processName, pkg.applicationInfo.uid); 6927 mReceivers.addActivity(a, "receiver"); 6928 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6929 if (r == null) { 6930 r = new StringBuilder(256); 6931 } else { 6932 r.append(' '); 6933 } 6934 r.append(a.info.name); 6935 } 6936 } 6937 if (r != null) { 6938 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6939 } 6940 6941 N = pkg.activities.size(); 6942 r = null; 6943 for (i=0; i<N; i++) { 6944 PackageParser.Activity a = pkg.activities.get(i); 6945 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6946 a.info.processName, pkg.applicationInfo.uid); 6947 mActivities.addActivity(a, "activity"); 6948 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6949 if (r == null) { 6950 r = new StringBuilder(256); 6951 } else { 6952 r.append(' '); 6953 } 6954 r.append(a.info.name); 6955 } 6956 } 6957 if (r != null) { 6958 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6959 } 6960 6961 N = pkg.permissionGroups.size(); 6962 r = null; 6963 for (i=0; i<N; i++) { 6964 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6965 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6966 if (cur == null) { 6967 mPermissionGroups.put(pg.info.name, pg); 6968 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6969 if (r == null) { 6970 r = new StringBuilder(256); 6971 } else { 6972 r.append(' '); 6973 } 6974 r.append(pg.info.name); 6975 } 6976 } else { 6977 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6978 + pg.info.packageName + " ignored: original from " 6979 + cur.info.packageName); 6980 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6981 if (r == null) { 6982 r = new StringBuilder(256); 6983 } else { 6984 r.append(' '); 6985 } 6986 r.append("DUP:"); 6987 r.append(pg.info.name); 6988 } 6989 } 6990 } 6991 if (r != null) { 6992 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6993 } 6994 6995 N = pkg.permissions.size(); 6996 r = null; 6997 for (i=0; i<N; i++) { 6998 PackageParser.Permission p = pkg.permissions.get(i); 6999 7000 // Now that permission groups have a special meaning, we ignore permission 7001 // groups for legacy apps to prevent unexpected behavior. In particular, 7002 // permissions for one app being granted to someone just becuase they happen 7003 // to be in a group defined by another app (before this had no implications). 7004 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7005 p.group = mPermissionGroups.get(p.info.group); 7006 // Warn for a permission in an unknown group. 7007 if (p.info.group != null && p.group == null) { 7008 Slog.w(TAG, "Permission " + p.info.name + " from package " 7009 + p.info.packageName + " in an unknown group " + p.info.group); 7010 } 7011 } 7012 7013 ArrayMap<String, BasePermission> permissionMap = 7014 p.tree ? mSettings.mPermissionTrees 7015 : mSettings.mPermissions; 7016 BasePermission bp = permissionMap.get(p.info.name); 7017 7018 // Allow system apps to redefine non-system permissions 7019 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7020 final boolean currentOwnerIsSystem = (bp.perm != null 7021 && isSystemApp(bp.perm.owner)); 7022 if (isSystemApp(p.owner)) { 7023 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7024 // It's a built-in permission and no owner, take ownership now 7025 bp.packageSetting = pkgSetting; 7026 bp.perm = p; 7027 bp.uid = pkg.applicationInfo.uid; 7028 bp.sourcePackage = p.info.packageName; 7029 } else if (!currentOwnerIsSystem) { 7030 String msg = "New decl " + p.owner + " of permission " 7031 + p.info.name + " is system; overriding " + bp.sourcePackage; 7032 reportSettingsProblem(Log.WARN, msg); 7033 bp = null; 7034 } 7035 } 7036 } 7037 7038 if (bp == null) { 7039 bp = new BasePermission(p.info.name, p.info.packageName, 7040 BasePermission.TYPE_NORMAL); 7041 permissionMap.put(p.info.name, bp); 7042 } 7043 7044 if (bp.perm == null) { 7045 if (bp.sourcePackage == null 7046 || bp.sourcePackage.equals(p.info.packageName)) { 7047 BasePermission tree = findPermissionTreeLP(p.info.name); 7048 if (tree == null 7049 || tree.sourcePackage.equals(p.info.packageName)) { 7050 bp.packageSetting = pkgSetting; 7051 bp.perm = p; 7052 bp.uid = pkg.applicationInfo.uid; 7053 bp.sourcePackage = p.info.packageName; 7054 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7055 if (r == null) { 7056 r = new StringBuilder(256); 7057 } else { 7058 r.append(' '); 7059 } 7060 r.append(p.info.name); 7061 } 7062 } else { 7063 Slog.w(TAG, "Permission " + p.info.name + " from package " 7064 + p.info.packageName + " ignored: base tree " 7065 + tree.name + " is from package " 7066 + tree.sourcePackage); 7067 } 7068 } else { 7069 Slog.w(TAG, "Permission " + p.info.name + " from package " 7070 + p.info.packageName + " ignored: original from " 7071 + bp.sourcePackage); 7072 } 7073 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7074 if (r == null) { 7075 r = new StringBuilder(256); 7076 } else { 7077 r.append(' '); 7078 } 7079 r.append("DUP:"); 7080 r.append(p.info.name); 7081 } 7082 if (bp.perm == p) { 7083 bp.protectionLevel = p.info.protectionLevel; 7084 } 7085 } 7086 7087 if (r != null) { 7088 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7089 } 7090 7091 N = pkg.instrumentation.size(); 7092 r = null; 7093 for (i=0; i<N; i++) { 7094 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7095 a.info.packageName = pkg.applicationInfo.packageName; 7096 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7097 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7098 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7099 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7100 a.info.dataDir = pkg.applicationInfo.dataDir; 7101 7102 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7103 // need other information about the application, like the ABI and what not ? 7104 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7105 mInstrumentation.put(a.getComponentName(), a); 7106 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7107 if (r == null) { 7108 r = new StringBuilder(256); 7109 } else { 7110 r.append(' '); 7111 } 7112 r.append(a.info.name); 7113 } 7114 } 7115 if (r != null) { 7116 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7117 } 7118 7119 if (pkg.protectedBroadcasts != null) { 7120 N = pkg.protectedBroadcasts.size(); 7121 for (i=0; i<N; i++) { 7122 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7123 } 7124 } 7125 7126 pkgSetting.setTimeStamp(scanFileTime); 7127 7128 // Create idmap files for pairs of (packages, overlay packages). 7129 // Note: "android", ie framework-res.apk, is handled by native layers. 7130 if (pkg.mOverlayTarget != null) { 7131 // This is an overlay package. 7132 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7133 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7134 mOverlays.put(pkg.mOverlayTarget, 7135 new ArrayMap<String, PackageParser.Package>()); 7136 } 7137 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7138 map.put(pkg.packageName, pkg); 7139 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7140 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7141 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7142 "scanPackageLI failed to createIdmap"); 7143 } 7144 } 7145 } else if (mOverlays.containsKey(pkg.packageName) && 7146 !pkg.packageName.equals("android")) { 7147 // This is a regular package, with one or more known overlay packages. 7148 createIdmapsForPackageLI(pkg); 7149 } 7150 } 7151 7152 return pkg; 7153 } 7154 7155 /** 7156 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7157 * is derived purely on the basis of the contents of {@code scanFile} and 7158 * {@code cpuAbiOverride}. 7159 * 7160 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7161 */ 7162 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7163 String cpuAbiOverride, boolean extractLibs) 7164 throws PackageManagerException { 7165 // TODO: We can probably be smarter about this stuff. For installed apps, 7166 // we can calculate this information at install time once and for all. For 7167 // system apps, we can probably assume that this information doesn't change 7168 // after the first boot scan. As things stand, we do lots of unnecessary work. 7169 7170 // Give ourselves some initial paths; we'll come back for another 7171 // pass once we've determined ABI below. 7172 setNativeLibraryPaths(pkg); 7173 7174 // We would never need to extract libs for forward-locked and external packages, 7175 // since the container service will do it for us. We shouldn't attempt to 7176 // extract libs from system app when it was not updated. 7177 if (pkg.isForwardLocked() || isExternal(pkg) || 7178 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7179 extractLibs = false; 7180 } 7181 7182 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7183 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7184 7185 NativeLibraryHelper.Handle handle = null; 7186 try { 7187 handle = NativeLibraryHelper.Handle.create(scanFile); 7188 // TODO(multiArch): This can be null for apps that didn't go through the 7189 // usual installation process. We can calculate it again, like we 7190 // do during install time. 7191 // 7192 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7193 // unnecessary. 7194 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7195 7196 // Null out the abis so that they can be recalculated. 7197 pkg.applicationInfo.primaryCpuAbi = null; 7198 pkg.applicationInfo.secondaryCpuAbi = null; 7199 if (isMultiArch(pkg.applicationInfo)) { 7200 // Warn if we've set an abiOverride for multi-lib packages.. 7201 // By definition, we need to copy both 32 and 64 bit libraries for 7202 // such packages. 7203 if (pkg.cpuAbiOverride != null 7204 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7205 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7206 } 7207 7208 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7209 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7210 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7211 if (extractLibs) { 7212 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7213 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7214 useIsaSpecificSubdirs); 7215 } else { 7216 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7217 } 7218 } 7219 7220 maybeThrowExceptionForMultiArchCopy( 7221 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7222 7223 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7224 if (extractLibs) { 7225 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7226 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7227 useIsaSpecificSubdirs); 7228 } else { 7229 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7230 } 7231 } 7232 7233 maybeThrowExceptionForMultiArchCopy( 7234 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7235 7236 if (abi64 >= 0) { 7237 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7238 } 7239 7240 if (abi32 >= 0) { 7241 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7242 if (abi64 >= 0) { 7243 pkg.applicationInfo.secondaryCpuAbi = abi; 7244 } else { 7245 pkg.applicationInfo.primaryCpuAbi = abi; 7246 } 7247 } 7248 } else { 7249 String[] abiList = (cpuAbiOverride != null) ? 7250 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7251 7252 // Enable gross and lame hacks for apps that are built with old 7253 // SDK tools. We must scan their APKs for renderscript bitcode and 7254 // not launch them if it's present. Don't bother checking on devices 7255 // that don't have 64 bit support. 7256 boolean needsRenderScriptOverride = false; 7257 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7258 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7259 abiList = Build.SUPPORTED_32_BIT_ABIS; 7260 needsRenderScriptOverride = true; 7261 } 7262 7263 final int copyRet; 7264 if (extractLibs) { 7265 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7266 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7267 } else { 7268 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7269 } 7270 7271 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7272 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7273 "Error unpackaging native libs for app, errorCode=" + copyRet); 7274 } 7275 7276 if (copyRet >= 0) { 7277 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7278 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7279 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7280 } else if (needsRenderScriptOverride) { 7281 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7282 } 7283 } 7284 } catch (IOException ioe) { 7285 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7286 } finally { 7287 IoUtils.closeQuietly(handle); 7288 } 7289 7290 // Now that we've calculated the ABIs and determined if it's an internal app, 7291 // we will go ahead and populate the nativeLibraryPath. 7292 setNativeLibraryPaths(pkg); 7293 } 7294 7295 /** 7296 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7297 * i.e, so that all packages can be run inside a single process if required. 7298 * 7299 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7300 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7301 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7302 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7303 * updating a package that belongs to a shared user. 7304 * 7305 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7306 * adds unnecessary complexity. 7307 */ 7308 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7309 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7310 String requiredInstructionSet = null; 7311 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7312 requiredInstructionSet = VMRuntime.getInstructionSet( 7313 scannedPackage.applicationInfo.primaryCpuAbi); 7314 } 7315 7316 PackageSetting requirer = null; 7317 for (PackageSetting ps : packagesForUser) { 7318 // If packagesForUser contains scannedPackage, we skip it. This will happen 7319 // when scannedPackage is an update of an existing package. Without this check, 7320 // we will never be able to change the ABI of any package belonging to a shared 7321 // user, even if it's compatible with other packages. 7322 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7323 if (ps.primaryCpuAbiString == null) { 7324 continue; 7325 } 7326 7327 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7328 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7329 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7330 // this but there's not much we can do. 7331 String errorMessage = "Instruction set mismatch, " 7332 + ((requirer == null) ? "[caller]" : requirer) 7333 + " requires " + requiredInstructionSet + " whereas " + ps 7334 + " requires " + instructionSet; 7335 Slog.w(TAG, errorMessage); 7336 } 7337 7338 if (requiredInstructionSet == null) { 7339 requiredInstructionSet = instructionSet; 7340 requirer = ps; 7341 } 7342 } 7343 } 7344 7345 if (requiredInstructionSet != null) { 7346 String adjustedAbi; 7347 if (requirer != null) { 7348 // requirer != null implies that either scannedPackage was null or that scannedPackage 7349 // did not require an ABI, in which case we have to adjust scannedPackage to match 7350 // the ABI of the set (which is the same as requirer's ABI) 7351 adjustedAbi = requirer.primaryCpuAbiString; 7352 if (scannedPackage != null) { 7353 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7354 } 7355 } else { 7356 // requirer == null implies that we're updating all ABIs in the set to 7357 // match scannedPackage. 7358 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7359 } 7360 7361 for (PackageSetting ps : packagesForUser) { 7362 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7363 if (ps.primaryCpuAbiString != null) { 7364 continue; 7365 } 7366 7367 ps.primaryCpuAbiString = adjustedAbi; 7368 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7369 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7370 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7371 7372 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7373 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7374 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7375 ps.primaryCpuAbiString = null; 7376 ps.pkg.applicationInfo.primaryCpuAbi = null; 7377 return; 7378 } else { 7379 mInstaller.rmdex(ps.codePathString, 7380 getDexCodeInstructionSet(getPreferredInstructionSet())); 7381 } 7382 } 7383 } 7384 } 7385 } 7386 } 7387 7388 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7389 synchronized (mPackages) { 7390 mResolverReplaced = true; 7391 // Set up information for custom user intent resolution activity. 7392 mResolveActivity.applicationInfo = pkg.applicationInfo; 7393 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7394 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7395 mResolveActivity.processName = pkg.applicationInfo.packageName; 7396 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7397 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7398 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7399 mResolveActivity.theme = 0; 7400 mResolveActivity.exported = true; 7401 mResolveActivity.enabled = true; 7402 mResolveInfo.activityInfo = mResolveActivity; 7403 mResolveInfo.priority = 0; 7404 mResolveInfo.preferredOrder = 0; 7405 mResolveInfo.match = 0; 7406 mResolveComponentName = mCustomResolverComponentName; 7407 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7408 mResolveComponentName); 7409 } 7410 } 7411 7412 private static String calculateBundledApkRoot(final String codePathString) { 7413 final File codePath = new File(codePathString); 7414 final File codeRoot; 7415 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7416 codeRoot = Environment.getRootDirectory(); 7417 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7418 codeRoot = Environment.getOemDirectory(); 7419 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7420 codeRoot = Environment.getVendorDirectory(); 7421 } else { 7422 // Unrecognized code path; take its top real segment as the apk root: 7423 // e.g. /something/app/blah.apk => /something 7424 try { 7425 File f = codePath.getCanonicalFile(); 7426 File parent = f.getParentFile(); // non-null because codePath is a file 7427 File tmp; 7428 while ((tmp = parent.getParentFile()) != null) { 7429 f = parent; 7430 parent = tmp; 7431 } 7432 codeRoot = f; 7433 Slog.w(TAG, "Unrecognized code path " 7434 + codePath + " - using " + codeRoot); 7435 } catch (IOException e) { 7436 // Can't canonicalize the code path -- shenanigans? 7437 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7438 return Environment.getRootDirectory().getPath(); 7439 } 7440 } 7441 return codeRoot.getPath(); 7442 } 7443 7444 /** 7445 * Derive and set the location of native libraries for the given package, 7446 * which varies depending on where and how the package was installed. 7447 */ 7448 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7449 final ApplicationInfo info = pkg.applicationInfo; 7450 final String codePath = pkg.codePath; 7451 final File codeFile = new File(codePath); 7452 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7453 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7454 7455 info.nativeLibraryRootDir = null; 7456 info.nativeLibraryRootRequiresIsa = false; 7457 info.nativeLibraryDir = null; 7458 info.secondaryNativeLibraryDir = null; 7459 7460 if (isApkFile(codeFile)) { 7461 // Monolithic install 7462 if (bundledApp) { 7463 // If "/system/lib64/apkname" exists, assume that is the per-package 7464 // native library directory to use; otherwise use "/system/lib/apkname". 7465 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7466 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7467 getPrimaryInstructionSet(info)); 7468 7469 // This is a bundled system app so choose the path based on the ABI. 7470 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7471 // is just the default path. 7472 final String apkName = deriveCodePathName(codePath); 7473 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7474 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7475 apkName).getAbsolutePath(); 7476 7477 if (info.secondaryCpuAbi != null) { 7478 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7479 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7480 secondaryLibDir, apkName).getAbsolutePath(); 7481 } 7482 } else if (asecApp) { 7483 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7484 .getAbsolutePath(); 7485 } else { 7486 final String apkName = deriveCodePathName(codePath); 7487 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7488 .getAbsolutePath(); 7489 } 7490 7491 info.nativeLibraryRootRequiresIsa = false; 7492 info.nativeLibraryDir = info.nativeLibraryRootDir; 7493 } else { 7494 // Cluster install 7495 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7496 info.nativeLibraryRootRequiresIsa = true; 7497 7498 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7499 getPrimaryInstructionSet(info)).getAbsolutePath(); 7500 7501 if (info.secondaryCpuAbi != null) { 7502 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7503 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7504 } 7505 } 7506 } 7507 7508 /** 7509 * Calculate the abis and roots for a bundled app. These can uniquely 7510 * be determined from the contents of the system partition, i.e whether 7511 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7512 * of this information, and instead assume that the system was built 7513 * sensibly. 7514 */ 7515 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7516 PackageSetting pkgSetting) { 7517 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7518 7519 // If "/system/lib64/apkname" exists, assume that is the per-package 7520 // native library directory to use; otherwise use "/system/lib/apkname". 7521 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7522 setBundledAppAbi(pkg, apkRoot, apkName); 7523 // pkgSetting might be null during rescan following uninstall of updates 7524 // to a bundled app, so accommodate that possibility. The settings in 7525 // that case will be established later from the parsed package. 7526 // 7527 // If the settings aren't null, sync them up with what we've just derived. 7528 // note that apkRoot isn't stored in the package settings. 7529 if (pkgSetting != null) { 7530 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7531 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7532 } 7533 } 7534 7535 /** 7536 * Deduces the ABI of a bundled app and sets the relevant fields on the 7537 * parsed pkg object. 7538 * 7539 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7540 * under which system libraries are installed. 7541 * @param apkName the name of the installed package. 7542 */ 7543 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7544 final File codeFile = new File(pkg.codePath); 7545 7546 final boolean has64BitLibs; 7547 final boolean has32BitLibs; 7548 if (isApkFile(codeFile)) { 7549 // Monolithic install 7550 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7551 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7552 } else { 7553 // Cluster install 7554 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7555 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7556 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7557 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7558 has64BitLibs = (new File(rootDir, isa)).exists(); 7559 } else { 7560 has64BitLibs = false; 7561 } 7562 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7563 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7564 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7565 has32BitLibs = (new File(rootDir, isa)).exists(); 7566 } else { 7567 has32BitLibs = false; 7568 } 7569 } 7570 7571 if (has64BitLibs && !has32BitLibs) { 7572 // The package has 64 bit libs, but not 32 bit libs. Its primary 7573 // ABI should be 64 bit. We can safely assume here that the bundled 7574 // native libraries correspond to the most preferred ABI in the list. 7575 7576 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7577 pkg.applicationInfo.secondaryCpuAbi = null; 7578 } else if (has32BitLibs && !has64BitLibs) { 7579 // The package has 32 bit libs but not 64 bit libs. Its primary 7580 // ABI should be 32 bit. 7581 7582 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7583 pkg.applicationInfo.secondaryCpuAbi = null; 7584 } else if (has32BitLibs && has64BitLibs) { 7585 // The application has both 64 and 32 bit bundled libraries. We check 7586 // here that the app declares multiArch support, and warn if it doesn't. 7587 // 7588 // We will be lenient here and record both ABIs. The primary will be the 7589 // ABI that's higher on the list, i.e, a device that's configured to prefer 7590 // 64 bit apps will see a 64 bit primary ABI, 7591 7592 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7593 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7594 } 7595 7596 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7597 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7598 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7599 } else { 7600 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7601 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7602 } 7603 } else { 7604 pkg.applicationInfo.primaryCpuAbi = null; 7605 pkg.applicationInfo.secondaryCpuAbi = null; 7606 } 7607 } 7608 7609 private void killApplication(String pkgName, int appId, String reason) { 7610 // Request the ActivityManager to kill the process(only for existing packages) 7611 // so that we do not end up in a confused state while the user is still using the older 7612 // version of the application while the new one gets installed. 7613 IActivityManager am = ActivityManagerNative.getDefault(); 7614 if (am != null) { 7615 try { 7616 am.killApplicationWithAppId(pkgName, appId, reason); 7617 } catch (RemoteException e) { 7618 } 7619 } 7620 } 7621 7622 void removePackageLI(PackageSetting ps, boolean chatty) { 7623 if (DEBUG_INSTALL) { 7624 if (chatty) 7625 Log.d(TAG, "Removing package " + ps.name); 7626 } 7627 7628 // writer 7629 synchronized (mPackages) { 7630 mPackages.remove(ps.name); 7631 final PackageParser.Package pkg = ps.pkg; 7632 if (pkg != null) { 7633 cleanPackageDataStructuresLILPw(pkg, chatty); 7634 } 7635 } 7636 } 7637 7638 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7639 if (DEBUG_INSTALL) { 7640 if (chatty) 7641 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7642 } 7643 7644 // writer 7645 synchronized (mPackages) { 7646 mPackages.remove(pkg.applicationInfo.packageName); 7647 cleanPackageDataStructuresLILPw(pkg, chatty); 7648 } 7649 } 7650 7651 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7652 int N = pkg.providers.size(); 7653 StringBuilder r = null; 7654 int i; 7655 for (i=0; i<N; i++) { 7656 PackageParser.Provider p = pkg.providers.get(i); 7657 mProviders.removeProvider(p); 7658 if (p.info.authority == null) { 7659 7660 /* There was another ContentProvider with this authority when 7661 * this app was installed so this authority is null, 7662 * Ignore it as we don't have to unregister the provider. 7663 */ 7664 continue; 7665 } 7666 String names[] = p.info.authority.split(";"); 7667 for (int j = 0; j < names.length; j++) { 7668 if (mProvidersByAuthority.get(names[j]) == p) { 7669 mProvidersByAuthority.remove(names[j]); 7670 if (DEBUG_REMOVE) { 7671 if (chatty) 7672 Log.d(TAG, "Unregistered content provider: " + names[j] 7673 + ", className = " + p.info.name + ", isSyncable = " 7674 + p.info.isSyncable); 7675 } 7676 } 7677 } 7678 if (DEBUG_REMOVE && chatty) { 7679 if (r == null) { 7680 r = new StringBuilder(256); 7681 } else { 7682 r.append(' '); 7683 } 7684 r.append(p.info.name); 7685 } 7686 } 7687 if (r != null) { 7688 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7689 } 7690 7691 N = pkg.services.size(); 7692 r = null; 7693 for (i=0; i<N; i++) { 7694 PackageParser.Service s = pkg.services.get(i); 7695 mServices.removeService(s); 7696 if (chatty) { 7697 if (r == null) { 7698 r = new StringBuilder(256); 7699 } else { 7700 r.append(' '); 7701 } 7702 r.append(s.info.name); 7703 } 7704 } 7705 if (r != null) { 7706 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7707 } 7708 7709 N = pkg.receivers.size(); 7710 r = null; 7711 for (i=0; i<N; i++) { 7712 PackageParser.Activity a = pkg.receivers.get(i); 7713 mReceivers.removeActivity(a, "receiver"); 7714 if (DEBUG_REMOVE && chatty) { 7715 if (r == null) { 7716 r = new StringBuilder(256); 7717 } else { 7718 r.append(' '); 7719 } 7720 r.append(a.info.name); 7721 } 7722 } 7723 if (r != null) { 7724 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7725 } 7726 7727 N = pkg.activities.size(); 7728 r = null; 7729 for (i=0; i<N; i++) { 7730 PackageParser.Activity a = pkg.activities.get(i); 7731 mActivities.removeActivity(a, "activity"); 7732 if (DEBUG_REMOVE && chatty) { 7733 if (r == null) { 7734 r = new StringBuilder(256); 7735 } else { 7736 r.append(' '); 7737 } 7738 r.append(a.info.name); 7739 } 7740 } 7741 if (r != null) { 7742 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7743 } 7744 7745 N = pkg.permissions.size(); 7746 r = null; 7747 for (i=0; i<N; i++) { 7748 PackageParser.Permission p = pkg.permissions.get(i); 7749 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7750 if (bp == null) { 7751 bp = mSettings.mPermissionTrees.get(p.info.name); 7752 } 7753 if (bp != null && bp.perm == p) { 7754 bp.perm = null; 7755 if (DEBUG_REMOVE && chatty) { 7756 if (r == null) { 7757 r = new StringBuilder(256); 7758 } else { 7759 r.append(' '); 7760 } 7761 r.append(p.info.name); 7762 } 7763 } 7764 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7765 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7766 if (appOpPerms != null) { 7767 appOpPerms.remove(pkg.packageName); 7768 } 7769 } 7770 } 7771 if (r != null) { 7772 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7773 } 7774 7775 N = pkg.requestedPermissions.size(); 7776 r = null; 7777 for (i=0; i<N; i++) { 7778 String perm = pkg.requestedPermissions.get(i); 7779 BasePermission bp = mSettings.mPermissions.get(perm); 7780 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7781 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7782 if (appOpPerms != null) { 7783 appOpPerms.remove(pkg.packageName); 7784 if (appOpPerms.isEmpty()) { 7785 mAppOpPermissionPackages.remove(perm); 7786 } 7787 } 7788 } 7789 } 7790 if (r != null) { 7791 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7792 } 7793 7794 N = pkg.instrumentation.size(); 7795 r = null; 7796 for (i=0; i<N; i++) { 7797 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7798 mInstrumentation.remove(a.getComponentName()); 7799 if (DEBUG_REMOVE && chatty) { 7800 if (r == null) { 7801 r = new StringBuilder(256); 7802 } else { 7803 r.append(' '); 7804 } 7805 r.append(a.info.name); 7806 } 7807 } 7808 if (r != null) { 7809 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7810 } 7811 7812 r = null; 7813 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7814 // Only system apps can hold shared libraries. 7815 if (pkg.libraryNames != null) { 7816 for (i=0; i<pkg.libraryNames.size(); i++) { 7817 String name = pkg.libraryNames.get(i); 7818 SharedLibraryEntry cur = mSharedLibraries.get(name); 7819 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7820 mSharedLibraries.remove(name); 7821 if (DEBUG_REMOVE && chatty) { 7822 if (r == null) { 7823 r = new StringBuilder(256); 7824 } else { 7825 r.append(' '); 7826 } 7827 r.append(name); 7828 } 7829 } 7830 } 7831 } 7832 } 7833 if (r != null) { 7834 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7835 } 7836 } 7837 7838 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7839 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7840 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7841 return true; 7842 } 7843 } 7844 return false; 7845 } 7846 7847 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7848 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7849 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7850 7851 private void updatePermissionsLPw(String changingPkg, 7852 PackageParser.Package pkgInfo, int flags) { 7853 // Make sure there are no dangling permission trees. 7854 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7855 while (it.hasNext()) { 7856 final BasePermission bp = it.next(); 7857 if (bp.packageSetting == null) { 7858 // We may not yet have parsed the package, so just see if 7859 // we still know about its settings. 7860 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7861 } 7862 if (bp.packageSetting == null) { 7863 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7864 + " from package " + bp.sourcePackage); 7865 it.remove(); 7866 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7867 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7868 Slog.i(TAG, "Removing old permission tree: " + bp.name 7869 + " from package " + bp.sourcePackage); 7870 flags |= UPDATE_PERMISSIONS_ALL; 7871 it.remove(); 7872 } 7873 } 7874 } 7875 7876 // Make sure all dynamic permissions have been assigned to a package, 7877 // and make sure there are no dangling permissions. 7878 it = mSettings.mPermissions.values().iterator(); 7879 while (it.hasNext()) { 7880 final BasePermission bp = it.next(); 7881 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7882 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7883 + bp.name + " pkg=" + bp.sourcePackage 7884 + " info=" + bp.pendingInfo); 7885 if (bp.packageSetting == null && bp.pendingInfo != null) { 7886 final BasePermission tree = findPermissionTreeLP(bp.name); 7887 if (tree != null && tree.perm != null) { 7888 bp.packageSetting = tree.packageSetting; 7889 bp.perm = new PackageParser.Permission(tree.perm.owner, 7890 new PermissionInfo(bp.pendingInfo)); 7891 bp.perm.info.packageName = tree.perm.info.packageName; 7892 bp.perm.info.name = bp.name; 7893 bp.uid = tree.uid; 7894 } 7895 } 7896 } 7897 if (bp.packageSetting == null) { 7898 // We may not yet have parsed the package, so just see if 7899 // we still know about its settings. 7900 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7901 } 7902 if (bp.packageSetting == null) { 7903 Slog.w(TAG, "Removing dangling permission: " + bp.name 7904 + " from package " + bp.sourcePackage); 7905 it.remove(); 7906 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7907 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7908 Slog.i(TAG, "Removing old permission: " + bp.name 7909 + " from package " + bp.sourcePackage); 7910 flags |= UPDATE_PERMISSIONS_ALL; 7911 it.remove(); 7912 } 7913 } 7914 } 7915 7916 // Now update the permissions for all packages, in particular 7917 // replace the granted permissions of the system packages. 7918 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7919 for (PackageParser.Package pkg : mPackages.values()) { 7920 if (pkg != pkgInfo) { 7921 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7922 changingPkg); 7923 } 7924 } 7925 } 7926 7927 if (pkgInfo != null) { 7928 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7929 } 7930 } 7931 7932 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7933 String packageOfInterest) { 7934 // IMPORTANT: There are two types of permissions: install and runtime. 7935 // Install time permissions are granted when the app is installed to 7936 // all device users and users added in the future. Runtime permissions 7937 // are granted at runtime explicitly to specific users. Normal and signature 7938 // protected permissions are install time permissions. Dangerous permissions 7939 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7940 // otherwise they are runtime permissions. This function does not manage 7941 // runtime permissions except for the case an app targeting Lollipop MR1 7942 // being upgraded to target a newer SDK, in which case dangerous permissions 7943 // are transformed from install time to runtime ones. 7944 7945 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7946 if (ps == null) { 7947 return; 7948 } 7949 7950 PermissionsState permissionsState = ps.getPermissionsState(); 7951 PermissionsState origPermissions = permissionsState; 7952 7953 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7954 7955 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7956 7957 boolean changedInstallPermission = false; 7958 7959 if (replace) { 7960 ps.installPermissionsFixed = false; 7961 if (!ps.isSharedUser()) { 7962 origPermissions = new PermissionsState(permissionsState); 7963 permissionsState.reset(); 7964 } 7965 } 7966 7967 permissionsState.setGlobalGids(mGlobalGids); 7968 7969 final int N = pkg.requestedPermissions.size(); 7970 for (int i=0; i<N; i++) { 7971 final String name = pkg.requestedPermissions.get(i); 7972 final BasePermission bp = mSettings.mPermissions.get(name); 7973 7974 if (DEBUG_INSTALL) { 7975 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7976 } 7977 7978 if (bp == null || bp.packageSetting == null) { 7979 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7980 Slog.w(TAG, "Unknown permission " + name 7981 + " in package " + pkg.packageName); 7982 } 7983 continue; 7984 } 7985 7986 final String perm = bp.name; 7987 boolean allowedSig = false; 7988 int grant = GRANT_DENIED; 7989 7990 // Keep track of app op permissions. 7991 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7992 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7993 if (pkgs == null) { 7994 pkgs = new ArraySet<>(); 7995 mAppOpPermissionPackages.put(bp.name, pkgs); 7996 } 7997 pkgs.add(pkg.packageName); 7998 } 7999 8000 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8001 switch (level) { 8002 case PermissionInfo.PROTECTION_NORMAL: { 8003 // For all apps normal permissions are install time ones. 8004 grant = GRANT_INSTALL; 8005 } break; 8006 8007 case PermissionInfo.PROTECTION_DANGEROUS: { 8008 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8009 // For legacy apps dangerous permissions are install time ones. 8010 grant = GRANT_INSTALL_LEGACY; 8011 } else if (origPermissions.hasInstallPermission(bp.name)) { 8012 // For legacy apps that became modern, install becomes runtime. 8013 grant = GRANT_UPGRADE; 8014 } else { 8015 // For modern apps keep runtime permissions unchanged. 8016 grant = GRANT_RUNTIME; 8017 } 8018 } break; 8019 8020 case PermissionInfo.PROTECTION_SIGNATURE: { 8021 // For all apps signature permissions are install time ones. 8022 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8023 if (allowedSig) { 8024 grant = GRANT_INSTALL; 8025 } 8026 } break; 8027 } 8028 8029 if (DEBUG_INSTALL) { 8030 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8031 } 8032 8033 if (grant != GRANT_DENIED) { 8034 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8035 // If this is an existing, non-system package, then 8036 // we can't add any new permissions to it. 8037 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8038 // Except... if this is a permission that was added 8039 // to the platform (note: need to only do this when 8040 // updating the platform). 8041 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8042 grant = GRANT_DENIED; 8043 } 8044 } 8045 } 8046 8047 switch (grant) { 8048 case GRANT_INSTALL: { 8049 // Revoke this as runtime permission to handle the case of 8050 // a runtime permission being downgraded to an install one. 8051 for (int userId : UserManagerService.getInstance().getUserIds()) { 8052 if (origPermissions.getRuntimePermissionState( 8053 bp.name, userId) != null) { 8054 // Revoke the runtime permission and clear the flags. 8055 origPermissions.revokeRuntimePermission(bp, userId); 8056 origPermissions.updatePermissionFlags(bp, userId, 8057 PackageManager.MASK_PERMISSION_FLAGS, 0); 8058 // If we revoked a permission permission, we have to write. 8059 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8060 changedRuntimePermissionUserIds, userId); 8061 } 8062 } 8063 // Grant an install permission. 8064 if (permissionsState.grantInstallPermission(bp) != 8065 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8066 changedInstallPermission = true; 8067 } 8068 } break; 8069 8070 case GRANT_INSTALL_LEGACY: { 8071 // Grant an install permission. 8072 if (permissionsState.grantInstallPermission(bp) != 8073 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8074 changedInstallPermission = true; 8075 } 8076 } break; 8077 8078 case GRANT_RUNTIME: { 8079 // Grant previously granted runtime permissions. 8080 for (int userId : UserManagerService.getInstance().getUserIds()) { 8081 PermissionState permissionState = origPermissions 8082 .getRuntimePermissionState(bp.name, userId); 8083 final int flags = permissionState != null 8084 ? permissionState.getFlags() : 0; 8085 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8086 if (permissionsState.grantRuntimePermission(bp, userId) == 8087 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8088 // If we cannot put the permission as it was, we have to write. 8089 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8090 changedRuntimePermissionUserIds, userId); 8091 } 8092 } 8093 // Propagate the permission flags. 8094 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8095 } 8096 } break; 8097 8098 case GRANT_UPGRADE: { 8099 // Grant runtime permissions for a previously held install permission. 8100 PermissionState permissionState = origPermissions 8101 .getInstallPermissionState(bp.name); 8102 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8103 8104 if (origPermissions.revokeInstallPermission(bp) 8105 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8106 // We will be transferring the permission flags, so clear them. 8107 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8108 PackageManager.MASK_PERMISSION_FLAGS, 0); 8109 changedInstallPermission = true; 8110 } 8111 8112 // If the permission is not to be promoted to runtime we ignore it and 8113 // also its other flags as they are not applicable to install permissions. 8114 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8115 for (int userId : currentUserIds) { 8116 if (permissionsState.grantRuntimePermission(bp, userId) != 8117 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8118 // Transfer the permission flags. 8119 permissionsState.updatePermissionFlags(bp, userId, 8120 flags, flags); 8121 // If we granted the permission, we have to write. 8122 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8123 changedRuntimePermissionUserIds, userId); 8124 } 8125 } 8126 } 8127 } break; 8128 8129 default: { 8130 if (packageOfInterest == null 8131 || packageOfInterest.equals(pkg.packageName)) { 8132 Slog.w(TAG, "Not granting permission " + perm 8133 + " to package " + pkg.packageName 8134 + " because it was previously installed without"); 8135 } 8136 } break; 8137 } 8138 } else { 8139 if (permissionsState.revokeInstallPermission(bp) != 8140 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8141 // Also drop the permission flags. 8142 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8143 PackageManager.MASK_PERMISSION_FLAGS, 0); 8144 changedInstallPermission = true; 8145 Slog.i(TAG, "Un-granting permission " + perm 8146 + " from package " + pkg.packageName 8147 + " (protectionLevel=" + bp.protectionLevel 8148 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8149 + ")"); 8150 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8151 // Don't print warning for app op permissions, since it is fine for them 8152 // not to be granted, there is a UI for the user to decide. 8153 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8154 Slog.w(TAG, "Not granting permission " + perm 8155 + " to package " + pkg.packageName 8156 + " (protectionLevel=" + bp.protectionLevel 8157 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8158 + ")"); 8159 } 8160 } 8161 } 8162 } 8163 8164 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8165 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8166 // This is the first that we have heard about this package, so the 8167 // permissions we have now selected are fixed until explicitly 8168 // changed. 8169 ps.installPermissionsFixed = true; 8170 } 8171 8172 // Persist the runtime permissions state for users with changes. 8173 for (int userId : changedRuntimePermissionUserIds) { 8174 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8175 } 8176 } 8177 8178 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8179 boolean allowed = false; 8180 final int NP = PackageParser.NEW_PERMISSIONS.length; 8181 for (int ip=0; ip<NP; ip++) { 8182 final PackageParser.NewPermissionInfo npi 8183 = PackageParser.NEW_PERMISSIONS[ip]; 8184 if (npi.name.equals(perm) 8185 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8186 allowed = true; 8187 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8188 + pkg.packageName); 8189 break; 8190 } 8191 } 8192 return allowed; 8193 } 8194 8195 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8196 BasePermission bp, PermissionsState origPermissions) { 8197 boolean allowed; 8198 allowed = (compareSignatures( 8199 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8200 == PackageManager.SIGNATURE_MATCH) 8201 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8202 == PackageManager.SIGNATURE_MATCH); 8203 if (!allowed && (bp.protectionLevel 8204 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8205 if (isSystemApp(pkg)) { 8206 // For updated system applications, a system permission 8207 // is granted only if it had been defined by the original application. 8208 if (pkg.isUpdatedSystemApp()) { 8209 final PackageSetting sysPs = mSettings 8210 .getDisabledSystemPkgLPr(pkg.packageName); 8211 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8212 // If the original was granted this permission, we take 8213 // that grant decision as read and propagate it to the 8214 // update. 8215 if (sysPs.isPrivileged()) { 8216 allowed = true; 8217 } 8218 } else { 8219 // The system apk may have been updated with an older 8220 // version of the one on the data partition, but which 8221 // granted a new system permission that it didn't have 8222 // before. In this case we do want to allow the app to 8223 // now get the new permission if the ancestral apk is 8224 // privileged to get it. 8225 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8226 for (int j=0; 8227 j<sysPs.pkg.requestedPermissions.size(); j++) { 8228 if (perm.equals( 8229 sysPs.pkg.requestedPermissions.get(j))) { 8230 allowed = true; 8231 break; 8232 } 8233 } 8234 } 8235 } 8236 } else { 8237 allowed = isPrivilegedApp(pkg); 8238 } 8239 } 8240 } 8241 if (!allowed && (bp.protectionLevel 8242 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8243 // For development permissions, a development permission 8244 // is granted only if it was already granted. 8245 allowed = origPermissions.hasInstallPermission(perm); 8246 } 8247 return allowed; 8248 } 8249 8250 final class ActivityIntentResolver 8251 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8252 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8253 boolean defaultOnly, int userId) { 8254 if (!sUserManager.exists(userId)) return null; 8255 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8256 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8257 } 8258 8259 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8260 int userId) { 8261 if (!sUserManager.exists(userId)) return null; 8262 mFlags = flags; 8263 return super.queryIntent(intent, resolvedType, 8264 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8265 } 8266 8267 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8268 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8269 if (!sUserManager.exists(userId)) return null; 8270 if (packageActivities == null) { 8271 return null; 8272 } 8273 mFlags = flags; 8274 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8275 final int N = packageActivities.size(); 8276 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8277 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8278 8279 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8280 for (int i = 0; i < N; ++i) { 8281 intentFilters = packageActivities.get(i).intents; 8282 if (intentFilters != null && intentFilters.size() > 0) { 8283 PackageParser.ActivityIntentInfo[] array = 8284 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8285 intentFilters.toArray(array); 8286 listCut.add(array); 8287 } 8288 } 8289 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8290 } 8291 8292 public final void addActivity(PackageParser.Activity a, String type) { 8293 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8294 mActivities.put(a.getComponentName(), a); 8295 if (DEBUG_SHOW_INFO) 8296 Log.v( 8297 TAG, " " + type + " " + 8298 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8299 if (DEBUG_SHOW_INFO) 8300 Log.v(TAG, " Class=" + a.info.name); 8301 final int NI = a.intents.size(); 8302 for (int j=0; j<NI; j++) { 8303 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8304 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8305 intent.setPriority(0); 8306 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8307 + a.className + " with priority > 0, forcing to 0"); 8308 } 8309 if (DEBUG_SHOW_INFO) { 8310 Log.v(TAG, " IntentFilter:"); 8311 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8312 } 8313 if (!intent.debugCheck()) { 8314 Log.w(TAG, "==> For Activity " + a.info.name); 8315 } 8316 addFilter(intent); 8317 } 8318 } 8319 8320 public final void removeActivity(PackageParser.Activity a, String type) { 8321 mActivities.remove(a.getComponentName()); 8322 if (DEBUG_SHOW_INFO) { 8323 Log.v(TAG, " " + type + " " 8324 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8325 : a.info.name) + ":"); 8326 Log.v(TAG, " Class=" + a.info.name); 8327 } 8328 final int NI = a.intents.size(); 8329 for (int j=0; j<NI; j++) { 8330 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8331 if (DEBUG_SHOW_INFO) { 8332 Log.v(TAG, " IntentFilter:"); 8333 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8334 } 8335 removeFilter(intent); 8336 } 8337 } 8338 8339 @Override 8340 protected boolean allowFilterResult( 8341 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8342 ActivityInfo filterAi = filter.activity.info; 8343 for (int i=dest.size()-1; i>=0; i--) { 8344 ActivityInfo destAi = dest.get(i).activityInfo; 8345 if (destAi.name == filterAi.name 8346 && destAi.packageName == filterAi.packageName) { 8347 return false; 8348 } 8349 } 8350 return true; 8351 } 8352 8353 @Override 8354 protected ActivityIntentInfo[] newArray(int size) { 8355 return new ActivityIntentInfo[size]; 8356 } 8357 8358 @Override 8359 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8360 if (!sUserManager.exists(userId)) return true; 8361 PackageParser.Package p = filter.activity.owner; 8362 if (p != null) { 8363 PackageSetting ps = (PackageSetting)p.mExtras; 8364 if (ps != null) { 8365 // System apps are never considered stopped for purposes of 8366 // filtering, because there may be no way for the user to 8367 // actually re-launch them. 8368 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8369 && ps.getStopped(userId); 8370 } 8371 } 8372 return false; 8373 } 8374 8375 @Override 8376 protected boolean isPackageForFilter(String packageName, 8377 PackageParser.ActivityIntentInfo info) { 8378 return packageName.equals(info.activity.owner.packageName); 8379 } 8380 8381 @Override 8382 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8383 int match, int userId) { 8384 if (!sUserManager.exists(userId)) return null; 8385 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8386 return null; 8387 } 8388 final PackageParser.Activity activity = info.activity; 8389 if (mSafeMode && (activity.info.applicationInfo.flags 8390 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8391 return null; 8392 } 8393 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8394 if (ps == null) { 8395 return null; 8396 } 8397 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8398 ps.readUserState(userId), userId); 8399 if (ai == null) { 8400 return null; 8401 } 8402 final ResolveInfo res = new ResolveInfo(); 8403 res.activityInfo = ai; 8404 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8405 res.filter = info; 8406 } 8407 if (info != null) { 8408 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8409 } 8410 res.priority = info.getPriority(); 8411 res.preferredOrder = activity.owner.mPreferredOrder; 8412 //System.out.println("Result: " + res.activityInfo.className + 8413 // " = " + res.priority); 8414 res.match = match; 8415 res.isDefault = info.hasDefault; 8416 res.labelRes = info.labelRes; 8417 res.nonLocalizedLabel = info.nonLocalizedLabel; 8418 if (userNeedsBadging(userId)) { 8419 res.noResourceId = true; 8420 } else { 8421 res.icon = info.icon; 8422 } 8423 res.iconResourceId = info.icon; 8424 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8425 return res; 8426 } 8427 8428 @Override 8429 protected void sortResults(List<ResolveInfo> results) { 8430 Collections.sort(results, mResolvePrioritySorter); 8431 } 8432 8433 @Override 8434 protected void dumpFilter(PrintWriter out, String prefix, 8435 PackageParser.ActivityIntentInfo filter) { 8436 out.print(prefix); out.print( 8437 Integer.toHexString(System.identityHashCode(filter.activity))); 8438 out.print(' '); 8439 filter.activity.printComponentShortName(out); 8440 out.print(" filter "); 8441 out.println(Integer.toHexString(System.identityHashCode(filter))); 8442 } 8443 8444 @Override 8445 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8446 return filter.activity; 8447 } 8448 8449 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8450 PackageParser.Activity activity = (PackageParser.Activity)label; 8451 out.print(prefix); out.print( 8452 Integer.toHexString(System.identityHashCode(activity))); 8453 out.print(' '); 8454 activity.printComponentShortName(out); 8455 if (count > 1) { 8456 out.print(" ("); out.print(count); out.print(" filters)"); 8457 } 8458 out.println(); 8459 } 8460 8461// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8462// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8463// final List<ResolveInfo> retList = Lists.newArrayList(); 8464// while (i.hasNext()) { 8465// final ResolveInfo resolveInfo = i.next(); 8466// if (isEnabledLP(resolveInfo.activityInfo)) { 8467// retList.add(resolveInfo); 8468// } 8469// } 8470// return retList; 8471// } 8472 8473 // Keys are String (activity class name), values are Activity. 8474 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8475 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8476 private int mFlags; 8477 } 8478 8479 private final class ServiceIntentResolver 8480 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8481 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8482 boolean defaultOnly, int userId) { 8483 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8484 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8485 } 8486 8487 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8488 int userId) { 8489 if (!sUserManager.exists(userId)) return null; 8490 mFlags = flags; 8491 return super.queryIntent(intent, resolvedType, 8492 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8493 } 8494 8495 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8496 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8497 if (!sUserManager.exists(userId)) return null; 8498 if (packageServices == null) { 8499 return null; 8500 } 8501 mFlags = flags; 8502 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8503 final int N = packageServices.size(); 8504 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8505 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8506 8507 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8508 for (int i = 0; i < N; ++i) { 8509 intentFilters = packageServices.get(i).intents; 8510 if (intentFilters != null && intentFilters.size() > 0) { 8511 PackageParser.ServiceIntentInfo[] array = 8512 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8513 intentFilters.toArray(array); 8514 listCut.add(array); 8515 } 8516 } 8517 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8518 } 8519 8520 public final void addService(PackageParser.Service s) { 8521 mServices.put(s.getComponentName(), s); 8522 if (DEBUG_SHOW_INFO) { 8523 Log.v(TAG, " " 8524 + (s.info.nonLocalizedLabel != null 8525 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8526 Log.v(TAG, " Class=" + s.info.name); 8527 } 8528 final int NI = s.intents.size(); 8529 int j; 8530 for (j=0; j<NI; j++) { 8531 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8532 if (DEBUG_SHOW_INFO) { 8533 Log.v(TAG, " IntentFilter:"); 8534 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8535 } 8536 if (!intent.debugCheck()) { 8537 Log.w(TAG, "==> For Service " + s.info.name); 8538 } 8539 addFilter(intent); 8540 } 8541 } 8542 8543 public final void removeService(PackageParser.Service s) { 8544 mServices.remove(s.getComponentName()); 8545 if (DEBUG_SHOW_INFO) { 8546 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8547 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8548 Log.v(TAG, " Class=" + s.info.name); 8549 } 8550 final int NI = s.intents.size(); 8551 int j; 8552 for (j=0; j<NI; j++) { 8553 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8554 if (DEBUG_SHOW_INFO) { 8555 Log.v(TAG, " IntentFilter:"); 8556 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8557 } 8558 removeFilter(intent); 8559 } 8560 } 8561 8562 @Override 8563 protected boolean allowFilterResult( 8564 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8565 ServiceInfo filterSi = filter.service.info; 8566 for (int i=dest.size()-1; i>=0; i--) { 8567 ServiceInfo destAi = dest.get(i).serviceInfo; 8568 if (destAi.name == filterSi.name 8569 && destAi.packageName == filterSi.packageName) { 8570 return false; 8571 } 8572 } 8573 return true; 8574 } 8575 8576 @Override 8577 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8578 return new PackageParser.ServiceIntentInfo[size]; 8579 } 8580 8581 @Override 8582 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8583 if (!sUserManager.exists(userId)) return true; 8584 PackageParser.Package p = filter.service.owner; 8585 if (p != null) { 8586 PackageSetting ps = (PackageSetting)p.mExtras; 8587 if (ps != null) { 8588 // System apps are never considered stopped for purposes of 8589 // filtering, because there may be no way for the user to 8590 // actually re-launch them. 8591 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8592 && ps.getStopped(userId); 8593 } 8594 } 8595 return false; 8596 } 8597 8598 @Override 8599 protected boolean isPackageForFilter(String packageName, 8600 PackageParser.ServiceIntentInfo info) { 8601 return packageName.equals(info.service.owner.packageName); 8602 } 8603 8604 @Override 8605 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8606 int match, int userId) { 8607 if (!sUserManager.exists(userId)) return null; 8608 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8609 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8610 return null; 8611 } 8612 final PackageParser.Service service = info.service; 8613 if (mSafeMode && (service.info.applicationInfo.flags 8614 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8615 return null; 8616 } 8617 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8618 if (ps == null) { 8619 return null; 8620 } 8621 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8622 ps.readUserState(userId), userId); 8623 if (si == null) { 8624 return null; 8625 } 8626 final ResolveInfo res = new ResolveInfo(); 8627 res.serviceInfo = si; 8628 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8629 res.filter = filter; 8630 } 8631 res.priority = info.getPriority(); 8632 res.preferredOrder = service.owner.mPreferredOrder; 8633 res.match = match; 8634 res.isDefault = info.hasDefault; 8635 res.labelRes = info.labelRes; 8636 res.nonLocalizedLabel = info.nonLocalizedLabel; 8637 res.icon = info.icon; 8638 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8639 return res; 8640 } 8641 8642 @Override 8643 protected void sortResults(List<ResolveInfo> results) { 8644 Collections.sort(results, mResolvePrioritySorter); 8645 } 8646 8647 @Override 8648 protected void dumpFilter(PrintWriter out, String prefix, 8649 PackageParser.ServiceIntentInfo filter) { 8650 out.print(prefix); out.print( 8651 Integer.toHexString(System.identityHashCode(filter.service))); 8652 out.print(' '); 8653 filter.service.printComponentShortName(out); 8654 out.print(" filter "); 8655 out.println(Integer.toHexString(System.identityHashCode(filter))); 8656 } 8657 8658 @Override 8659 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8660 return filter.service; 8661 } 8662 8663 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8664 PackageParser.Service service = (PackageParser.Service)label; 8665 out.print(prefix); out.print( 8666 Integer.toHexString(System.identityHashCode(service))); 8667 out.print(' '); 8668 service.printComponentShortName(out); 8669 if (count > 1) { 8670 out.print(" ("); out.print(count); out.print(" filters)"); 8671 } 8672 out.println(); 8673 } 8674 8675// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8676// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8677// final List<ResolveInfo> retList = Lists.newArrayList(); 8678// while (i.hasNext()) { 8679// final ResolveInfo resolveInfo = (ResolveInfo) i; 8680// if (isEnabledLP(resolveInfo.serviceInfo)) { 8681// retList.add(resolveInfo); 8682// } 8683// } 8684// return retList; 8685// } 8686 8687 // Keys are String (activity class name), values are Activity. 8688 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8689 = new ArrayMap<ComponentName, PackageParser.Service>(); 8690 private int mFlags; 8691 }; 8692 8693 private final class ProviderIntentResolver 8694 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8695 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8696 boolean defaultOnly, int userId) { 8697 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8698 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8699 } 8700 8701 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8702 int userId) { 8703 if (!sUserManager.exists(userId)) 8704 return null; 8705 mFlags = flags; 8706 return super.queryIntent(intent, resolvedType, 8707 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8708 } 8709 8710 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8711 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8712 if (!sUserManager.exists(userId)) 8713 return null; 8714 if (packageProviders == null) { 8715 return null; 8716 } 8717 mFlags = flags; 8718 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8719 final int N = packageProviders.size(); 8720 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8721 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8722 8723 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8724 for (int i = 0; i < N; ++i) { 8725 intentFilters = packageProviders.get(i).intents; 8726 if (intentFilters != null && intentFilters.size() > 0) { 8727 PackageParser.ProviderIntentInfo[] array = 8728 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8729 intentFilters.toArray(array); 8730 listCut.add(array); 8731 } 8732 } 8733 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8734 } 8735 8736 public final void addProvider(PackageParser.Provider p) { 8737 if (mProviders.containsKey(p.getComponentName())) { 8738 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8739 return; 8740 } 8741 8742 mProviders.put(p.getComponentName(), p); 8743 if (DEBUG_SHOW_INFO) { 8744 Log.v(TAG, " " 8745 + (p.info.nonLocalizedLabel != null 8746 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8747 Log.v(TAG, " Class=" + p.info.name); 8748 } 8749 final int NI = p.intents.size(); 8750 int j; 8751 for (j = 0; j < NI; j++) { 8752 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8753 if (DEBUG_SHOW_INFO) { 8754 Log.v(TAG, " IntentFilter:"); 8755 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8756 } 8757 if (!intent.debugCheck()) { 8758 Log.w(TAG, "==> For Provider " + p.info.name); 8759 } 8760 addFilter(intent); 8761 } 8762 } 8763 8764 public final void removeProvider(PackageParser.Provider p) { 8765 mProviders.remove(p.getComponentName()); 8766 if (DEBUG_SHOW_INFO) { 8767 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8768 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8769 Log.v(TAG, " Class=" + p.info.name); 8770 } 8771 final int NI = p.intents.size(); 8772 int j; 8773 for (j = 0; j < NI; j++) { 8774 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8775 if (DEBUG_SHOW_INFO) { 8776 Log.v(TAG, " IntentFilter:"); 8777 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8778 } 8779 removeFilter(intent); 8780 } 8781 } 8782 8783 @Override 8784 protected boolean allowFilterResult( 8785 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8786 ProviderInfo filterPi = filter.provider.info; 8787 for (int i = dest.size() - 1; i >= 0; i--) { 8788 ProviderInfo destPi = dest.get(i).providerInfo; 8789 if (destPi.name == filterPi.name 8790 && destPi.packageName == filterPi.packageName) { 8791 return false; 8792 } 8793 } 8794 return true; 8795 } 8796 8797 @Override 8798 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8799 return new PackageParser.ProviderIntentInfo[size]; 8800 } 8801 8802 @Override 8803 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8804 if (!sUserManager.exists(userId)) 8805 return true; 8806 PackageParser.Package p = filter.provider.owner; 8807 if (p != null) { 8808 PackageSetting ps = (PackageSetting) p.mExtras; 8809 if (ps != null) { 8810 // System apps are never considered stopped for purposes of 8811 // filtering, because there may be no way for the user to 8812 // actually re-launch them. 8813 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8814 && ps.getStopped(userId); 8815 } 8816 } 8817 return false; 8818 } 8819 8820 @Override 8821 protected boolean isPackageForFilter(String packageName, 8822 PackageParser.ProviderIntentInfo info) { 8823 return packageName.equals(info.provider.owner.packageName); 8824 } 8825 8826 @Override 8827 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8828 int match, int userId) { 8829 if (!sUserManager.exists(userId)) 8830 return null; 8831 final PackageParser.ProviderIntentInfo info = filter; 8832 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8833 return null; 8834 } 8835 final PackageParser.Provider provider = info.provider; 8836 if (mSafeMode && (provider.info.applicationInfo.flags 8837 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8838 return null; 8839 } 8840 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8841 if (ps == null) { 8842 return null; 8843 } 8844 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8845 ps.readUserState(userId), userId); 8846 if (pi == null) { 8847 return null; 8848 } 8849 final ResolveInfo res = new ResolveInfo(); 8850 res.providerInfo = pi; 8851 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8852 res.filter = filter; 8853 } 8854 res.priority = info.getPriority(); 8855 res.preferredOrder = provider.owner.mPreferredOrder; 8856 res.match = match; 8857 res.isDefault = info.hasDefault; 8858 res.labelRes = info.labelRes; 8859 res.nonLocalizedLabel = info.nonLocalizedLabel; 8860 res.icon = info.icon; 8861 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8862 return res; 8863 } 8864 8865 @Override 8866 protected void sortResults(List<ResolveInfo> results) { 8867 Collections.sort(results, mResolvePrioritySorter); 8868 } 8869 8870 @Override 8871 protected void dumpFilter(PrintWriter out, String prefix, 8872 PackageParser.ProviderIntentInfo filter) { 8873 out.print(prefix); 8874 out.print( 8875 Integer.toHexString(System.identityHashCode(filter.provider))); 8876 out.print(' '); 8877 filter.provider.printComponentShortName(out); 8878 out.print(" filter "); 8879 out.println(Integer.toHexString(System.identityHashCode(filter))); 8880 } 8881 8882 @Override 8883 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8884 return filter.provider; 8885 } 8886 8887 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8888 PackageParser.Provider provider = (PackageParser.Provider)label; 8889 out.print(prefix); out.print( 8890 Integer.toHexString(System.identityHashCode(provider))); 8891 out.print(' '); 8892 provider.printComponentShortName(out); 8893 if (count > 1) { 8894 out.print(" ("); out.print(count); out.print(" filters)"); 8895 } 8896 out.println(); 8897 } 8898 8899 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8900 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8901 private int mFlags; 8902 }; 8903 8904 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8905 new Comparator<ResolveInfo>() { 8906 public int compare(ResolveInfo r1, ResolveInfo r2) { 8907 int v1 = r1.priority; 8908 int v2 = r2.priority; 8909 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8910 if (v1 != v2) { 8911 return (v1 > v2) ? -1 : 1; 8912 } 8913 v1 = r1.preferredOrder; 8914 v2 = r2.preferredOrder; 8915 if (v1 != v2) { 8916 return (v1 > v2) ? -1 : 1; 8917 } 8918 if (r1.isDefault != r2.isDefault) { 8919 return r1.isDefault ? -1 : 1; 8920 } 8921 v1 = r1.match; 8922 v2 = r2.match; 8923 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8924 if (v1 != v2) { 8925 return (v1 > v2) ? -1 : 1; 8926 } 8927 if (r1.system != r2.system) { 8928 return r1.system ? -1 : 1; 8929 } 8930 return 0; 8931 } 8932 }; 8933 8934 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8935 new Comparator<ProviderInfo>() { 8936 public int compare(ProviderInfo p1, ProviderInfo p2) { 8937 final int v1 = p1.initOrder; 8938 final int v2 = p2.initOrder; 8939 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8940 } 8941 }; 8942 8943 final void sendPackageBroadcast(final String action, final String pkg, 8944 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8945 final int[] userIds) { 8946 mHandler.post(new Runnable() { 8947 @Override 8948 public void run() { 8949 try { 8950 final IActivityManager am = ActivityManagerNative.getDefault(); 8951 if (am == null) return; 8952 final int[] resolvedUserIds; 8953 if (userIds == null) { 8954 resolvedUserIds = am.getRunningUserIds(); 8955 } else { 8956 resolvedUserIds = userIds; 8957 } 8958 for (int id : resolvedUserIds) { 8959 final Intent intent = new Intent(action, 8960 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8961 if (extras != null) { 8962 intent.putExtras(extras); 8963 } 8964 if (targetPkg != null) { 8965 intent.setPackage(targetPkg); 8966 } 8967 // Modify the UID when posting to other users 8968 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8969 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8970 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8971 intent.putExtra(Intent.EXTRA_UID, uid); 8972 } 8973 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8974 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8975 if (DEBUG_BROADCASTS) { 8976 RuntimeException here = new RuntimeException("here"); 8977 here.fillInStackTrace(); 8978 Slog.d(TAG, "Sending to user " + id + ": " 8979 + intent.toShortString(false, true, false, false) 8980 + " " + intent.getExtras(), here); 8981 } 8982 am.broadcastIntent(null, intent, null, finishedReceiver, 8983 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8984 null, finishedReceiver != null, false, id); 8985 } 8986 } catch (RemoteException ex) { 8987 } 8988 } 8989 }); 8990 } 8991 8992 /** 8993 * Check if the external storage media is available. This is true if there 8994 * is a mounted external storage medium or if the external storage is 8995 * emulated. 8996 */ 8997 private boolean isExternalMediaAvailable() { 8998 return mMediaMounted || Environment.isExternalStorageEmulated(); 8999 } 9000 9001 @Override 9002 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9003 // writer 9004 synchronized (mPackages) { 9005 if (!isExternalMediaAvailable()) { 9006 // If the external storage is no longer mounted at this point, 9007 // the caller may not have been able to delete all of this 9008 // packages files and can not delete any more. Bail. 9009 return null; 9010 } 9011 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9012 if (lastPackage != null) { 9013 pkgs.remove(lastPackage); 9014 } 9015 if (pkgs.size() > 0) { 9016 return pkgs.get(0); 9017 } 9018 } 9019 return null; 9020 } 9021 9022 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9023 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9024 userId, andCode ? 1 : 0, packageName); 9025 if (mSystemReady) { 9026 msg.sendToTarget(); 9027 } else { 9028 if (mPostSystemReadyMessages == null) { 9029 mPostSystemReadyMessages = new ArrayList<>(); 9030 } 9031 mPostSystemReadyMessages.add(msg); 9032 } 9033 } 9034 9035 void startCleaningPackages() { 9036 // reader 9037 synchronized (mPackages) { 9038 if (!isExternalMediaAvailable()) { 9039 return; 9040 } 9041 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9042 return; 9043 } 9044 } 9045 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9046 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9047 IActivityManager am = ActivityManagerNative.getDefault(); 9048 if (am != null) { 9049 try { 9050 am.startService(null, intent, null, UserHandle.USER_OWNER); 9051 } catch (RemoteException e) { 9052 } 9053 } 9054 } 9055 9056 @Override 9057 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9058 int installFlags, String installerPackageName, VerificationParams verificationParams, 9059 String packageAbiOverride) { 9060 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9061 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9062 } 9063 9064 @Override 9065 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9066 int installFlags, String installerPackageName, VerificationParams verificationParams, 9067 String packageAbiOverride, int userId) { 9068 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9069 9070 final int callingUid = Binder.getCallingUid(); 9071 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9072 9073 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9074 try { 9075 if (observer != null) { 9076 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9077 } 9078 } catch (RemoteException re) { 9079 } 9080 return; 9081 } 9082 9083 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9084 installFlags |= PackageManager.INSTALL_FROM_ADB; 9085 9086 } else { 9087 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9088 // about installerPackageName. 9089 9090 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9091 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9092 } 9093 9094 UserHandle user; 9095 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9096 user = UserHandle.ALL; 9097 } else { 9098 user = new UserHandle(userId); 9099 } 9100 9101 // Only system components can circumvent runtime permissions when installing. 9102 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9103 && mContext.checkCallingOrSelfPermission(Manifest.permission 9104 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9105 throw new SecurityException("You need the " 9106 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9107 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9108 } 9109 9110 verificationParams.setInstallerUid(callingUid); 9111 9112 final File originFile = new File(originPath); 9113 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9114 9115 final Message msg = mHandler.obtainMessage(INIT_COPY); 9116 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9117 null, verificationParams, user, packageAbiOverride); 9118 mHandler.sendMessage(msg); 9119 } 9120 9121 void installStage(String packageName, File stagedDir, String stagedCid, 9122 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9123 String installerPackageName, int installerUid, UserHandle user) { 9124 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9125 params.referrerUri, installerUid, null); 9126 verifParams.setInstallerUid(installerUid); 9127 9128 final OriginInfo origin; 9129 if (stagedDir != null) { 9130 origin = OriginInfo.fromStagedFile(stagedDir); 9131 } else { 9132 origin = OriginInfo.fromStagedContainer(stagedCid); 9133 } 9134 9135 final Message msg = mHandler.obtainMessage(INIT_COPY); 9136 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9137 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9138 mHandler.sendMessage(msg); 9139 } 9140 9141 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9142 Bundle extras = new Bundle(1); 9143 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9144 9145 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9146 packageName, extras, null, null, new int[] {userId}); 9147 try { 9148 IActivityManager am = ActivityManagerNative.getDefault(); 9149 final boolean isSystem = 9150 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9151 if (isSystem && am.isUserRunning(userId, false)) { 9152 // The just-installed/enabled app is bundled on the system, so presumed 9153 // to be able to run automatically without needing an explicit launch. 9154 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9155 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9156 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9157 .setPackage(packageName); 9158 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9159 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9160 } 9161 } catch (RemoteException e) { 9162 // shouldn't happen 9163 Slog.w(TAG, "Unable to bootstrap installed package", e); 9164 } 9165 } 9166 9167 @Override 9168 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9169 int userId) { 9170 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9171 PackageSetting pkgSetting; 9172 final int uid = Binder.getCallingUid(); 9173 enforceCrossUserPermission(uid, userId, true, true, 9174 "setApplicationHiddenSetting for user " + userId); 9175 9176 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9177 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9178 return false; 9179 } 9180 9181 long callingId = Binder.clearCallingIdentity(); 9182 try { 9183 boolean sendAdded = false; 9184 boolean sendRemoved = false; 9185 // writer 9186 synchronized (mPackages) { 9187 pkgSetting = mSettings.mPackages.get(packageName); 9188 if (pkgSetting == null) { 9189 return false; 9190 } 9191 if (pkgSetting.getHidden(userId) != hidden) { 9192 pkgSetting.setHidden(hidden, userId); 9193 mSettings.writePackageRestrictionsLPr(userId); 9194 if (hidden) { 9195 sendRemoved = true; 9196 } else { 9197 sendAdded = true; 9198 } 9199 } 9200 } 9201 if (sendAdded) { 9202 sendPackageAddedForUser(packageName, pkgSetting, userId); 9203 return true; 9204 } 9205 if (sendRemoved) { 9206 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9207 "hiding pkg"); 9208 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9209 } 9210 } finally { 9211 Binder.restoreCallingIdentity(callingId); 9212 } 9213 return false; 9214 } 9215 9216 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9217 int userId) { 9218 final PackageRemovedInfo info = new PackageRemovedInfo(); 9219 info.removedPackage = packageName; 9220 info.removedUsers = new int[] {userId}; 9221 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9222 info.sendBroadcast(false, false, false); 9223 } 9224 9225 /** 9226 * Returns true if application is not found or there was an error. Otherwise it returns 9227 * the hidden state of the package for the given user. 9228 */ 9229 @Override 9230 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9231 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9232 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9233 false, "getApplicationHidden for user " + userId); 9234 PackageSetting pkgSetting; 9235 long callingId = Binder.clearCallingIdentity(); 9236 try { 9237 // writer 9238 synchronized (mPackages) { 9239 pkgSetting = mSettings.mPackages.get(packageName); 9240 if (pkgSetting == null) { 9241 return true; 9242 } 9243 return pkgSetting.getHidden(userId); 9244 } 9245 } finally { 9246 Binder.restoreCallingIdentity(callingId); 9247 } 9248 } 9249 9250 /** 9251 * @hide 9252 */ 9253 @Override 9254 public int installExistingPackageAsUser(String packageName, int userId) { 9255 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9256 null); 9257 PackageSetting pkgSetting; 9258 final int uid = Binder.getCallingUid(); 9259 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9260 + userId); 9261 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9262 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9263 } 9264 9265 long callingId = Binder.clearCallingIdentity(); 9266 try { 9267 boolean sendAdded = false; 9268 9269 // writer 9270 synchronized (mPackages) { 9271 pkgSetting = mSettings.mPackages.get(packageName); 9272 if (pkgSetting == null) { 9273 return PackageManager.INSTALL_FAILED_INVALID_URI; 9274 } 9275 if (!pkgSetting.getInstalled(userId)) { 9276 pkgSetting.setInstalled(true, userId); 9277 pkgSetting.setHidden(false, userId); 9278 mSettings.writePackageRestrictionsLPr(userId); 9279 sendAdded = true; 9280 } 9281 } 9282 9283 if (sendAdded) { 9284 sendPackageAddedForUser(packageName, pkgSetting, userId); 9285 } 9286 } finally { 9287 Binder.restoreCallingIdentity(callingId); 9288 } 9289 9290 return PackageManager.INSTALL_SUCCEEDED; 9291 } 9292 9293 boolean isUserRestricted(int userId, String restrictionKey) { 9294 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9295 if (restrictions.getBoolean(restrictionKey, false)) { 9296 Log.w(TAG, "User is restricted: " + restrictionKey); 9297 return true; 9298 } 9299 return false; 9300 } 9301 9302 @Override 9303 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9304 mContext.enforceCallingOrSelfPermission( 9305 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9306 "Only package verification agents can verify applications"); 9307 9308 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9309 final PackageVerificationResponse response = new PackageVerificationResponse( 9310 verificationCode, Binder.getCallingUid()); 9311 msg.arg1 = id; 9312 msg.obj = response; 9313 mHandler.sendMessage(msg); 9314 } 9315 9316 @Override 9317 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9318 long millisecondsToDelay) { 9319 mContext.enforceCallingOrSelfPermission( 9320 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9321 "Only package verification agents can extend verification timeouts"); 9322 9323 final PackageVerificationState state = mPendingVerification.get(id); 9324 final PackageVerificationResponse response = new PackageVerificationResponse( 9325 verificationCodeAtTimeout, Binder.getCallingUid()); 9326 9327 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9328 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9329 } 9330 if (millisecondsToDelay < 0) { 9331 millisecondsToDelay = 0; 9332 } 9333 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9334 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9335 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9336 } 9337 9338 if ((state != null) && !state.timeoutExtended()) { 9339 state.extendTimeout(); 9340 9341 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9342 msg.arg1 = id; 9343 msg.obj = response; 9344 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9345 } 9346 } 9347 9348 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9349 int verificationCode, UserHandle user) { 9350 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9351 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9352 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9353 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9354 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9355 9356 mContext.sendBroadcastAsUser(intent, user, 9357 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9358 } 9359 9360 private ComponentName matchComponentForVerifier(String packageName, 9361 List<ResolveInfo> receivers) { 9362 ActivityInfo targetReceiver = null; 9363 9364 final int NR = receivers.size(); 9365 for (int i = 0; i < NR; i++) { 9366 final ResolveInfo info = receivers.get(i); 9367 if (info.activityInfo == null) { 9368 continue; 9369 } 9370 9371 if (packageName.equals(info.activityInfo.packageName)) { 9372 targetReceiver = info.activityInfo; 9373 break; 9374 } 9375 } 9376 9377 if (targetReceiver == null) { 9378 return null; 9379 } 9380 9381 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9382 } 9383 9384 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9385 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9386 if (pkgInfo.verifiers.length == 0) { 9387 return null; 9388 } 9389 9390 final int N = pkgInfo.verifiers.length; 9391 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9392 for (int i = 0; i < N; i++) { 9393 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9394 9395 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9396 receivers); 9397 if (comp == null) { 9398 continue; 9399 } 9400 9401 final int verifierUid = getUidForVerifier(verifierInfo); 9402 if (verifierUid == -1) { 9403 continue; 9404 } 9405 9406 if (DEBUG_VERIFY) { 9407 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9408 + " with the correct signature"); 9409 } 9410 sufficientVerifiers.add(comp); 9411 verificationState.addSufficientVerifier(verifierUid); 9412 } 9413 9414 return sufficientVerifiers; 9415 } 9416 9417 private int getUidForVerifier(VerifierInfo verifierInfo) { 9418 synchronized (mPackages) { 9419 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9420 if (pkg == null) { 9421 return -1; 9422 } else if (pkg.mSignatures.length != 1) { 9423 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9424 + " has more than one signature; ignoring"); 9425 return -1; 9426 } 9427 9428 /* 9429 * If the public key of the package's signature does not match 9430 * our expected public key, then this is a different package and 9431 * we should skip. 9432 */ 9433 9434 final byte[] expectedPublicKey; 9435 try { 9436 final Signature verifierSig = pkg.mSignatures[0]; 9437 final PublicKey publicKey = verifierSig.getPublicKey(); 9438 expectedPublicKey = publicKey.getEncoded(); 9439 } catch (CertificateException e) { 9440 return -1; 9441 } 9442 9443 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9444 9445 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9446 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9447 + " does not have the expected public key; ignoring"); 9448 return -1; 9449 } 9450 9451 return pkg.applicationInfo.uid; 9452 } 9453 } 9454 9455 @Override 9456 public void finishPackageInstall(int token) { 9457 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9458 9459 if (DEBUG_INSTALL) { 9460 Slog.v(TAG, "BM finishing package install for " + token); 9461 } 9462 9463 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9464 mHandler.sendMessage(msg); 9465 } 9466 9467 /** 9468 * Get the verification agent timeout. 9469 * 9470 * @return verification timeout in milliseconds 9471 */ 9472 private long getVerificationTimeout() { 9473 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9474 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9475 DEFAULT_VERIFICATION_TIMEOUT); 9476 } 9477 9478 /** 9479 * Get the default verification agent response code. 9480 * 9481 * @return default verification response code 9482 */ 9483 private int getDefaultVerificationResponse() { 9484 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9485 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9486 DEFAULT_VERIFICATION_RESPONSE); 9487 } 9488 9489 /** 9490 * Check whether or not package verification has been enabled. 9491 * 9492 * @return true if verification should be performed 9493 */ 9494 private boolean isVerificationEnabled(int userId, int installFlags) { 9495 if (!DEFAULT_VERIFY_ENABLE) { 9496 return false; 9497 } 9498 9499 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9500 9501 // Check if installing from ADB 9502 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9503 // Do not run verification in a test harness environment 9504 if (ActivityManager.isRunningInTestHarness()) { 9505 return false; 9506 } 9507 if (ensureVerifyAppsEnabled) { 9508 return true; 9509 } 9510 // Check if the developer does not want package verification for ADB installs 9511 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9512 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9513 return false; 9514 } 9515 } 9516 9517 if (ensureVerifyAppsEnabled) { 9518 return true; 9519 } 9520 9521 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9522 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9523 } 9524 9525 @Override 9526 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9527 throws RemoteException { 9528 mContext.enforceCallingOrSelfPermission( 9529 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9530 "Only intentfilter verification agents can verify applications"); 9531 9532 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9533 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9534 Binder.getCallingUid(), verificationCode, failedDomains); 9535 msg.arg1 = id; 9536 msg.obj = response; 9537 mHandler.sendMessage(msg); 9538 } 9539 9540 @Override 9541 public int getIntentVerificationStatus(String packageName, int userId) { 9542 synchronized (mPackages) { 9543 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9544 } 9545 } 9546 9547 @Override 9548 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9549 boolean result = false; 9550 synchronized (mPackages) { 9551 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9552 } 9553 if (result) { 9554 scheduleWritePackageRestrictionsLocked(userId); 9555 } 9556 return result; 9557 } 9558 9559 @Override 9560 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9561 synchronized (mPackages) { 9562 return mSettings.getIntentFilterVerificationsLPr(packageName); 9563 } 9564 } 9565 9566 @Override 9567 public List<IntentFilter> getAllIntentFilters(String packageName) { 9568 if (TextUtils.isEmpty(packageName)) { 9569 return Collections.<IntentFilter>emptyList(); 9570 } 9571 synchronized (mPackages) { 9572 PackageParser.Package pkg = mPackages.get(packageName); 9573 if (pkg == null || pkg.activities == null) { 9574 return Collections.<IntentFilter>emptyList(); 9575 } 9576 final int count = pkg.activities.size(); 9577 ArrayList<IntentFilter> result = new ArrayList<>(); 9578 for (int n=0; n<count; n++) { 9579 PackageParser.Activity activity = pkg.activities.get(n); 9580 if (activity.intents != null || activity.intents.size() > 0) { 9581 result.addAll(activity.intents); 9582 } 9583 } 9584 return result; 9585 } 9586 } 9587 9588 @Override 9589 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9590 synchronized (mPackages) { 9591 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9592 if (packageName != null) { 9593 result |= updateIntentVerificationStatus(packageName, 9594 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9595 UserHandle.myUserId()); 9596 } 9597 return result; 9598 } 9599 } 9600 9601 @Override 9602 public String getDefaultBrowserPackageName(int userId) { 9603 synchronized (mPackages) { 9604 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9605 } 9606 } 9607 9608 /** 9609 * Get the "allow unknown sources" setting. 9610 * 9611 * @return the current "allow unknown sources" setting 9612 */ 9613 private int getUnknownSourcesSettings() { 9614 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9615 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9616 -1); 9617 } 9618 9619 @Override 9620 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9621 final int uid = Binder.getCallingUid(); 9622 // writer 9623 synchronized (mPackages) { 9624 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9625 if (targetPackageSetting == null) { 9626 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9627 } 9628 9629 PackageSetting installerPackageSetting; 9630 if (installerPackageName != null) { 9631 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9632 if (installerPackageSetting == null) { 9633 throw new IllegalArgumentException("Unknown installer package: " 9634 + installerPackageName); 9635 } 9636 } else { 9637 installerPackageSetting = null; 9638 } 9639 9640 Signature[] callerSignature; 9641 Object obj = mSettings.getUserIdLPr(uid); 9642 if (obj != null) { 9643 if (obj instanceof SharedUserSetting) { 9644 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9645 } else if (obj instanceof PackageSetting) { 9646 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9647 } else { 9648 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9649 } 9650 } else { 9651 throw new SecurityException("Unknown calling uid " + uid); 9652 } 9653 9654 // Verify: can't set installerPackageName to a package that is 9655 // not signed with the same cert as the caller. 9656 if (installerPackageSetting != null) { 9657 if (compareSignatures(callerSignature, 9658 installerPackageSetting.signatures.mSignatures) 9659 != PackageManager.SIGNATURE_MATCH) { 9660 throw new SecurityException( 9661 "Caller does not have same cert as new installer package " 9662 + installerPackageName); 9663 } 9664 } 9665 9666 // Verify: if target already has an installer package, it must 9667 // be signed with the same cert as the caller. 9668 if (targetPackageSetting.installerPackageName != null) { 9669 PackageSetting setting = mSettings.mPackages.get( 9670 targetPackageSetting.installerPackageName); 9671 // If the currently set package isn't valid, then it's always 9672 // okay to change it. 9673 if (setting != null) { 9674 if (compareSignatures(callerSignature, 9675 setting.signatures.mSignatures) 9676 != PackageManager.SIGNATURE_MATCH) { 9677 throw new SecurityException( 9678 "Caller does not have same cert as old installer package " 9679 + targetPackageSetting.installerPackageName); 9680 } 9681 } 9682 } 9683 9684 // Okay! 9685 targetPackageSetting.installerPackageName = installerPackageName; 9686 scheduleWriteSettingsLocked(); 9687 } 9688 } 9689 9690 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9691 // Queue up an async operation since the package installation may take a little while. 9692 mHandler.post(new Runnable() { 9693 public void run() { 9694 mHandler.removeCallbacks(this); 9695 // Result object to be returned 9696 PackageInstalledInfo res = new PackageInstalledInfo(); 9697 res.returnCode = currentStatus; 9698 res.uid = -1; 9699 res.pkg = null; 9700 res.removedInfo = new PackageRemovedInfo(); 9701 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9702 args.doPreInstall(res.returnCode); 9703 synchronized (mInstallLock) { 9704 installPackageLI(args, res); 9705 } 9706 args.doPostInstall(res.returnCode, res.uid); 9707 } 9708 9709 // A restore should be performed at this point if (a) the install 9710 // succeeded, (b) the operation is not an update, and (c) the new 9711 // package has not opted out of backup participation. 9712 final boolean update = res.removedInfo.removedPackage != null; 9713 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9714 boolean doRestore = !update 9715 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9716 9717 // Set up the post-install work request bookkeeping. This will be used 9718 // and cleaned up by the post-install event handling regardless of whether 9719 // there's a restore pass performed. Token values are >= 1. 9720 int token; 9721 if (mNextInstallToken < 0) mNextInstallToken = 1; 9722 token = mNextInstallToken++; 9723 9724 PostInstallData data = new PostInstallData(args, res); 9725 mRunningInstalls.put(token, data); 9726 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9727 9728 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9729 // Pass responsibility to the Backup Manager. It will perform a 9730 // restore if appropriate, then pass responsibility back to the 9731 // Package Manager to run the post-install observer callbacks 9732 // and broadcasts. 9733 IBackupManager bm = IBackupManager.Stub.asInterface( 9734 ServiceManager.getService(Context.BACKUP_SERVICE)); 9735 if (bm != null) { 9736 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9737 + " to BM for possible restore"); 9738 try { 9739 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9740 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9741 } else { 9742 doRestore = false; 9743 } 9744 } catch (RemoteException e) { 9745 // can't happen; the backup manager is local 9746 } catch (Exception e) { 9747 Slog.e(TAG, "Exception trying to enqueue restore", e); 9748 doRestore = false; 9749 } 9750 } else { 9751 Slog.e(TAG, "Backup Manager not found!"); 9752 doRestore = false; 9753 } 9754 } 9755 9756 if (!doRestore) { 9757 // No restore possible, or the Backup Manager was mysteriously not 9758 // available -- just fire the post-install work request directly. 9759 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9760 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9761 mHandler.sendMessage(msg); 9762 } 9763 } 9764 }); 9765 } 9766 9767 private abstract class HandlerParams { 9768 private static final int MAX_RETRIES = 4; 9769 9770 /** 9771 * Number of times startCopy() has been attempted and had a non-fatal 9772 * error. 9773 */ 9774 private int mRetries = 0; 9775 9776 /** User handle for the user requesting the information or installation. */ 9777 private final UserHandle mUser; 9778 9779 HandlerParams(UserHandle user) { 9780 mUser = user; 9781 } 9782 9783 UserHandle getUser() { 9784 return mUser; 9785 } 9786 9787 final boolean startCopy() { 9788 boolean res; 9789 try { 9790 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9791 9792 if (++mRetries > MAX_RETRIES) { 9793 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9794 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9795 handleServiceError(); 9796 return false; 9797 } else { 9798 handleStartCopy(); 9799 res = true; 9800 } 9801 } catch (RemoteException e) { 9802 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9803 mHandler.sendEmptyMessage(MCS_RECONNECT); 9804 res = false; 9805 } 9806 handleReturnCode(); 9807 return res; 9808 } 9809 9810 final void serviceError() { 9811 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9812 handleServiceError(); 9813 handleReturnCode(); 9814 } 9815 9816 abstract void handleStartCopy() throws RemoteException; 9817 abstract void handleServiceError(); 9818 abstract void handleReturnCode(); 9819 } 9820 9821 class MeasureParams extends HandlerParams { 9822 private final PackageStats mStats; 9823 private boolean mSuccess; 9824 9825 private final IPackageStatsObserver mObserver; 9826 9827 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9828 super(new UserHandle(stats.userHandle)); 9829 mObserver = observer; 9830 mStats = stats; 9831 } 9832 9833 @Override 9834 public String toString() { 9835 return "MeasureParams{" 9836 + Integer.toHexString(System.identityHashCode(this)) 9837 + " " + mStats.packageName + "}"; 9838 } 9839 9840 @Override 9841 void handleStartCopy() throws RemoteException { 9842 synchronized (mInstallLock) { 9843 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9844 } 9845 9846 if (mSuccess) { 9847 final boolean mounted; 9848 if (Environment.isExternalStorageEmulated()) { 9849 mounted = true; 9850 } else { 9851 final String status = Environment.getExternalStorageState(); 9852 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9853 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9854 } 9855 9856 if (mounted) { 9857 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9858 9859 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9860 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9861 9862 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9863 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9864 9865 // Always subtract cache size, since it's a subdirectory 9866 mStats.externalDataSize -= mStats.externalCacheSize; 9867 9868 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9869 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9870 9871 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9872 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9873 } 9874 } 9875 } 9876 9877 @Override 9878 void handleReturnCode() { 9879 if (mObserver != null) { 9880 try { 9881 mObserver.onGetStatsCompleted(mStats, mSuccess); 9882 } catch (RemoteException e) { 9883 Slog.i(TAG, "Observer no longer exists."); 9884 } 9885 } 9886 } 9887 9888 @Override 9889 void handleServiceError() { 9890 Slog.e(TAG, "Could not measure application " + mStats.packageName 9891 + " external storage"); 9892 } 9893 } 9894 9895 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9896 throws RemoteException { 9897 long result = 0; 9898 for (File path : paths) { 9899 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9900 } 9901 return result; 9902 } 9903 9904 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9905 for (File path : paths) { 9906 try { 9907 mcs.clearDirectory(path.getAbsolutePath()); 9908 } catch (RemoteException e) { 9909 } 9910 } 9911 } 9912 9913 static class OriginInfo { 9914 /** 9915 * Location where install is coming from, before it has been 9916 * copied/renamed into place. This could be a single monolithic APK 9917 * file, or a cluster directory. This location may be untrusted. 9918 */ 9919 final File file; 9920 final String cid; 9921 9922 /** 9923 * Flag indicating that {@link #file} or {@link #cid} has already been 9924 * staged, meaning downstream users don't need to defensively copy the 9925 * contents. 9926 */ 9927 final boolean staged; 9928 9929 /** 9930 * Flag indicating that {@link #file} or {@link #cid} is an already 9931 * installed app that is being moved. 9932 */ 9933 final boolean existing; 9934 9935 final String resolvedPath; 9936 final File resolvedFile; 9937 9938 static OriginInfo fromNothing() { 9939 return new OriginInfo(null, null, false, false); 9940 } 9941 9942 static OriginInfo fromUntrustedFile(File file) { 9943 return new OriginInfo(file, null, false, false); 9944 } 9945 9946 static OriginInfo fromExistingFile(File file) { 9947 return new OriginInfo(file, null, false, true); 9948 } 9949 9950 static OriginInfo fromStagedFile(File file) { 9951 return new OriginInfo(file, null, true, false); 9952 } 9953 9954 static OriginInfo fromStagedContainer(String cid) { 9955 return new OriginInfo(null, cid, true, false); 9956 } 9957 9958 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9959 this.file = file; 9960 this.cid = cid; 9961 this.staged = staged; 9962 this.existing = existing; 9963 9964 if (cid != null) { 9965 resolvedPath = PackageHelper.getSdDir(cid); 9966 resolvedFile = new File(resolvedPath); 9967 } else if (file != null) { 9968 resolvedPath = file.getAbsolutePath(); 9969 resolvedFile = file; 9970 } else { 9971 resolvedPath = null; 9972 resolvedFile = null; 9973 } 9974 } 9975 } 9976 9977 class MoveInfo { 9978 final int moveId; 9979 final String fromUuid; 9980 final String toUuid; 9981 final String packageName; 9982 final String dataAppName; 9983 final int appId; 9984 final String seinfo; 9985 9986 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9987 String dataAppName, int appId, String seinfo) { 9988 this.moveId = moveId; 9989 this.fromUuid = fromUuid; 9990 this.toUuid = toUuid; 9991 this.packageName = packageName; 9992 this.dataAppName = dataAppName; 9993 this.appId = appId; 9994 this.seinfo = seinfo; 9995 } 9996 } 9997 9998 class InstallParams extends HandlerParams { 9999 final OriginInfo origin; 10000 final MoveInfo move; 10001 final IPackageInstallObserver2 observer; 10002 int installFlags; 10003 final String installerPackageName; 10004 final String volumeUuid; 10005 final VerificationParams verificationParams; 10006 private InstallArgs mArgs; 10007 private int mRet; 10008 final String packageAbiOverride; 10009 10010 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10011 int installFlags, String installerPackageName, String volumeUuid, 10012 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10013 super(user); 10014 this.origin = origin; 10015 this.move = move; 10016 this.observer = observer; 10017 this.installFlags = installFlags; 10018 this.installerPackageName = installerPackageName; 10019 this.volumeUuid = volumeUuid; 10020 this.verificationParams = verificationParams; 10021 this.packageAbiOverride = packageAbiOverride; 10022 } 10023 10024 @Override 10025 public String toString() { 10026 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10027 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10028 } 10029 10030 public ManifestDigest getManifestDigest() { 10031 if (verificationParams == null) { 10032 return null; 10033 } 10034 return verificationParams.getManifestDigest(); 10035 } 10036 10037 private int installLocationPolicy(PackageInfoLite pkgLite) { 10038 String packageName = pkgLite.packageName; 10039 int installLocation = pkgLite.installLocation; 10040 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10041 // reader 10042 synchronized (mPackages) { 10043 PackageParser.Package pkg = mPackages.get(packageName); 10044 if (pkg != null) { 10045 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10046 // Check for downgrading. 10047 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10048 try { 10049 checkDowngrade(pkg, pkgLite); 10050 } catch (PackageManagerException e) { 10051 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10052 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10053 } 10054 } 10055 // Check for updated system application. 10056 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10057 if (onSd) { 10058 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10059 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10060 } 10061 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10062 } else { 10063 if (onSd) { 10064 // Install flag overrides everything. 10065 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10066 } 10067 // If current upgrade specifies particular preference 10068 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10069 // Application explicitly specified internal. 10070 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10071 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10072 // App explictly prefers external. Let policy decide 10073 } else { 10074 // Prefer previous location 10075 if (isExternal(pkg)) { 10076 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10077 } 10078 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10079 } 10080 } 10081 } else { 10082 // Invalid install. Return error code 10083 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10084 } 10085 } 10086 } 10087 // All the special cases have been taken care of. 10088 // Return result based on recommended install location. 10089 if (onSd) { 10090 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10091 } 10092 return pkgLite.recommendedInstallLocation; 10093 } 10094 10095 /* 10096 * Invoke remote method to get package information and install 10097 * location values. Override install location based on default 10098 * policy if needed and then create install arguments based 10099 * on the install location. 10100 */ 10101 public void handleStartCopy() throws RemoteException { 10102 int ret = PackageManager.INSTALL_SUCCEEDED; 10103 10104 // If we're already staged, we've firmly committed to an install location 10105 if (origin.staged) { 10106 if (origin.file != null) { 10107 installFlags |= PackageManager.INSTALL_INTERNAL; 10108 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10109 } else if (origin.cid != null) { 10110 installFlags |= PackageManager.INSTALL_EXTERNAL; 10111 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10112 } else { 10113 throw new IllegalStateException("Invalid stage location"); 10114 } 10115 } 10116 10117 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10118 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10119 10120 PackageInfoLite pkgLite = null; 10121 10122 if (onInt && onSd) { 10123 // Check if both bits are set. 10124 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10125 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10126 } else { 10127 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10128 packageAbiOverride); 10129 10130 /* 10131 * If we have too little free space, try to free cache 10132 * before giving up. 10133 */ 10134 if (!origin.staged && pkgLite.recommendedInstallLocation 10135 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10136 // TODO: focus freeing disk space on the target device 10137 final StorageManager storage = StorageManager.from(mContext); 10138 final long lowThreshold = storage.getStorageLowBytes( 10139 Environment.getDataDirectory()); 10140 10141 final long sizeBytes = mContainerService.calculateInstalledSize( 10142 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10143 10144 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10145 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10146 installFlags, packageAbiOverride); 10147 } 10148 10149 /* 10150 * The cache free must have deleted the file we 10151 * downloaded to install. 10152 * 10153 * TODO: fix the "freeCache" call to not delete 10154 * the file we care about. 10155 */ 10156 if (pkgLite.recommendedInstallLocation 10157 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10158 pkgLite.recommendedInstallLocation 10159 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10160 } 10161 } 10162 } 10163 10164 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10165 int loc = pkgLite.recommendedInstallLocation; 10166 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10167 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10168 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10169 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10170 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10171 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10172 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10173 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10174 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10175 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10176 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10177 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10178 } else { 10179 // Override with defaults if needed. 10180 loc = installLocationPolicy(pkgLite); 10181 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10182 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10183 } else if (!onSd && !onInt) { 10184 // Override install location with flags 10185 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10186 // Set the flag to install on external media. 10187 installFlags |= PackageManager.INSTALL_EXTERNAL; 10188 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10189 } else { 10190 // Make sure the flag for installing on external 10191 // media is unset 10192 installFlags |= PackageManager.INSTALL_INTERNAL; 10193 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10194 } 10195 } 10196 } 10197 } 10198 10199 final InstallArgs args = createInstallArgs(this); 10200 mArgs = args; 10201 10202 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10203 /* 10204 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10205 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10206 */ 10207 int userIdentifier = getUser().getIdentifier(); 10208 if (userIdentifier == UserHandle.USER_ALL 10209 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10210 userIdentifier = UserHandle.USER_OWNER; 10211 } 10212 10213 /* 10214 * Determine if we have any installed package verifiers. If we 10215 * do, then we'll defer to them to verify the packages. 10216 */ 10217 final int requiredUid = mRequiredVerifierPackage == null ? -1 10218 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10219 if (!origin.existing && requiredUid != -1 10220 && isVerificationEnabled(userIdentifier, installFlags)) { 10221 final Intent verification = new Intent( 10222 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10223 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10224 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10225 PACKAGE_MIME_TYPE); 10226 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10227 10228 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10229 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10230 0 /* TODO: Which userId? */); 10231 10232 if (DEBUG_VERIFY) { 10233 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10234 + verification.toString() + " with " + pkgLite.verifiers.length 10235 + " optional verifiers"); 10236 } 10237 10238 final int verificationId = mPendingVerificationToken++; 10239 10240 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10241 10242 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10243 installerPackageName); 10244 10245 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10246 installFlags); 10247 10248 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10249 pkgLite.packageName); 10250 10251 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10252 pkgLite.versionCode); 10253 10254 if (verificationParams != null) { 10255 if (verificationParams.getVerificationURI() != null) { 10256 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10257 verificationParams.getVerificationURI()); 10258 } 10259 if (verificationParams.getOriginatingURI() != null) { 10260 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10261 verificationParams.getOriginatingURI()); 10262 } 10263 if (verificationParams.getReferrer() != null) { 10264 verification.putExtra(Intent.EXTRA_REFERRER, 10265 verificationParams.getReferrer()); 10266 } 10267 if (verificationParams.getOriginatingUid() >= 0) { 10268 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10269 verificationParams.getOriginatingUid()); 10270 } 10271 if (verificationParams.getInstallerUid() >= 0) { 10272 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10273 verificationParams.getInstallerUid()); 10274 } 10275 } 10276 10277 final PackageVerificationState verificationState = new PackageVerificationState( 10278 requiredUid, args); 10279 10280 mPendingVerification.append(verificationId, verificationState); 10281 10282 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10283 receivers, verificationState); 10284 10285 /* 10286 * If any sufficient verifiers were listed in the package 10287 * manifest, attempt to ask them. 10288 */ 10289 if (sufficientVerifiers != null) { 10290 final int N = sufficientVerifiers.size(); 10291 if (N == 0) { 10292 Slog.i(TAG, "Additional verifiers required, but none installed."); 10293 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10294 } else { 10295 for (int i = 0; i < N; i++) { 10296 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10297 10298 final Intent sufficientIntent = new Intent(verification); 10299 sufficientIntent.setComponent(verifierComponent); 10300 10301 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10302 } 10303 } 10304 } 10305 10306 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10307 mRequiredVerifierPackage, receivers); 10308 if (ret == PackageManager.INSTALL_SUCCEEDED 10309 && mRequiredVerifierPackage != null) { 10310 /* 10311 * Send the intent to the required verification agent, 10312 * but only start the verification timeout after the 10313 * target BroadcastReceivers have run. 10314 */ 10315 verification.setComponent(requiredVerifierComponent); 10316 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10317 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10318 new BroadcastReceiver() { 10319 @Override 10320 public void onReceive(Context context, Intent intent) { 10321 final Message msg = mHandler 10322 .obtainMessage(CHECK_PENDING_VERIFICATION); 10323 msg.arg1 = verificationId; 10324 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10325 } 10326 }, null, 0, null, null); 10327 10328 /* 10329 * We don't want the copy to proceed until verification 10330 * succeeds, so null out this field. 10331 */ 10332 mArgs = null; 10333 } 10334 } else { 10335 /* 10336 * No package verification is enabled, so immediately start 10337 * the remote call to initiate copy using temporary file. 10338 */ 10339 ret = args.copyApk(mContainerService, true); 10340 } 10341 } 10342 10343 mRet = ret; 10344 } 10345 10346 @Override 10347 void handleReturnCode() { 10348 // If mArgs is null, then MCS couldn't be reached. When it 10349 // reconnects, it will try again to install. At that point, this 10350 // will succeed. 10351 if (mArgs != null) { 10352 processPendingInstall(mArgs, mRet); 10353 } 10354 } 10355 10356 @Override 10357 void handleServiceError() { 10358 mArgs = createInstallArgs(this); 10359 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10360 } 10361 10362 public boolean isForwardLocked() { 10363 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10364 } 10365 } 10366 10367 /** 10368 * Used during creation of InstallArgs 10369 * 10370 * @param installFlags package installation flags 10371 * @return true if should be installed on external storage 10372 */ 10373 private static boolean installOnExternalAsec(int installFlags) { 10374 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10375 return false; 10376 } 10377 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10378 return true; 10379 } 10380 return false; 10381 } 10382 10383 /** 10384 * Used during creation of InstallArgs 10385 * 10386 * @param installFlags package installation flags 10387 * @return true if should be installed as forward locked 10388 */ 10389 private static boolean installForwardLocked(int installFlags) { 10390 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10391 } 10392 10393 private InstallArgs createInstallArgs(InstallParams params) { 10394 if (params.move != null) { 10395 return new MoveInstallArgs(params); 10396 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10397 return new AsecInstallArgs(params); 10398 } else { 10399 return new FileInstallArgs(params); 10400 } 10401 } 10402 10403 /** 10404 * Create args that describe an existing installed package. Typically used 10405 * when cleaning up old installs, or used as a move source. 10406 */ 10407 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10408 String resourcePath, String[] instructionSets) { 10409 final boolean isInAsec; 10410 if (installOnExternalAsec(installFlags)) { 10411 /* Apps on SD card are always in ASEC containers. */ 10412 isInAsec = true; 10413 } else if (installForwardLocked(installFlags) 10414 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10415 /* 10416 * Forward-locked apps are only in ASEC containers if they're the 10417 * new style 10418 */ 10419 isInAsec = true; 10420 } else { 10421 isInAsec = false; 10422 } 10423 10424 if (isInAsec) { 10425 return new AsecInstallArgs(codePath, instructionSets, 10426 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10427 } else { 10428 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10429 } 10430 } 10431 10432 static abstract class InstallArgs { 10433 /** @see InstallParams#origin */ 10434 final OriginInfo origin; 10435 /** @see InstallParams#move */ 10436 final MoveInfo move; 10437 10438 final IPackageInstallObserver2 observer; 10439 // Always refers to PackageManager flags only 10440 final int installFlags; 10441 final String installerPackageName; 10442 final String volumeUuid; 10443 final ManifestDigest manifestDigest; 10444 final UserHandle user; 10445 final String abiOverride; 10446 10447 // The list of instruction sets supported by this app. This is currently 10448 // only used during the rmdex() phase to clean up resources. We can get rid of this 10449 // if we move dex files under the common app path. 10450 /* nullable */ String[] instructionSets; 10451 10452 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10453 int installFlags, String installerPackageName, String volumeUuid, 10454 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10455 String abiOverride) { 10456 this.origin = origin; 10457 this.move = move; 10458 this.installFlags = installFlags; 10459 this.observer = observer; 10460 this.installerPackageName = installerPackageName; 10461 this.volumeUuid = volumeUuid; 10462 this.manifestDigest = manifestDigest; 10463 this.user = user; 10464 this.instructionSets = instructionSets; 10465 this.abiOverride = abiOverride; 10466 } 10467 10468 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10469 abstract int doPreInstall(int status); 10470 10471 /** 10472 * Rename package into final resting place. All paths on the given 10473 * scanned package should be updated to reflect the rename. 10474 */ 10475 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10476 abstract int doPostInstall(int status, int uid); 10477 10478 /** @see PackageSettingBase#codePathString */ 10479 abstract String getCodePath(); 10480 /** @see PackageSettingBase#resourcePathString */ 10481 abstract String getResourcePath(); 10482 10483 // Need installer lock especially for dex file removal. 10484 abstract void cleanUpResourcesLI(); 10485 abstract boolean doPostDeleteLI(boolean delete); 10486 10487 /** 10488 * Called before the source arguments are copied. This is used mostly 10489 * for MoveParams when it needs to read the source file to put it in the 10490 * destination. 10491 */ 10492 int doPreCopy() { 10493 return PackageManager.INSTALL_SUCCEEDED; 10494 } 10495 10496 /** 10497 * Called after the source arguments are copied. This is used mostly for 10498 * MoveParams when it needs to read the source file to put it in the 10499 * destination. 10500 * 10501 * @return 10502 */ 10503 int doPostCopy(int uid) { 10504 return PackageManager.INSTALL_SUCCEEDED; 10505 } 10506 10507 protected boolean isFwdLocked() { 10508 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10509 } 10510 10511 protected boolean isExternalAsec() { 10512 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10513 } 10514 10515 UserHandle getUser() { 10516 return user; 10517 } 10518 } 10519 10520 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10521 if (!allCodePaths.isEmpty()) { 10522 if (instructionSets == null) { 10523 throw new IllegalStateException("instructionSet == null"); 10524 } 10525 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10526 for (String codePath : allCodePaths) { 10527 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10528 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10529 if (retCode < 0) { 10530 Slog.w(TAG, "Couldn't remove dex file for package: " 10531 + " at location " + codePath + ", retcode=" + retCode); 10532 // we don't consider this to be a failure of the core package deletion 10533 } 10534 } 10535 } 10536 } 10537 } 10538 10539 /** 10540 * Logic to handle installation of non-ASEC applications, including copying 10541 * and renaming logic. 10542 */ 10543 class FileInstallArgs extends InstallArgs { 10544 private File codeFile; 10545 private File resourceFile; 10546 10547 // Example topology: 10548 // /data/app/com.example/base.apk 10549 // /data/app/com.example/split_foo.apk 10550 // /data/app/com.example/lib/arm/libfoo.so 10551 // /data/app/com.example/lib/arm64/libfoo.so 10552 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10553 10554 /** New install */ 10555 FileInstallArgs(InstallParams params) { 10556 super(params.origin, params.move, params.observer, params.installFlags, 10557 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10558 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10559 if (isFwdLocked()) { 10560 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10561 } 10562 } 10563 10564 /** Existing install */ 10565 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10566 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10567 null); 10568 this.codeFile = (codePath != null) ? new File(codePath) : null; 10569 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10570 } 10571 10572 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10573 if (origin.staged) { 10574 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10575 codeFile = origin.file; 10576 resourceFile = origin.file; 10577 return PackageManager.INSTALL_SUCCEEDED; 10578 } 10579 10580 try { 10581 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10582 codeFile = tempDir; 10583 resourceFile = tempDir; 10584 } catch (IOException e) { 10585 Slog.w(TAG, "Failed to create copy file: " + e); 10586 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10587 } 10588 10589 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10590 @Override 10591 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10592 if (!FileUtils.isValidExtFilename(name)) { 10593 throw new IllegalArgumentException("Invalid filename: " + name); 10594 } 10595 try { 10596 final File file = new File(codeFile, name); 10597 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10598 O_RDWR | O_CREAT, 0644); 10599 Os.chmod(file.getAbsolutePath(), 0644); 10600 return new ParcelFileDescriptor(fd); 10601 } catch (ErrnoException e) { 10602 throw new RemoteException("Failed to open: " + e.getMessage()); 10603 } 10604 } 10605 }; 10606 10607 int ret = PackageManager.INSTALL_SUCCEEDED; 10608 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10609 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10610 Slog.e(TAG, "Failed to copy package"); 10611 return ret; 10612 } 10613 10614 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10615 NativeLibraryHelper.Handle handle = null; 10616 try { 10617 handle = NativeLibraryHelper.Handle.create(codeFile); 10618 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10619 abiOverride); 10620 } catch (IOException e) { 10621 Slog.e(TAG, "Copying native libraries failed", e); 10622 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10623 } finally { 10624 IoUtils.closeQuietly(handle); 10625 } 10626 10627 return ret; 10628 } 10629 10630 int doPreInstall(int status) { 10631 if (status != PackageManager.INSTALL_SUCCEEDED) { 10632 cleanUp(); 10633 } 10634 return status; 10635 } 10636 10637 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10638 if (status != PackageManager.INSTALL_SUCCEEDED) { 10639 cleanUp(); 10640 return false; 10641 } 10642 10643 final File targetDir = codeFile.getParentFile(); 10644 final File beforeCodeFile = codeFile; 10645 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10646 10647 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10648 try { 10649 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10650 } catch (ErrnoException e) { 10651 Slog.w(TAG, "Failed to rename", e); 10652 return false; 10653 } 10654 10655 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10656 Slog.w(TAG, "Failed to restorecon"); 10657 return false; 10658 } 10659 10660 // Reflect the rename internally 10661 codeFile = afterCodeFile; 10662 resourceFile = afterCodeFile; 10663 10664 // Reflect the rename in scanned details 10665 pkg.codePath = afterCodeFile.getAbsolutePath(); 10666 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10667 pkg.baseCodePath); 10668 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10669 pkg.splitCodePaths); 10670 10671 // Reflect the rename in app info 10672 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10673 pkg.applicationInfo.setCodePath(pkg.codePath); 10674 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10675 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10676 pkg.applicationInfo.setResourcePath(pkg.codePath); 10677 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10678 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10679 10680 return true; 10681 } 10682 10683 int doPostInstall(int status, int uid) { 10684 if (status != PackageManager.INSTALL_SUCCEEDED) { 10685 cleanUp(); 10686 } 10687 return status; 10688 } 10689 10690 @Override 10691 String getCodePath() { 10692 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10693 } 10694 10695 @Override 10696 String getResourcePath() { 10697 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10698 } 10699 10700 private boolean cleanUp() { 10701 if (codeFile == null || !codeFile.exists()) { 10702 return false; 10703 } 10704 10705 if (codeFile.isDirectory()) { 10706 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10707 } else { 10708 codeFile.delete(); 10709 } 10710 10711 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10712 resourceFile.delete(); 10713 } 10714 10715 return true; 10716 } 10717 10718 void cleanUpResourcesLI() { 10719 // Try enumerating all code paths before deleting 10720 List<String> allCodePaths = Collections.EMPTY_LIST; 10721 if (codeFile != null && codeFile.exists()) { 10722 try { 10723 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10724 allCodePaths = pkg.getAllCodePaths(); 10725 } catch (PackageParserException e) { 10726 // Ignored; we tried our best 10727 } 10728 } 10729 10730 cleanUp(); 10731 removeDexFiles(allCodePaths, instructionSets); 10732 } 10733 10734 boolean doPostDeleteLI(boolean delete) { 10735 // XXX err, shouldn't we respect the delete flag? 10736 cleanUpResourcesLI(); 10737 return true; 10738 } 10739 } 10740 10741 private boolean isAsecExternal(String cid) { 10742 final String asecPath = PackageHelper.getSdFilesystem(cid); 10743 return !asecPath.startsWith(mAsecInternalPath); 10744 } 10745 10746 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10747 PackageManagerException { 10748 if (copyRet < 0) { 10749 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10750 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10751 throw new PackageManagerException(copyRet, message); 10752 } 10753 } 10754 } 10755 10756 /** 10757 * Extract the MountService "container ID" from the full code path of an 10758 * .apk. 10759 */ 10760 static String cidFromCodePath(String fullCodePath) { 10761 int eidx = fullCodePath.lastIndexOf("/"); 10762 String subStr1 = fullCodePath.substring(0, eidx); 10763 int sidx = subStr1.lastIndexOf("/"); 10764 return subStr1.substring(sidx+1, eidx); 10765 } 10766 10767 /** 10768 * Logic to handle installation of ASEC applications, including copying and 10769 * renaming logic. 10770 */ 10771 class AsecInstallArgs extends InstallArgs { 10772 static final String RES_FILE_NAME = "pkg.apk"; 10773 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10774 10775 String cid; 10776 String packagePath; 10777 String resourcePath; 10778 10779 /** New install */ 10780 AsecInstallArgs(InstallParams params) { 10781 super(params.origin, params.move, params.observer, params.installFlags, 10782 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10783 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10784 } 10785 10786 /** Existing install */ 10787 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10788 boolean isExternal, boolean isForwardLocked) { 10789 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10790 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10791 instructionSets, null); 10792 // Hackily pretend we're still looking at a full code path 10793 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10794 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10795 } 10796 10797 // Extract cid from fullCodePath 10798 int eidx = fullCodePath.lastIndexOf("/"); 10799 String subStr1 = fullCodePath.substring(0, eidx); 10800 int sidx = subStr1.lastIndexOf("/"); 10801 cid = subStr1.substring(sidx+1, eidx); 10802 setMountPath(subStr1); 10803 } 10804 10805 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10806 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10807 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10808 instructionSets, null); 10809 this.cid = cid; 10810 setMountPath(PackageHelper.getSdDir(cid)); 10811 } 10812 10813 void createCopyFile() { 10814 cid = mInstallerService.allocateExternalStageCidLegacy(); 10815 } 10816 10817 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10818 if (origin.staged) { 10819 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10820 cid = origin.cid; 10821 setMountPath(PackageHelper.getSdDir(cid)); 10822 return PackageManager.INSTALL_SUCCEEDED; 10823 } 10824 10825 if (temp) { 10826 createCopyFile(); 10827 } else { 10828 /* 10829 * Pre-emptively destroy the container since it's destroyed if 10830 * copying fails due to it existing anyway. 10831 */ 10832 PackageHelper.destroySdDir(cid); 10833 } 10834 10835 final String newMountPath = imcs.copyPackageToContainer( 10836 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10837 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10838 10839 if (newMountPath != null) { 10840 setMountPath(newMountPath); 10841 return PackageManager.INSTALL_SUCCEEDED; 10842 } else { 10843 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10844 } 10845 } 10846 10847 @Override 10848 String getCodePath() { 10849 return packagePath; 10850 } 10851 10852 @Override 10853 String getResourcePath() { 10854 return resourcePath; 10855 } 10856 10857 int doPreInstall(int status) { 10858 if (status != PackageManager.INSTALL_SUCCEEDED) { 10859 // Destroy container 10860 PackageHelper.destroySdDir(cid); 10861 } else { 10862 boolean mounted = PackageHelper.isContainerMounted(cid); 10863 if (!mounted) { 10864 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10865 Process.SYSTEM_UID); 10866 if (newMountPath != null) { 10867 setMountPath(newMountPath); 10868 } else { 10869 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10870 } 10871 } 10872 } 10873 return status; 10874 } 10875 10876 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10877 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10878 String newMountPath = null; 10879 if (PackageHelper.isContainerMounted(cid)) { 10880 // Unmount the container 10881 if (!PackageHelper.unMountSdDir(cid)) { 10882 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10883 return false; 10884 } 10885 } 10886 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10887 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10888 " which might be stale. Will try to clean up."); 10889 // Clean up the stale container and proceed to recreate. 10890 if (!PackageHelper.destroySdDir(newCacheId)) { 10891 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10892 return false; 10893 } 10894 // Successfully cleaned up stale container. Try to rename again. 10895 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10896 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10897 + " inspite of cleaning it up."); 10898 return false; 10899 } 10900 } 10901 if (!PackageHelper.isContainerMounted(newCacheId)) { 10902 Slog.w(TAG, "Mounting container " + newCacheId); 10903 newMountPath = PackageHelper.mountSdDir(newCacheId, 10904 getEncryptKey(), Process.SYSTEM_UID); 10905 } else { 10906 newMountPath = PackageHelper.getSdDir(newCacheId); 10907 } 10908 if (newMountPath == null) { 10909 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10910 return false; 10911 } 10912 Log.i(TAG, "Succesfully renamed " + cid + 10913 " to " + newCacheId + 10914 " at new path: " + newMountPath); 10915 cid = newCacheId; 10916 10917 final File beforeCodeFile = new File(packagePath); 10918 setMountPath(newMountPath); 10919 final File afterCodeFile = new File(packagePath); 10920 10921 // Reflect the rename in scanned details 10922 pkg.codePath = afterCodeFile.getAbsolutePath(); 10923 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10924 pkg.baseCodePath); 10925 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10926 pkg.splitCodePaths); 10927 10928 // Reflect the rename in app info 10929 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10930 pkg.applicationInfo.setCodePath(pkg.codePath); 10931 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10932 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10933 pkg.applicationInfo.setResourcePath(pkg.codePath); 10934 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10935 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10936 10937 return true; 10938 } 10939 10940 private void setMountPath(String mountPath) { 10941 final File mountFile = new File(mountPath); 10942 10943 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10944 if (monolithicFile.exists()) { 10945 packagePath = monolithicFile.getAbsolutePath(); 10946 if (isFwdLocked()) { 10947 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10948 } else { 10949 resourcePath = packagePath; 10950 } 10951 } else { 10952 packagePath = mountFile.getAbsolutePath(); 10953 resourcePath = packagePath; 10954 } 10955 } 10956 10957 int doPostInstall(int status, int uid) { 10958 if (status != PackageManager.INSTALL_SUCCEEDED) { 10959 cleanUp(); 10960 } else { 10961 final int groupOwner; 10962 final String protectedFile; 10963 if (isFwdLocked()) { 10964 groupOwner = UserHandle.getSharedAppGid(uid); 10965 protectedFile = RES_FILE_NAME; 10966 } else { 10967 groupOwner = -1; 10968 protectedFile = null; 10969 } 10970 10971 if (uid < Process.FIRST_APPLICATION_UID 10972 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10973 Slog.e(TAG, "Failed to finalize " + cid); 10974 PackageHelper.destroySdDir(cid); 10975 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10976 } 10977 10978 boolean mounted = PackageHelper.isContainerMounted(cid); 10979 if (!mounted) { 10980 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10981 } 10982 } 10983 return status; 10984 } 10985 10986 private void cleanUp() { 10987 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10988 10989 // Destroy secure container 10990 PackageHelper.destroySdDir(cid); 10991 } 10992 10993 private List<String> getAllCodePaths() { 10994 final File codeFile = new File(getCodePath()); 10995 if (codeFile != null && codeFile.exists()) { 10996 try { 10997 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10998 return pkg.getAllCodePaths(); 10999 } catch (PackageParserException e) { 11000 // Ignored; we tried our best 11001 } 11002 } 11003 return Collections.EMPTY_LIST; 11004 } 11005 11006 void cleanUpResourcesLI() { 11007 // Enumerate all code paths before deleting 11008 cleanUpResourcesLI(getAllCodePaths()); 11009 } 11010 11011 private void cleanUpResourcesLI(List<String> allCodePaths) { 11012 cleanUp(); 11013 removeDexFiles(allCodePaths, instructionSets); 11014 } 11015 11016 String getPackageName() { 11017 return getAsecPackageName(cid); 11018 } 11019 11020 boolean doPostDeleteLI(boolean delete) { 11021 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11022 final List<String> allCodePaths = getAllCodePaths(); 11023 boolean mounted = PackageHelper.isContainerMounted(cid); 11024 if (mounted) { 11025 // Unmount first 11026 if (PackageHelper.unMountSdDir(cid)) { 11027 mounted = false; 11028 } 11029 } 11030 if (!mounted && delete) { 11031 cleanUpResourcesLI(allCodePaths); 11032 } 11033 return !mounted; 11034 } 11035 11036 @Override 11037 int doPreCopy() { 11038 if (isFwdLocked()) { 11039 if (!PackageHelper.fixSdPermissions(cid, 11040 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11041 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11042 } 11043 } 11044 11045 return PackageManager.INSTALL_SUCCEEDED; 11046 } 11047 11048 @Override 11049 int doPostCopy(int uid) { 11050 if (isFwdLocked()) { 11051 if (uid < Process.FIRST_APPLICATION_UID 11052 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11053 RES_FILE_NAME)) { 11054 Slog.e(TAG, "Failed to finalize " + cid); 11055 PackageHelper.destroySdDir(cid); 11056 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11057 } 11058 } 11059 11060 return PackageManager.INSTALL_SUCCEEDED; 11061 } 11062 } 11063 11064 /** 11065 * Logic to handle movement of existing installed applications. 11066 */ 11067 class MoveInstallArgs extends InstallArgs { 11068 private File codeFile; 11069 private File resourceFile; 11070 11071 /** New install */ 11072 MoveInstallArgs(InstallParams params) { 11073 super(params.origin, params.move, params.observer, params.installFlags, 11074 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11075 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11076 } 11077 11078 int copyApk(IMediaContainerService imcs, boolean temp) { 11079 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11080 + move.fromUuid + " to " + move.toUuid); 11081 synchronized (mInstaller) { 11082 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11083 move.dataAppName, move.appId, move.seinfo) != 0) { 11084 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11085 } 11086 } 11087 11088 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11089 resourceFile = codeFile; 11090 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11091 11092 return PackageManager.INSTALL_SUCCEEDED; 11093 } 11094 11095 int doPreInstall(int status) { 11096 if (status != PackageManager.INSTALL_SUCCEEDED) { 11097 cleanUp(); 11098 } 11099 return status; 11100 } 11101 11102 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11103 if (status != PackageManager.INSTALL_SUCCEEDED) { 11104 cleanUp(); 11105 return false; 11106 } 11107 11108 // Reflect the move in app info 11109 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11110 pkg.applicationInfo.setCodePath(pkg.codePath); 11111 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11112 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11113 pkg.applicationInfo.setResourcePath(pkg.codePath); 11114 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11115 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11116 11117 return true; 11118 } 11119 11120 int doPostInstall(int status, int uid) { 11121 if (status != PackageManager.INSTALL_SUCCEEDED) { 11122 cleanUp(); 11123 } 11124 return status; 11125 } 11126 11127 @Override 11128 String getCodePath() { 11129 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11130 } 11131 11132 @Override 11133 String getResourcePath() { 11134 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11135 } 11136 11137 private boolean cleanUp() { 11138 if (codeFile == null || !codeFile.exists()) { 11139 return false; 11140 } 11141 11142 if (codeFile.isDirectory()) { 11143 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11144 } else { 11145 codeFile.delete(); 11146 } 11147 11148 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11149 resourceFile.delete(); 11150 } 11151 11152 return true; 11153 } 11154 11155 void cleanUpResourcesLI() { 11156 cleanUp(); 11157 } 11158 11159 boolean doPostDeleteLI(boolean delete) { 11160 // XXX err, shouldn't we respect the delete flag? 11161 cleanUpResourcesLI(); 11162 return true; 11163 } 11164 } 11165 11166 static String getAsecPackageName(String packageCid) { 11167 int idx = packageCid.lastIndexOf("-"); 11168 if (idx == -1) { 11169 return packageCid; 11170 } 11171 return packageCid.substring(0, idx); 11172 } 11173 11174 // Utility method used to create code paths based on package name and available index. 11175 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11176 String idxStr = ""; 11177 int idx = 1; 11178 // Fall back to default value of idx=1 if prefix is not 11179 // part of oldCodePath 11180 if (oldCodePath != null) { 11181 String subStr = oldCodePath; 11182 // Drop the suffix right away 11183 if (suffix != null && subStr.endsWith(suffix)) { 11184 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11185 } 11186 // If oldCodePath already contains prefix find out the 11187 // ending index to either increment or decrement. 11188 int sidx = subStr.lastIndexOf(prefix); 11189 if (sidx != -1) { 11190 subStr = subStr.substring(sidx + prefix.length()); 11191 if (subStr != null) { 11192 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11193 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11194 } 11195 try { 11196 idx = Integer.parseInt(subStr); 11197 if (idx <= 1) { 11198 idx++; 11199 } else { 11200 idx--; 11201 } 11202 } catch(NumberFormatException e) { 11203 } 11204 } 11205 } 11206 } 11207 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11208 return prefix + idxStr; 11209 } 11210 11211 private File getNextCodePath(File targetDir, String packageName) { 11212 int suffix = 1; 11213 File result; 11214 do { 11215 result = new File(targetDir, packageName + "-" + suffix); 11216 suffix++; 11217 } while (result.exists()); 11218 return result; 11219 } 11220 11221 // Utility method that returns the relative package path with respect 11222 // to the installation directory. Like say for /data/data/com.test-1.apk 11223 // string com.test-1 is returned. 11224 static String deriveCodePathName(String codePath) { 11225 if (codePath == null) { 11226 return null; 11227 } 11228 final File codeFile = new File(codePath); 11229 final String name = codeFile.getName(); 11230 if (codeFile.isDirectory()) { 11231 return name; 11232 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11233 final int lastDot = name.lastIndexOf('.'); 11234 return name.substring(0, lastDot); 11235 } else { 11236 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11237 return null; 11238 } 11239 } 11240 11241 class PackageInstalledInfo { 11242 String name; 11243 int uid; 11244 // The set of users that originally had this package installed. 11245 int[] origUsers; 11246 // The set of users that now have this package installed. 11247 int[] newUsers; 11248 PackageParser.Package pkg; 11249 int returnCode; 11250 String returnMsg; 11251 PackageRemovedInfo removedInfo; 11252 11253 public void setError(int code, String msg) { 11254 returnCode = code; 11255 returnMsg = msg; 11256 Slog.w(TAG, msg); 11257 } 11258 11259 public void setError(String msg, PackageParserException e) { 11260 returnCode = e.error; 11261 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11262 Slog.w(TAG, msg, e); 11263 } 11264 11265 public void setError(String msg, PackageManagerException e) { 11266 returnCode = e.error; 11267 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11268 Slog.w(TAG, msg, e); 11269 } 11270 11271 // In some error cases we want to convey more info back to the observer 11272 String origPackage; 11273 String origPermission; 11274 } 11275 11276 /* 11277 * Install a non-existing package. 11278 */ 11279 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11280 UserHandle user, String installerPackageName, String volumeUuid, 11281 PackageInstalledInfo res) { 11282 // Remember this for later, in case we need to rollback this install 11283 String pkgName = pkg.packageName; 11284 11285 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11286 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11287 UserHandle.USER_OWNER).exists(); 11288 synchronized(mPackages) { 11289 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11290 // A package with the same name is already installed, though 11291 // it has been renamed to an older name. The package we 11292 // are trying to install should be installed as an update to 11293 // the existing one, but that has not been requested, so bail. 11294 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11295 + " without first uninstalling package running as " 11296 + mSettings.mRenamedPackages.get(pkgName)); 11297 return; 11298 } 11299 if (mPackages.containsKey(pkgName)) { 11300 // Don't allow installation over an existing package with the same name. 11301 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11302 + " without first uninstalling."); 11303 return; 11304 } 11305 } 11306 11307 try { 11308 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11309 System.currentTimeMillis(), user); 11310 11311 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11312 // delete the partially installed application. the data directory will have to be 11313 // restored if it was already existing 11314 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11315 // remove package from internal structures. Note that we want deletePackageX to 11316 // delete the package data and cache directories that it created in 11317 // scanPackageLocked, unless those directories existed before we even tried to 11318 // install. 11319 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11320 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11321 res.removedInfo, true); 11322 } 11323 11324 } catch (PackageManagerException e) { 11325 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11326 } 11327 } 11328 11329 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11330 // Can't rotate keys during boot or if sharedUser. 11331 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11332 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11333 return false; 11334 } 11335 // app is using upgradeKeySets; make sure all are valid 11336 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11337 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11338 for (int i = 0; i < upgradeKeySets.length; i++) { 11339 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11340 Slog.wtf(TAG, "Package " 11341 + (oldPs.name != null ? oldPs.name : "<null>") 11342 + " contains upgrade-key-set reference to unknown key-set: " 11343 + upgradeKeySets[i] 11344 + " reverting to signatures check."); 11345 return false; 11346 } 11347 } 11348 return true; 11349 } 11350 11351 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11352 // Upgrade keysets are being used. Determine if new package has a superset of the 11353 // required keys. 11354 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11355 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11356 for (int i = 0; i < upgradeKeySets.length; i++) { 11357 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11358 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11359 return true; 11360 } 11361 } 11362 return false; 11363 } 11364 11365 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11366 UserHandle user, String installerPackageName, String volumeUuid, 11367 PackageInstalledInfo res) { 11368 final PackageParser.Package oldPackage; 11369 final String pkgName = pkg.packageName; 11370 final int[] allUsers; 11371 final boolean[] perUserInstalled; 11372 final boolean weFroze; 11373 11374 // First find the old package info and check signatures 11375 synchronized(mPackages) { 11376 oldPackage = mPackages.get(pkgName); 11377 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11378 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11379 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11380 if(!checkUpgradeKeySetLP(ps, pkg)) { 11381 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11382 "New package not signed by keys specified by upgrade-keysets: " 11383 + pkgName); 11384 return; 11385 } 11386 } else { 11387 // default to original signature matching 11388 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11389 != PackageManager.SIGNATURE_MATCH) { 11390 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11391 "New package has a different signature: " + pkgName); 11392 return; 11393 } 11394 } 11395 11396 // In case of rollback, remember per-user/profile install state 11397 allUsers = sUserManager.getUserIds(); 11398 perUserInstalled = new boolean[allUsers.length]; 11399 for (int i = 0; i < allUsers.length; i++) { 11400 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11401 } 11402 11403 // Mark the app as frozen to prevent launching during the upgrade 11404 // process, and then kill all running instances 11405 if (!ps.frozen) { 11406 ps.frozen = true; 11407 weFroze = true; 11408 } else { 11409 weFroze = false; 11410 } 11411 } 11412 11413 // Now that we're guarded by frozen state, kill app during upgrade 11414 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11415 11416 try { 11417 boolean sysPkg = (isSystemApp(oldPackage)); 11418 if (sysPkg) { 11419 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11420 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11421 } else { 11422 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11423 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11424 } 11425 } finally { 11426 // Regardless of success or failure of upgrade steps above, always 11427 // unfreeze the package if we froze it 11428 if (weFroze) { 11429 unfreezePackage(pkgName); 11430 } 11431 } 11432 } 11433 11434 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11435 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11436 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11437 String volumeUuid, PackageInstalledInfo res) { 11438 String pkgName = deletedPackage.packageName; 11439 boolean deletedPkg = true; 11440 boolean updatedSettings = false; 11441 11442 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11443 + deletedPackage); 11444 long origUpdateTime; 11445 if (pkg.mExtras != null) { 11446 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11447 } else { 11448 origUpdateTime = 0; 11449 } 11450 11451 // First delete the existing package while retaining the data directory 11452 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11453 res.removedInfo, true)) { 11454 // If the existing package wasn't successfully deleted 11455 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11456 deletedPkg = false; 11457 } else { 11458 // Successfully deleted the old package; proceed with replace. 11459 11460 // If deleted package lived in a container, give users a chance to 11461 // relinquish resources before killing. 11462 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11463 if (DEBUG_INSTALL) { 11464 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11465 } 11466 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11467 final ArrayList<String> pkgList = new ArrayList<String>(1); 11468 pkgList.add(deletedPackage.applicationInfo.packageName); 11469 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11470 } 11471 11472 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11473 try { 11474 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11475 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11476 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11477 perUserInstalled, res, user); 11478 updatedSettings = true; 11479 } catch (PackageManagerException e) { 11480 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11481 } 11482 } 11483 11484 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11485 // remove package from internal structures. Note that we want deletePackageX to 11486 // delete the package data and cache directories that it created in 11487 // scanPackageLocked, unless those directories existed before we even tried to 11488 // install. 11489 if(updatedSettings) { 11490 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11491 deletePackageLI( 11492 pkgName, null, true, allUsers, perUserInstalled, 11493 PackageManager.DELETE_KEEP_DATA, 11494 res.removedInfo, true); 11495 } 11496 // Since we failed to install the new package we need to restore the old 11497 // package that we deleted. 11498 if (deletedPkg) { 11499 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11500 File restoreFile = new File(deletedPackage.codePath); 11501 // Parse old package 11502 boolean oldExternal = isExternal(deletedPackage); 11503 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11504 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11505 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11506 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11507 try { 11508 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11509 } catch (PackageManagerException e) { 11510 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11511 + e.getMessage()); 11512 return; 11513 } 11514 // Restore of old package succeeded. Update permissions. 11515 // writer 11516 synchronized (mPackages) { 11517 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11518 UPDATE_PERMISSIONS_ALL); 11519 // can downgrade to reader 11520 mSettings.writeLPr(); 11521 } 11522 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11523 } 11524 } 11525 } 11526 11527 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11528 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11529 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11530 String volumeUuid, PackageInstalledInfo res) { 11531 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11532 + ", old=" + deletedPackage); 11533 boolean disabledSystem = false; 11534 boolean updatedSettings = false; 11535 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11536 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11537 != 0) { 11538 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11539 } 11540 String packageName = deletedPackage.packageName; 11541 if (packageName == null) { 11542 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11543 "Attempt to delete null packageName."); 11544 return; 11545 } 11546 PackageParser.Package oldPkg; 11547 PackageSetting oldPkgSetting; 11548 // reader 11549 synchronized (mPackages) { 11550 oldPkg = mPackages.get(packageName); 11551 oldPkgSetting = mSettings.mPackages.get(packageName); 11552 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11553 (oldPkgSetting == null)) { 11554 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11555 "Couldn't find package:" + packageName + " information"); 11556 return; 11557 } 11558 } 11559 11560 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11561 res.removedInfo.removedPackage = packageName; 11562 // Remove existing system package 11563 removePackageLI(oldPkgSetting, true); 11564 // writer 11565 synchronized (mPackages) { 11566 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11567 if (!disabledSystem && deletedPackage != null) { 11568 // We didn't need to disable the .apk as a current system package, 11569 // which means we are replacing another update that is already 11570 // installed. We need to make sure to delete the older one's .apk. 11571 res.removedInfo.args = createInstallArgsForExisting(0, 11572 deletedPackage.applicationInfo.getCodePath(), 11573 deletedPackage.applicationInfo.getResourcePath(), 11574 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11575 } else { 11576 res.removedInfo.args = null; 11577 } 11578 } 11579 11580 // Successfully disabled the old package. Now proceed with re-installation 11581 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11582 11583 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11584 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11585 11586 PackageParser.Package newPackage = null; 11587 try { 11588 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11589 if (newPackage.mExtras != null) { 11590 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11591 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11592 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11593 11594 // is the update attempting to change shared user? that isn't going to work... 11595 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11596 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11597 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11598 + " to " + newPkgSetting.sharedUser); 11599 updatedSettings = true; 11600 } 11601 } 11602 11603 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11604 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11605 perUserInstalled, res, user); 11606 updatedSettings = true; 11607 } 11608 11609 } catch (PackageManagerException e) { 11610 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11611 } 11612 11613 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11614 // Re installation failed. Restore old information 11615 // Remove new pkg information 11616 if (newPackage != null) { 11617 removeInstalledPackageLI(newPackage, true); 11618 } 11619 // Add back the old system package 11620 try { 11621 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11622 } catch (PackageManagerException e) { 11623 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11624 } 11625 // Restore the old system information in Settings 11626 synchronized (mPackages) { 11627 if (disabledSystem) { 11628 mSettings.enableSystemPackageLPw(packageName); 11629 } 11630 if (updatedSettings) { 11631 mSettings.setInstallerPackageName(packageName, 11632 oldPkgSetting.installerPackageName); 11633 } 11634 mSettings.writeLPr(); 11635 } 11636 } 11637 } 11638 11639 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11640 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11641 UserHandle user) { 11642 String pkgName = newPackage.packageName; 11643 synchronized (mPackages) { 11644 //write settings. the installStatus will be incomplete at this stage. 11645 //note that the new package setting would have already been 11646 //added to mPackages. It hasn't been persisted yet. 11647 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11648 mSettings.writeLPr(); 11649 } 11650 11651 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11652 11653 synchronized (mPackages) { 11654 updatePermissionsLPw(newPackage.packageName, newPackage, 11655 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11656 ? UPDATE_PERMISSIONS_ALL : 0)); 11657 // For system-bundled packages, we assume that installing an upgraded version 11658 // of the package implies that the user actually wants to run that new code, 11659 // so we enable the package. 11660 PackageSetting ps = mSettings.mPackages.get(pkgName); 11661 if (ps != null) { 11662 if (isSystemApp(newPackage)) { 11663 // NB: implicit assumption that system package upgrades apply to all users 11664 if (DEBUG_INSTALL) { 11665 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11666 } 11667 if (res.origUsers != null) { 11668 for (int userHandle : res.origUsers) { 11669 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11670 userHandle, installerPackageName); 11671 } 11672 } 11673 // Also convey the prior install/uninstall state 11674 if (allUsers != null && perUserInstalled != null) { 11675 for (int i = 0; i < allUsers.length; i++) { 11676 if (DEBUG_INSTALL) { 11677 Slog.d(TAG, " user " + allUsers[i] 11678 + " => " + perUserInstalled[i]); 11679 } 11680 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11681 } 11682 // these install state changes will be persisted in the 11683 // upcoming call to mSettings.writeLPr(). 11684 } 11685 } 11686 // It's implied that when a user requests installation, they want the app to be 11687 // installed and enabled. 11688 int userId = user.getIdentifier(); 11689 if (userId != UserHandle.USER_ALL) { 11690 ps.setInstalled(true, userId); 11691 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11692 } 11693 } 11694 res.name = pkgName; 11695 res.uid = newPackage.applicationInfo.uid; 11696 res.pkg = newPackage; 11697 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11698 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11699 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11700 //to update install status 11701 mSettings.writeLPr(); 11702 } 11703 } 11704 11705 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11706 final int installFlags = args.installFlags; 11707 final String installerPackageName = args.installerPackageName; 11708 final String volumeUuid = args.volumeUuid; 11709 final File tmpPackageFile = new File(args.getCodePath()); 11710 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11711 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11712 || (args.volumeUuid != null)); 11713 boolean replace = false; 11714 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11715 if (args.move != null) { 11716 // moving a complete application; perfom an initial scan on the new install location 11717 scanFlags |= SCAN_INITIAL; 11718 } 11719 // Result object to be returned 11720 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11721 11722 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11723 // Retrieve PackageSettings and parse package 11724 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11725 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11726 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11727 PackageParser pp = new PackageParser(); 11728 pp.setSeparateProcesses(mSeparateProcesses); 11729 pp.setDisplayMetrics(mMetrics); 11730 11731 final PackageParser.Package pkg; 11732 try { 11733 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11734 } catch (PackageParserException e) { 11735 res.setError("Failed parse during installPackageLI", e); 11736 return; 11737 } 11738 11739 // Mark that we have an install time CPU ABI override. 11740 pkg.cpuAbiOverride = args.abiOverride; 11741 11742 String pkgName = res.name = pkg.packageName; 11743 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11744 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11745 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11746 return; 11747 } 11748 } 11749 11750 try { 11751 pp.collectCertificates(pkg, parseFlags); 11752 pp.collectManifestDigest(pkg); 11753 } catch (PackageParserException e) { 11754 res.setError("Failed collect during installPackageLI", e); 11755 return; 11756 } 11757 11758 /* If the installer passed in a manifest digest, compare it now. */ 11759 if (args.manifestDigest != null) { 11760 if (DEBUG_INSTALL) { 11761 final String parsedManifest = pkg.manifestDigest == null ? "null" 11762 : pkg.manifestDigest.toString(); 11763 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11764 + parsedManifest); 11765 } 11766 11767 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11768 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11769 return; 11770 } 11771 } else if (DEBUG_INSTALL) { 11772 final String parsedManifest = pkg.manifestDigest == null 11773 ? "null" : pkg.manifestDigest.toString(); 11774 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11775 } 11776 11777 // Get rid of all references to package scan path via parser. 11778 pp = null; 11779 String oldCodePath = null; 11780 boolean systemApp = false; 11781 synchronized (mPackages) { 11782 // Check if installing already existing package 11783 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11784 String oldName = mSettings.mRenamedPackages.get(pkgName); 11785 if (pkg.mOriginalPackages != null 11786 && pkg.mOriginalPackages.contains(oldName) 11787 && mPackages.containsKey(oldName)) { 11788 // This package is derived from an original package, 11789 // and this device has been updating from that original 11790 // name. We must continue using the original name, so 11791 // rename the new package here. 11792 pkg.setPackageName(oldName); 11793 pkgName = pkg.packageName; 11794 replace = true; 11795 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11796 + oldName + " pkgName=" + pkgName); 11797 } else if (mPackages.containsKey(pkgName)) { 11798 // This package, under its official name, already exists 11799 // on the device; we should replace it. 11800 replace = true; 11801 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11802 } 11803 11804 // Prevent apps opting out from runtime permissions 11805 if (replace) { 11806 PackageParser.Package oldPackage = mPackages.get(pkgName); 11807 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11808 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11809 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11810 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11811 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11812 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11813 + " doesn't support runtime permissions but the old" 11814 + " target SDK " + oldTargetSdk + " does."); 11815 return; 11816 } 11817 } 11818 } 11819 11820 PackageSetting ps = mSettings.mPackages.get(pkgName); 11821 if (ps != null) { 11822 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11823 11824 // Quick sanity check that we're signed correctly if updating; 11825 // we'll check this again later when scanning, but we want to 11826 // bail early here before tripping over redefined permissions. 11827 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11828 if (!checkUpgradeKeySetLP(ps, pkg)) { 11829 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11830 + pkg.packageName + " upgrade keys do not match the " 11831 + "previously installed version"); 11832 return; 11833 } 11834 } else { 11835 try { 11836 verifySignaturesLP(ps, pkg); 11837 } catch (PackageManagerException e) { 11838 res.setError(e.error, e.getMessage()); 11839 return; 11840 } 11841 } 11842 11843 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11844 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11845 systemApp = (ps.pkg.applicationInfo.flags & 11846 ApplicationInfo.FLAG_SYSTEM) != 0; 11847 } 11848 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11849 } 11850 11851 // Check whether the newly-scanned package wants to define an already-defined perm 11852 int N = pkg.permissions.size(); 11853 for (int i = N-1; i >= 0; i--) { 11854 PackageParser.Permission perm = pkg.permissions.get(i); 11855 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11856 if (bp != null) { 11857 // If the defining package is signed with our cert, it's okay. This 11858 // also includes the "updating the same package" case, of course. 11859 // "updating same package" could also involve key-rotation. 11860 final boolean sigsOk; 11861 if (bp.sourcePackage.equals(pkg.packageName) 11862 && (bp.packageSetting instanceof PackageSetting) 11863 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11864 scanFlags))) { 11865 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11866 } else { 11867 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11868 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11869 } 11870 if (!sigsOk) { 11871 // If the owning package is the system itself, we log but allow 11872 // install to proceed; we fail the install on all other permission 11873 // redefinitions. 11874 if (!bp.sourcePackage.equals("android")) { 11875 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11876 + pkg.packageName + " attempting to redeclare permission " 11877 + perm.info.name + " already owned by " + bp.sourcePackage); 11878 res.origPermission = perm.info.name; 11879 res.origPackage = bp.sourcePackage; 11880 return; 11881 } else { 11882 Slog.w(TAG, "Package " + pkg.packageName 11883 + " attempting to redeclare system permission " 11884 + perm.info.name + "; ignoring new declaration"); 11885 pkg.permissions.remove(i); 11886 } 11887 } 11888 } 11889 } 11890 11891 } 11892 11893 if (systemApp && onExternal) { 11894 // Disable updates to system apps on sdcard 11895 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11896 "Cannot install updates to system apps on sdcard"); 11897 return; 11898 } 11899 11900 if (args.move != null) { 11901 // We did an in-place move, so dex is ready to roll 11902 scanFlags |= SCAN_NO_DEX; 11903 scanFlags |= SCAN_MOVE; 11904 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11905 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11906 scanFlags |= SCAN_NO_DEX; 11907 11908 try { 11909 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11910 true /* extract libs */); 11911 } catch (PackageManagerException pme) { 11912 Slog.e(TAG, "Error deriving application ABI", pme); 11913 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11914 return; 11915 } 11916 11917 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11918 int result = mPackageDexOptimizer 11919 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11920 false /* defer */, false /* inclDependencies */); 11921 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11922 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11923 return; 11924 } 11925 } 11926 11927 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11928 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11929 return; 11930 } 11931 11932 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 11933 11934 if (replace) { 11935 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11936 installerPackageName, volumeUuid, res); 11937 } else { 11938 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11939 args.user, installerPackageName, volumeUuid, res); 11940 } 11941 synchronized (mPackages) { 11942 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11943 if (ps != null) { 11944 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11945 } 11946 } 11947 } 11948 11949 private void startIntentFilterVerifications(int userId, boolean replacing, 11950 PackageParser.Package pkg) { 11951 if (mIntentFilterVerifierComponent == null) { 11952 Slog.w(TAG, "No IntentFilter verification will not be done as " 11953 + "there is no IntentFilterVerifier available!"); 11954 return; 11955 } 11956 11957 final int verifierUid = getPackageUid( 11958 mIntentFilterVerifierComponent.getPackageName(), 11959 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11960 11961 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11962 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11963 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 11964 mHandler.sendMessage(msg); 11965 } 11966 11967 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 11968 PackageParser.Package pkg) { 11969 int size = pkg.activities.size(); 11970 if (size == 0) { 11971 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11972 "No activity, so no need to verify any IntentFilter!"); 11973 return; 11974 } 11975 11976 final boolean hasDomainURLs = hasDomainURLs(pkg); 11977 if (!hasDomainURLs) { 11978 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11979 "No domain URLs, so no need to verify any IntentFilter!"); 11980 return; 11981 } 11982 11983 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11984 + " if any IntentFilter from the " + size 11985 + " Activities needs verification ..."); 11986 11987 int count = 0; 11988 final String packageName = pkg.packageName; 11989 11990 synchronized (mPackages) { 11991 // If this is a new install and we see that we've already run verification for this 11992 // package, we have nothing to do: it means the state was restored from backup. 11993 if (!replacing) { 11994 IntentFilterVerificationInfo ivi = 11995 mSettings.getIntentFilterVerificationLPr(packageName); 11996 if (ivi != null) { 11997 if (DEBUG_DOMAIN_VERIFICATION) { 11998 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 11999 + ivi.getStatusString()); 12000 } 12001 return; 12002 } 12003 } 12004 12005 // If any filters need to be verified, then all need to be. 12006 boolean needToVerify = false; 12007 for (PackageParser.Activity a : pkg.activities) { 12008 for (ActivityIntentInfo filter : a.intents) { 12009 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12010 if (DEBUG_DOMAIN_VERIFICATION) { 12011 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12012 } 12013 needToVerify = true; 12014 break; 12015 } 12016 } 12017 } 12018 12019 if (needToVerify) { 12020 final int verificationId = mIntentFilterVerificationToken++; 12021 for (PackageParser.Activity a : pkg.activities) { 12022 for (ActivityIntentInfo filter : a.intents) { 12023 if (filter.hasOnlyWebDataURI() && needsNetworkVerificationLPr(filter)) { 12024 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12025 "Verification needed for IntentFilter:" + filter.toString()); 12026 mIntentFilterVerifier.addOneIntentFilterVerification( 12027 verifierUid, userId, verificationId, filter, packageName); 12028 count++; 12029 } 12030 } 12031 } 12032 } 12033 } 12034 12035 if (count > 0) { 12036 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12037 + " IntentFilter verification" + (count > 1 ? "s" : "") 12038 + " for userId:" + userId); 12039 mIntentFilterVerifier.startVerifications(userId); 12040 } else { 12041 if (DEBUG_DOMAIN_VERIFICATION) { 12042 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12043 } 12044 } 12045 } 12046 12047 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12048 final ComponentName cn = filter.activity.getComponentName(); 12049 final String packageName = cn.getPackageName(); 12050 12051 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12052 packageName); 12053 if (ivi == null) { 12054 return true; 12055 } 12056 int status = ivi.getStatus(); 12057 switch (status) { 12058 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12059 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12060 return true; 12061 12062 default: 12063 // Nothing to do 12064 return false; 12065 } 12066 } 12067 12068 private static boolean isMultiArch(PackageSetting ps) { 12069 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12070 } 12071 12072 private static boolean isMultiArch(ApplicationInfo info) { 12073 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12074 } 12075 12076 private static boolean isExternal(PackageParser.Package pkg) { 12077 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12078 } 12079 12080 private static boolean isExternal(PackageSetting ps) { 12081 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12082 } 12083 12084 private static boolean isExternal(ApplicationInfo info) { 12085 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12086 } 12087 12088 private static boolean isSystemApp(PackageParser.Package pkg) { 12089 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12090 } 12091 12092 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12093 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12094 } 12095 12096 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12097 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12098 } 12099 12100 private static boolean isSystemApp(PackageSetting ps) { 12101 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12102 } 12103 12104 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12105 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12106 } 12107 12108 private int packageFlagsToInstallFlags(PackageSetting ps) { 12109 int installFlags = 0; 12110 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12111 // This existing package was an external ASEC install when we have 12112 // the external flag without a UUID 12113 installFlags |= PackageManager.INSTALL_EXTERNAL; 12114 } 12115 if (ps.isForwardLocked()) { 12116 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12117 } 12118 return installFlags; 12119 } 12120 12121 private void deleteTempPackageFiles() { 12122 final FilenameFilter filter = new FilenameFilter() { 12123 public boolean accept(File dir, String name) { 12124 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12125 } 12126 }; 12127 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12128 file.delete(); 12129 } 12130 } 12131 12132 @Override 12133 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12134 int flags) { 12135 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12136 flags); 12137 } 12138 12139 @Override 12140 public void deletePackage(final String packageName, 12141 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12142 mContext.enforceCallingOrSelfPermission( 12143 android.Manifest.permission.DELETE_PACKAGES, null); 12144 final int uid = Binder.getCallingUid(); 12145 if (UserHandle.getUserId(uid) != userId) { 12146 mContext.enforceCallingPermission( 12147 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12148 "deletePackage for user " + userId); 12149 } 12150 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12151 try { 12152 observer.onPackageDeleted(packageName, 12153 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12154 } catch (RemoteException re) { 12155 } 12156 return; 12157 } 12158 12159 boolean uninstallBlocked = false; 12160 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12161 int[] users = sUserManager.getUserIds(); 12162 for (int i = 0; i < users.length; ++i) { 12163 if (getBlockUninstallForUser(packageName, users[i])) { 12164 uninstallBlocked = true; 12165 break; 12166 } 12167 } 12168 } else { 12169 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12170 } 12171 if (uninstallBlocked) { 12172 try { 12173 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12174 null); 12175 } catch (RemoteException re) { 12176 } 12177 return; 12178 } 12179 12180 if (DEBUG_REMOVE) { 12181 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12182 } 12183 // Queue up an async operation since the package deletion may take a little while. 12184 mHandler.post(new Runnable() { 12185 public void run() { 12186 mHandler.removeCallbacks(this); 12187 final int returnCode = deletePackageX(packageName, userId, flags); 12188 if (observer != null) { 12189 try { 12190 observer.onPackageDeleted(packageName, returnCode, null); 12191 } catch (RemoteException e) { 12192 Log.i(TAG, "Observer no longer exists."); 12193 } //end catch 12194 } //end if 12195 } //end run 12196 }); 12197 } 12198 12199 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12200 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12201 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12202 try { 12203 if (dpm != null) { 12204 if (dpm.isDeviceOwner(packageName)) { 12205 return true; 12206 } 12207 int[] users; 12208 if (userId == UserHandle.USER_ALL) { 12209 users = sUserManager.getUserIds(); 12210 } else { 12211 users = new int[]{userId}; 12212 } 12213 for (int i = 0; i < users.length; ++i) { 12214 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12215 return true; 12216 } 12217 } 12218 } 12219 } catch (RemoteException e) { 12220 } 12221 return false; 12222 } 12223 12224 /** 12225 * This method is an internal method that could be get invoked either 12226 * to delete an installed package or to clean up a failed installation. 12227 * After deleting an installed package, a broadcast is sent to notify any 12228 * listeners that the package has been installed. For cleaning up a failed 12229 * installation, the broadcast is not necessary since the package's 12230 * installation wouldn't have sent the initial broadcast either 12231 * The key steps in deleting a package are 12232 * deleting the package information in internal structures like mPackages, 12233 * deleting the packages base directories through installd 12234 * updating mSettings to reflect current status 12235 * persisting settings for later use 12236 * sending a broadcast if necessary 12237 */ 12238 private int deletePackageX(String packageName, int userId, int flags) { 12239 final PackageRemovedInfo info = new PackageRemovedInfo(); 12240 final boolean res; 12241 12242 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12243 ? UserHandle.ALL : new UserHandle(userId); 12244 12245 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12246 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12247 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12248 } 12249 12250 boolean removedForAllUsers = false; 12251 boolean systemUpdate = false; 12252 12253 // for the uninstall-updates case and restricted profiles, remember the per- 12254 // userhandle installed state 12255 int[] allUsers; 12256 boolean[] perUserInstalled; 12257 synchronized (mPackages) { 12258 PackageSetting ps = mSettings.mPackages.get(packageName); 12259 allUsers = sUserManager.getUserIds(); 12260 perUserInstalled = new boolean[allUsers.length]; 12261 for (int i = 0; i < allUsers.length; i++) { 12262 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12263 } 12264 } 12265 12266 synchronized (mInstallLock) { 12267 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12268 res = deletePackageLI(packageName, removeForUser, 12269 true, allUsers, perUserInstalled, 12270 flags | REMOVE_CHATTY, info, true); 12271 systemUpdate = info.isRemovedPackageSystemUpdate; 12272 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12273 removedForAllUsers = true; 12274 } 12275 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12276 + " removedForAllUsers=" + removedForAllUsers); 12277 } 12278 12279 if (res) { 12280 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12281 12282 // If the removed package was a system update, the old system package 12283 // was re-enabled; we need to broadcast this information 12284 if (systemUpdate) { 12285 Bundle extras = new Bundle(1); 12286 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12287 ? info.removedAppId : info.uid); 12288 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12289 12290 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12291 extras, null, null, null); 12292 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12293 extras, null, null, null); 12294 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12295 null, packageName, null, null); 12296 } 12297 } 12298 // Force a gc here. 12299 Runtime.getRuntime().gc(); 12300 // Delete the resources here after sending the broadcast to let 12301 // other processes clean up before deleting resources. 12302 if (info.args != null) { 12303 synchronized (mInstallLock) { 12304 info.args.doPostDeleteLI(true); 12305 } 12306 } 12307 12308 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12309 } 12310 12311 class PackageRemovedInfo { 12312 String removedPackage; 12313 int uid = -1; 12314 int removedAppId = -1; 12315 int[] removedUsers = null; 12316 boolean isRemovedPackageSystemUpdate = false; 12317 // Clean up resources deleted packages. 12318 InstallArgs args = null; 12319 12320 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12321 Bundle extras = new Bundle(1); 12322 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12323 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12324 if (replacing) { 12325 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12326 } 12327 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12328 if (removedPackage != null) { 12329 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12330 extras, null, null, removedUsers); 12331 if (fullRemove && !replacing) { 12332 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12333 extras, null, null, removedUsers); 12334 } 12335 } 12336 if (removedAppId >= 0) { 12337 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12338 removedUsers); 12339 } 12340 } 12341 } 12342 12343 /* 12344 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12345 * flag is not set, the data directory is removed as well. 12346 * make sure this flag is set for partially installed apps. If not its meaningless to 12347 * delete a partially installed application. 12348 */ 12349 private void removePackageDataLI(PackageSetting ps, 12350 int[] allUserHandles, boolean[] perUserInstalled, 12351 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12352 String packageName = ps.name; 12353 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12354 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12355 // Retrieve object to delete permissions for shared user later on 12356 final PackageSetting deletedPs; 12357 // reader 12358 synchronized (mPackages) { 12359 deletedPs = mSettings.mPackages.get(packageName); 12360 if (outInfo != null) { 12361 outInfo.removedPackage = packageName; 12362 outInfo.removedUsers = deletedPs != null 12363 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12364 : null; 12365 } 12366 } 12367 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12368 removeDataDirsLI(ps.volumeUuid, packageName); 12369 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12370 } 12371 // writer 12372 synchronized (mPackages) { 12373 if (deletedPs != null) { 12374 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12375 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12376 clearDefaultBrowserIfNeeded(packageName); 12377 if (outInfo != null) { 12378 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12379 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12380 } 12381 updatePermissionsLPw(deletedPs.name, null, 0); 12382 if (deletedPs.sharedUser != null) { 12383 // Remove permissions associated with package. Since runtime 12384 // permissions are per user we have to kill the removed package 12385 // or packages running under the shared user of the removed 12386 // package if revoking the permissions requested only by the removed 12387 // package is successful and this causes a change in gids. 12388 for (int userId : UserManagerService.getInstance().getUserIds()) { 12389 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12390 userId); 12391 if (userIdToKill == UserHandle.USER_ALL 12392 || userIdToKill >= UserHandle.USER_OWNER) { 12393 // If gids changed for this user, kill all affected packages. 12394 mHandler.post(new Runnable() { 12395 @Override 12396 public void run() { 12397 // This has to happen with no lock held. 12398 killSettingPackagesForUser(deletedPs, userIdToKill, 12399 KILL_APP_REASON_GIDS_CHANGED); 12400 } 12401 }); 12402 break; 12403 } 12404 } 12405 } 12406 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12407 } 12408 // make sure to preserve per-user disabled state if this removal was just 12409 // a downgrade of a system app to the factory package 12410 if (allUserHandles != null && perUserInstalled != null) { 12411 if (DEBUG_REMOVE) { 12412 Slog.d(TAG, "Propagating install state across downgrade"); 12413 } 12414 for (int i = 0; i < allUserHandles.length; i++) { 12415 if (DEBUG_REMOVE) { 12416 Slog.d(TAG, " user " + allUserHandles[i] 12417 + " => " + perUserInstalled[i]); 12418 } 12419 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12420 } 12421 } 12422 } 12423 // can downgrade to reader 12424 if (writeSettings) { 12425 // Save settings now 12426 mSettings.writeLPr(); 12427 } 12428 } 12429 if (outInfo != null) { 12430 // A user ID was deleted here. Go through all users and remove it 12431 // from KeyStore. 12432 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12433 } 12434 } 12435 12436 static boolean locationIsPrivileged(File path) { 12437 try { 12438 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12439 .getCanonicalPath(); 12440 return path.getCanonicalPath().startsWith(privilegedAppDir); 12441 } catch (IOException e) { 12442 Slog.e(TAG, "Unable to access code path " + path); 12443 } 12444 return false; 12445 } 12446 12447 /* 12448 * Tries to delete system package. 12449 */ 12450 private boolean deleteSystemPackageLI(PackageSetting newPs, 12451 int[] allUserHandles, boolean[] perUserInstalled, 12452 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12453 final boolean applyUserRestrictions 12454 = (allUserHandles != null) && (perUserInstalled != null); 12455 PackageSetting disabledPs = null; 12456 // Confirm if the system package has been updated 12457 // An updated system app can be deleted. This will also have to restore 12458 // the system pkg from system partition 12459 // reader 12460 synchronized (mPackages) { 12461 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12462 } 12463 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12464 + " disabledPs=" + disabledPs); 12465 if (disabledPs == null) { 12466 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12467 return false; 12468 } else if (DEBUG_REMOVE) { 12469 Slog.d(TAG, "Deleting system pkg from data partition"); 12470 } 12471 if (DEBUG_REMOVE) { 12472 if (applyUserRestrictions) { 12473 Slog.d(TAG, "Remembering install states:"); 12474 for (int i = 0; i < allUserHandles.length; i++) { 12475 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12476 } 12477 } 12478 } 12479 // Delete the updated package 12480 outInfo.isRemovedPackageSystemUpdate = true; 12481 if (disabledPs.versionCode < newPs.versionCode) { 12482 // Delete data for downgrades 12483 flags &= ~PackageManager.DELETE_KEEP_DATA; 12484 } else { 12485 // Preserve data by setting flag 12486 flags |= PackageManager.DELETE_KEEP_DATA; 12487 } 12488 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12489 allUserHandles, perUserInstalled, outInfo, writeSettings); 12490 if (!ret) { 12491 return false; 12492 } 12493 // writer 12494 synchronized (mPackages) { 12495 // Reinstate the old system package 12496 mSettings.enableSystemPackageLPw(newPs.name); 12497 // Remove any native libraries from the upgraded package. 12498 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12499 } 12500 // Install the system package 12501 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12502 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12503 if (locationIsPrivileged(disabledPs.codePath)) { 12504 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12505 } 12506 12507 final PackageParser.Package newPkg; 12508 try { 12509 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12510 } catch (PackageManagerException e) { 12511 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12512 return false; 12513 } 12514 12515 // writer 12516 synchronized (mPackages) { 12517 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12518 updatePermissionsLPw(newPkg.packageName, newPkg, 12519 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12520 if (applyUserRestrictions) { 12521 if (DEBUG_REMOVE) { 12522 Slog.d(TAG, "Propagating install state across reinstall"); 12523 } 12524 for (int i = 0; i < allUserHandles.length; i++) { 12525 if (DEBUG_REMOVE) { 12526 Slog.d(TAG, " user " + allUserHandles[i] 12527 + " => " + perUserInstalled[i]); 12528 } 12529 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12530 } 12531 // Regardless of writeSettings we need to ensure that this restriction 12532 // state propagation is persisted 12533 mSettings.writeAllUsersPackageRestrictionsLPr(); 12534 } 12535 // can downgrade to reader here 12536 if (writeSettings) { 12537 mSettings.writeLPr(); 12538 } 12539 } 12540 return true; 12541 } 12542 12543 private boolean deleteInstalledPackageLI(PackageSetting ps, 12544 boolean deleteCodeAndResources, int flags, 12545 int[] allUserHandles, boolean[] perUserInstalled, 12546 PackageRemovedInfo outInfo, boolean writeSettings) { 12547 if (outInfo != null) { 12548 outInfo.uid = ps.appId; 12549 } 12550 12551 // Delete package data from internal structures and also remove data if flag is set 12552 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12553 12554 // Delete application code and resources 12555 if (deleteCodeAndResources && (outInfo != null)) { 12556 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12557 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12558 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12559 } 12560 return true; 12561 } 12562 12563 @Override 12564 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12565 int userId) { 12566 mContext.enforceCallingOrSelfPermission( 12567 android.Manifest.permission.DELETE_PACKAGES, null); 12568 synchronized (mPackages) { 12569 PackageSetting ps = mSettings.mPackages.get(packageName); 12570 if (ps == null) { 12571 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12572 return false; 12573 } 12574 if (!ps.getInstalled(userId)) { 12575 // Can't block uninstall for an app that is not installed or enabled. 12576 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12577 return false; 12578 } 12579 ps.setBlockUninstall(blockUninstall, userId); 12580 mSettings.writePackageRestrictionsLPr(userId); 12581 } 12582 return true; 12583 } 12584 12585 @Override 12586 public boolean getBlockUninstallForUser(String packageName, int userId) { 12587 synchronized (mPackages) { 12588 PackageSetting ps = mSettings.mPackages.get(packageName); 12589 if (ps == null) { 12590 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12591 return false; 12592 } 12593 return ps.getBlockUninstall(userId); 12594 } 12595 } 12596 12597 /* 12598 * This method handles package deletion in general 12599 */ 12600 private boolean deletePackageLI(String packageName, UserHandle user, 12601 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12602 int flags, PackageRemovedInfo outInfo, 12603 boolean writeSettings) { 12604 if (packageName == null) { 12605 Slog.w(TAG, "Attempt to delete null packageName."); 12606 return false; 12607 } 12608 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12609 PackageSetting ps; 12610 boolean dataOnly = false; 12611 int removeUser = -1; 12612 int appId = -1; 12613 synchronized (mPackages) { 12614 ps = mSettings.mPackages.get(packageName); 12615 if (ps == null) { 12616 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12617 return false; 12618 } 12619 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12620 && user.getIdentifier() != UserHandle.USER_ALL) { 12621 // The caller is asking that the package only be deleted for a single 12622 // user. To do this, we just mark its uninstalled state and delete 12623 // its data. If this is a system app, we only allow this to happen if 12624 // they have set the special DELETE_SYSTEM_APP which requests different 12625 // semantics than normal for uninstalling system apps. 12626 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12627 ps.setUserState(user.getIdentifier(), 12628 COMPONENT_ENABLED_STATE_DEFAULT, 12629 false, //installed 12630 true, //stopped 12631 true, //notLaunched 12632 false, //hidden 12633 null, null, null, 12634 false, // blockUninstall 12635 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12636 if (!isSystemApp(ps)) { 12637 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12638 // Other user still have this package installed, so all 12639 // we need to do is clear this user's data and save that 12640 // it is uninstalled. 12641 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12642 removeUser = user.getIdentifier(); 12643 appId = ps.appId; 12644 scheduleWritePackageRestrictionsLocked(removeUser); 12645 } else { 12646 // We need to set it back to 'installed' so the uninstall 12647 // broadcasts will be sent correctly. 12648 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12649 ps.setInstalled(true, user.getIdentifier()); 12650 } 12651 } else { 12652 // This is a system app, so we assume that the 12653 // other users still have this package installed, so all 12654 // we need to do is clear this user's data and save that 12655 // it is uninstalled. 12656 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12657 removeUser = user.getIdentifier(); 12658 appId = ps.appId; 12659 scheduleWritePackageRestrictionsLocked(removeUser); 12660 } 12661 } 12662 } 12663 12664 if (removeUser >= 0) { 12665 // From above, we determined that we are deleting this only 12666 // for a single user. Continue the work here. 12667 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12668 if (outInfo != null) { 12669 outInfo.removedPackage = packageName; 12670 outInfo.removedAppId = appId; 12671 outInfo.removedUsers = new int[] {removeUser}; 12672 } 12673 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12674 removeKeystoreDataIfNeeded(removeUser, appId); 12675 schedulePackageCleaning(packageName, removeUser, false); 12676 synchronized (mPackages) { 12677 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12678 scheduleWritePackageRestrictionsLocked(removeUser); 12679 } 12680 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12681 removeUser); 12682 } 12683 return true; 12684 } 12685 12686 if (dataOnly) { 12687 // Delete application data first 12688 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12689 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12690 return true; 12691 } 12692 12693 boolean ret = false; 12694 if (isSystemApp(ps)) { 12695 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12696 // When an updated system application is deleted we delete the existing resources as well and 12697 // fall back to existing code in system partition 12698 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12699 flags, outInfo, writeSettings); 12700 } else { 12701 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12702 // Kill application pre-emptively especially for apps on sd. 12703 killApplication(packageName, ps.appId, "uninstall pkg"); 12704 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12705 allUserHandles, perUserInstalled, 12706 outInfo, writeSettings); 12707 } 12708 12709 return ret; 12710 } 12711 12712 private final class ClearStorageConnection implements ServiceConnection { 12713 IMediaContainerService mContainerService; 12714 12715 @Override 12716 public void onServiceConnected(ComponentName name, IBinder service) { 12717 synchronized (this) { 12718 mContainerService = IMediaContainerService.Stub.asInterface(service); 12719 notifyAll(); 12720 } 12721 } 12722 12723 @Override 12724 public void onServiceDisconnected(ComponentName name) { 12725 } 12726 } 12727 12728 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12729 final boolean mounted; 12730 if (Environment.isExternalStorageEmulated()) { 12731 mounted = true; 12732 } else { 12733 final String status = Environment.getExternalStorageState(); 12734 12735 mounted = status.equals(Environment.MEDIA_MOUNTED) 12736 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12737 } 12738 12739 if (!mounted) { 12740 return; 12741 } 12742 12743 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12744 int[] users; 12745 if (userId == UserHandle.USER_ALL) { 12746 users = sUserManager.getUserIds(); 12747 } else { 12748 users = new int[] { userId }; 12749 } 12750 final ClearStorageConnection conn = new ClearStorageConnection(); 12751 if (mContext.bindServiceAsUser( 12752 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12753 try { 12754 for (int curUser : users) { 12755 long timeout = SystemClock.uptimeMillis() + 5000; 12756 synchronized (conn) { 12757 long now = SystemClock.uptimeMillis(); 12758 while (conn.mContainerService == null && now < timeout) { 12759 try { 12760 conn.wait(timeout - now); 12761 } catch (InterruptedException e) { 12762 } 12763 } 12764 } 12765 if (conn.mContainerService == null) { 12766 return; 12767 } 12768 12769 final UserEnvironment userEnv = new UserEnvironment(curUser); 12770 clearDirectory(conn.mContainerService, 12771 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12772 if (allData) { 12773 clearDirectory(conn.mContainerService, 12774 userEnv.buildExternalStorageAppDataDirs(packageName)); 12775 clearDirectory(conn.mContainerService, 12776 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12777 } 12778 } 12779 } finally { 12780 mContext.unbindService(conn); 12781 } 12782 } 12783 } 12784 12785 @Override 12786 public void clearApplicationUserData(final String packageName, 12787 final IPackageDataObserver observer, final int userId) { 12788 mContext.enforceCallingOrSelfPermission( 12789 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12790 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12791 // Queue up an async operation since the package deletion may take a little while. 12792 mHandler.post(new Runnable() { 12793 public void run() { 12794 mHandler.removeCallbacks(this); 12795 final boolean succeeded; 12796 synchronized (mInstallLock) { 12797 succeeded = clearApplicationUserDataLI(packageName, userId); 12798 } 12799 clearExternalStorageDataSync(packageName, userId, true); 12800 if (succeeded) { 12801 // invoke DeviceStorageMonitor's update method to clear any notifications 12802 DeviceStorageMonitorInternal 12803 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12804 if (dsm != null) { 12805 dsm.checkMemory(); 12806 } 12807 } 12808 if(observer != null) { 12809 try { 12810 observer.onRemoveCompleted(packageName, succeeded); 12811 } catch (RemoteException e) { 12812 Log.i(TAG, "Observer no longer exists."); 12813 } 12814 } //end if observer 12815 } //end run 12816 }); 12817 } 12818 12819 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12820 if (packageName == null) { 12821 Slog.w(TAG, "Attempt to delete null packageName."); 12822 return false; 12823 } 12824 12825 // Try finding details about the requested package 12826 PackageParser.Package pkg; 12827 synchronized (mPackages) { 12828 pkg = mPackages.get(packageName); 12829 if (pkg == null) { 12830 final PackageSetting ps = mSettings.mPackages.get(packageName); 12831 if (ps != null) { 12832 pkg = ps.pkg; 12833 } 12834 } 12835 12836 if (pkg == null) { 12837 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12838 return false; 12839 } 12840 12841 PackageSetting ps = (PackageSetting) pkg.mExtras; 12842 PermissionsState permissionsState = ps.getPermissionsState(); 12843 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12844 } 12845 12846 // Always delete data directories for package, even if we found no other 12847 // record of app. This helps users recover from UID mismatches without 12848 // resorting to a full data wipe. 12849 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12850 if (retCode < 0) { 12851 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12852 return false; 12853 } 12854 12855 final int appId = pkg.applicationInfo.uid; 12856 removeKeystoreDataIfNeeded(userId, appId); 12857 12858 // Create a native library symlink only if we have native libraries 12859 // and if the native libraries are 32 bit libraries. We do not provide 12860 // this symlink for 64 bit libraries. 12861 if (pkg.applicationInfo.primaryCpuAbi != null && 12862 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12863 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12864 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12865 nativeLibPath, userId) < 0) { 12866 Slog.w(TAG, "Failed linking native library dir"); 12867 return false; 12868 } 12869 } 12870 12871 return true; 12872 } 12873 12874 12875 /** 12876 * Revokes granted runtime permissions and clears resettable flags 12877 * which are flags that can be set by a user interaction. 12878 * 12879 * @param permissionsState The permission state to reset. 12880 * @param userId The device user for which to do a reset. 12881 */ 12882 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12883 PermissionsState permissionsState, int userId) { 12884 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12885 | PackageManager.FLAG_PERMISSION_USER_FIXED 12886 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12887 12888 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 12889 } 12890 12891 /** 12892 * Revokes granted runtime permissions and clears all flags. 12893 * 12894 * @param permissionsState The permission state to reset. 12895 * @param userId The device user for which to do a reset. 12896 */ 12897 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 12898 PermissionsState permissionsState, int userId) { 12899 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 12900 PackageManager.MASK_PERMISSION_FLAGS); 12901 } 12902 12903 /** 12904 * Revokes granted runtime permissions and clears certain flags. 12905 * 12906 * @param permissionsState The permission state to reset. 12907 * @param userId The device user for which to do a reset. 12908 * @param flags The flags that is going to be reset. 12909 */ 12910 private void revokeRuntimePermissionsAndClearFlagsLocked( 12911 PermissionsState permissionsState, int userId, int flags) { 12912 boolean needsWrite = false; 12913 12914 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12915 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12916 if (bp != null) { 12917 permissionsState.revokeRuntimePermission(bp, userId); 12918 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 12919 needsWrite = true; 12920 } 12921 } 12922 12923 // Ensure default permissions are never cleared. 12924 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 12925 12926 if (needsWrite) { 12927 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12928 } 12929 } 12930 12931 /** 12932 * Remove entries from the keystore daemon. Will only remove it if the 12933 * {@code appId} is valid. 12934 */ 12935 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12936 if (appId < 0) { 12937 return; 12938 } 12939 12940 final KeyStore keyStore = KeyStore.getInstance(); 12941 if (keyStore != null) { 12942 if (userId == UserHandle.USER_ALL) { 12943 for (final int individual : sUserManager.getUserIds()) { 12944 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12945 } 12946 } else { 12947 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12948 } 12949 } else { 12950 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12951 } 12952 } 12953 12954 @Override 12955 public void deleteApplicationCacheFiles(final String packageName, 12956 final IPackageDataObserver observer) { 12957 mContext.enforceCallingOrSelfPermission( 12958 android.Manifest.permission.DELETE_CACHE_FILES, null); 12959 // Queue up an async operation since the package deletion may take a little while. 12960 final int userId = UserHandle.getCallingUserId(); 12961 mHandler.post(new Runnable() { 12962 public void run() { 12963 mHandler.removeCallbacks(this); 12964 final boolean succeded; 12965 synchronized (mInstallLock) { 12966 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12967 } 12968 clearExternalStorageDataSync(packageName, userId, false); 12969 if (observer != null) { 12970 try { 12971 observer.onRemoveCompleted(packageName, succeded); 12972 } catch (RemoteException e) { 12973 Log.i(TAG, "Observer no longer exists."); 12974 } 12975 } //end if observer 12976 } //end run 12977 }); 12978 } 12979 12980 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12981 if (packageName == null) { 12982 Slog.w(TAG, "Attempt to delete null packageName."); 12983 return false; 12984 } 12985 PackageParser.Package p; 12986 synchronized (mPackages) { 12987 p = mPackages.get(packageName); 12988 } 12989 if (p == null) { 12990 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12991 return false; 12992 } 12993 final ApplicationInfo applicationInfo = p.applicationInfo; 12994 if (applicationInfo == null) { 12995 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12996 return false; 12997 } 12998 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12999 if (retCode < 0) { 13000 Slog.w(TAG, "Couldn't remove cache files for package: " 13001 + packageName + " u" + userId); 13002 return false; 13003 } 13004 return true; 13005 } 13006 13007 @Override 13008 public void getPackageSizeInfo(final String packageName, int userHandle, 13009 final IPackageStatsObserver observer) { 13010 mContext.enforceCallingOrSelfPermission( 13011 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13012 if (packageName == null) { 13013 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13014 } 13015 13016 PackageStats stats = new PackageStats(packageName, userHandle); 13017 13018 /* 13019 * Queue up an async operation since the package measurement may take a 13020 * little while. 13021 */ 13022 Message msg = mHandler.obtainMessage(INIT_COPY); 13023 msg.obj = new MeasureParams(stats, observer); 13024 mHandler.sendMessage(msg); 13025 } 13026 13027 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13028 PackageStats pStats) { 13029 if (packageName == null) { 13030 Slog.w(TAG, "Attempt to get size of null packageName."); 13031 return false; 13032 } 13033 PackageParser.Package p; 13034 boolean dataOnly = false; 13035 String libDirRoot = null; 13036 String asecPath = null; 13037 PackageSetting ps = null; 13038 synchronized (mPackages) { 13039 p = mPackages.get(packageName); 13040 ps = mSettings.mPackages.get(packageName); 13041 if(p == null) { 13042 dataOnly = true; 13043 if((ps == null) || (ps.pkg == null)) { 13044 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13045 return false; 13046 } 13047 p = ps.pkg; 13048 } 13049 if (ps != null) { 13050 libDirRoot = ps.legacyNativeLibraryPathString; 13051 } 13052 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13053 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13054 if (secureContainerId != null) { 13055 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13056 } 13057 } 13058 } 13059 String publicSrcDir = null; 13060 if(!dataOnly) { 13061 final ApplicationInfo applicationInfo = p.applicationInfo; 13062 if (applicationInfo == null) { 13063 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13064 return false; 13065 } 13066 if (p.isForwardLocked()) { 13067 publicSrcDir = applicationInfo.getBaseResourcePath(); 13068 } 13069 } 13070 // TODO: extend to measure size of split APKs 13071 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13072 // not just the first level. 13073 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13074 // just the primary. 13075 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13076 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13077 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13078 if (res < 0) { 13079 return false; 13080 } 13081 13082 // Fix-up for forward-locked applications in ASEC containers. 13083 if (!isExternal(p)) { 13084 pStats.codeSize += pStats.externalCodeSize; 13085 pStats.externalCodeSize = 0L; 13086 } 13087 13088 return true; 13089 } 13090 13091 13092 @Override 13093 public void addPackageToPreferred(String packageName) { 13094 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13095 } 13096 13097 @Override 13098 public void removePackageFromPreferred(String packageName) { 13099 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13100 } 13101 13102 @Override 13103 public List<PackageInfo> getPreferredPackages(int flags) { 13104 return new ArrayList<PackageInfo>(); 13105 } 13106 13107 private int getUidTargetSdkVersionLockedLPr(int uid) { 13108 Object obj = mSettings.getUserIdLPr(uid); 13109 if (obj instanceof SharedUserSetting) { 13110 final SharedUserSetting sus = (SharedUserSetting) obj; 13111 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13112 final Iterator<PackageSetting> it = sus.packages.iterator(); 13113 while (it.hasNext()) { 13114 final PackageSetting ps = it.next(); 13115 if (ps.pkg != null) { 13116 int v = ps.pkg.applicationInfo.targetSdkVersion; 13117 if (v < vers) vers = v; 13118 } 13119 } 13120 return vers; 13121 } else if (obj instanceof PackageSetting) { 13122 final PackageSetting ps = (PackageSetting) obj; 13123 if (ps.pkg != null) { 13124 return ps.pkg.applicationInfo.targetSdkVersion; 13125 } 13126 } 13127 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13128 } 13129 13130 @Override 13131 public void addPreferredActivity(IntentFilter filter, int match, 13132 ComponentName[] set, ComponentName activity, int userId) { 13133 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13134 "Adding preferred"); 13135 } 13136 13137 private void addPreferredActivityInternal(IntentFilter filter, int match, 13138 ComponentName[] set, ComponentName activity, boolean always, int userId, 13139 String opname) { 13140 // writer 13141 int callingUid = Binder.getCallingUid(); 13142 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13143 if (filter.countActions() == 0) { 13144 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13145 return; 13146 } 13147 synchronized (mPackages) { 13148 if (mContext.checkCallingOrSelfPermission( 13149 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13150 != PackageManager.PERMISSION_GRANTED) { 13151 if (getUidTargetSdkVersionLockedLPr(callingUid) 13152 < Build.VERSION_CODES.FROYO) { 13153 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13154 + callingUid); 13155 return; 13156 } 13157 mContext.enforceCallingOrSelfPermission( 13158 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13159 } 13160 13161 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13162 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13163 + userId + ":"); 13164 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13165 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13166 scheduleWritePackageRestrictionsLocked(userId); 13167 } 13168 } 13169 13170 @Override 13171 public void replacePreferredActivity(IntentFilter filter, int match, 13172 ComponentName[] set, ComponentName activity, int userId) { 13173 if (filter.countActions() != 1) { 13174 throw new IllegalArgumentException( 13175 "replacePreferredActivity expects filter to have only 1 action."); 13176 } 13177 if (filter.countDataAuthorities() != 0 13178 || filter.countDataPaths() != 0 13179 || filter.countDataSchemes() > 1 13180 || filter.countDataTypes() != 0) { 13181 throw new IllegalArgumentException( 13182 "replacePreferredActivity expects filter to have no data authorities, " + 13183 "paths, or types; and at most one scheme."); 13184 } 13185 13186 final int callingUid = Binder.getCallingUid(); 13187 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13188 synchronized (mPackages) { 13189 if (mContext.checkCallingOrSelfPermission( 13190 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13191 != PackageManager.PERMISSION_GRANTED) { 13192 if (getUidTargetSdkVersionLockedLPr(callingUid) 13193 < Build.VERSION_CODES.FROYO) { 13194 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13195 + Binder.getCallingUid()); 13196 return; 13197 } 13198 mContext.enforceCallingOrSelfPermission( 13199 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13200 } 13201 13202 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13203 if (pir != null) { 13204 // Get all of the existing entries that exactly match this filter. 13205 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13206 if (existing != null && existing.size() == 1) { 13207 PreferredActivity cur = existing.get(0); 13208 if (DEBUG_PREFERRED) { 13209 Slog.i(TAG, "Checking replace of preferred:"); 13210 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13211 if (!cur.mPref.mAlways) { 13212 Slog.i(TAG, " -- CUR; not mAlways!"); 13213 } else { 13214 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13215 Slog.i(TAG, " -- CUR: mSet=" 13216 + Arrays.toString(cur.mPref.mSetComponents)); 13217 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13218 Slog.i(TAG, " -- NEW: mMatch=" 13219 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13220 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13221 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13222 } 13223 } 13224 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13225 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13226 && cur.mPref.sameSet(set)) { 13227 // Setting the preferred activity to what it happens to be already 13228 if (DEBUG_PREFERRED) { 13229 Slog.i(TAG, "Replacing with same preferred activity " 13230 + cur.mPref.mShortComponent + " for user " 13231 + userId + ":"); 13232 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13233 } 13234 return; 13235 } 13236 } 13237 13238 if (existing != null) { 13239 if (DEBUG_PREFERRED) { 13240 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13241 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13242 } 13243 for (int i = 0; i < existing.size(); i++) { 13244 PreferredActivity pa = existing.get(i); 13245 if (DEBUG_PREFERRED) { 13246 Slog.i(TAG, "Removing existing preferred activity " 13247 + pa.mPref.mComponent + ":"); 13248 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13249 } 13250 pir.removeFilter(pa); 13251 } 13252 } 13253 } 13254 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13255 "Replacing preferred"); 13256 } 13257 } 13258 13259 @Override 13260 public void clearPackagePreferredActivities(String packageName) { 13261 final int uid = Binder.getCallingUid(); 13262 // writer 13263 synchronized (mPackages) { 13264 PackageParser.Package pkg = mPackages.get(packageName); 13265 if (pkg == null || pkg.applicationInfo.uid != uid) { 13266 if (mContext.checkCallingOrSelfPermission( 13267 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13268 != PackageManager.PERMISSION_GRANTED) { 13269 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13270 < Build.VERSION_CODES.FROYO) { 13271 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13272 + Binder.getCallingUid()); 13273 return; 13274 } 13275 mContext.enforceCallingOrSelfPermission( 13276 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13277 } 13278 } 13279 13280 int user = UserHandle.getCallingUserId(); 13281 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13282 scheduleWritePackageRestrictionsLocked(user); 13283 } 13284 } 13285 } 13286 13287 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13288 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13289 ArrayList<PreferredActivity> removed = null; 13290 boolean changed = false; 13291 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13292 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13293 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13294 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13295 continue; 13296 } 13297 Iterator<PreferredActivity> it = pir.filterIterator(); 13298 while (it.hasNext()) { 13299 PreferredActivity pa = it.next(); 13300 // Mark entry for removal only if it matches the package name 13301 // and the entry is of type "always". 13302 if (packageName == null || 13303 (pa.mPref.mComponent.getPackageName().equals(packageName) 13304 && pa.mPref.mAlways)) { 13305 if (removed == null) { 13306 removed = new ArrayList<PreferredActivity>(); 13307 } 13308 removed.add(pa); 13309 } 13310 } 13311 if (removed != null) { 13312 for (int j=0; j<removed.size(); j++) { 13313 PreferredActivity pa = removed.get(j); 13314 pir.removeFilter(pa); 13315 } 13316 changed = true; 13317 } 13318 } 13319 return changed; 13320 } 13321 13322 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13323 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13324 if (userId == UserHandle.USER_ALL) { 13325 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13326 sUserManager.getUserIds())) { 13327 for (int oneUserId : sUserManager.getUserIds()) { 13328 scheduleWritePackageRestrictionsLocked(oneUserId); 13329 } 13330 } 13331 } else { 13332 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13333 scheduleWritePackageRestrictionsLocked(userId); 13334 } 13335 } 13336 } 13337 13338 13339 void clearDefaultBrowserIfNeeded(String packageName) { 13340 for (int oneUserId : sUserManager.getUserIds()) { 13341 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13342 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13343 if (packageName.equals(defaultBrowserPackageName)) { 13344 setDefaultBrowserPackageName(null, oneUserId); 13345 } 13346 } 13347 } 13348 13349 @Override 13350 public void resetPreferredActivities(int userId) { 13351 /* TODO: Actually use userId. Why is it being passed in? */ 13352 mContext.enforceCallingOrSelfPermission( 13353 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13354 // writer 13355 synchronized (mPackages) { 13356 int user = UserHandle.getCallingUserId(); 13357 clearPackagePreferredActivitiesLPw(null, user); 13358 mSettings.readDefaultPreferredAppsLPw(this, user); 13359 scheduleWritePackageRestrictionsLocked(user); 13360 } 13361 } 13362 13363 @Override 13364 public int getPreferredActivities(List<IntentFilter> outFilters, 13365 List<ComponentName> outActivities, String packageName) { 13366 13367 int num = 0; 13368 final int userId = UserHandle.getCallingUserId(); 13369 // reader 13370 synchronized (mPackages) { 13371 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13372 if (pir != null) { 13373 final Iterator<PreferredActivity> it = pir.filterIterator(); 13374 while (it.hasNext()) { 13375 final PreferredActivity pa = it.next(); 13376 if (packageName == null 13377 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13378 && pa.mPref.mAlways)) { 13379 if (outFilters != null) { 13380 outFilters.add(new IntentFilter(pa)); 13381 } 13382 if (outActivities != null) { 13383 outActivities.add(pa.mPref.mComponent); 13384 } 13385 } 13386 } 13387 } 13388 } 13389 13390 return num; 13391 } 13392 13393 @Override 13394 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13395 int userId) { 13396 int callingUid = Binder.getCallingUid(); 13397 if (callingUid != Process.SYSTEM_UID) { 13398 throw new SecurityException( 13399 "addPersistentPreferredActivity can only be run by the system"); 13400 } 13401 if (filter.countActions() == 0) { 13402 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13403 return; 13404 } 13405 synchronized (mPackages) { 13406 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13407 " :"); 13408 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13409 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13410 new PersistentPreferredActivity(filter, activity)); 13411 scheduleWritePackageRestrictionsLocked(userId); 13412 } 13413 } 13414 13415 @Override 13416 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13417 int callingUid = Binder.getCallingUid(); 13418 if (callingUid != Process.SYSTEM_UID) { 13419 throw new SecurityException( 13420 "clearPackagePersistentPreferredActivities can only be run by the system"); 13421 } 13422 ArrayList<PersistentPreferredActivity> removed = null; 13423 boolean changed = false; 13424 synchronized (mPackages) { 13425 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13426 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13427 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13428 .valueAt(i); 13429 if (userId != thisUserId) { 13430 continue; 13431 } 13432 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13433 while (it.hasNext()) { 13434 PersistentPreferredActivity ppa = it.next(); 13435 // Mark entry for removal only if it matches the package name. 13436 if (ppa.mComponent.getPackageName().equals(packageName)) { 13437 if (removed == null) { 13438 removed = new ArrayList<PersistentPreferredActivity>(); 13439 } 13440 removed.add(ppa); 13441 } 13442 } 13443 if (removed != null) { 13444 for (int j=0; j<removed.size(); j++) { 13445 PersistentPreferredActivity ppa = removed.get(j); 13446 ppir.removeFilter(ppa); 13447 } 13448 changed = true; 13449 } 13450 } 13451 13452 if (changed) { 13453 scheduleWritePackageRestrictionsLocked(userId); 13454 } 13455 } 13456 } 13457 13458 /** 13459 * Common machinery for picking apart a restored XML blob and passing 13460 * it to a caller-supplied functor to be applied to the running system. 13461 */ 13462 private void restoreFromXml(XmlPullParser parser, int userId, 13463 String expectedStartTag, BlobXmlRestorer functor) 13464 throws IOException, XmlPullParserException { 13465 int type; 13466 while ((type = parser.next()) != XmlPullParser.START_TAG 13467 && type != XmlPullParser.END_DOCUMENT) { 13468 } 13469 if (type != XmlPullParser.START_TAG) { 13470 // oops didn't find a start tag?! 13471 if (DEBUG_BACKUP) { 13472 Slog.e(TAG, "Didn't find start tag during restore"); 13473 } 13474 return; 13475 } 13476 13477 // this is supposed to be TAG_PREFERRED_BACKUP 13478 if (!expectedStartTag.equals(parser.getName())) { 13479 if (DEBUG_BACKUP) { 13480 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13481 } 13482 return; 13483 } 13484 13485 // skip interfering stuff, then we're aligned with the backing implementation 13486 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13487 functor.apply(parser, userId); 13488 } 13489 13490 private interface BlobXmlRestorer { 13491 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13492 } 13493 13494 /** 13495 * Non-Binder method, support for the backup/restore mechanism: write the 13496 * full set of preferred activities in its canonical XML format. Returns the 13497 * XML output as a byte array, or null if there is none. 13498 */ 13499 @Override 13500 public byte[] getPreferredActivityBackup(int userId) { 13501 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13502 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13503 } 13504 13505 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13506 try { 13507 final XmlSerializer serializer = new FastXmlSerializer(); 13508 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13509 serializer.startDocument(null, true); 13510 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13511 13512 synchronized (mPackages) { 13513 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13514 } 13515 13516 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13517 serializer.endDocument(); 13518 serializer.flush(); 13519 } catch (Exception e) { 13520 if (DEBUG_BACKUP) { 13521 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13522 } 13523 return null; 13524 } 13525 13526 return dataStream.toByteArray(); 13527 } 13528 13529 @Override 13530 public void restorePreferredActivities(byte[] backup, int userId) { 13531 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13532 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13533 } 13534 13535 try { 13536 final XmlPullParser parser = Xml.newPullParser(); 13537 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13538 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13539 new BlobXmlRestorer() { 13540 @Override 13541 public void apply(XmlPullParser parser, int userId) 13542 throws XmlPullParserException, IOException { 13543 synchronized (mPackages) { 13544 mSettings.readPreferredActivitiesLPw(parser, userId); 13545 } 13546 } 13547 } ); 13548 } catch (Exception e) { 13549 if (DEBUG_BACKUP) { 13550 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13551 } 13552 } 13553 } 13554 13555 /** 13556 * Non-Binder method, support for the backup/restore mechanism: write the 13557 * default browser (etc) settings in its canonical XML format. Returns the default 13558 * browser XML representation as a byte array, or null if there is none. 13559 */ 13560 @Override 13561 public byte[] getDefaultAppsBackup(int userId) { 13562 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13563 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13564 } 13565 13566 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13567 try { 13568 final XmlSerializer serializer = new FastXmlSerializer(); 13569 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13570 serializer.startDocument(null, true); 13571 serializer.startTag(null, TAG_DEFAULT_APPS); 13572 13573 synchronized (mPackages) { 13574 mSettings.writeDefaultAppsLPr(serializer, userId); 13575 } 13576 13577 serializer.endTag(null, TAG_DEFAULT_APPS); 13578 serializer.endDocument(); 13579 serializer.flush(); 13580 } catch (Exception e) { 13581 if (DEBUG_BACKUP) { 13582 Slog.e(TAG, "Unable to write default apps for backup", e); 13583 } 13584 return null; 13585 } 13586 13587 return dataStream.toByteArray(); 13588 } 13589 13590 @Override 13591 public void restoreDefaultApps(byte[] backup, int userId) { 13592 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13593 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13594 } 13595 13596 try { 13597 final XmlPullParser parser = Xml.newPullParser(); 13598 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13599 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13600 new BlobXmlRestorer() { 13601 @Override 13602 public void apply(XmlPullParser parser, int userId) 13603 throws XmlPullParserException, IOException { 13604 synchronized (mPackages) { 13605 mSettings.readDefaultAppsLPw(parser, userId); 13606 } 13607 } 13608 } ); 13609 } catch (Exception e) { 13610 if (DEBUG_BACKUP) { 13611 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13612 } 13613 } 13614 } 13615 13616 @Override 13617 public byte[] getIntentFilterVerificationBackup(int userId) { 13618 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13619 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13620 } 13621 13622 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13623 try { 13624 final XmlSerializer serializer = new FastXmlSerializer(); 13625 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13626 serializer.startDocument(null, true); 13627 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13628 13629 synchronized (mPackages) { 13630 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13631 } 13632 13633 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13634 serializer.endDocument(); 13635 serializer.flush(); 13636 } catch (Exception e) { 13637 if (DEBUG_BACKUP) { 13638 Slog.e(TAG, "Unable to write default apps for backup", e); 13639 } 13640 return null; 13641 } 13642 13643 return dataStream.toByteArray(); 13644 } 13645 13646 @Override 13647 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13648 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13649 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13650 } 13651 13652 try { 13653 final XmlPullParser parser = Xml.newPullParser(); 13654 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13655 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13656 new BlobXmlRestorer() { 13657 @Override 13658 public void apply(XmlPullParser parser, int userId) 13659 throws XmlPullParserException, IOException { 13660 synchronized (mPackages) { 13661 mSettings.readAllDomainVerificationsLPr(parser, userId); 13662 mSettings.writeLPr(); 13663 } 13664 } 13665 } ); 13666 } catch (Exception e) { 13667 if (DEBUG_BACKUP) { 13668 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13669 } 13670 } 13671 } 13672 13673 @Override 13674 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13675 int sourceUserId, int targetUserId, int flags) { 13676 mContext.enforceCallingOrSelfPermission( 13677 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13678 int callingUid = Binder.getCallingUid(); 13679 enforceOwnerRights(ownerPackage, callingUid); 13680 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13681 if (intentFilter.countActions() == 0) { 13682 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13683 return; 13684 } 13685 synchronized (mPackages) { 13686 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13687 ownerPackage, targetUserId, flags); 13688 CrossProfileIntentResolver resolver = 13689 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13690 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13691 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13692 if (existing != null) { 13693 int size = existing.size(); 13694 for (int i = 0; i < size; i++) { 13695 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13696 return; 13697 } 13698 } 13699 } 13700 resolver.addFilter(newFilter); 13701 scheduleWritePackageRestrictionsLocked(sourceUserId); 13702 } 13703 } 13704 13705 @Override 13706 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13707 mContext.enforceCallingOrSelfPermission( 13708 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13709 int callingUid = Binder.getCallingUid(); 13710 enforceOwnerRights(ownerPackage, callingUid); 13711 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13712 synchronized (mPackages) { 13713 CrossProfileIntentResolver resolver = 13714 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13715 ArraySet<CrossProfileIntentFilter> set = 13716 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13717 for (CrossProfileIntentFilter filter : set) { 13718 if (filter.getOwnerPackage().equals(ownerPackage)) { 13719 resolver.removeFilter(filter); 13720 } 13721 } 13722 scheduleWritePackageRestrictionsLocked(sourceUserId); 13723 } 13724 } 13725 13726 // Enforcing that callingUid is owning pkg on userId 13727 private void enforceOwnerRights(String pkg, int callingUid) { 13728 // The system owns everything. 13729 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13730 return; 13731 } 13732 int callingUserId = UserHandle.getUserId(callingUid); 13733 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13734 if (pi == null) { 13735 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13736 + callingUserId); 13737 } 13738 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13739 throw new SecurityException("Calling uid " + callingUid 13740 + " does not own package " + pkg); 13741 } 13742 } 13743 13744 @Override 13745 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13746 Intent intent = new Intent(Intent.ACTION_MAIN); 13747 intent.addCategory(Intent.CATEGORY_HOME); 13748 13749 final int callingUserId = UserHandle.getCallingUserId(); 13750 List<ResolveInfo> list = queryIntentActivities(intent, null, 13751 PackageManager.GET_META_DATA, callingUserId); 13752 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13753 true, false, false, callingUserId); 13754 13755 allHomeCandidates.clear(); 13756 if (list != null) { 13757 for (ResolveInfo ri : list) { 13758 allHomeCandidates.add(ri); 13759 } 13760 } 13761 return (preferred == null || preferred.activityInfo == null) 13762 ? null 13763 : new ComponentName(preferred.activityInfo.packageName, 13764 preferred.activityInfo.name); 13765 } 13766 13767 @Override 13768 public void setApplicationEnabledSetting(String appPackageName, 13769 int newState, int flags, int userId, String callingPackage) { 13770 if (!sUserManager.exists(userId)) return; 13771 if (callingPackage == null) { 13772 callingPackage = Integer.toString(Binder.getCallingUid()); 13773 } 13774 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13775 } 13776 13777 @Override 13778 public void setComponentEnabledSetting(ComponentName componentName, 13779 int newState, int flags, int userId) { 13780 if (!sUserManager.exists(userId)) return; 13781 setEnabledSetting(componentName.getPackageName(), 13782 componentName.getClassName(), newState, flags, userId, null); 13783 } 13784 13785 private void setEnabledSetting(final String packageName, String className, int newState, 13786 final int flags, int userId, String callingPackage) { 13787 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13788 || newState == COMPONENT_ENABLED_STATE_ENABLED 13789 || newState == COMPONENT_ENABLED_STATE_DISABLED 13790 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13791 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13792 throw new IllegalArgumentException("Invalid new component state: " 13793 + newState); 13794 } 13795 PackageSetting pkgSetting; 13796 final int uid = Binder.getCallingUid(); 13797 final int permission = mContext.checkCallingOrSelfPermission( 13798 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13799 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13800 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13801 boolean sendNow = false; 13802 boolean isApp = (className == null); 13803 String componentName = isApp ? packageName : className; 13804 int packageUid = -1; 13805 ArrayList<String> components; 13806 13807 // writer 13808 synchronized (mPackages) { 13809 pkgSetting = mSettings.mPackages.get(packageName); 13810 if (pkgSetting == null) { 13811 if (className == null) { 13812 throw new IllegalArgumentException( 13813 "Unknown package: " + packageName); 13814 } 13815 throw new IllegalArgumentException( 13816 "Unknown component: " + packageName 13817 + "/" + className); 13818 } 13819 // Allow root and verify that userId is not being specified by a different user 13820 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13821 throw new SecurityException( 13822 "Permission Denial: attempt to change component state from pid=" 13823 + Binder.getCallingPid() 13824 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13825 } 13826 if (className == null) { 13827 // We're dealing with an application/package level state change 13828 if (pkgSetting.getEnabled(userId) == newState) { 13829 // Nothing to do 13830 return; 13831 } 13832 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13833 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13834 // Don't care about who enables an app. 13835 callingPackage = null; 13836 } 13837 pkgSetting.setEnabled(newState, userId, callingPackage); 13838 // pkgSetting.pkg.mSetEnabled = newState; 13839 } else { 13840 // We're dealing with a component level state change 13841 // First, verify that this is a valid class name. 13842 PackageParser.Package pkg = pkgSetting.pkg; 13843 if (pkg == null || !pkg.hasComponentClassName(className)) { 13844 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13845 throw new IllegalArgumentException("Component class " + className 13846 + " does not exist in " + packageName); 13847 } else { 13848 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13849 + className + " does not exist in " + packageName); 13850 } 13851 } 13852 switch (newState) { 13853 case COMPONENT_ENABLED_STATE_ENABLED: 13854 if (!pkgSetting.enableComponentLPw(className, userId)) { 13855 return; 13856 } 13857 break; 13858 case COMPONENT_ENABLED_STATE_DISABLED: 13859 if (!pkgSetting.disableComponentLPw(className, userId)) { 13860 return; 13861 } 13862 break; 13863 case COMPONENT_ENABLED_STATE_DEFAULT: 13864 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13865 return; 13866 } 13867 break; 13868 default: 13869 Slog.e(TAG, "Invalid new component state: " + newState); 13870 return; 13871 } 13872 } 13873 scheduleWritePackageRestrictionsLocked(userId); 13874 components = mPendingBroadcasts.get(userId, packageName); 13875 final boolean newPackage = components == null; 13876 if (newPackage) { 13877 components = new ArrayList<String>(); 13878 } 13879 if (!components.contains(componentName)) { 13880 components.add(componentName); 13881 } 13882 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13883 sendNow = true; 13884 // Purge entry from pending broadcast list if another one exists already 13885 // since we are sending one right away. 13886 mPendingBroadcasts.remove(userId, packageName); 13887 } else { 13888 if (newPackage) { 13889 mPendingBroadcasts.put(userId, packageName, components); 13890 } 13891 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13892 // Schedule a message 13893 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13894 } 13895 } 13896 } 13897 13898 long callingId = Binder.clearCallingIdentity(); 13899 try { 13900 if (sendNow) { 13901 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13902 sendPackageChangedBroadcast(packageName, 13903 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13904 } 13905 } finally { 13906 Binder.restoreCallingIdentity(callingId); 13907 } 13908 } 13909 13910 private void sendPackageChangedBroadcast(String packageName, 13911 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13912 if (DEBUG_INSTALL) 13913 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13914 + componentNames); 13915 Bundle extras = new Bundle(4); 13916 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13917 String nameList[] = new String[componentNames.size()]; 13918 componentNames.toArray(nameList); 13919 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13920 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13921 extras.putInt(Intent.EXTRA_UID, packageUid); 13922 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13923 new int[] {UserHandle.getUserId(packageUid)}); 13924 } 13925 13926 @Override 13927 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13928 if (!sUserManager.exists(userId)) return; 13929 final int uid = Binder.getCallingUid(); 13930 final int permission = mContext.checkCallingOrSelfPermission( 13931 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13932 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13933 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13934 // writer 13935 synchronized (mPackages) { 13936 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13937 allowedByPermission, uid, userId)) { 13938 scheduleWritePackageRestrictionsLocked(userId); 13939 } 13940 } 13941 } 13942 13943 @Override 13944 public String getInstallerPackageName(String packageName) { 13945 // reader 13946 synchronized (mPackages) { 13947 return mSettings.getInstallerPackageNameLPr(packageName); 13948 } 13949 } 13950 13951 @Override 13952 public int getApplicationEnabledSetting(String packageName, int userId) { 13953 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13954 int uid = Binder.getCallingUid(); 13955 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13956 // reader 13957 synchronized (mPackages) { 13958 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13959 } 13960 } 13961 13962 @Override 13963 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13964 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13965 int uid = Binder.getCallingUid(); 13966 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13967 // reader 13968 synchronized (mPackages) { 13969 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13970 } 13971 } 13972 13973 @Override 13974 public void enterSafeMode() { 13975 enforceSystemOrRoot("Only the system can request entering safe mode"); 13976 13977 if (!mSystemReady) { 13978 mSafeMode = true; 13979 } 13980 } 13981 13982 @Override 13983 public void systemReady() { 13984 mSystemReady = true; 13985 13986 // Read the compatibilty setting when the system is ready. 13987 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13988 mContext.getContentResolver(), 13989 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13990 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13991 if (DEBUG_SETTINGS) { 13992 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13993 } 13994 13995 synchronized (mPackages) { 13996 // Verify that all of the preferred activity components actually 13997 // exist. It is possible for applications to be updated and at 13998 // that point remove a previously declared activity component that 13999 // had been set as a preferred activity. We try to clean this up 14000 // the next time we encounter that preferred activity, but it is 14001 // possible for the user flow to never be able to return to that 14002 // situation so here we do a sanity check to make sure we haven't 14003 // left any junk around. 14004 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14005 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14006 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14007 removed.clear(); 14008 for (PreferredActivity pa : pir.filterSet()) { 14009 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14010 removed.add(pa); 14011 } 14012 } 14013 if (removed.size() > 0) { 14014 for (int r=0; r<removed.size(); r++) { 14015 PreferredActivity pa = removed.get(r); 14016 Slog.w(TAG, "Removing dangling preferred activity: " 14017 + pa.mPref.mComponent); 14018 pir.removeFilter(pa); 14019 } 14020 mSettings.writePackageRestrictionsLPr( 14021 mSettings.mPreferredActivities.keyAt(i)); 14022 } 14023 } 14024 } 14025 sUserManager.systemReady(); 14026 14027 // If we upgraded grant all default permissions before kicking off. 14028 if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) { 14029 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14030 for (int userId : UserManagerService.getInstance().getUserIds()) { 14031 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14032 } 14033 } 14034 14035 // Kick off any messages waiting for system ready 14036 if (mPostSystemReadyMessages != null) { 14037 for (Message msg : mPostSystemReadyMessages) { 14038 msg.sendToTarget(); 14039 } 14040 mPostSystemReadyMessages = null; 14041 } 14042 14043 // Watch for external volumes that come and go over time 14044 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14045 storage.registerListener(mStorageListener); 14046 14047 mInstallerService.systemReady(); 14048 mPackageDexOptimizer.systemReady(); 14049 } 14050 14051 @Override 14052 public boolean isSafeMode() { 14053 return mSafeMode; 14054 } 14055 14056 @Override 14057 public boolean hasSystemUidErrors() { 14058 return mHasSystemUidErrors; 14059 } 14060 14061 static String arrayToString(int[] array) { 14062 StringBuffer buf = new StringBuffer(128); 14063 buf.append('['); 14064 if (array != null) { 14065 for (int i=0; i<array.length; i++) { 14066 if (i > 0) buf.append(", "); 14067 buf.append(array[i]); 14068 } 14069 } 14070 buf.append(']'); 14071 return buf.toString(); 14072 } 14073 14074 static class DumpState { 14075 public static final int DUMP_LIBS = 1 << 0; 14076 public static final int DUMP_FEATURES = 1 << 1; 14077 public static final int DUMP_RESOLVERS = 1 << 2; 14078 public static final int DUMP_PERMISSIONS = 1 << 3; 14079 public static final int DUMP_PACKAGES = 1 << 4; 14080 public static final int DUMP_SHARED_USERS = 1 << 5; 14081 public static final int DUMP_MESSAGES = 1 << 6; 14082 public static final int DUMP_PROVIDERS = 1 << 7; 14083 public static final int DUMP_VERIFIERS = 1 << 8; 14084 public static final int DUMP_PREFERRED = 1 << 9; 14085 public static final int DUMP_PREFERRED_XML = 1 << 10; 14086 public static final int DUMP_KEYSETS = 1 << 11; 14087 public static final int DUMP_VERSION = 1 << 12; 14088 public static final int DUMP_INSTALLS = 1 << 13; 14089 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14090 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14091 14092 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14093 14094 private int mTypes; 14095 14096 private int mOptions; 14097 14098 private boolean mTitlePrinted; 14099 14100 private SharedUserSetting mSharedUser; 14101 14102 public boolean isDumping(int type) { 14103 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14104 return true; 14105 } 14106 14107 return (mTypes & type) != 0; 14108 } 14109 14110 public void setDump(int type) { 14111 mTypes |= type; 14112 } 14113 14114 public boolean isOptionEnabled(int option) { 14115 return (mOptions & option) != 0; 14116 } 14117 14118 public void setOptionEnabled(int option) { 14119 mOptions |= option; 14120 } 14121 14122 public boolean onTitlePrinted() { 14123 final boolean printed = mTitlePrinted; 14124 mTitlePrinted = true; 14125 return printed; 14126 } 14127 14128 public boolean getTitlePrinted() { 14129 return mTitlePrinted; 14130 } 14131 14132 public void setTitlePrinted(boolean enabled) { 14133 mTitlePrinted = enabled; 14134 } 14135 14136 public SharedUserSetting getSharedUser() { 14137 return mSharedUser; 14138 } 14139 14140 public void setSharedUser(SharedUserSetting user) { 14141 mSharedUser = user; 14142 } 14143 } 14144 14145 @Override 14146 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14147 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14148 != PackageManager.PERMISSION_GRANTED) { 14149 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14150 + Binder.getCallingPid() 14151 + ", uid=" + Binder.getCallingUid() 14152 + " without permission " 14153 + android.Manifest.permission.DUMP); 14154 return; 14155 } 14156 14157 DumpState dumpState = new DumpState(); 14158 boolean fullPreferred = false; 14159 boolean checkin = false; 14160 14161 String packageName = null; 14162 14163 int opti = 0; 14164 while (opti < args.length) { 14165 String opt = args[opti]; 14166 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14167 break; 14168 } 14169 opti++; 14170 14171 if ("-a".equals(opt)) { 14172 // Right now we only know how to print all. 14173 } else if ("-h".equals(opt)) { 14174 pw.println("Package manager dump options:"); 14175 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14176 pw.println(" --checkin: dump for a checkin"); 14177 pw.println(" -f: print details of intent filters"); 14178 pw.println(" -h: print this help"); 14179 pw.println(" cmd may be one of:"); 14180 pw.println(" l[ibraries]: list known shared libraries"); 14181 pw.println(" f[ibraries]: list device features"); 14182 pw.println(" k[eysets]: print known keysets"); 14183 pw.println(" r[esolvers]: dump intent resolvers"); 14184 pw.println(" perm[issions]: dump permissions"); 14185 pw.println(" pref[erred]: print preferred package settings"); 14186 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14187 pw.println(" prov[iders]: dump content providers"); 14188 pw.println(" p[ackages]: dump installed packages"); 14189 pw.println(" s[hared-users]: dump shared user IDs"); 14190 pw.println(" m[essages]: print collected runtime messages"); 14191 pw.println(" v[erifiers]: print package verifier info"); 14192 pw.println(" version: print database version info"); 14193 pw.println(" write: write current settings now"); 14194 pw.println(" <package.name>: info about given package"); 14195 pw.println(" installs: details about install sessions"); 14196 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14197 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14198 return; 14199 } else if ("--checkin".equals(opt)) { 14200 checkin = true; 14201 } else if ("-f".equals(opt)) { 14202 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14203 } else { 14204 pw.println("Unknown argument: " + opt + "; use -h for help"); 14205 } 14206 } 14207 14208 // Is the caller requesting to dump a particular piece of data? 14209 if (opti < args.length) { 14210 String cmd = args[opti]; 14211 opti++; 14212 // Is this a package name? 14213 if ("android".equals(cmd) || cmd.contains(".")) { 14214 packageName = cmd; 14215 // When dumping a single package, we always dump all of its 14216 // filter information since the amount of data will be reasonable. 14217 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14218 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14219 dumpState.setDump(DumpState.DUMP_LIBS); 14220 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14221 dumpState.setDump(DumpState.DUMP_FEATURES); 14222 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14223 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14224 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14225 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14226 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14227 dumpState.setDump(DumpState.DUMP_PREFERRED); 14228 } else if ("preferred-xml".equals(cmd)) { 14229 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14230 if (opti < args.length && "--full".equals(args[opti])) { 14231 fullPreferred = true; 14232 opti++; 14233 } 14234 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14235 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14236 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14237 dumpState.setDump(DumpState.DUMP_PACKAGES); 14238 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14239 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14240 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14241 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14242 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14243 dumpState.setDump(DumpState.DUMP_MESSAGES); 14244 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14245 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14246 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14247 || "intent-filter-verifiers".equals(cmd)) { 14248 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14249 } else if ("version".equals(cmd)) { 14250 dumpState.setDump(DumpState.DUMP_VERSION); 14251 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14252 dumpState.setDump(DumpState.DUMP_KEYSETS); 14253 } else if ("installs".equals(cmd)) { 14254 dumpState.setDump(DumpState.DUMP_INSTALLS); 14255 } else if ("write".equals(cmd)) { 14256 synchronized (mPackages) { 14257 mSettings.writeLPr(); 14258 pw.println("Settings written."); 14259 return; 14260 } 14261 } 14262 } 14263 14264 if (checkin) { 14265 pw.println("vers,1"); 14266 } 14267 14268 // reader 14269 synchronized (mPackages) { 14270 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14271 if (!checkin) { 14272 if (dumpState.onTitlePrinted()) 14273 pw.println(); 14274 pw.println("Database versions:"); 14275 pw.print(" SDK Version:"); 14276 pw.print(" internal="); 14277 pw.print(mSettings.mInternalSdkPlatform); 14278 pw.print(" external="); 14279 pw.println(mSettings.mExternalSdkPlatform); 14280 pw.print(" DB Version:"); 14281 pw.print(" internal="); 14282 pw.print(mSettings.mInternalDatabaseVersion); 14283 pw.print(" external="); 14284 pw.println(mSettings.mExternalDatabaseVersion); 14285 } 14286 } 14287 14288 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14289 if (!checkin) { 14290 if (dumpState.onTitlePrinted()) 14291 pw.println(); 14292 pw.println("Verifiers:"); 14293 pw.print(" Required: "); 14294 pw.print(mRequiredVerifierPackage); 14295 pw.print(" (uid="); 14296 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14297 pw.println(")"); 14298 } else if (mRequiredVerifierPackage != null) { 14299 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14300 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14301 } 14302 } 14303 14304 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14305 packageName == null) { 14306 if (mIntentFilterVerifierComponent != null) { 14307 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14308 if (!checkin) { 14309 if (dumpState.onTitlePrinted()) 14310 pw.println(); 14311 pw.println("Intent Filter Verifier:"); 14312 pw.print(" Using: "); 14313 pw.print(verifierPackageName); 14314 pw.print(" (uid="); 14315 pw.print(getPackageUid(verifierPackageName, 0)); 14316 pw.println(")"); 14317 } else if (verifierPackageName != null) { 14318 pw.print("ifv,"); pw.print(verifierPackageName); 14319 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14320 } 14321 } else { 14322 pw.println(); 14323 pw.println("No Intent Filter Verifier available!"); 14324 } 14325 } 14326 14327 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14328 boolean printedHeader = false; 14329 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14330 while (it.hasNext()) { 14331 String name = it.next(); 14332 SharedLibraryEntry ent = mSharedLibraries.get(name); 14333 if (!checkin) { 14334 if (!printedHeader) { 14335 if (dumpState.onTitlePrinted()) 14336 pw.println(); 14337 pw.println("Libraries:"); 14338 printedHeader = true; 14339 } 14340 pw.print(" "); 14341 } else { 14342 pw.print("lib,"); 14343 } 14344 pw.print(name); 14345 if (!checkin) { 14346 pw.print(" -> "); 14347 } 14348 if (ent.path != null) { 14349 if (!checkin) { 14350 pw.print("(jar) "); 14351 pw.print(ent.path); 14352 } else { 14353 pw.print(",jar,"); 14354 pw.print(ent.path); 14355 } 14356 } else { 14357 if (!checkin) { 14358 pw.print("(apk) "); 14359 pw.print(ent.apk); 14360 } else { 14361 pw.print(",apk,"); 14362 pw.print(ent.apk); 14363 } 14364 } 14365 pw.println(); 14366 } 14367 } 14368 14369 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14370 if (dumpState.onTitlePrinted()) 14371 pw.println(); 14372 if (!checkin) { 14373 pw.println("Features:"); 14374 } 14375 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14376 while (it.hasNext()) { 14377 String name = it.next(); 14378 if (!checkin) { 14379 pw.print(" "); 14380 } else { 14381 pw.print("feat,"); 14382 } 14383 pw.println(name); 14384 } 14385 } 14386 14387 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14388 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14389 : "Activity Resolver Table:", " ", packageName, 14390 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14391 dumpState.setTitlePrinted(true); 14392 } 14393 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14394 : "Receiver Resolver Table:", " ", packageName, 14395 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14396 dumpState.setTitlePrinted(true); 14397 } 14398 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14399 : "Service Resolver Table:", " ", packageName, 14400 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14401 dumpState.setTitlePrinted(true); 14402 } 14403 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14404 : "Provider Resolver Table:", " ", packageName, 14405 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14406 dumpState.setTitlePrinted(true); 14407 } 14408 } 14409 14410 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14411 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14412 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14413 int user = mSettings.mPreferredActivities.keyAt(i); 14414 if (pir.dump(pw, 14415 dumpState.getTitlePrinted() 14416 ? "\nPreferred Activities User " + user + ":" 14417 : "Preferred Activities User " + user + ":", " ", 14418 packageName, true, false)) { 14419 dumpState.setTitlePrinted(true); 14420 } 14421 } 14422 } 14423 14424 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14425 pw.flush(); 14426 FileOutputStream fout = new FileOutputStream(fd); 14427 BufferedOutputStream str = new BufferedOutputStream(fout); 14428 XmlSerializer serializer = new FastXmlSerializer(); 14429 try { 14430 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14431 serializer.startDocument(null, true); 14432 serializer.setFeature( 14433 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14434 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14435 serializer.endDocument(); 14436 serializer.flush(); 14437 } catch (IllegalArgumentException e) { 14438 pw.println("Failed writing: " + e); 14439 } catch (IllegalStateException e) { 14440 pw.println("Failed writing: " + e); 14441 } catch (IOException e) { 14442 pw.println("Failed writing: " + e); 14443 } 14444 } 14445 14446 if (!checkin 14447 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14448 && packageName == null) { 14449 pw.println(); 14450 int count = mSettings.mPackages.size(); 14451 if (count == 0) { 14452 pw.println("No domain preferred apps!"); 14453 pw.println(); 14454 } else { 14455 final String prefix = " "; 14456 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14457 if (allPackageSettings.size() == 0) { 14458 pw.println("No domain preferred apps!"); 14459 pw.println(); 14460 } else { 14461 pw.println("Domain preferred apps status:"); 14462 pw.println(); 14463 count = 0; 14464 for (PackageSetting ps : allPackageSettings) { 14465 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14466 if (ivi == null || ivi.getPackageName() == null) continue; 14467 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14468 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14469 pw.println(prefix + "Status: " + ivi.getStatusString()); 14470 pw.println(); 14471 count++; 14472 } 14473 if (count == 0) { 14474 pw.println(prefix + "No domain preferred app status!"); 14475 pw.println(); 14476 } 14477 for (int userId : sUserManager.getUserIds()) { 14478 pw.println("Domain preferred apps for User " + userId + ":"); 14479 pw.println(); 14480 count = 0; 14481 for (PackageSetting ps : allPackageSettings) { 14482 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14483 if (ivi == null || ivi.getPackageName() == null) { 14484 continue; 14485 } 14486 final int status = ps.getDomainVerificationStatusForUser(userId); 14487 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14488 continue; 14489 } 14490 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14491 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14492 String statusStr = IntentFilterVerificationInfo. 14493 getStatusStringFromValue(status); 14494 pw.println(prefix + "Status: " + statusStr); 14495 pw.println(); 14496 count++; 14497 } 14498 if (count == 0) { 14499 pw.println(prefix + "No domain preferred apps!"); 14500 pw.println(); 14501 } 14502 } 14503 } 14504 } 14505 } 14506 14507 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14508 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14509 if (packageName == null) { 14510 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14511 if (iperm == 0) { 14512 if (dumpState.onTitlePrinted()) 14513 pw.println(); 14514 pw.println("AppOp Permissions:"); 14515 } 14516 pw.print(" AppOp Permission "); 14517 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14518 pw.println(":"); 14519 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14520 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14521 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14522 } 14523 } 14524 } 14525 } 14526 14527 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14528 boolean printedSomething = false; 14529 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14530 if (packageName != null && !packageName.equals(p.info.packageName)) { 14531 continue; 14532 } 14533 if (!printedSomething) { 14534 if (dumpState.onTitlePrinted()) 14535 pw.println(); 14536 pw.println("Registered ContentProviders:"); 14537 printedSomething = true; 14538 } 14539 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14540 pw.print(" "); pw.println(p.toString()); 14541 } 14542 printedSomething = false; 14543 for (Map.Entry<String, PackageParser.Provider> entry : 14544 mProvidersByAuthority.entrySet()) { 14545 PackageParser.Provider p = entry.getValue(); 14546 if (packageName != null && !packageName.equals(p.info.packageName)) { 14547 continue; 14548 } 14549 if (!printedSomething) { 14550 if (dumpState.onTitlePrinted()) 14551 pw.println(); 14552 pw.println("ContentProvider Authorities:"); 14553 printedSomething = true; 14554 } 14555 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14556 pw.print(" "); pw.println(p.toString()); 14557 if (p.info != null && p.info.applicationInfo != null) { 14558 final String appInfo = p.info.applicationInfo.toString(); 14559 pw.print(" applicationInfo="); pw.println(appInfo); 14560 } 14561 } 14562 } 14563 14564 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14565 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14566 } 14567 14568 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14569 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14570 } 14571 14572 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14573 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14574 } 14575 14576 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14577 // XXX should handle packageName != null by dumping only install data that 14578 // the given package is involved with. 14579 if (dumpState.onTitlePrinted()) pw.println(); 14580 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14581 } 14582 14583 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14584 if (dumpState.onTitlePrinted()) pw.println(); 14585 mSettings.dumpReadMessagesLPr(pw, dumpState); 14586 14587 pw.println(); 14588 pw.println("Package warning messages:"); 14589 BufferedReader in = null; 14590 String line = null; 14591 try { 14592 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14593 while ((line = in.readLine()) != null) { 14594 if (line.contains("ignored: updated version")) continue; 14595 pw.println(line); 14596 } 14597 } catch (IOException ignored) { 14598 } finally { 14599 IoUtils.closeQuietly(in); 14600 } 14601 } 14602 14603 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14604 BufferedReader in = null; 14605 String line = null; 14606 try { 14607 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14608 while ((line = in.readLine()) != null) { 14609 if (line.contains("ignored: updated version")) continue; 14610 pw.print("msg,"); 14611 pw.println(line); 14612 } 14613 } catch (IOException ignored) { 14614 } finally { 14615 IoUtils.closeQuietly(in); 14616 } 14617 } 14618 } 14619 } 14620 14621 // ------- apps on sdcard specific code ------- 14622 static final boolean DEBUG_SD_INSTALL = false; 14623 14624 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14625 14626 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14627 14628 private boolean mMediaMounted = false; 14629 14630 static String getEncryptKey() { 14631 try { 14632 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14633 SD_ENCRYPTION_KEYSTORE_NAME); 14634 if (sdEncKey == null) { 14635 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14636 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14637 if (sdEncKey == null) { 14638 Slog.e(TAG, "Failed to create encryption keys"); 14639 return null; 14640 } 14641 } 14642 return sdEncKey; 14643 } catch (NoSuchAlgorithmException nsae) { 14644 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14645 return null; 14646 } catch (IOException ioe) { 14647 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14648 return null; 14649 } 14650 } 14651 14652 /* 14653 * Update media status on PackageManager. 14654 */ 14655 @Override 14656 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14657 int callingUid = Binder.getCallingUid(); 14658 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14659 throw new SecurityException("Media status can only be updated by the system"); 14660 } 14661 // reader; this apparently protects mMediaMounted, but should probably 14662 // be a different lock in that case. 14663 synchronized (mPackages) { 14664 Log.i(TAG, "Updating external media status from " 14665 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14666 + (mediaStatus ? "mounted" : "unmounted")); 14667 if (DEBUG_SD_INSTALL) 14668 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14669 + ", mMediaMounted=" + mMediaMounted); 14670 if (mediaStatus == mMediaMounted) { 14671 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14672 : 0, -1); 14673 mHandler.sendMessage(msg); 14674 return; 14675 } 14676 mMediaMounted = mediaStatus; 14677 } 14678 // Queue up an async operation since the package installation may take a 14679 // little while. 14680 mHandler.post(new Runnable() { 14681 public void run() { 14682 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14683 } 14684 }); 14685 } 14686 14687 /** 14688 * Called by MountService when the initial ASECs to scan are available. 14689 * Should block until all the ASEC containers are finished being scanned. 14690 */ 14691 public void scanAvailableAsecs() { 14692 updateExternalMediaStatusInner(true, false, false); 14693 if (mShouldRestoreconData) { 14694 SELinuxMMAC.setRestoreconDone(); 14695 mShouldRestoreconData = false; 14696 } 14697 } 14698 14699 /* 14700 * Collect information of applications on external media, map them against 14701 * existing containers and update information based on current mount status. 14702 * Please note that we always have to report status if reportStatus has been 14703 * set to true especially when unloading packages. 14704 */ 14705 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14706 boolean externalStorage) { 14707 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14708 int[] uidArr = EmptyArray.INT; 14709 14710 final String[] list = PackageHelper.getSecureContainerList(); 14711 if (ArrayUtils.isEmpty(list)) { 14712 Log.i(TAG, "No secure containers found"); 14713 } else { 14714 // Process list of secure containers and categorize them 14715 // as active or stale based on their package internal state. 14716 14717 // reader 14718 synchronized (mPackages) { 14719 for (String cid : list) { 14720 // Leave stages untouched for now; installer service owns them 14721 if (PackageInstallerService.isStageName(cid)) continue; 14722 14723 if (DEBUG_SD_INSTALL) 14724 Log.i(TAG, "Processing container " + cid); 14725 String pkgName = getAsecPackageName(cid); 14726 if (pkgName == null) { 14727 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14728 continue; 14729 } 14730 if (DEBUG_SD_INSTALL) 14731 Log.i(TAG, "Looking for pkg : " + pkgName); 14732 14733 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14734 if (ps == null) { 14735 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14736 continue; 14737 } 14738 14739 /* 14740 * Skip packages that are not external if we're unmounting 14741 * external storage. 14742 */ 14743 if (externalStorage && !isMounted && !isExternal(ps)) { 14744 continue; 14745 } 14746 14747 final AsecInstallArgs args = new AsecInstallArgs(cid, 14748 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14749 // The package status is changed only if the code path 14750 // matches between settings and the container id. 14751 if (ps.codePathString != null 14752 && ps.codePathString.startsWith(args.getCodePath())) { 14753 if (DEBUG_SD_INSTALL) { 14754 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14755 + " at code path: " + ps.codePathString); 14756 } 14757 14758 // We do have a valid package installed on sdcard 14759 processCids.put(args, ps.codePathString); 14760 final int uid = ps.appId; 14761 if (uid != -1) { 14762 uidArr = ArrayUtils.appendInt(uidArr, uid); 14763 } 14764 } else { 14765 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14766 + ps.codePathString); 14767 } 14768 } 14769 } 14770 14771 Arrays.sort(uidArr); 14772 } 14773 14774 // Process packages with valid entries. 14775 if (isMounted) { 14776 if (DEBUG_SD_INSTALL) 14777 Log.i(TAG, "Loading packages"); 14778 loadMediaPackages(processCids, uidArr); 14779 startCleaningPackages(); 14780 mInstallerService.onSecureContainersAvailable(); 14781 } else { 14782 if (DEBUG_SD_INSTALL) 14783 Log.i(TAG, "Unloading packages"); 14784 unloadMediaPackages(processCids, uidArr, reportStatus); 14785 } 14786 } 14787 14788 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14789 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14790 final int size = infos.size(); 14791 final String[] packageNames = new String[size]; 14792 final int[] packageUids = new int[size]; 14793 for (int i = 0; i < size; i++) { 14794 final ApplicationInfo info = infos.get(i); 14795 packageNames[i] = info.packageName; 14796 packageUids[i] = info.uid; 14797 } 14798 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14799 finishedReceiver); 14800 } 14801 14802 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14803 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14804 sendResourcesChangedBroadcast(mediaStatus, replacing, 14805 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14806 } 14807 14808 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14809 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14810 int size = pkgList.length; 14811 if (size > 0) { 14812 // Send broadcasts here 14813 Bundle extras = new Bundle(); 14814 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14815 if (uidArr != null) { 14816 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14817 } 14818 if (replacing) { 14819 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14820 } 14821 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14822 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14823 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14824 } 14825 } 14826 14827 /* 14828 * Look at potentially valid container ids from processCids If package 14829 * information doesn't match the one on record or package scanning fails, 14830 * the cid is added to list of removeCids. We currently don't delete stale 14831 * containers. 14832 */ 14833 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14834 ArrayList<String> pkgList = new ArrayList<String>(); 14835 Set<AsecInstallArgs> keys = processCids.keySet(); 14836 14837 for (AsecInstallArgs args : keys) { 14838 String codePath = processCids.get(args); 14839 if (DEBUG_SD_INSTALL) 14840 Log.i(TAG, "Loading container : " + args.cid); 14841 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14842 try { 14843 // Make sure there are no container errors first. 14844 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14845 Slog.e(TAG, "Failed to mount cid : " + args.cid 14846 + " when installing from sdcard"); 14847 continue; 14848 } 14849 // Check code path here. 14850 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14851 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14852 + " does not match one in settings " + codePath); 14853 continue; 14854 } 14855 // Parse package 14856 int parseFlags = mDefParseFlags; 14857 if (args.isExternalAsec()) { 14858 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14859 } 14860 if (args.isFwdLocked()) { 14861 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14862 } 14863 14864 synchronized (mInstallLock) { 14865 PackageParser.Package pkg = null; 14866 try { 14867 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14868 } catch (PackageManagerException e) { 14869 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14870 } 14871 // Scan the package 14872 if (pkg != null) { 14873 /* 14874 * TODO why is the lock being held? doPostInstall is 14875 * called in other places without the lock. This needs 14876 * to be straightened out. 14877 */ 14878 // writer 14879 synchronized (mPackages) { 14880 retCode = PackageManager.INSTALL_SUCCEEDED; 14881 pkgList.add(pkg.packageName); 14882 // Post process args 14883 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14884 pkg.applicationInfo.uid); 14885 } 14886 } else { 14887 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14888 } 14889 } 14890 14891 } finally { 14892 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14893 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14894 } 14895 } 14896 } 14897 // writer 14898 synchronized (mPackages) { 14899 // If the platform SDK has changed since the last time we booted, 14900 // we need to re-grant app permission to catch any new ones that 14901 // appear. This is really a hack, and means that apps can in some 14902 // cases get permissions that the user didn't initially explicitly 14903 // allow... it would be nice to have some better way to handle 14904 // this situation. 14905 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14906 if (regrantPermissions) 14907 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14908 + mSdkVersion + "; regranting permissions for external storage"); 14909 mSettings.mExternalSdkPlatform = mSdkVersion; 14910 14911 // Make sure group IDs have been assigned, and any permission 14912 // changes in other apps are accounted for 14913 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14914 | (regrantPermissions 14915 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14916 : 0)); 14917 14918 mSettings.updateExternalDatabaseVersion(); 14919 14920 // can downgrade to reader 14921 // Persist settings 14922 mSettings.writeLPr(); 14923 } 14924 // Send a broadcast to let everyone know we are done processing 14925 if (pkgList.size() > 0) { 14926 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14927 } 14928 } 14929 14930 /* 14931 * Utility method to unload a list of specified containers 14932 */ 14933 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14934 // Just unmount all valid containers. 14935 for (AsecInstallArgs arg : cidArgs) { 14936 synchronized (mInstallLock) { 14937 arg.doPostDeleteLI(false); 14938 } 14939 } 14940 } 14941 14942 /* 14943 * Unload packages mounted on external media. This involves deleting package 14944 * data from internal structures, sending broadcasts about diabled packages, 14945 * gc'ing to free up references, unmounting all secure containers 14946 * corresponding to packages on external media, and posting a 14947 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14948 * that we always have to post this message if status has been requested no 14949 * matter what. 14950 */ 14951 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14952 final boolean reportStatus) { 14953 if (DEBUG_SD_INSTALL) 14954 Log.i(TAG, "unloading media packages"); 14955 ArrayList<String> pkgList = new ArrayList<String>(); 14956 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14957 final Set<AsecInstallArgs> keys = processCids.keySet(); 14958 for (AsecInstallArgs args : keys) { 14959 String pkgName = args.getPackageName(); 14960 if (DEBUG_SD_INSTALL) 14961 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14962 // Delete package internally 14963 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14964 synchronized (mInstallLock) { 14965 boolean res = deletePackageLI(pkgName, null, false, null, null, 14966 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14967 if (res) { 14968 pkgList.add(pkgName); 14969 } else { 14970 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14971 failedList.add(args); 14972 } 14973 } 14974 } 14975 14976 // reader 14977 synchronized (mPackages) { 14978 // We didn't update the settings after removing each package; 14979 // write them now for all packages. 14980 mSettings.writeLPr(); 14981 } 14982 14983 // We have to absolutely send UPDATED_MEDIA_STATUS only 14984 // after confirming that all the receivers processed the ordered 14985 // broadcast when packages get disabled, force a gc to clean things up. 14986 // and unload all the containers. 14987 if (pkgList.size() > 0) { 14988 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14989 new IIntentReceiver.Stub() { 14990 public void performReceive(Intent intent, int resultCode, String data, 14991 Bundle extras, boolean ordered, boolean sticky, 14992 int sendingUser) throws RemoteException { 14993 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14994 reportStatus ? 1 : 0, 1, keys); 14995 mHandler.sendMessage(msg); 14996 } 14997 }); 14998 } else { 14999 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15000 keys); 15001 mHandler.sendMessage(msg); 15002 } 15003 } 15004 15005 private void loadPrivatePackages(VolumeInfo vol) { 15006 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15007 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15008 synchronized (mInstallLock) { 15009 synchronized (mPackages) { 15010 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15011 for (PackageSetting ps : packages) { 15012 final PackageParser.Package pkg; 15013 try { 15014 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15015 loaded.add(pkg.applicationInfo); 15016 } catch (PackageManagerException e) { 15017 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15018 } 15019 } 15020 15021 // TODO: regrant any permissions that changed based since original install 15022 15023 mSettings.writeLPr(); 15024 } 15025 } 15026 15027 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15028 sendResourcesChangedBroadcast(true, false, loaded, null); 15029 } 15030 15031 private void unloadPrivatePackages(VolumeInfo vol) { 15032 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15033 synchronized (mInstallLock) { 15034 synchronized (mPackages) { 15035 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15036 for (PackageSetting ps : packages) { 15037 if (ps.pkg == null) continue; 15038 15039 final ApplicationInfo info = ps.pkg.applicationInfo; 15040 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15041 if (deletePackageLI(ps.name, null, false, null, null, 15042 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15043 unloaded.add(info); 15044 } else { 15045 Slog.w(TAG, "Failed to unload " + ps.codePath); 15046 } 15047 } 15048 15049 mSettings.writeLPr(); 15050 } 15051 } 15052 15053 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15054 sendResourcesChangedBroadcast(false, false, unloaded, null); 15055 } 15056 15057 private void unfreezePackage(String packageName) { 15058 synchronized (mPackages) { 15059 final PackageSetting ps = mSettings.mPackages.get(packageName); 15060 if (ps != null) { 15061 ps.frozen = false; 15062 } 15063 } 15064 } 15065 15066 @Override 15067 public int movePackage(final String packageName, final String volumeUuid) { 15068 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15069 15070 final int moveId = mNextMoveId.getAndIncrement(); 15071 try { 15072 movePackageInternal(packageName, volumeUuid, moveId); 15073 } catch (PackageManagerException e) { 15074 Slog.w(TAG, "Failed to move " + packageName, e); 15075 mMoveCallbacks.notifyStatusChanged(moveId, 15076 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15077 } 15078 return moveId; 15079 } 15080 15081 private void movePackageInternal(final String packageName, final String volumeUuid, 15082 final int moveId) throws PackageManagerException { 15083 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15084 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15085 final PackageManager pm = mContext.getPackageManager(); 15086 15087 final boolean currentAsec; 15088 final String currentVolumeUuid; 15089 final File codeFile; 15090 final String installerPackageName; 15091 final String packageAbiOverride; 15092 final int appId; 15093 final String seinfo; 15094 final String label; 15095 15096 // reader 15097 synchronized (mPackages) { 15098 final PackageParser.Package pkg = mPackages.get(packageName); 15099 final PackageSetting ps = mSettings.mPackages.get(packageName); 15100 if (pkg == null || ps == null) { 15101 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15102 } 15103 15104 if (pkg.applicationInfo.isSystemApp()) { 15105 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15106 "Cannot move system application"); 15107 } 15108 15109 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15110 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15111 "Package already moved to " + volumeUuid); 15112 } 15113 15114 final File probe = new File(pkg.codePath); 15115 final File probeOat = new File(probe, "oat"); 15116 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15117 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15118 "Move only supported for modern cluster style installs"); 15119 } 15120 15121 if (ps.frozen) { 15122 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15123 "Failed to move already frozen package"); 15124 } 15125 ps.frozen = true; 15126 15127 currentAsec = pkg.applicationInfo.isForwardLocked() 15128 || pkg.applicationInfo.isExternalAsec(); 15129 currentVolumeUuid = ps.volumeUuid; 15130 codeFile = new File(pkg.codePath); 15131 installerPackageName = ps.installerPackageName; 15132 packageAbiOverride = ps.cpuAbiOverrideString; 15133 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15134 seinfo = pkg.applicationInfo.seinfo; 15135 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15136 } 15137 15138 // Now that we're guarded by frozen state, kill app during move 15139 killApplication(packageName, appId, "move pkg"); 15140 15141 final Bundle extras = new Bundle(); 15142 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15143 extras.putString(Intent.EXTRA_TITLE, label); 15144 mMoveCallbacks.notifyCreated(moveId, extras); 15145 15146 int installFlags; 15147 final boolean moveCompleteApp; 15148 final File measurePath; 15149 15150 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15151 installFlags = INSTALL_INTERNAL; 15152 moveCompleteApp = !currentAsec; 15153 measurePath = Environment.getDataAppDirectory(volumeUuid); 15154 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15155 installFlags = INSTALL_EXTERNAL; 15156 moveCompleteApp = false; 15157 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15158 } else { 15159 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15160 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15161 || !volume.isMountedWritable()) { 15162 unfreezePackage(packageName); 15163 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15164 "Move location not mounted private volume"); 15165 } 15166 15167 Preconditions.checkState(!currentAsec); 15168 15169 installFlags = INSTALL_INTERNAL; 15170 moveCompleteApp = true; 15171 measurePath = Environment.getDataAppDirectory(volumeUuid); 15172 } 15173 15174 final PackageStats stats = new PackageStats(null, -1); 15175 synchronized (mInstaller) { 15176 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15177 unfreezePackage(packageName); 15178 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15179 "Failed to measure package size"); 15180 } 15181 } 15182 15183 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15184 + stats.dataSize); 15185 15186 final long startFreeBytes = measurePath.getFreeSpace(); 15187 final long sizeBytes; 15188 if (moveCompleteApp) { 15189 sizeBytes = stats.codeSize + stats.dataSize; 15190 } else { 15191 sizeBytes = stats.codeSize; 15192 } 15193 15194 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15195 unfreezePackage(packageName); 15196 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15197 "Not enough free space to move"); 15198 } 15199 15200 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15201 15202 final CountDownLatch installedLatch = new CountDownLatch(1); 15203 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15204 @Override 15205 public void onUserActionRequired(Intent intent) throws RemoteException { 15206 throw new IllegalStateException(); 15207 } 15208 15209 @Override 15210 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15211 Bundle extras) throws RemoteException { 15212 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15213 + PackageManager.installStatusToString(returnCode, msg)); 15214 15215 installedLatch.countDown(); 15216 15217 // Regardless of success or failure of the move operation, 15218 // always unfreeze the package 15219 unfreezePackage(packageName); 15220 15221 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15222 switch (status) { 15223 case PackageInstaller.STATUS_SUCCESS: 15224 mMoveCallbacks.notifyStatusChanged(moveId, 15225 PackageManager.MOVE_SUCCEEDED); 15226 break; 15227 case PackageInstaller.STATUS_FAILURE_STORAGE: 15228 mMoveCallbacks.notifyStatusChanged(moveId, 15229 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15230 break; 15231 default: 15232 mMoveCallbacks.notifyStatusChanged(moveId, 15233 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15234 break; 15235 } 15236 } 15237 }; 15238 15239 final MoveInfo move; 15240 if (moveCompleteApp) { 15241 // Kick off a thread to report progress estimates 15242 new Thread() { 15243 @Override 15244 public void run() { 15245 while (true) { 15246 try { 15247 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15248 break; 15249 } 15250 } catch (InterruptedException ignored) { 15251 } 15252 15253 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15254 final int progress = 10 + (int) MathUtils.constrain( 15255 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15256 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15257 } 15258 } 15259 }.start(); 15260 15261 final String dataAppName = codeFile.getName(); 15262 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15263 dataAppName, appId, seinfo); 15264 } else { 15265 move = null; 15266 } 15267 15268 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15269 15270 final Message msg = mHandler.obtainMessage(INIT_COPY); 15271 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15272 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15273 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15274 mHandler.sendMessage(msg); 15275 } 15276 15277 @Override 15278 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15279 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15280 15281 final int realMoveId = mNextMoveId.getAndIncrement(); 15282 final Bundle extras = new Bundle(); 15283 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15284 mMoveCallbacks.notifyCreated(realMoveId, extras); 15285 15286 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15287 @Override 15288 public void onCreated(int moveId, Bundle extras) { 15289 // Ignored 15290 } 15291 15292 @Override 15293 public void onStatusChanged(int moveId, int status, long estMillis) { 15294 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15295 } 15296 }; 15297 15298 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15299 storage.setPrimaryStorageUuid(volumeUuid, callback); 15300 return realMoveId; 15301 } 15302 15303 @Override 15304 public int getMoveStatus(int moveId) { 15305 mContext.enforceCallingOrSelfPermission( 15306 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15307 return mMoveCallbacks.mLastStatus.get(moveId); 15308 } 15309 15310 @Override 15311 public void registerMoveCallback(IPackageMoveObserver callback) { 15312 mContext.enforceCallingOrSelfPermission( 15313 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15314 mMoveCallbacks.register(callback); 15315 } 15316 15317 @Override 15318 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15319 mContext.enforceCallingOrSelfPermission( 15320 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15321 mMoveCallbacks.unregister(callback); 15322 } 15323 15324 @Override 15325 public boolean setInstallLocation(int loc) { 15326 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15327 null); 15328 if (getInstallLocation() == loc) { 15329 return true; 15330 } 15331 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15332 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15333 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15334 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15335 return true; 15336 } 15337 return false; 15338 } 15339 15340 @Override 15341 public int getInstallLocation() { 15342 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15343 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15344 PackageHelper.APP_INSTALL_AUTO); 15345 } 15346 15347 /** Called by UserManagerService */ 15348 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15349 mDirtyUsers.remove(userHandle); 15350 mSettings.removeUserLPw(userHandle); 15351 mPendingBroadcasts.remove(userHandle); 15352 if (mInstaller != null) { 15353 // Technically, we shouldn't be doing this with the package lock 15354 // held. However, this is very rare, and there is already so much 15355 // other disk I/O going on, that we'll let it slide for now. 15356 final StorageManager storage = StorageManager.from(mContext); 15357 final List<VolumeInfo> vols = storage.getVolumes(); 15358 for (VolumeInfo vol : vols) { 15359 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15360 final String volumeUuid = vol.getFsUuid(); 15361 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15362 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15363 } 15364 } 15365 } 15366 mUserNeedsBadging.delete(userHandle); 15367 removeUnusedPackagesLILPw(userManager, userHandle); 15368 } 15369 15370 /** 15371 * We're removing userHandle and would like to remove any downloaded packages 15372 * that are no longer in use by any other user. 15373 * @param userHandle the user being removed 15374 */ 15375 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15376 final boolean DEBUG_CLEAN_APKS = false; 15377 int [] users = userManager.getUserIdsLPr(); 15378 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15379 while (psit.hasNext()) { 15380 PackageSetting ps = psit.next(); 15381 if (ps.pkg == null) { 15382 continue; 15383 } 15384 final String packageName = ps.pkg.packageName; 15385 // Skip over if system app 15386 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15387 continue; 15388 } 15389 if (DEBUG_CLEAN_APKS) { 15390 Slog.i(TAG, "Checking package " + packageName); 15391 } 15392 boolean keep = false; 15393 for (int i = 0; i < users.length; i++) { 15394 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15395 keep = true; 15396 if (DEBUG_CLEAN_APKS) { 15397 Slog.i(TAG, " Keeping package " + packageName + " for user " 15398 + users[i]); 15399 } 15400 break; 15401 } 15402 } 15403 if (!keep) { 15404 if (DEBUG_CLEAN_APKS) { 15405 Slog.i(TAG, " Removing package " + packageName); 15406 } 15407 mHandler.post(new Runnable() { 15408 public void run() { 15409 deletePackageX(packageName, userHandle, 0); 15410 } //end run 15411 }); 15412 } 15413 } 15414 } 15415 15416 /** Called by UserManagerService */ 15417 void createNewUserLILPw(int userHandle, File path) { 15418 if (mInstaller != null) { 15419 mInstaller.createUserConfig(userHandle); 15420 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15421 } 15422 } 15423 15424 void newUserCreatedLILPw(final int userHandle) { 15425 // We cannot grant the default permissions with a lock held as 15426 // we query providers from other components for default handlers 15427 // such as enabled IMEs, etc. 15428 mHandler.post(new Runnable() { 15429 @Override 15430 public void run() { 15431 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15432 } 15433 }); 15434 } 15435 15436 @Override 15437 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15438 mContext.enforceCallingOrSelfPermission( 15439 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15440 "Only package verification agents can read the verifier device identity"); 15441 15442 synchronized (mPackages) { 15443 return mSettings.getVerifierDeviceIdentityLPw(); 15444 } 15445 } 15446 15447 @Override 15448 public void setPermissionEnforced(String permission, boolean enforced) { 15449 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15450 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15451 synchronized (mPackages) { 15452 if (mSettings.mReadExternalStorageEnforced == null 15453 || mSettings.mReadExternalStorageEnforced != enforced) { 15454 mSettings.mReadExternalStorageEnforced = enforced; 15455 mSettings.writeLPr(); 15456 } 15457 } 15458 // kill any non-foreground processes so we restart them and 15459 // grant/revoke the GID. 15460 final IActivityManager am = ActivityManagerNative.getDefault(); 15461 if (am != null) { 15462 final long token = Binder.clearCallingIdentity(); 15463 try { 15464 am.killProcessesBelowForeground("setPermissionEnforcement"); 15465 } catch (RemoteException e) { 15466 } finally { 15467 Binder.restoreCallingIdentity(token); 15468 } 15469 } 15470 } else { 15471 throw new IllegalArgumentException("No selective enforcement for " + permission); 15472 } 15473 } 15474 15475 @Override 15476 @Deprecated 15477 public boolean isPermissionEnforced(String permission) { 15478 return true; 15479 } 15480 15481 @Override 15482 public boolean isStorageLow() { 15483 final long token = Binder.clearCallingIdentity(); 15484 try { 15485 final DeviceStorageMonitorInternal 15486 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15487 if (dsm != null) { 15488 return dsm.isMemoryLow(); 15489 } else { 15490 return false; 15491 } 15492 } finally { 15493 Binder.restoreCallingIdentity(token); 15494 } 15495 } 15496 15497 @Override 15498 public IPackageInstaller getPackageInstaller() { 15499 return mInstallerService; 15500 } 15501 15502 private boolean userNeedsBadging(int userId) { 15503 int index = mUserNeedsBadging.indexOfKey(userId); 15504 if (index < 0) { 15505 final UserInfo userInfo; 15506 final long token = Binder.clearCallingIdentity(); 15507 try { 15508 userInfo = sUserManager.getUserInfo(userId); 15509 } finally { 15510 Binder.restoreCallingIdentity(token); 15511 } 15512 final boolean b; 15513 if (userInfo != null && userInfo.isManagedProfile()) { 15514 b = true; 15515 } else { 15516 b = false; 15517 } 15518 mUserNeedsBadging.put(userId, b); 15519 return b; 15520 } 15521 return mUserNeedsBadging.valueAt(index); 15522 } 15523 15524 @Override 15525 public KeySet getKeySetByAlias(String packageName, String alias) { 15526 if (packageName == null || alias == null) { 15527 return null; 15528 } 15529 synchronized(mPackages) { 15530 final PackageParser.Package pkg = mPackages.get(packageName); 15531 if (pkg == null) { 15532 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15533 throw new IllegalArgumentException("Unknown package: " + packageName); 15534 } 15535 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15536 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15537 } 15538 } 15539 15540 @Override 15541 public KeySet getSigningKeySet(String packageName) { 15542 if (packageName == null) { 15543 return null; 15544 } 15545 synchronized(mPackages) { 15546 final PackageParser.Package pkg = mPackages.get(packageName); 15547 if (pkg == null) { 15548 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15549 throw new IllegalArgumentException("Unknown package: " + packageName); 15550 } 15551 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15552 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15553 throw new SecurityException("May not access signing KeySet of other apps."); 15554 } 15555 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15556 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15557 } 15558 } 15559 15560 @Override 15561 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15562 if (packageName == null || ks == null) { 15563 return false; 15564 } 15565 synchronized(mPackages) { 15566 final PackageParser.Package pkg = mPackages.get(packageName); 15567 if (pkg == null) { 15568 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15569 throw new IllegalArgumentException("Unknown package: " + packageName); 15570 } 15571 IBinder ksh = ks.getToken(); 15572 if (ksh instanceof KeySetHandle) { 15573 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15574 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15575 } 15576 return false; 15577 } 15578 } 15579 15580 @Override 15581 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15582 if (packageName == null || ks == null) { 15583 return false; 15584 } 15585 synchronized(mPackages) { 15586 final PackageParser.Package pkg = mPackages.get(packageName); 15587 if (pkg == null) { 15588 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15589 throw new IllegalArgumentException("Unknown package: " + packageName); 15590 } 15591 IBinder ksh = ks.getToken(); 15592 if (ksh instanceof KeySetHandle) { 15593 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15594 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15595 } 15596 return false; 15597 } 15598 } 15599 15600 public void getUsageStatsIfNoPackageUsageInfo() { 15601 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15602 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15603 if (usm == null) { 15604 throw new IllegalStateException("UsageStatsManager must be initialized"); 15605 } 15606 long now = System.currentTimeMillis(); 15607 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15608 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15609 String packageName = entry.getKey(); 15610 PackageParser.Package pkg = mPackages.get(packageName); 15611 if (pkg == null) { 15612 continue; 15613 } 15614 UsageStats usage = entry.getValue(); 15615 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15616 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15617 } 15618 } 15619 } 15620 15621 /** 15622 * Check and throw if the given before/after packages would be considered a 15623 * downgrade. 15624 */ 15625 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15626 throws PackageManagerException { 15627 if (after.versionCode < before.mVersionCode) { 15628 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15629 "Update version code " + after.versionCode + " is older than current " 15630 + before.mVersionCode); 15631 } else if (after.versionCode == before.mVersionCode) { 15632 if (after.baseRevisionCode < before.baseRevisionCode) { 15633 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15634 "Update base revision code " + after.baseRevisionCode 15635 + " is older than current " + before.baseRevisionCode); 15636 } 15637 15638 if (!ArrayUtils.isEmpty(after.splitNames)) { 15639 for (int i = 0; i < after.splitNames.length; i++) { 15640 final String splitName = after.splitNames[i]; 15641 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15642 if (j != -1) { 15643 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15644 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15645 "Update split " + splitName + " revision code " 15646 + after.splitRevisionCodes[i] + " is older than current " 15647 + before.splitRevisionCodes[j]); 15648 } 15649 } 15650 } 15651 } 15652 } 15653 } 15654 15655 private static class MoveCallbacks extends Handler { 15656 private static final int MSG_CREATED = 1; 15657 private static final int MSG_STATUS_CHANGED = 2; 15658 15659 private final RemoteCallbackList<IPackageMoveObserver> 15660 mCallbacks = new RemoteCallbackList<>(); 15661 15662 private final SparseIntArray mLastStatus = new SparseIntArray(); 15663 15664 public MoveCallbacks(Looper looper) { 15665 super(looper); 15666 } 15667 15668 public void register(IPackageMoveObserver callback) { 15669 mCallbacks.register(callback); 15670 } 15671 15672 public void unregister(IPackageMoveObserver callback) { 15673 mCallbacks.unregister(callback); 15674 } 15675 15676 @Override 15677 public void handleMessage(Message msg) { 15678 final SomeArgs args = (SomeArgs) msg.obj; 15679 final int n = mCallbacks.beginBroadcast(); 15680 for (int i = 0; i < n; i++) { 15681 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15682 try { 15683 invokeCallback(callback, msg.what, args); 15684 } catch (RemoteException ignored) { 15685 } 15686 } 15687 mCallbacks.finishBroadcast(); 15688 args.recycle(); 15689 } 15690 15691 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15692 throws RemoteException { 15693 switch (what) { 15694 case MSG_CREATED: { 15695 callback.onCreated(args.argi1, (Bundle) args.arg2); 15696 break; 15697 } 15698 case MSG_STATUS_CHANGED: { 15699 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15700 break; 15701 } 15702 } 15703 } 15704 15705 private void notifyCreated(int moveId, Bundle extras) { 15706 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15707 15708 final SomeArgs args = SomeArgs.obtain(); 15709 args.argi1 = moveId; 15710 args.arg2 = extras; 15711 obtainMessage(MSG_CREATED, args).sendToTarget(); 15712 } 15713 15714 private void notifyStatusChanged(int moveId, int status) { 15715 notifyStatusChanged(moveId, status, -1); 15716 } 15717 15718 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15719 Slog.v(TAG, "Move " + moveId + " status " + status); 15720 15721 final SomeArgs args = SomeArgs.obtain(); 15722 args.argi1 = moveId; 15723 args.argi2 = status; 15724 args.arg3 = estMillis; 15725 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15726 15727 synchronized (mLastStatus) { 15728 mLastStatus.put(moveId, status); 15729 } 15730 } 15731 } 15732 15733 private final class OnPermissionChangeListeners extends Handler { 15734 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15735 15736 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15737 new RemoteCallbackList<>(); 15738 15739 public OnPermissionChangeListeners(Looper looper) { 15740 super(looper); 15741 } 15742 15743 @Override 15744 public void handleMessage(Message msg) { 15745 switch (msg.what) { 15746 case MSG_ON_PERMISSIONS_CHANGED: { 15747 final int uid = msg.arg1; 15748 handleOnPermissionsChanged(uid); 15749 } break; 15750 } 15751 } 15752 15753 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15754 mPermissionListeners.register(listener); 15755 15756 } 15757 15758 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15759 mPermissionListeners.unregister(listener); 15760 } 15761 15762 public void onPermissionsChanged(int uid) { 15763 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15764 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15765 } 15766 } 15767 15768 private void handleOnPermissionsChanged(int uid) { 15769 final int count = mPermissionListeners.beginBroadcast(); 15770 try { 15771 for (int i = 0; i < count; i++) { 15772 IOnPermissionsChangeListener callback = mPermissionListeners 15773 .getBroadcastItem(i); 15774 try { 15775 callback.onPermissionsChanged(uid); 15776 } catch (RemoteException e) { 15777 Log.e(TAG, "Permission listener is dead", e); 15778 } 15779 } 15780 } finally { 15781 mPermissionListeners.finishBroadcast(); 15782 } 15783 } 15784 } 15785 15786 private class PackageManagerInternalImpl extends PackageManagerInternal { 15787 @Override 15788 public void setLocationPackagesProvider(PackagesProvider provider) { 15789 synchronized (mPackages) { 15790 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15791 } 15792 } 15793 15794 @Override 15795 public void setImePackagesProvider(PackagesProvider provider) { 15796 synchronized (mPackages) { 15797 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15798 } 15799 } 15800 15801 @Override 15802 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15803 synchronized (mPackages) { 15804 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15805 } 15806 } 15807 } 15808 15809 @Override 15810 public void grantDefaultPermissions(final int userId) { 15811 enforceSystemOrPhoneCaller("grantDefaultPermissions"); 15812 long token = Binder.clearCallingIdentity(); 15813 try { 15814 // We cannot grant the default permissions with a lock held as 15815 // we query providers from other components for default handlers 15816 // such as enabled IMEs, etc. 15817 mHandler.post(new Runnable() { 15818 @Override 15819 public void run() { 15820 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15821 } 15822 }); 15823 } finally { 15824 Binder.restoreCallingIdentity(token); 15825 } 15826 } 15827 15828 @Override 15829 public void setCarrierAppPackagesProvider(final IPackagesProvider provider) { 15830 enforceSystemOrPhoneCaller("setCarrierAppPackagesProvider"); 15831 long token = Binder.clearCallingIdentity(); 15832 try { 15833 PackageManagerInternal.PackagesProvider wrapper = 15834 new PackageManagerInternal.PackagesProvider() { 15835 @Override 15836 public String[] getPackages(int userId) { 15837 try { 15838 return provider.getPackages(userId); 15839 } catch (RemoteException e) { 15840 return null; 15841 } 15842 } 15843 }; 15844 synchronized (mPackages) { 15845 mDefaultPermissionPolicy.setCarrierAppPackagesProviderLPw(wrapper); 15846 } 15847 } finally { 15848 Binder.restoreCallingIdentity(token); 15849 } 15850 } 15851 15852 private static void enforceSystemOrPhoneCaller(String tag) { 15853 int callingUid = Binder.getCallingUid(); 15854 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 15855 throw new SecurityException( 15856 "Cannot call " + tag + " from UID " + callingUid); 15857 } 15858 } 15859} 15860