PackageManagerService.java revision 61d7acae0cafc265e94a35ad3ba1677f60346de9
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 28import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 29import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 46import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 47import static android.content.pm.PackageManager.INSTALL_INTERNAL; 48import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 53import static android.content.pm.PackageManager.MATCH_ALL; 54import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 55import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 56import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 57import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 58import static android.content.pm.PackageManager.PERMISSION_GRANTED; 59import static android.content.pm.PackageParser.isApkFile; 60import static android.os.Process.PACKAGE_INFO_GID; 61import static android.os.Process.SYSTEM_UID; 62import static android.system.OsConstants.O_CREAT; 63import static android.system.OsConstants.O_RDWR; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 66import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 67import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 68import static com.android.internal.util.ArrayUtils.appendInt; 69import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 72import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 73import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 74 75import android.Manifest; 76import android.app.ActivityManager; 77import android.app.ActivityManagerNative; 78import android.app.AppGlobals; 79import android.app.IActivityManager; 80import android.app.admin.IDevicePolicyManager; 81import android.app.backup.IBackupManager; 82import android.app.usage.UsageStats; 83import android.app.usage.UsageStatsManager; 84import android.content.BroadcastReceiver; 85import android.content.ComponentName; 86import android.content.Context; 87import android.content.IIntentReceiver; 88import android.content.Intent; 89import android.content.IntentFilter; 90import android.content.IntentSender; 91import android.content.IntentSender.SendIntentException; 92import android.content.ServiceConnection; 93import android.content.pm.ActivityInfo; 94import android.content.pm.ApplicationInfo; 95import android.content.pm.FeatureInfo; 96import android.content.pm.IOnPermissionsChangeListener; 97import android.content.pm.IPackageDataObserver; 98import android.content.pm.IPackageDeleteObserver; 99import android.content.pm.IPackageDeleteObserver2; 100import android.content.pm.IPackageInstallObserver2; 101import android.content.pm.IPackageInstaller; 102import android.content.pm.IPackageManager; 103import android.content.pm.IPackageMoveObserver; 104import android.content.pm.IPackageStatsObserver; 105import android.content.pm.InstrumentationInfo; 106import android.content.pm.IntentFilterVerificationInfo; 107import android.content.pm.KeySet; 108import android.content.pm.ManifestDigest; 109import android.content.pm.PackageCleanItem; 110import android.content.pm.PackageInfo; 111import android.content.pm.PackageInfoLite; 112import android.content.pm.PackageInstaller; 113import android.content.pm.PackageManager; 114import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 115import android.content.pm.PackageManagerInternal; 116import android.content.pm.PackageParser; 117import android.content.pm.PackageParser.ActivityIntentInfo; 118import android.content.pm.PackageParser.PackageLite; 119import android.content.pm.PackageParser.PackageParserException; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Debug; 140import android.os.Environment; 141import android.os.Environment.UserEnvironment; 142import android.os.FileUtils; 143import android.os.Handler; 144import android.os.IBinder; 145import android.os.Looper; 146import android.os.Message; 147import android.os.Parcel; 148import android.os.ParcelFileDescriptor; 149import android.os.Process; 150import android.os.RemoteCallbackList; 151import android.os.RemoteException; 152import android.os.SELinux; 153import android.os.ServiceManager; 154import android.os.SystemClock; 155import android.os.SystemProperties; 156import android.os.UserHandle; 157import android.os.UserManager; 158import android.os.storage.IMountService; 159import android.os.storage.StorageEventListener; 160import android.os.storage.StorageManager; 161import android.os.storage.VolumeInfo; 162import android.os.storage.VolumeRecord; 163import android.security.KeyStore; 164import android.security.SystemKeyStore; 165import android.system.ErrnoException; 166import android.system.Os; 167import android.system.StructStat; 168import android.text.TextUtils; 169import android.text.format.DateUtils; 170import android.util.ArrayMap; 171import android.util.ArraySet; 172import android.util.AtomicFile; 173import android.util.DisplayMetrics; 174import android.util.EventLog; 175import android.util.ExceptionUtils; 176import android.util.Log; 177import android.util.LogPrinter; 178import android.util.MathUtils; 179import android.util.PrintStreamPrinter; 180import android.util.Slog; 181import android.util.SparseArray; 182import android.util.SparseBooleanArray; 183import android.util.SparseIntArray; 184import android.util.Xml; 185import android.view.Display; 186 187import dalvik.system.DexFile; 188import dalvik.system.VMRuntime; 189 190import libcore.io.IoUtils; 191import libcore.util.EmptyArray; 192 193import com.android.internal.R; 194import com.android.internal.app.IMediaContainerService; 195import com.android.internal.app.ResolverActivity; 196import com.android.internal.content.NativeLibraryHelper; 197import com.android.internal.content.PackageHelper; 198import com.android.internal.os.IParcelFileDescriptorFactory; 199import com.android.internal.os.SomeArgs; 200import com.android.internal.os.Zygote; 201import com.android.internal.util.ArrayUtils; 202import com.android.internal.util.FastPrintWriter; 203import com.android.internal.util.FastXmlSerializer; 204import com.android.internal.util.IndentingPrintWriter; 205import com.android.internal.util.Preconditions; 206import com.android.server.EventLogTags; 207import com.android.server.FgThread; 208import com.android.server.IntentResolver; 209import com.android.server.LocalServices; 210import com.android.server.ServiceThread; 211import com.android.server.SystemConfig; 212import com.android.server.Watchdog; 213import com.android.server.pm.PermissionsState.PermissionState; 214import com.android.server.pm.Settings.DatabaseVersion; 215import com.android.server.storage.DeviceStorageMonitorInternal; 216 217import org.xmlpull.v1.XmlPullParser; 218import org.xmlpull.v1.XmlPullParserException; 219import org.xmlpull.v1.XmlSerializer; 220 221import java.io.BufferedInputStream; 222import java.io.BufferedOutputStream; 223import java.io.BufferedReader; 224import java.io.ByteArrayInputStream; 225import java.io.ByteArrayOutputStream; 226import java.io.File; 227import java.io.FileDescriptor; 228import java.io.FileNotFoundException; 229import java.io.FileOutputStream; 230import java.io.FileReader; 231import java.io.FilenameFilter; 232import java.io.IOException; 233import java.io.InputStream; 234import java.io.PrintWriter; 235import java.nio.charset.StandardCharsets; 236import java.security.NoSuchAlgorithmException; 237import java.security.PublicKey; 238import java.security.cert.CertificateEncodingException; 239import java.security.cert.CertificateException; 240import java.text.SimpleDateFormat; 241import java.util.ArrayList; 242import java.util.Arrays; 243import java.util.Collection; 244import java.util.Collections; 245import java.util.Comparator; 246import java.util.Date; 247import java.util.Iterator; 248import java.util.List; 249import java.util.Map; 250import java.util.Objects; 251import java.util.Set; 252import java.util.concurrent.CountDownLatch; 253import java.util.concurrent.TimeUnit; 254import java.util.concurrent.atomic.AtomicBoolean; 255import java.util.concurrent.atomic.AtomicInteger; 256import java.util.concurrent.atomic.AtomicLong; 257 258/** 259 * Keep track of all those .apks everywhere. 260 * 261 * This is very central to the platform's security; please run the unit 262 * tests whenever making modifications here: 263 * 264mmm frameworks/base/tests/AndroidTests 265adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 266adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 267 * 268 * {@hide} 269 */ 270public class PackageManagerService extends IPackageManager.Stub { 271 static final String TAG = "PackageManager"; 272 static final boolean DEBUG_SETTINGS = false; 273 static final boolean DEBUG_PREFERRED = false; 274 static final boolean DEBUG_UPGRADE = false; 275 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 276 private static final boolean DEBUG_BACKUP = true; 277 private static final boolean DEBUG_INSTALL = false; 278 private static final boolean DEBUG_REMOVE = false; 279 private static final boolean DEBUG_BROADCASTS = false; 280 private static final boolean DEBUG_SHOW_INFO = false; 281 private static final boolean DEBUG_PACKAGE_INFO = false; 282 private static final boolean DEBUG_INTENT_MATCHING = false; 283 private static final boolean DEBUG_PACKAGE_SCANNING = false; 284 private static final boolean DEBUG_VERIFY = false; 285 private static final boolean DEBUG_DEXOPT = false; 286 private static final boolean DEBUG_ABI_SELECTION = false; 287 288 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 289 290 private static final int RADIO_UID = Process.PHONE_UID; 291 private static final int LOG_UID = Process.LOG_UID; 292 private static final int NFC_UID = Process.NFC_UID; 293 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 294 private static final int SHELL_UID = Process.SHELL_UID; 295 296 // Cap the size of permission trees that 3rd party apps can define 297 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 298 299 // Suffix used during package installation when copying/moving 300 // package apks to install directory. 301 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 302 303 static final int SCAN_NO_DEX = 1<<1; 304 static final int SCAN_FORCE_DEX = 1<<2; 305 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 306 static final int SCAN_NEW_INSTALL = 1<<4; 307 static final int SCAN_NO_PATHS = 1<<5; 308 static final int SCAN_UPDATE_TIME = 1<<6; 309 static final int SCAN_DEFER_DEX = 1<<7; 310 static final int SCAN_BOOTING = 1<<8; 311 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 312 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 313 static final int SCAN_REQUIRE_KNOWN = 1<<12; 314 static final int SCAN_MOVE = 1<<13; 315 static final int SCAN_INITIAL = 1<<14; 316 317 static final int REMOVE_CHATTY = 1<<16; 318 319 private static final int[] EMPTY_INT_ARRAY = new int[0]; 320 321 /** 322 * Timeout (in milliseconds) after which the watchdog should declare that 323 * our handler thread is wedged. The usual default for such things is one 324 * minute but we sometimes do very lengthy I/O operations on this thread, 325 * such as installing multi-gigabyte applications, so ours needs to be longer. 326 */ 327 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 328 329 /** 330 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 331 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 332 * settings entry if available, otherwise we use the hardcoded default. If it's been 333 * more than this long since the last fstrim, we force one during the boot sequence. 334 * 335 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 336 * one gets run at the next available charging+idle time. This final mandatory 337 * no-fstrim check kicks in only of the other scheduling criteria is never met. 338 */ 339 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 340 341 /** 342 * Whether verification is enabled by default. 343 */ 344 private static final boolean DEFAULT_VERIFY_ENABLE = true; 345 346 /** 347 * The default maximum time to wait for the verification agent to return in 348 * milliseconds. 349 */ 350 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 351 352 /** 353 * The default response for package verification timeout. 354 * 355 * This can be either PackageManager.VERIFICATION_ALLOW or 356 * PackageManager.VERIFICATION_REJECT. 357 */ 358 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 359 360 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 361 362 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 363 DEFAULT_CONTAINER_PACKAGE, 364 "com.android.defcontainer.DefaultContainerService"); 365 366 private static final String KILL_APP_REASON_GIDS_CHANGED = 367 "permission grant or revoke changed gids"; 368 369 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 370 "permissions revoked"; 371 372 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 373 374 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 375 376 /** Permission grant: not grant the permission. */ 377 private static final int GRANT_DENIED = 1; 378 379 /** Permission grant: grant the permission as an install permission. */ 380 private static final int GRANT_INSTALL = 2; 381 382 /** Permission grant: grant the permission as an install permission for a legacy app. */ 383 private static final int GRANT_INSTALL_LEGACY = 3; 384 385 /** Permission grant: grant the permission as a runtime one. */ 386 private static final int GRANT_RUNTIME = 4; 387 388 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 389 private static final int GRANT_UPGRADE = 5; 390 391 /** Canonical intent used to identify what counts as a "web browser" app */ 392 private static final Intent sBrowserIntent; 393 static { 394 sBrowserIntent = new Intent(); 395 sBrowserIntent.setAction(Intent.ACTION_VIEW); 396 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 397 sBrowserIntent.setData(Uri.parse("http:")); 398 } 399 400 final ServiceThread mHandlerThread; 401 402 final PackageHandler mHandler; 403 404 /** 405 * Messages for {@link #mHandler} that need to wait for system ready before 406 * being dispatched. 407 */ 408 private ArrayList<Message> mPostSystemReadyMessages; 409 410 final int mSdkVersion = Build.VERSION.SDK_INT; 411 412 final Context mContext; 413 final boolean mFactoryTest; 414 final boolean mOnlyCore; 415 final boolean mLazyDexOpt; 416 final long mDexOptLRUThresholdInMills; 417 final DisplayMetrics mMetrics; 418 final int mDefParseFlags; 419 final String[] mSeparateProcesses; 420 final boolean mIsUpgrade; 421 422 // This is where all application persistent data goes. 423 final File mAppDataDir; 424 425 // This is where all application persistent data goes for secondary users. 426 final File mUserAppDataDir; 427 428 /** The location for ASEC container files on internal storage. */ 429 final String mAsecInternalPath; 430 431 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 432 // LOCK HELD. Can be called with mInstallLock held. 433 final Installer mInstaller; 434 435 /** Directory where installed third-party apps stored */ 436 final File mAppInstallDir; 437 438 /** 439 * Directory to which applications installed internally have their 440 * 32 bit native libraries copied. 441 */ 442 private File mAppLib32InstallDir; 443 444 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 445 // apps. 446 final File mDrmAppPrivateInstallDir; 447 448 // ---------------------------------------------------------------- 449 450 // Lock for state used when installing and doing other long running 451 // operations. Methods that must be called with this lock held have 452 // the suffix "LI". 453 final Object mInstallLock = new Object(); 454 455 // ---------------------------------------------------------------- 456 457 // Keys are String (package name), values are Package. This also serves 458 // as the lock for the global state. Methods that must be called with 459 // this lock held have the prefix "LP". 460 final ArrayMap<String, PackageParser.Package> mPackages = 461 new ArrayMap<String, PackageParser.Package>(); 462 463 // Tracks available target package names -> overlay package paths. 464 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 465 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 466 467 final Settings mSettings; 468 boolean mRestoredSettings; 469 470 // System configuration read by SystemConfig. 471 final int[] mGlobalGids; 472 final SparseArray<ArraySet<String>> mSystemPermissions; 473 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 474 475 // If mac_permissions.xml was found for seinfo labeling. 476 boolean mFoundPolicyFile; 477 478 // If a recursive restorecon of /data/data/<pkg> is needed. 479 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 480 481 public static final class SharedLibraryEntry { 482 public final String path; 483 public final String apk; 484 485 SharedLibraryEntry(String _path, String _apk) { 486 path = _path; 487 apk = _apk; 488 } 489 } 490 491 // Currently known shared libraries. 492 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 493 new ArrayMap<String, SharedLibraryEntry>(); 494 495 // All available activities, for your resolving pleasure. 496 final ActivityIntentResolver mActivities = 497 new ActivityIntentResolver(); 498 499 // All available receivers, for your resolving pleasure. 500 final ActivityIntentResolver mReceivers = 501 new ActivityIntentResolver(); 502 503 // All available services, for your resolving pleasure. 504 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 505 506 // All available providers, for your resolving pleasure. 507 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 508 509 // Mapping from provider base names (first directory in content URI codePath) 510 // to the provider information. 511 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 512 new ArrayMap<String, PackageParser.Provider>(); 513 514 // Mapping from instrumentation class names to info about them. 515 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 516 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 517 518 // Mapping from permission names to info about them. 519 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 520 new ArrayMap<String, PackageParser.PermissionGroup>(); 521 522 // Packages whose data we have transfered into another package, thus 523 // should no longer exist. 524 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 525 526 // Broadcast actions that are only available to the system. 527 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 528 529 /** List of packages waiting for verification. */ 530 final SparseArray<PackageVerificationState> mPendingVerification 531 = new SparseArray<PackageVerificationState>(); 532 533 /** Set of packages associated with each app op permission. */ 534 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 535 536 final PackageInstallerService mInstallerService; 537 538 private final PackageDexOptimizer mPackageDexOptimizer; 539 540 private AtomicInteger mNextMoveId = new AtomicInteger(); 541 private final MoveCallbacks mMoveCallbacks; 542 543 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 544 545 // Cache of users who need badging. 546 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 547 548 /** Token for keys in mPendingVerification. */ 549 private int mPendingVerificationToken = 0; 550 551 volatile boolean mSystemReady; 552 volatile boolean mSafeMode; 553 volatile boolean mHasSystemUidErrors; 554 555 ApplicationInfo mAndroidApplication; 556 final ActivityInfo mResolveActivity = new ActivityInfo(); 557 final ResolveInfo mResolveInfo = new ResolveInfo(); 558 ComponentName mResolveComponentName; 559 PackageParser.Package mPlatformPackage; 560 ComponentName mCustomResolverComponentName; 561 562 boolean mResolverReplaced = false; 563 564 private final ComponentName mIntentFilterVerifierComponent; 565 private int mIntentFilterVerificationToken = 0; 566 567 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 568 = new SparseArray<IntentFilterVerificationState>(); 569 570 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 571 new DefaultPermissionGrantPolicy(this); 572 573 private static class IFVerificationParams { 574 PackageParser.Package pkg; 575 boolean replacing; 576 int userId; 577 int verifierUid; 578 579 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 580 int _userId, int _verifierUid) { 581 pkg = _pkg; 582 replacing = _replacing; 583 userId = _userId; 584 replacing = _replacing; 585 verifierUid = _verifierUid; 586 } 587 } 588 589 private interface IntentFilterVerifier<T extends IntentFilter> { 590 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 591 T filter, String packageName); 592 void startVerifications(int userId); 593 void receiveVerificationResponse(int verificationId); 594 } 595 596 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 597 private Context mContext; 598 private ComponentName mIntentFilterVerifierComponent; 599 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 600 601 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 602 mContext = context; 603 mIntentFilterVerifierComponent = verifierComponent; 604 } 605 606 private String getDefaultScheme() { 607 return IntentFilter.SCHEME_HTTPS; 608 } 609 610 @Override 611 public void startVerifications(int userId) { 612 // Launch verifications requests 613 int count = mCurrentIntentFilterVerifications.size(); 614 for (int n=0; n<count; n++) { 615 int verificationId = mCurrentIntentFilterVerifications.get(n); 616 final IntentFilterVerificationState ivs = 617 mIntentFilterVerificationStates.get(verificationId); 618 619 String packageName = ivs.getPackageName(); 620 621 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 622 final int filterCount = filters.size(); 623 ArraySet<String> domainsSet = new ArraySet<>(); 624 for (int m=0; m<filterCount; m++) { 625 PackageParser.ActivityIntentInfo filter = filters.get(m); 626 domainsSet.addAll(filter.getHostsList()); 627 } 628 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 629 synchronized (mPackages) { 630 if (mSettings.createIntentFilterVerificationIfNeededLPw( 631 packageName, domainsList) != null) { 632 scheduleWriteSettingsLocked(); 633 } 634 } 635 sendVerificationRequest(userId, verificationId, ivs); 636 } 637 mCurrentIntentFilterVerifications.clear(); 638 } 639 640 private void sendVerificationRequest(int userId, int verificationId, 641 IntentFilterVerificationState ivs) { 642 643 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 644 verificationIntent.putExtra( 645 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 646 verificationId); 647 verificationIntent.putExtra( 648 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 649 getDefaultScheme()); 650 verificationIntent.putExtra( 651 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 652 ivs.getHostsString()); 653 verificationIntent.putExtra( 654 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 655 ivs.getPackageName()); 656 verificationIntent.setComponent(mIntentFilterVerifierComponent); 657 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 658 659 UserHandle user = new UserHandle(userId); 660 mContext.sendBroadcastAsUser(verificationIntent, user); 661 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 662 "Sending IntentFilter verification broadcast"); 663 } 664 665 public void receiveVerificationResponse(int verificationId) { 666 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 667 668 final boolean verified = ivs.isVerified(); 669 670 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 671 final int count = filters.size(); 672 if (DEBUG_DOMAIN_VERIFICATION) { 673 Slog.i(TAG, "Received verification response " + verificationId 674 + " for " + count + " filters, verified=" + verified); 675 } 676 for (int n=0; n<count; n++) { 677 PackageParser.ActivityIntentInfo filter = filters.get(n); 678 filter.setVerified(verified); 679 680 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 681 + " verified with result:" + verified + " and hosts:" 682 + ivs.getHostsString()); 683 } 684 685 mIntentFilterVerificationStates.remove(verificationId); 686 687 final String packageName = ivs.getPackageName(); 688 IntentFilterVerificationInfo ivi = null; 689 690 synchronized (mPackages) { 691 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 692 } 693 if (ivi == null) { 694 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 695 + verificationId + " packageName:" + packageName); 696 return; 697 } 698 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 699 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 700 701 synchronized (mPackages) { 702 if (verified) { 703 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 704 } else { 705 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 706 } 707 scheduleWriteSettingsLocked(); 708 709 final int userId = ivs.getUserId(); 710 if (userId != UserHandle.USER_ALL) { 711 final int userStatus = 712 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 713 714 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 715 boolean needUpdate = false; 716 717 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 718 // already been set by the User thru the Disambiguation dialog 719 switch (userStatus) { 720 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 721 if (verified) { 722 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 723 } else { 724 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 725 } 726 needUpdate = true; 727 break; 728 729 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 730 if (verified) { 731 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 732 needUpdate = true; 733 } 734 break; 735 736 default: 737 // Nothing to do 738 } 739 740 if (needUpdate) { 741 mSettings.updateIntentFilterVerificationStatusLPw( 742 packageName, updatedStatus, userId); 743 scheduleWritePackageRestrictionsLocked(userId); 744 } 745 } 746 } 747 } 748 749 @Override 750 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 751 ActivityIntentInfo filter, String packageName) { 752 if (!hasValidDomains(filter)) { 753 return false; 754 } 755 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 756 if (ivs == null) { 757 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 758 packageName); 759 } 760 if (DEBUG_DOMAIN_VERIFICATION) { 761 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 762 } 763 ivs.addFilter(filter); 764 return true; 765 } 766 767 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 768 int userId, int verificationId, String packageName) { 769 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 770 verifierUid, userId, packageName); 771 ivs.setPendingState(); 772 synchronized (mPackages) { 773 mIntentFilterVerificationStates.append(verificationId, ivs); 774 mCurrentIntentFilterVerifications.add(verificationId); 775 } 776 return ivs; 777 } 778 } 779 780 private static boolean hasValidDomains(ActivityIntentInfo filter) { 781 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 782 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 783 if (!hasHTTPorHTTPS) { 784 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 785 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 786 return false; 787 } 788 return true; 789 } 790 791 private IntentFilterVerifier mIntentFilterVerifier; 792 793 // Set of pending broadcasts for aggregating enable/disable of components. 794 static class PendingPackageBroadcasts { 795 // for each user id, a map of <package name -> components within that package> 796 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 797 798 public PendingPackageBroadcasts() { 799 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 800 } 801 802 public ArrayList<String> get(int userId, String packageName) { 803 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 804 return packages.get(packageName); 805 } 806 807 public void put(int userId, String packageName, ArrayList<String> components) { 808 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 809 packages.put(packageName, components); 810 } 811 812 public void remove(int userId, String packageName) { 813 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 814 if (packages != null) { 815 packages.remove(packageName); 816 } 817 } 818 819 public void remove(int userId) { 820 mUidMap.remove(userId); 821 } 822 823 public int userIdCount() { 824 return mUidMap.size(); 825 } 826 827 public int userIdAt(int n) { 828 return mUidMap.keyAt(n); 829 } 830 831 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 832 return mUidMap.get(userId); 833 } 834 835 public int size() { 836 // total number of pending broadcast entries across all userIds 837 int num = 0; 838 for (int i = 0; i< mUidMap.size(); i++) { 839 num += mUidMap.valueAt(i).size(); 840 } 841 return num; 842 } 843 844 public void clear() { 845 mUidMap.clear(); 846 } 847 848 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 849 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 850 if (map == null) { 851 map = new ArrayMap<String, ArrayList<String>>(); 852 mUidMap.put(userId, map); 853 } 854 return map; 855 } 856 } 857 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 858 859 // Service Connection to remote media container service to copy 860 // package uri's from external media onto secure containers 861 // or internal storage. 862 private IMediaContainerService mContainerService = null; 863 864 static final int SEND_PENDING_BROADCAST = 1; 865 static final int MCS_BOUND = 3; 866 static final int END_COPY = 4; 867 static final int INIT_COPY = 5; 868 static final int MCS_UNBIND = 6; 869 static final int START_CLEANING_PACKAGE = 7; 870 static final int FIND_INSTALL_LOC = 8; 871 static final int POST_INSTALL = 9; 872 static final int MCS_RECONNECT = 10; 873 static final int MCS_GIVE_UP = 11; 874 static final int UPDATED_MEDIA_STATUS = 12; 875 static final int WRITE_SETTINGS = 13; 876 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 877 static final int PACKAGE_VERIFIED = 15; 878 static final int CHECK_PENDING_VERIFICATION = 16; 879 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 880 static final int INTENT_FILTER_VERIFIED = 18; 881 882 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 883 884 // Delay time in millisecs 885 static final int BROADCAST_DELAY = 10 * 1000; 886 887 static UserManagerService sUserManager; 888 889 // Stores a list of users whose package restrictions file needs to be updated 890 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 891 892 final private DefaultContainerConnection mDefContainerConn = 893 new DefaultContainerConnection(); 894 class DefaultContainerConnection implements ServiceConnection { 895 public void onServiceConnected(ComponentName name, IBinder service) { 896 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 897 IMediaContainerService imcs = 898 IMediaContainerService.Stub.asInterface(service); 899 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 900 } 901 902 public void onServiceDisconnected(ComponentName name) { 903 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 904 } 905 } 906 907 // Recordkeeping of restore-after-install operations that are currently in flight 908 // between the Package Manager and the Backup Manager 909 class PostInstallData { 910 public InstallArgs args; 911 public PackageInstalledInfo res; 912 913 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 914 args = _a; 915 res = _r; 916 } 917 } 918 919 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 920 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 921 922 // XML tags for backup/restore of various bits of state 923 private static final String TAG_PREFERRED_BACKUP = "pa"; 924 private static final String TAG_DEFAULT_APPS = "da"; 925 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 926 927 private final String mRequiredVerifierPackage; 928 929 private final PackageUsage mPackageUsage = new PackageUsage(); 930 931 private class PackageUsage { 932 private static final int WRITE_INTERVAL 933 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 934 935 private final Object mFileLock = new Object(); 936 private final AtomicLong mLastWritten = new AtomicLong(0); 937 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 938 939 private boolean mIsHistoricalPackageUsageAvailable = true; 940 941 boolean isHistoricalPackageUsageAvailable() { 942 return mIsHistoricalPackageUsageAvailable; 943 } 944 945 void write(boolean force) { 946 if (force) { 947 writeInternal(); 948 return; 949 } 950 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 951 && !DEBUG_DEXOPT) { 952 return; 953 } 954 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 955 new Thread("PackageUsage_DiskWriter") { 956 @Override 957 public void run() { 958 try { 959 writeInternal(); 960 } finally { 961 mBackgroundWriteRunning.set(false); 962 } 963 } 964 }.start(); 965 } 966 } 967 968 private void writeInternal() { 969 synchronized (mPackages) { 970 synchronized (mFileLock) { 971 AtomicFile file = getFile(); 972 FileOutputStream f = null; 973 try { 974 f = file.startWrite(); 975 BufferedOutputStream out = new BufferedOutputStream(f); 976 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 977 StringBuilder sb = new StringBuilder(); 978 for (PackageParser.Package pkg : mPackages.values()) { 979 if (pkg.mLastPackageUsageTimeInMills == 0) { 980 continue; 981 } 982 sb.setLength(0); 983 sb.append(pkg.packageName); 984 sb.append(' '); 985 sb.append((long)pkg.mLastPackageUsageTimeInMills); 986 sb.append('\n'); 987 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 988 } 989 out.flush(); 990 file.finishWrite(f); 991 } catch (IOException e) { 992 if (f != null) { 993 file.failWrite(f); 994 } 995 Log.e(TAG, "Failed to write package usage times", e); 996 } 997 } 998 } 999 mLastWritten.set(SystemClock.elapsedRealtime()); 1000 } 1001 1002 void readLP() { 1003 synchronized (mFileLock) { 1004 AtomicFile file = getFile(); 1005 BufferedInputStream in = null; 1006 try { 1007 in = new BufferedInputStream(file.openRead()); 1008 StringBuffer sb = new StringBuffer(); 1009 while (true) { 1010 String packageName = readToken(in, sb, ' '); 1011 if (packageName == null) { 1012 break; 1013 } 1014 String timeInMillisString = readToken(in, sb, '\n'); 1015 if (timeInMillisString == null) { 1016 throw new IOException("Failed to find last usage time for package " 1017 + packageName); 1018 } 1019 PackageParser.Package pkg = mPackages.get(packageName); 1020 if (pkg == null) { 1021 continue; 1022 } 1023 long timeInMillis; 1024 try { 1025 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1026 } catch (NumberFormatException e) { 1027 throw new IOException("Failed to parse " + timeInMillisString 1028 + " as a long.", e); 1029 } 1030 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1031 } 1032 } catch (FileNotFoundException expected) { 1033 mIsHistoricalPackageUsageAvailable = false; 1034 } catch (IOException e) { 1035 Log.w(TAG, "Failed to read package usage times", e); 1036 } finally { 1037 IoUtils.closeQuietly(in); 1038 } 1039 } 1040 mLastWritten.set(SystemClock.elapsedRealtime()); 1041 } 1042 1043 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1044 throws IOException { 1045 sb.setLength(0); 1046 while (true) { 1047 int ch = in.read(); 1048 if (ch == -1) { 1049 if (sb.length() == 0) { 1050 return null; 1051 } 1052 throw new IOException("Unexpected EOF"); 1053 } 1054 if (ch == endOfToken) { 1055 return sb.toString(); 1056 } 1057 sb.append((char)ch); 1058 } 1059 } 1060 1061 private AtomicFile getFile() { 1062 File dataDir = Environment.getDataDirectory(); 1063 File systemDir = new File(dataDir, "system"); 1064 File fname = new File(systemDir, "package-usage.list"); 1065 return new AtomicFile(fname); 1066 } 1067 } 1068 1069 class PackageHandler extends Handler { 1070 private boolean mBound = false; 1071 final ArrayList<HandlerParams> mPendingInstalls = 1072 new ArrayList<HandlerParams>(); 1073 1074 private boolean connectToService() { 1075 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1076 " DefaultContainerService"); 1077 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1078 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1079 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1080 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1081 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1082 mBound = true; 1083 return true; 1084 } 1085 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1086 return false; 1087 } 1088 1089 private void disconnectService() { 1090 mContainerService = null; 1091 mBound = false; 1092 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1093 mContext.unbindService(mDefContainerConn); 1094 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1095 } 1096 1097 PackageHandler(Looper looper) { 1098 super(looper); 1099 } 1100 1101 public void handleMessage(Message msg) { 1102 try { 1103 doHandleMessage(msg); 1104 } finally { 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 } 1107 } 1108 1109 void doHandleMessage(Message msg) { 1110 switch (msg.what) { 1111 case INIT_COPY: { 1112 HandlerParams params = (HandlerParams) msg.obj; 1113 int idx = mPendingInstalls.size(); 1114 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1115 // If a bind was already initiated we dont really 1116 // need to do anything. The pending install 1117 // will be processed later on. 1118 if (!mBound) { 1119 // If this is the only one pending we might 1120 // have to bind to the service again. 1121 if (!connectToService()) { 1122 Slog.e(TAG, "Failed to bind to media container service"); 1123 params.serviceError(); 1124 return; 1125 } else { 1126 // Once we bind to the service, the first 1127 // pending request will be processed. 1128 mPendingInstalls.add(idx, params); 1129 } 1130 } else { 1131 mPendingInstalls.add(idx, params); 1132 // Already bound to the service. Just make 1133 // sure we trigger off processing the first request. 1134 if (idx == 0) { 1135 mHandler.sendEmptyMessage(MCS_BOUND); 1136 } 1137 } 1138 break; 1139 } 1140 case MCS_BOUND: { 1141 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1142 if (msg.obj != null) { 1143 mContainerService = (IMediaContainerService) msg.obj; 1144 } 1145 if (mContainerService == null) { 1146 if (!mBound) { 1147 // Something seriously wrong since we are not bound and we are not 1148 // waiting for connection. Bail out. 1149 Slog.e(TAG, "Cannot bind to media container service"); 1150 for (HandlerParams params : mPendingInstalls) { 1151 // Indicate service bind error 1152 params.serviceError(); 1153 } 1154 mPendingInstalls.clear(); 1155 } else { 1156 Slog.w(TAG, "Waiting to connect to media container service"); 1157 } 1158 } else if (mPendingInstalls.size() > 0) { 1159 HandlerParams params = mPendingInstalls.get(0); 1160 if (params != null) { 1161 if (params.startCopy()) { 1162 // We are done... look for more work or to 1163 // go idle. 1164 if (DEBUG_SD_INSTALL) Log.i(TAG, 1165 "Checking for more work or unbind..."); 1166 // Delete pending install 1167 if (mPendingInstalls.size() > 0) { 1168 mPendingInstalls.remove(0); 1169 } 1170 if (mPendingInstalls.size() == 0) { 1171 if (mBound) { 1172 if (DEBUG_SD_INSTALL) Log.i(TAG, 1173 "Posting delayed MCS_UNBIND"); 1174 removeMessages(MCS_UNBIND); 1175 Message ubmsg = obtainMessage(MCS_UNBIND); 1176 // Unbind after a little delay, to avoid 1177 // continual thrashing. 1178 sendMessageDelayed(ubmsg, 10000); 1179 } 1180 } else { 1181 // There are more pending requests in queue. 1182 // Just post MCS_BOUND message to trigger processing 1183 // of next pending install. 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, 1185 "Posting MCS_BOUND for next work"); 1186 mHandler.sendEmptyMessage(MCS_BOUND); 1187 } 1188 } 1189 } 1190 } else { 1191 // Should never happen ideally. 1192 Slog.w(TAG, "Empty queue"); 1193 } 1194 break; 1195 } 1196 case MCS_RECONNECT: { 1197 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1198 if (mPendingInstalls.size() > 0) { 1199 if (mBound) { 1200 disconnectService(); 1201 } 1202 if (!connectToService()) { 1203 Slog.e(TAG, "Failed to bind to media container service"); 1204 for (HandlerParams params : mPendingInstalls) { 1205 // Indicate service bind error 1206 params.serviceError(); 1207 } 1208 mPendingInstalls.clear(); 1209 } 1210 } 1211 break; 1212 } 1213 case MCS_UNBIND: { 1214 // If there is no actual work left, then time to unbind. 1215 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1216 1217 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1218 if (mBound) { 1219 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1220 1221 disconnectService(); 1222 } 1223 } else if (mPendingInstalls.size() > 0) { 1224 // There are more pending requests in queue. 1225 // Just post MCS_BOUND message to trigger processing 1226 // of next pending install. 1227 mHandler.sendEmptyMessage(MCS_BOUND); 1228 } 1229 1230 break; 1231 } 1232 case MCS_GIVE_UP: { 1233 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1234 mPendingInstalls.remove(0); 1235 break; 1236 } 1237 case SEND_PENDING_BROADCAST: { 1238 String packages[]; 1239 ArrayList<String> components[]; 1240 int size = 0; 1241 int uids[]; 1242 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1243 synchronized (mPackages) { 1244 if (mPendingBroadcasts == null) { 1245 return; 1246 } 1247 size = mPendingBroadcasts.size(); 1248 if (size <= 0) { 1249 // Nothing to be done. Just return 1250 return; 1251 } 1252 packages = new String[size]; 1253 components = new ArrayList[size]; 1254 uids = new int[size]; 1255 int i = 0; // filling out the above arrays 1256 1257 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1258 int packageUserId = mPendingBroadcasts.userIdAt(n); 1259 Iterator<Map.Entry<String, ArrayList<String>>> it 1260 = mPendingBroadcasts.packagesForUserId(packageUserId) 1261 .entrySet().iterator(); 1262 while (it.hasNext() && i < size) { 1263 Map.Entry<String, ArrayList<String>> ent = it.next(); 1264 packages[i] = ent.getKey(); 1265 components[i] = ent.getValue(); 1266 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1267 uids[i] = (ps != null) 1268 ? UserHandle.getUid(packageUserId, ps.appId) 1269 : -1; 1270 i++; 1271 } 1272 } 1273 size = i; 1274 mPendingBroadcasts.clear(); 1275 } 1276 // Send broadcasts 1277 for (int i = 0; i < size; i++) { 1278 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1279 } 1280 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1281 break; 1282 } 1283 case START_CLEANING_PACKAGE: { 1284 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1285 final String packageName = (String)msg.obj; 1286 final int userId = msg.arg1; 1287 final boolean andCode = msg.arg2 != 0; 1288 synchronized (mPackages) { 1289 if (userId == UserHandle.USER_ALL) { 1290 int[] users = sUserManager.getUserIds(); 1291 for (int user : users) { 1292 mSettings.addPackageToCleanLPw( 1293 new PackageCleanItem(user, packageName, andCode)); 1294 } 1295 } else { 1296 mSettings.addPackageToCleanLPw( 1297 new PackageCleanItem(userId, packageName, andCode)); 1298 } 1299 } 1300 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1301 startCleaningPackages(); 1302 } break; 1303 case POST_INSTALL: { 1304 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1305 PostInstallData data = mRunningInstalls.get(msg.arg1); 1306 mRunningInstalls.delete(msg.arg1); 1307 boolean deleteOld = false; 1308 1309 if (data != null) { 1310 InstallArgs args = data.args; 1311 PackageInstalledInfo res = data.res; 1312 final String packageName = res.pkg.applicationInfo.packageName; 1313 1314 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1315 res.removedInfo.sendBroadcast(false, true, false); 1316 Bundle extras = new Bundle(1); 1317 extras.putInt(Intent.EXTRA_UID, res.uid); 1318 1319 // Now that we successfully installed the package, grant runtime 1320 // permissions if requested before broadcasting the install. 1321 if ((args.installFlags 1322 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1323 grantRequestedRuntimePermissions(res.pkg, 1324 args.user.getIdentifier()); 1325 } 1326 1327 // Determine the set of users who are adding this 1328 // package for the first time vs. those who are seeing 1329 // an update. 1330 int[] firstUsers; 1331 int[] updateUsers = new int[0]; 1332 if (res.origUsers == null || res.origUsers.length == 0) { 1333 firstUsers = res.newUsers; 1334 } else { 1335 firstUsers = new int[0]; 1336 for (int i=0; i<res.newUsers.length; i++) { 1337 int user = res.newUsers[i]; 1338 boolean isNew = true; 1339 for (int j=0; j<res.origUsers.length; j++) { 1340 if (res.origUsers[j] == user) { 1341 isNew = false; 1342 break; 1343 } 1344 } 1345 if (isNew) { 1346 int[] newFirst = new int[firstUsers.length+1]; 1347 System.arraycopy(firstUsers, 0, newFirst, 0, 1348 firstUsers.length); 1349 newFirst[firstUsers.length] = user; 1350 firstUsers = newFirst; 1351 } else { 1352 int[] newUpdate = new int[updateUsers.length+1]; 1353 System.arraycopy(updateUsers, 0, newUpdate, 0, 1354 updateUsers.length); 1355 newUpdate[updateUsers.length] = user; 1356 updateUsers = newUpdate; 1357 } 1358 } 1359 } 1360 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1361 packageName, extras, null, null, firstUsers); 1362 final boolean update = res.removedInfo.removedPackage != null; 1363 if (update) { 1364 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1365 } 1366 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1367 packageName, extras, null, null, updateUsers); 1368 if (update) { 1369 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1370 packageName, extras, null, null, updateUsers); 1371 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1372 null, null, packageName, null, updateUsers); 1373 1374 // treat asec-hosted packages like removable media on upgrade 1375 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1376 if (DEBUG_INSTALL) { 1377 Slog.i(TAG, "upgrading pkg " + res.pkg 1378 + " is ASEC-hosted -> AVAILABLE"); 1379 } 1380 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1381 ArrayList<String> pkgList = new ArrayList<String>(1); 1382 pkgList.add(packageName); 1383 sendResourcesChangedBroadcast(true, true, 1384 pkgList,uidArray, null); 1385 } 1386 } 1387 if (res.removedInfo.args != null) { 1388 // Remove the replaced package's older resources safely now 1389 deleteOld = true; 1390 } 1391 1392 // If this app is a browser and it's newly-installed for some 1393 // users, clear any default-browser state in those users 1394 if (firstUsers.length > 0) { 1395 // the app's nature doesn't depend on the user, so we can just 1396 // check its browser nature in any user and generalize. 1397 if (packageIsBrowser(packageName, firstUsers[0])) { 1398 synchronized (mPackages) { 1399 for (int userId : firstUsers) { 1400 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1401 } 1402 } 1403 } 1404 } 1405 // Log current value of "unknown sources" setting 1406 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1407 getUnknownSourcesSettings()); 1408 } 1409 // Force a gc to clear up things 1410 Runtime.getRuntime().gc(); 1411 // We delete after a gc for applications on sdcard. 1412 if (deleteOld) { 1413 synchronized (mInstallLock) { 1414 res.removedInfo.args.doPostDeleteLI(true); 1415 } 1416 } 1417 if (args.observer != null) { 1418 try { 1419 Bundle extras = extrasForInstallResult(res); 1420 args.observer.onPackageInstalled(res.name, res.returnCode, 1421 res.returnMsg, extras); 1422 } catch (RemoteException e) { 1423 Slog.i(TAG, "Observer no longer exists."); 1424 } 1425 } 1426 } else { 1427 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1428 } 1429 } break; 1430 case UPDATED_MEDIA_STATUS: { 1431 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1432 boolean reportStatus = msg.arg1 == 1; 1433 boolean doGc = msg.arg2 == 1; 1434 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1435 if (doGc) { 1436 // Force a gc to clear up stale containers. 1437 Runtime.getRuntime().gc(); 1438 } 1439 if (msg.obj != null) { 1440 @SuppressWarnings("unchecked") 1441 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1442 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1443 // Unload containers 1444 unloadAllContainers(args); 1445 } 1446 if (reportStatus) { 1447 try { 1448 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1449 PackageHelper.getMountService().finishMediaUpdate(); 1450 } catch (RemoteException e) { 1451 Log.e(TAG, "MountService not running?"); 1452 } 1453 } 1454 } break; 1455 case WRITE_SETTINGS: { 1456 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1457 synchronized (mPackages) { 1458 removeMessages(WRITE_SETTINGS); 1459 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1460 mSettings.writeLPr(); 1461 mDirtyUsers.clear(); 1462 } 1463 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1464 } break; 1465 case WRITE_PACKAGE_RESTRICTIONS: { 1466 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1467 synchronized (mPackages) { 1468 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1469 for (int userId : mDirtyUsers) { 1470 mSettings.writePackageRestrictionsLPr(userId); 1471 } 1472 mDirtyUsers.clear(); 1473 } 1474 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1475 } break; 1476 case CHECK_PENDING_VERIFICATION: { 1477 final int verificationId = msg.arg1; 1478 final PackageVerificationState state = mPendingVerification.get(verificationId); 1479 1480 if ((state != null) && !state.timeoutExtended()) { 1481 final InstallArgs args = state.getInstallArgs(); 1482 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1483 1484 Slog.i(TAG, "Verification timed out for " + originUri); 1485 mPendingVerification.remove(verificationId); 1486 1487 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1488 1489 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1490 Slog.i(TAG, "Continuing with installation of " + originUri); 1491 state.setVerifierResponse(Binder.getCallingUid(), 1492 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1493 broadcastPackageVerified(verificationId, originUri, 1494 PackageManager.VERIFICATION_ALLOW, 1495 state.getInstallArgs().getUser()); 1496 try { 1497 ret = args.copyApk(mContainerService, true); 1498 } catch (RemoteException e) { 1499 Slog.e(TAG, "Could not contact the ContainerService"); 1500 } 1501 } else { 1502 broadcastPackageVerified(verificationId, originUri, 1503 PackageManager.VERIFICATION_REJECT, 1504 state.getInstallArgs().getUser()); 1505 } 1506 1507 processPendingInstall(args, ret); 1508 mHandler.sendEmptyMessage(MCS_UNBIND); 1509 } 1510 break; 1511 } 1512 case PACKAGE_VERIFIED: { 1513 final int verificationId = msg.arg1; 1514 1515 final PackageVerificationState state = mPendingVerification.get(verificationId); 1516 if (state == null) { 1517 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1518 break; 1519 } 1520 1521 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1522 1523 state.setVerifierResponse(response.callerUid, response.code); 1524 1525 if (state.isVerificationComplete()) { 1526 mPendingVerification.remove(verificationId); 1527 1528 final InstallArgs args = state.getInstallArgs(); 1529 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1530 1531 int ret; 1532 if (state.isInstallAllowed()) { 1533 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1534 broadcastPackageVerified(verificationId, originUri, 1535 response.code, state.getInstallArgs().getUser()); 1536 try { 1537 ret = args.copyApk(mContainerService, true); 1538 } catch (RemoteException e) { 1539 Slog.e(TAG, "Could not contact the ContainerService"); 1540 } 1541 } else { 1542 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1543 } 1544 1545 processPendingInstall(args, ret); 1546 1547 mHandler.sendEmptyMessage(MCS_UNBIND); 1548 } 1549 1550 break; 1551 } 1552 case START_INTENT_FILTER_VERIFICATIONS: { 1553 IFVerificationParams params = (IFVerificationParams) msg.obj; 1554 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1555 params.replacing, params.pkg); 1556 break; 1557 } 1558 case INTENT_FILTER_VERIFIED: { 1559 final int verificationId = msg.arg1; 1560 1561 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1562 verificationId); 1563 if (state == null) { 1564 Slog.w(TAG, "Invalid IntentFilter verification token " 1565 + verificationId + " received"); 1566 break; 1567 } 1568 1569 final int userId = state.getUserId(); 1570 1571 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1572 "Processing IntentFilter verification with token:" 1573 + verificationId + " and userId:" + userId); 1574 1575 final IntentFilterVerificationResponse response = 1576 (IntentFilterVerificationResponse) msg.obj; 1577 1578 state.setVerifierResponse(response.callerUid, response.code); 1579 1580 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1581 "IntentFilter verification with token:" + verificationId 1582 + " and userId:" + userId 1583 + " is settings verifier response with response code:" 1584 + response.code); 1585 1586 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1587 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1588 + response.getFailedDomainsString()); 1589 } 1590 1591 if (state.isVerificationComplete()) { 1592 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1593 } else { 1594 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1595 "IntentFilter verification with token:" + verificationId 1596 + " was not said to be complete"); 1597 } 1598 1599 break; 1600 } 1601 } 1602 } 1603 } 1604 1605 private StorageEventListener mStorageListener = new StorageEventListener() { 1606 @Override 1607 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1608 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1609 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1610 // TODO: ensure that private directories exist for all active users 1611 // TODO: remove user data whose serial number doesn't match 1612 loadPrivatePackages(vol); 1613 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1614 unloadPrivatePackages(vol); 1615 } 1616 } 1617 1618 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1619 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1620 updateExternalMediaStatus(true, false); 1621 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1622 updateExternalMediaStatus(false, false); 1623 } 1624 } 1625 } 1626 1627 @Override 1628 public void onVolumeForgotten(String fsUuid) { 1629 // TODO: remove all packages hosted on this uuid 1630 } 1631 }; 1632 1633 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1634 if (userId >= UserHandle.USER_OWNER) { 1635 grantRequestedRuntimePermissionsForUser(pkg, userId); 1636 } else if (userId == UserHandle.USER_ALL) { 1637 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1638 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1639 } 1640 } 1641 1642 // We could have touched GID membership, so flush out packages.list 1643 synchronized (mPackages) { 1644 mSettings.writePackageListLPr(); 1645 } 1646 } 1647 1648 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1649 SettingBase sb = (SettingBase) pkg.mExtras; 1650 if (sb == null) { 1651 return; 1652 } 1653 1654 PermissionsState permissionsState = sb.getPermissionsState(); 1655 1656 for (String permission : pkg.requestedPermissions) { 1657 BasePermission bp = mSettings.mPermissions.get(permission); 1658 if (bp != null && bp.isRuntime()) { 1659 permissionsState.grantRuntimePermission(bp, userId); 1660 } 1661 } 1662 } 1663 1664 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1665 Bundle extras = null; 1666 switch (res.returnCode) { 1667 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1668 extras = new Bundle(); 1669 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1670 res.origPermission); 1671 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1672 res.origPackage); 1673 break; 1674 } 1675 case PackageManager.INSTALL_SUCCEEDED: { 1676 extras = new Bundle(); 1677 extras.putBoolean(Intent.EXTRA_REPLACING, 1678 res.removedInfo != null && res.removedInfo.removedPackage != null); 1679 break; 1680 } 1681 } 1682 return extras; 1683 } 1684 1685 void scheduleWriteSettingsLocked() { 1686 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1687 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1688 } 1689 } 1690 1691 void scheduleWritePackageRestrictionsLocked(int userId) { 1692 if (!sUserManager.exists(userId)) return; 1693 mDirtyUsers.add(userId); 1694 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1695 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1696 } 1697 } 1698 1699 public static PackageManagerService main(Context context, Installer installer, 1700 boolean factoryTest, boolean onlyCore) { 1701 PackageManagerService m = new PackageManagerService(context, installer, 1702 factoryTest, onlyCore); 1703 ServiceManager.addService("package", m); 1704 return m; 1705 } 1706 1707 static String[] splitString(String str, char sep) { 1708 int count = 1; 1709 int i = 0; 1710 while ((i=str.indexOf(sep, i)) >= 0) { 1711 count++; 1712 i++; 1713 } 1714 1715 String[] res = new String[count]; 1716 i=0; 1717 count = 0; 1718 int lastI=0; 1719 while ((i=str.indexOf(sep, i)) >= 0) { 1720 res[count] = str.substring(lastI, i); 1721 count++; 1722 i++; 1723 lastI = i; 1724 } 1725 res[count] = str.substring(lastI, str.length()); 1726 return res; 1727 } 1728 1729 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1730 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1731 Context.DISPLAY_SERVICE); 1732 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1733 } 1734 1735 public PackageManagerService(Context context, Installer installer, 1736 boolean factoryTest, boolean onlyCore) { 1737 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1738 SystemClock.uptimeMillis()); 1739 1740 if (mSdkVersion <= 0) { 1741 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1742 } 1743 1744 mContext = context; 1745 mFactoryTest = factoryTest; 1746 mOnlyCore = onlyCore; 1747 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1748 mMetrics = new DisplayMetrics(); 1749 mSettings = new Settings(mPackages); 1750 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1751 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1752 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1753 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1754 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1755 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1756 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1757 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1758 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1759 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1760 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1761 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1762 1763 // TODO: add a property to control this? 1764 long dexOptLRUThresholdInMinutes; 1765 if (mLazyDexOpt) { 1766 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1767 } else { 1768 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1769 } 1770 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1771 1772 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1773 if (separateProcesses != null && separateProcesses.length() > 0) { 1774 if ("*".equals(separateProcesses)) { 1775 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1776 mSeparateProcesses = null; 1777 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1778 } else { 1779 mDefParseFlags = 0; 1780 mSeparateProcesses = separateProcesses.split(","); 1781 Slog.w(TAG, "Running with debug.separate_processes: " 1782 + separateProcesses); 1783 } 1784 } else { 1785 mDefParseFlags = 0; 1786 mSeparateProcesses = null; 1787 } 1788 1789 mInstaller = installer; 1790 mPackageDexOptimizer = new PackageDexOptimizer(this); 1791 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1792 1793 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1794 FgThread.get().getLooper()); 1795 1796 getDefaultDisplayMetrics(context, mMetrics); 1797 1798 SystemConfig systemConfig = SystemConfig.getInstance(); 1799 mGlobalGids = systemConfig.getGlobalGids(); 1800 mSystemPermissions = systemConfig.getSystemPermissions(); 1801 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1802 1803 synchronized (mInstallLock) { 1804 // writer 1805 synchronized (mPackages) { 1806 mHandlerThread = new ServiceThread(TAG, 1807 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1808 mHandlerThread.start(); 1809 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1810 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1811 1812 File dataDir = Environment.getDataDirectory(); 1813 mAppDataDir = new File(dataDir, "data"); 1814 mAppInstallDir = new File(dataDir, "app"); 1815 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1816 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1817 mUserAppDataDir = new File(dataDir, "user"); 1818 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1819 1820 sUserManager = new UserManagerService(context, this, 1821 mInstallLock, mPackages); 1822 1823 // Propagate permission configuration in to package manager. 1824 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1825 = systemConfig.getPermissions(); 1826 for (int i=0; i<permConfig.size(); i++) { 1827 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1828 BasePermission bp = mSettings.mPermissions.get(perm.name); 1829 if (bp == null) { 1830 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1831 mSettings.mPermissions.put(perm.name, bp); 1832 } 1833 if (perm.gids != null) { 1834 bp.setGids(perm.gids, perm.perUser); 1835 } 1836 } 1837 1838 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1839 for (int i=0; i<libConfig.size(); i++) { 1840 mSharedLibraries.put(libConfig.keyAt(i), 1841 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1842 } 1843 1844 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1845 1846 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1847 mSdkVersion, mOnlyCore); 1848 1849 String customResolverActivity = Resources.getSystem().getString( 1850 R.string.config_customResolverActivity); 1851 if (TextUtils.isEmpty(customResolverActivity)) { 1852 customResolverActivity = null; 1853 } else { 1854 mCustomResolverComponentName = ComponentName.unflattenFromString( 1855 customResolverActivity); 1856 } 1857 1858 long startTime = SystemClock.uptimeMillis(); 1859 1860 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1861 startTime); 1862 1863 // Set flag to monitor and not change apk file paths when 1864 // scanning install directories. 1865 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1866 1867 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1868 1869 /** 1870 * Add everything in the in the boot class path to the 1871 * list of process files because dexopt will have been run 1872 * if necessary during zygote startup. 1873 */ 1874 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1875 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1876 1877 if (bootClassPath != null) { 1878 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1879 for (String element : bootClassPathElements) { 1880 alreadyDexOpted.add(element); 1881 } 1882 } else { 1883 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1884 } 1885 1886 if (systemServerClassPath != null) { 1887 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1888 for (String element : systemServerClassPathElements) { 1889 alreadyDexOpted.add(element); 1890 } 1891 } else { 1892 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1893 } 1894 1895 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1896 final String[] dexCodeInstructionSets = 1897 getDexCodeInstructionSets( 1898 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1899 1900 /** 1901 * Ensure all external libraries have had dexopt run on them. 1902 */ 1903 if (mSharedLibraries.size() > 0) { 1904 // NOTE: For now, we're compiling these system "shared libraries" 1905 // (and framework jars) into all available architectures. It's possible 1906 // to compile them only when we come across an app that uses them (there's 1907 // already logic for that in scanPackageLI) but that adds some complexity. 1908 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1909 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1910 final String lib = libEntry.path; 1911 if (lib == null) { 1912 continue; 1913 } 1914 1915 try { 1916 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1917 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1918 alreadyDexOpted.add(lib); 1919 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1920 } 1921 } catch (FileNotFoundException e) { 1922 Slog.w(TAG, "Library not found: " + lib); 1923 } catch (IOException e) { 1924 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1925 + e.getMessage()); 1926 } 1927 } 1928 } 1929 } 1930 1931 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1932 1933 // Gross hack for now: we know this file doesn't contain any 1934 // code, so don't dexopt it to avoid the resulting log spew. 1935 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1936 1937 // Gross hack for now: we know this file is only part of 1938 // the boot class path for art, so don't dexopt it to 1939 // avoid the resulting log spew. 1940 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1941 1942 /** 1943 * There are a number of commands implemented in Java, which 1944 * we currently need to do the dexopt on so that they can be 1945 * run from a non-root shell. 1946 */ 1947 String[] frameworkFiles = frameworkDir.list(); 1948 if (frameworkFiles != null) { 1949 // TODO: We could compile these only for the most preferred ABI. We should 1950 // first double check that the dex files for these commands are not referenced 1951 // by other system apps. 1952 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1953 for (int i=0; i<frameworkFiles.length; i++) { 1954 File libPath = new File(frameworkDir, frameworkFiles[i]); 1955 String path = libPath.getPath(); 1956 // Skip the file if we already did it. 1957 if (alreadyDexOpted.contains(path)) { 1958 continue; 1959 } 1960 // Skip the file if it is not a type we want to dexopt. 1961 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1962 continue; 1963 } 1964 try { 1965 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1966 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1967 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1968 } 1969 } catch (FileNotFoundException e) { 1970 Slog.w(TAG, "Jar not found: " + path); 1971 } catch (IOException e) { 1972 Slog.w(TAG, "Exception reading jar: " + path, e); 1973 } 1974 } 1975 } 1976 } 1977 1978 // Collect vendor overlay packages. 1979 // (Do this before scanning any apps.) 1980 // For security and version matching reason, only consider 1981 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1982 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1983 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1984 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1985 1986 // Find base frameworks (resource packages without code). 1987 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1988 | PackageParser.PARSE_IS_SYSTEM_DIR 1989 | PackageParser.PARSE_IS_PRIVILEGED, 1990 scanFlags | SCAN_NO_DEX, 0); 1991 1992 // Collected privileged system packages. 1993 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1994 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1995 | PackageParser.PARSE_IS_SYSTEM_DIR 1996 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1997 1998 // Collect ordinary system packages. 1999 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2000 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2001 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2002 2003 // Collect all vendor packages. 2004 File vendorAppDir = new File("/vendor/app"); 2005 try { 2006 vendorAppDir = vendorAppDir.getCanonicalFile(); 2007 } catch (IOException e) { 2008 // failed to look up canonical path, continue with original one 2009 } 2010 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2011 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2012 2013 // Collect all OEM packages. 2014 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2015 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2016 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2017 2018 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2019 mInstaller.moveFiles(); 2020 2021 // Prune any system packages that no longer exist. 2022 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2023 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2024 if (!mOnlyCore) { 2025 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2026 while (psit.hasNext()) { 2027 PackageSetting ps = psit.next(); 2028 2029 /* 2030 * If this is not a system app, it can't be a 2031 * disable system app. 2032 */ 2033 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2034 continue; 2035 } 2036 2037 /* 2038 * If the package is scanned, it's not erased. 2039 */ 2040 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2041 if (scannedPkg != null) { 2042 /* 2043 * If the system app is both scanned and in the 2044 * disabled packages list, then it must have been 2045 * added via OTA. Remove it from the currently 2046 * scanned package so the previously user-installed 2047 * application can be scanned. 2048 */ 2049 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2050 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2051 + ps.name + "; removing system app. Last known codePath=" 2052 + ps.codePathString + ", installStatus=" + ps.installStatus 2053 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2054 + scannedPkg.mVersionCode); 2055 removePackageLI(ps, true); 2056 expectingBetter.put(ps.name, ps.codePath); 2057 } 2058 2059 continue; 2060 } 2061 2062 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2063 psit.remove(); 2064 logCriticalInfo(Log.WARN, "System package " + ps.name 2065 + " no longer exists; wiping its data"); 2066 removeDataDirsLI(null, ps.name); 2067 } else { 2068 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2069 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2070 possiblyDeletedUpdatedSystemApps.add(ps.name); 2071 } 2072 } 2073 } 2074 } 2075 2076 //look for any incomplete package installations 2077 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2078 //clean up list 2079 for(int i = 0; i < deletePkgsList.size(); i++) { 2080 //clean up here 2081 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2082 } 2083 //delete tmp files 2084 deleteTempPackageFiles(); 2085 2086 // Remove any shared userIDs that have no associated packages 2087 mSettings.pruneSharedUsersLPw(); 2088 2089 if (!mOnlyCore) { 2090 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2091 SystemClock.uptimeMillis()); 2092 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2093 2094 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2095 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2096 2097 /** 2098 * Remove disable package settings for any updated system 2099 * apps that were removed via an OTA. If they're not a 2100 * previously-updated app, remove them completely. 2101 * Otherwise, just revoke their system-level permissions. 2102 */ 2103 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2104 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2105 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2106 2107 String msg; 2108 if (deletedPkg == null) { 2109 msg = "Updated system package " + deletedAppName 2110 + " no longer exists; wiping its data"; 2111 removeDataDirsLI(null, deletedAppName); 2112 } else { 2113 msg = "Updated system app + " + deletedAppName 2114 + " no longer present; removing system privileges for " 2115 + deletedAppName; 2116 2117 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2118 2119 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2120 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2121 } 2122 logCriticalInfo(Log.WARN, msg); 2123 } 2124 2125 /** 2126 * Make sure all system apps that we expected to appear on 2127 * the userdata partition actually showed up. If they never 2128 * appeared, crawl back and revive the system version. 2129 */ 2130 for (int i = 0; i < expectingBetter.size(); i++) { 2131 final String packageName = expectingBetter.keyAt(i); 2132 if (!mPackages.containsKey(packageName)) { 2133 final File scanFile = expectingBetter.valueAt(i); 2134 2135 logCriticalInfo(Log.WARN, "Expected better " + packageName 2136 + " but never showed up; reverting to system"); 2137 2138 final int reparseFlags; 2139 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2140 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2141 | PackageParser.PARSE_IS_SYSTEM_DIR 2142 | PackageParser.PARSE_IS_PRIVILEGED; 2143 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2144 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2145 | PackageParser.PARSE_IS_SYSTEM_DIR; 2146 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2147 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2148 | PackageParser.PARSE_IS_SYSTEM_DIR; 2149 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2150 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2151 | PackageParser.PARSE_IS_SYSTEM_DIR; 2152 } else { 2153 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2154 continue; 2155 } 2156 2157 mSettings.enableSystemPackageLPw(packageName); 2158 2159 try { 2160 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2161 } catch (PackageManagerException e) { 2162 Slog.e(TAG, "Failed to parse original system package: " 2163 + e.getMessage()); 2164 } 2165 } 2166 } 2167 } 2168 2169 // Now that we know all of the shared libraries, update all clients to have 2170 // the correct library paths. 2171 updateAllSharedLibrariesLPw(); 2172 2173 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2174 // NOTE: We ignore potential failures here during a system scan (like 2175 // the rest of the commands above) because there's precious little we 2176 // can do about it. A settings error is reported, though. 2177 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2178 false /* force dexopt */, false /* defer dexopt */); 2179 } 2180 2181 // Now that we know all the packages we are keeping, 2182 // read and update their last usage times. 2183 mPackageUsage.readLP(); 2184 2185 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2186 SystemClock.uptimeMillis()); 2187 Slog.i(TAG, "Time to scan packages: " 2188 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2189 + " seconds"); 2190 2191 // If the platform SDK has changed since the last time we booted, 2192 // we need to re-grant app permission to catch any new ones that 2193 // appear. This is really a hack, and means that apps can in some 2194 // cases get permissions that the user didn't initially explicitly 2195 // allow... it would be nice to have some better way to handle 2196 // this situation. 2197 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2198 != mSdkVersion; 2199 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2200 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2201 + "; regranting permissions for internal storage"); 2202 mSettings.mInternalSdkPlatform = mSdkVersion; 2203 2204 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2205 | (regrantPermissions 2206 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2207 : 0)); 2208 2209 // If this is the first boot, and it is a normal boot, then 2210 // we need to initialize the default preferred apps. 2211 if (!mRestoredSettings && !onlyCore) { 2212 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2213 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2214 } 2215 2216 // If this is first boot after an OTA, and a normal boot, then 2217 // we need to clear code cache directories. 2218 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2219 if (mIsUpgrade && !onlyCore) { 2220 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2221 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2222 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2223 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2224 } 2225 mSettings.mFingerprint = Build.FINGERPRINT; 2226 } 2227 2228 primeDomainVerificationsLPw(); 2229 checkDefaultBrowser(); 2230 2231 // All the changes are done during package scanning. 2232 mSettings.updateInternalDatabaseVersion(); 2233 2234 // can downgrade to reader 2235 mSettings.writeLPr(); 2236 2237 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2238 SystemClock.uptimeMillis()); 2239 2240 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2241 2242 mInstallerService = new PackageInstallerService(context, this); 2243 2244 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2245 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2246 mIntentFilterVerifierComponent); 2247 2248 } // synchronized (mPackages) 2249 } // synchronized (mInstallLock) 2250 2251 // Now after opening every single application zip, make sure they 2252 // are all flushed. Not really needed, but keeps things nice and 2253 // tidy. 2254 Runtime.getRuntime().gc(); 2255 2256 // Expose private service for system components to use. 2257 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2258 } 2259 2260 @Override 2261 public boolean isFirstBoot() { 2262 return !mRestoredSettings; 2263 } 2264 2265 @Override 2266 public boolean isOnlyCoreApps() { 2267 return mOnlyCore; 2268 } 2269 2270 @Override 2271 public boolean isUpgrade() { 2272 return mIsUpgrade; 2273 } 2274 2275 private String getRequiredVerifierLPr() { 2276 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2277 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2278 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2279 2280 String requiredVerifier = null; 2281 2282 final int N = receivers.size(); 2283 for (int i = 0; i < N; i++) { 2284 final ResolveInfo info = receivers.get(i); 2285 2286 if (info.activityInfo == null) { 2287 continue; 2288 } 2289 2290 final String packageName = info.activityInfo.packageName; 2291 2292 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2293 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2294 continue; 2295 } 2296 2297 if (requiredVerifier != null) { 2298 throw new RuntimeException("There can be only one required verifier"); 2299 } 2300 2301 requiredVerifier = packageName; 2302 } 2303 2304 return requiredVerifier; 2305 } 2306 2307 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2308 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2309 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2310 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2311 2312 ComponentName verifierComponentName = null; 2313 2314 int priority = -1000; 2315 final int N = receivers.size(); 2316 for (int i = 0; i < N; i++) { 2317 final ResolveInfo info = receivers.get(i); 2318 2319 if (info.activityInfo == null) { 2320 continue; 2321 } 2322 2323 final String packageName = info.activityInfo.packageName; 2324 2325 final PackageSetting ps = mSettings.mPackages.get(packageName); 2326 if (ps == null) { 2327 continue; 2328 } 2329 2330 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2331 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2332 continue; 2333 } 2334 2335 // Select the IntentFilterVerifier with the highest priority 2336 if (priority < info.priority) { 2337 priority = info.priority; 2338 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2339 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2340 + verifierComponentName + " with priority: " + info.priority); 2341 } 2342 } 2343 2344 return verifierComponentName; 2345 } 2346 2347 private void primeDomainVerificationsLPw() { 2348 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2349 boolean updated = false; 2350 ArraySet<String> allHostsSet = new ArraySet<>(); 2351 for (PackageParser.Package pkg : mPackages.values()) { 2352 final String packageName = pkg.packageName; 2353 if (!hasDomainURLs(pkg)) { 2354 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2355 "package with no domain URLs: " + packageName); 2356 continue; 2357 } 2358 if (!pkg.isSystemApp()) { 2359 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2360 "No priming domain verifications for a non system package : " + 2361 packageName); 2362 continue; 2363 } 2364 for (PackageParser.Activity a : pkg.activities) { 2365 for (ActivityIntentInfo filter : a.intents) { 2366 if (hasValidDomains(filter)) { 2367 allHostsSet.addAll(filter.getHostsList()); 2368 } 2369 } 2370 } 2371 if (allHostsSet.size() == 0) { 2372 allHostsSet.add("*"); 2373 } 2374 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2375 IntentFilterVerificationInfo ivi = 2376 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2377 if (ivi != null) { 2378 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2379 "Priming domain verifications for package: " + packageName + 2380 " with hosts:" + ivi.getDomainsString()); 2381 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2382 updated = true; 2383 } 2384 else { 2385 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2386 "No priming domain verifications for package: " + packageName); 2387 } 2388 allHostsSet.clear(); 2389 } 2390 if (updated) { 2391 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2392 "Will need to write primed domain verifications"); 2393 } 2394 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2395 } 2396 2397 private void applyFactoryDefaultBrowserLPw(int userId) { 2398 // The default browser app's package name is stored in a string resource, 2399 // with a product-specific overlay used for vendor customization. 2400 String browserPkg = mContext.getResources().getString( 2401 com.android.internal.R.string.default_browser); 2402 if (browserPkg != null) { 2403 // non-empty string => required to be a known package 2404 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2405 if (ps == null) { 2406 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2407 browserPkg = null; 2408 } else { 2409 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2410 } 2411 } 2412 2413 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2414 // default. If there's more than one, just leave everything alone. 2415 if (browserPkg == null) { 2416 calculateDefaultBrowserLPw(userId); 2417 } 2418 } 2419 2420 private void calculateDefaultBrowserLPw(int userId) { 2421 List<String> allBrowsers = resolveAllBrowserApps(userId); 2422 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2423 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2424 } 2425 2426 private List<String> resolveAllBrowserApps(int userId) { 2427 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2428 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2429 PackageManager.MATCH_ALL, userId); 2430 2431 final int count = list.size(); 2432 List<String> result = new ArrayList<String>(count); 2433 for (int i=0; i<count; i++) { 2434 ResolveInfo info = list.get(i); 2435 if (info.activityInfo == null 2436 || !info.handleAllWebDataURI 2437 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2438 || result.contains(info.activityInfo.packageName)) { 2439 continue; 2440 } 2441 result.add(info.activityInfo.packageName); 2442 } 2443 2444 return result; 2445 } 2446 2447 private boolean packageIsBrowser(String packageName, int userId) { 2448 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2449 PackageManager.MATCH_ALL, userId); 2450 final int N = list.size(); 2451 for (int i = 0; i < N; i++) { 2452 ResolveInfo info = list.get(i); 2453 if (packageName.equals(info.activityInfo.packageName)) { 2454 return true; 2455 } 2456 } 2457 return false; 2458 } 2459 2460 private void checkDefaultBrowser() { 2461 final int myUserId = UserHandle.myUserId(); 2462 final String packageName = getDefaultBrowserPackageName(myUserId); 2463 if (packageName != null) { 2464 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2465 if (info == null) { 2466 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2467 synchronized (mPackages) { 2468 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2469 } 2470 } 2471 } 2472 } 2473 2474 @Override 2475 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2476 throws RemoteException { 2477 try { 2478 return super.onTransact(code, data, reply, flags); 2479 } catch (RuntimeException e) { 2480 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2481 Slog.wtf(TAG, "Package Manager Crash", e); 2482 } 2483 throw e; 2484 } 2485 } 2486 2487 void cleanupInstallFailedPackage(PackageSetting ps) { 2488 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2489 2490 removeDataDirsLI(ps.volumeUuid, ps.name); 2491 if (ps.codePath != null) { 2492 if (ps.codePath.isDirectory()) { 2493 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2494 } else { 2495 ps.codePath.delete(); 2496 } 2497 } 2498 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2499 if (ps.resourcePath.isDirectory()) { 2500 FileUtils.deleteContents(ps.resourcePath); 2501 } 2502 ps.resourcePath.delete(); 2503 } 2504 mSettings.removePackageLPw(ps.name); 2505 } 2506 2507 static int[] appendInts(int[] cur, int[] add) { 2508 if (add == null) return cur; 2509 if (cur == null) return add; 2510 final int N = add.length; 2511 for (int i=0; i<N; i++) { 2512 cur = appendInt(cur, add[i]); 2513 } 2514 return cur; 2515 } 2516 2517 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2518 if (!sUserManager.exists(userId)) return null; 2519 final PackageSetting ps = (PackageSetting) p.mExtras; 2520 if (ps == null) { 2521 return null; 2522 } 2523 2524 final PermissionsState permissionsState = ps.getPermissionsState(); 2525 2526 final int[] gids = permissionsState.computeGids(userId); 2527 final Set<String> permissions = permissionsState.getPermissions(userId); 2528 final PackageUserState state = ps.readUserState(userId); 2529 2530 return PackageParser.generatePackageInfo(p, gids, flags, 2531 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2532 } 2533 2534 @Override 2535 public boolean isPackageFrozen(String packageName) { 2536 synchronized (mPackages) { 2537 final PackageSetting ps = mSettings.mPackages.get(packageName); 2538 if (ps != null) { 2539 return ps.frozen; 2540 } 2541 } 2542 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2543 return true; 2544 } 2545 2546 @Override 2547 public boolean isPackageAvailable(String packageName, int userId) { 2548 if (!sUserManager.exists(userId)) return false; 2549 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2550 synchronized (mPackages) { 2551 PackageParser.Package p = mPackages.get(packageName); 2552 if (p != null) { 2553 final PackageSetting ps = (PackageSetting) p.mExtras; 2554 if (ps != null) { 2555 final PackageUserState state = ps.readUserState(userId); 2556 if (state != null) { 2557 return PackageParser.isAvailable(state); 2558 } 2559 } 2560 } 2561 } 2562 return false; 2563 } 2564 2565 @Override 2566 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2567 if (!sUserManager.exists(userId)) return null; 2568 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2569 // reader 2570 synchronized (mPackages) { 2571 PackageParser.Package p = mPackages.get(packageName); 2572 if (DEBUG_PACKAGE_INFO) 2573 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2574 if (p != null) { 2575 return generatePackageInfo(p, flags, userId); 2576 } 2577 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2578 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2579 } 2580 } 2581 return null; 2582 } 2583 2584 @Override 2585 public String[] currentToCanonicalPackageNames(String[] names) { 2586 String[] out = new String[names.length]; 2587 // reader 2588 synchronized (mPackages) { 2589 for (int i=names.length-1; i>=0; i--) { 2590 PackageSetting ps = mSettings.mPackages.get(names[i]); 2591 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2592 } 2593 } 2594 return out; 2595 } 2596 2597 @Override 2598 public String[] canonicalToCurrentPackageNames(String[] names) { 2599 String[] out = new String[names.length]; 2600 // reader 2601 synchronized (mPackages) { 2602 for (int i=names.length-1; i>=0; i--) { 2603 String cur = mSettings.mRenamedPackages.get(names[i]); 2604 out[i] = cur != null ? cur : names[i]; 2605 } 2606 } 2607 return out; 2608 } 2609 2610 @Override 2611 public int getPackageUid(String packageName, int userId) { 2612 if (!sUserManager.exists(userId)) return -1; 2613 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2614 2615 // reader 2616 synchronized (mPackages) { 2617 PackageParser.Package p = mPackages.get(packageName); 2618 if(p != null) { 2619 return UserHandle.getUid(userId, p.applicationInfo.uid); 2620 } 2621 PackageSetting ps = mSettings.mPackages.get(packageName); 2622 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2623 return -1; 2624 } 2625 p = ps.pkg; 2626 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2627 } 2628 } 2629 2630 @Override 2631 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2632 if (!sUserManager.exists(userId)) { 2633 return null; 2634 } 2635 2636 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2637 "getPackageGids"); 2638 2639 // reader 2640 synchronized (mPackages) { 2641 PackageParser.Package p = mPackages.get(packageName); 2642 if (DEBUG_PACKAGE_INFO) { 2643 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2644 } 2645 if (p != null) { 2646 PackageSetting ps = (PackageSetting) p.mExtras; 2647 return ps.getPermissionsState().computeGids(userId); 2648 } 2649 } 2650 2651 return null; 2652 } 2653 2654 @Override 2655 public int getMountExternalMode(int uid) { 2656 if (Process.isIsolated(uid)) { 2657 return Zygote.MOUNT_EXTERNAL_NONE; 2658 } else { 2659 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2660 return Zygote.MOUNT_EXTERNAL_WRITE; 2661 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2662 return Zygote.MOUNT_EXTERNAL_READ; 2663 } else { 2664 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2665 } 2666 } 2667 } 2668 2669 static PermissionInfo generatePermissionInfo( 2670 BasePermission bp, int flags) { 2671 if (bp.perm != null) { 2672 return PackageParser.generatePermissionInfo(bp.perm, flags); 2673 } 2674 PermissionInfo pi = new PermissionInfo(); 2675 pi.name = bp.name; 2676 pi.packageName = bp.sourcePackage; 2677 pi.nonLocalizedLabel = bp.name; 2678 pi.protectionLevel = bp.protectionLevel; 2679 return pi; 2680 } 2681 2682 @Override 2683 public PermissionInfo getPermissionInfo(String name, int flags) { 2684 // reader 2685 synchronized (mPackages) { 2686 final BasePermission p = mSettings.mPermissions.get(name); 2687 if (p != null) { 2688 return generatePermissionInfo(p, flags); 2689 } 2690 return null; 2691 } 2692 } 2693 2694 @Override 2695 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2696 // reader 2697 synchronized (mPackages) { 2698 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2699 for (BasePermission p : mSettings.mPermissions.values()) { 2700 if (group == null) { 2701 if (p.perm == null || p.perm.info.group == null) { 2702 out.add(generatePermissionInfo(p, flags)); 2703 } 2704 } else { 2705 if (p.perm != null && group.equals(p.perm.info.group)) { 2706 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2707 } 2708 } 2709 } 2710 2711 if (out.size() > 0) { 2712 return out; 2713 } 2714 return mPermissionGroups.containsKey(group) ? out : null; 2715 } 2716 } 2717 2718 @Override 2719 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2720 // reader 2721 synchronized (mPackages) { 2722 return PackageParser.generatePermissionGroupInfo( 2723 mPermissionGroups.get(name), flags); 2724 } 2725 } 2726 2727 @Override 2728 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2729 // reader 2730 synchronized (mPackages) { 2731 final int N = mPermissionGroups.size(); 2732 ArrayList<PermissionGroupInfo> out 2733 = new ArrayList<PermissionGroupInfo>(N); 2734 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2735 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2736 } 2737 return out; 2738 } 2739 } 2740 2741 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2742 int userId) { 2743 if (!sUserManager.exists(userId)) return null; 2744 PackageSetting ps = mSettings.mPackages.get(packageName); 2745 if (ps != null) { 2746 if (ps.pkg == null) { 2747 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2748 flags, userId); 2749 if (pInfo != null) { 2750 return pInfo.applicationInfo; 2751 } 2752 return null; 2753 } 2754 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2755 ps.readUserState(userId), userId); 2756 } 2757 return null; 2758 } 2759 2760 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2761 int userId) { 2762 if (!sUserManager.exists(userId)) return null; 2763 PackageSetting ps = mSettings.mPackages.get(packageName); 2764 if (ps != null) { 2765 PackageParser.Package pkg = ps.pkg; 2766 if (pkg == null) { 2767 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2768 return null; 2769 } 2770 // Only data remains, so we aren't worried about code paths 2771 pkg = new PackageParser.Package(packageName); 2772 pkg.applicationInfo.packageName = packageName; 2773 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2774 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2775 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2776 packageName, userId).getAbsolutePath(); 2777 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2778 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2779 } 2780 return generatePackageInfo(pkg, flags, userId); 2781 } 2782 return null; 2783 } 2784 2785 @Override 2786 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2787 if (!sUserManager.exists(userId)) return null; 2788 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2789 // writer 2790 synchronized (mPackages) { 2791 PackageParser.Package p = mPackages.get(packageName); 2792 if (DEBUG_PACKAGE_INFO) Log.v( 2793 TAG, "getApplicationInfo " + packageName 2794 + ": " + p); 2795 if (p != null) { 2796 PackageSetting ps = mSettings.mPackages.get(packageName); 2797 if (ps == null) return null; 2798 // Note: isEnabledLP() does not apply here - always return info 2799 return PackageParser.generateApplicationInfo( 2800 p, flags, ps.readUserState(userId), userId); 2801 } 2802 if ("android".equals(packageName)||"system".equals(packageName)) { 2803 return mAndroidApplication; 2804 } 2805 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2806 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2807 } 2808 } 2809 return null; 2810 } 2811 2812 @Override 2813 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2814 final IPackageDataObserver observer) { 2815 mContext.enforceCallingOrSelfPermission( 2816 android.Manifest.permission.CLEAR_APP_CACHE, null); 2817 // Queue up an async operation since clearing cache may take a little while. 2818 mHandler.post(new Runnable() { 2819 public void run() { 2820 mHandler.removeCallbacks(this); 2821 int retCode = -1; 2822 synchronized (mInstallLock) { 2823 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2824 if (retCode < 0) { 2825 Slog.w(TAG, "Couldn't clear application caches"); 2826 } 2827 } 2828 if (observer != null) { 2829 try { 2830 observer.onRemoveCompleted(null, (retCode >= 0)); 2831 } catch (RemoteException e) { 2832 Slog.w(TAG, "RemoveException when invoking call back"); 2833 } 2834 } 2835 } 2836 }); 2837 } 2838 2839 @Override 2840 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2841 final IntentSender pi) { 2842 mContext.enforceCallingOrSelfPermission( 2843 android.Manifest.permission.CLEAR_APP_CACHE, null); 2844 // Queue up an async operation since clearing cache may take a little while. 2845 mHandler.post(new Runnable() { 2846 public void run() { 2847 mHandler.removeCallbacks(this); 2848 int retCode = -1; 2849 synchronized (mInstallLock) { 2850 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2851 if (retCode < 0) { 2852 Slog.w(TAG, "Couldn't clear application caches"); 2853 } 2854 } 2855 if(pi != null) { 2856 try { 2857 // Callback via pending intent 2858 int code = (retCode >= 0) ? 1 : 0; 2859 pi.sendIntent(null, code, null, 2860 null, null); 2861 } catch (SendIntentException e1) { 2862 Slog.i(TAG, "Failed to send pending intent"); 2863 } 2864 } 2865 } 2866 }); 2867 } 2868 2869 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2870 synchronized (mInstallLock) { 2871 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2872 throw new IOException("Failed to free enough space"); 2873 } 2874 } 2875 } 2876 2877 @Override 2878 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2879 if (!sUserManager.exists(userId)) return null; 2880 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2881 synchronized (mPackages) { 2882 PackageParser.Activity a = mActivities.mActivities.get(component); 2883 2884 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2885 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2886 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2887 if (ps == null) return null; 2888 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2889 userId); 2890 } 2891 if (mResolveComponentName.equals(component)) { 2892 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2893 new PackageUserState(), userId); 2894 } 2895 } 2896 return null; 2897 } 2898 2899 @Override 2900 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2901 String resolvedType) { 2902 synchronized (mPackages) { 2903 PackageParser.Activity a = mActivities.mActivities.get(component); 2904 if (a == null) { 2905 return false; 2906 } 2907 for (int i=0; i<a.intents.size(); i++) { 2908 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2909 intent.getData(), intent.getCategories(), TAG) >= 0) { 2910 return true; 2911 } 2912 } 2913 return false; 2914 } 2915 } 2916 2917 @Override 2918 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2919 if (!sUserManager.exists(userId)) return null; 2920 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2921 synchronized (mPackages) { 2922 PackageParser.Activity a = mReceivers.mActivities.get(component); 2923 if (DEBUG_PACKAGE_INFO) Log.v( 2924 TAG, "getReceiverInfo " + component + ": " + a); 2925 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2926 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2927 if (ps == null) return null; 2928 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2929 userId); 2930 } 2931 } 2932 return null; 2933 } 2934 2935 @Override 2936 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2937 if (!sUserManager.exists(userId)) return null; 2938 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2939 synchronized (mPackages) { 2940 PackageParser.Service s = mServices.mServices.get(component); 2941 if (DEBUG_PACKAGE_INFO) Log.v( 2942 TAG, "getServiceInfo " + component + ": " + s); 2943 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2944 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2945 if (ps == null) return null; 2946 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2947 userId); 2948 } 2949 } 2950 return null; 2951 } 2952 2953 @Override 2954 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2955 if (!sUserManager.exists(userId)) return null; 2956 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2957 synchronized (mPackages) { 2958 PackageParser.Provider p = mProviders.mProviders.get(component); 2959 if (DEBUG_PACKAGE_INFO) Log.v( 2960 TAG, "getProviderInfo " + component + ": " + p); 2961 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2962 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2963 if (ps == null) return null; 2964 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2965 userId); 2966 } 2967 } 2968 return null; 2969 } 2970 2971 @Override 2972 public String[] getSystemSharedLibraryNames() { 2973 Set<String> libSet; 2974 synchronized (mPackages) { 2975 libSet = mSharedLibraries.keySet(); 2976 int size = libSet.size(); 2977 if (size > 0) { 2978 String[] libs = new String[size]; 2979 libSet.toArray(libs); 2980 return libs; 2981 } 2982 } 2983 return null; 2984 } 2985 2986 /** 2987 * @hide 2988 */ 2989 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2990 synchronized (mPackages) { 2991 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2992 if (lib != null && lib.apk != null) { 2993 return mPackages.get(lib.apk); 2994 } 2995 } 2996 return null; 2997 } 2998 2999 @Override 3000 public FeatureInfo[] getSystemAvailableFeatures() { 3001 Collection<FeatureInfo> featSet; 3002 synchronized (mPackages) { 3003 featSet = mAvailableFeatures.values(); 3004 int size = featSet.size(); 3005 if (size > 0) { 3006 FeatureInfo[] features = new FeatureInfo[size+1]; 3007 featSet.toArray(features); 3008 FeatureInfo fi = new FeatureInfo(); 3009 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3010 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3011 features[size] = fi; 3012 return features; 3013 } 3014 } 3015 return null; 3016 } 3017 3018 @Override 3019 public boolean hasSystemFeature(String name) { 3020 synchronized (mPackages) { 3021 return mAvailableFeatures.containsKey(name); 3022 } 3023 } 3024 3025 private void checkValidCaller(int uid, int userId) { 3026 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3027 return; 3028 3029 throw new SecurityException("Caller uid=" + uid 3030 + " is not privileged to communicate with user=" + userId); 3031 } 3032 3033 @Override 3034 public int checkPermission(String permName, String pkgName, int userId) { 3035 if (!sUserManager.exists(userId)) { 3036 return PackageManager.PERMISSION_DENIED; 3037 } 3038 3039 synchronized (mPackages) { 3040 final PackageParser.Package p = mPackages.get(pkgName); 3041 if (p != null && p.mExtras != null) { 3042 final PackageSetting ps = (PackageSetting) p.mExtras; 3043 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3044 return PackageManager.PERMISSION_GRANTED; 3045 } 3046 } 3047 } 3048 3049 return PackageManager.PERMISSION_DENIED; 3050 } 3051 3052 @Override 3053 public int checkUidPermission(String permName, int uid) { 3054 final int userId = UserHandle.getUserId(uid); 3055 3056 if (!sUserManager.exists(userId)) { 3057 return PackageManager.PERMISSION_DENIED; 3058 } 3059 3060 synchronized (mPackages) { 3061 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3062 if (obj != null) { 3063 final SettingBase ps = (SettingBase) obj; 3064 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3065 return PackageManager.PERMISSION_GRANTED; 3066 } 3067 } else { 3068 ArraySet<String> perms = mSystemPermissions.get(uid); 3069 if (perms != null && perms.contains(permName)) { 3070 return PackageManager.PERMISSION_GRANTED; 3071 } 3072 } 3073 } 3074 3075 return PackageManager.PERMISSION_DENIED; 3076 } 3077 3078 /** 3079 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3080 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3081 * @param checkShell TODO(yamasani): 3082 * @param message the message to log on security exception 3083 */ 3084 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3085 boolean checkShell, String message) { 3086 if (userId < 0) { 3087 throw new IllegalArgumentException("Invalid userId " + userId); 3088 } 3089 if (checkShell) { 3090 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3091 } 3092 if (userId == UserHandle.getUserId(callingUid)) return; 3093 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3094 if (requireFullPermission) { 3095 mContext.enforceCallingOrSelfPermission( 3096 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3097 } else { 3098 try { 3099 mContext.enforceCallingOrSelfPermission( 3100 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3101 } catch (SecurityException se) { 3102 mContext.enforceCallingOrSelfPermission( 3103 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3104 } 3105 } 3106 } 3107 } 3108 3109 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3110 if (callingUid == Process.SHELL_UID) { 3111 if (userHandle >= 0 3112 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3113 throw new SecurityException("Shell does not have permission to access user " 3114 + userHandle); 3115 } else if (userHandle < 0) { 3116 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3117 + Debug.getCallers(3)); 3118 } 3119 } 3120 } 3121 3122 private BasePermission findPermissionTreeLP(String permName) { 3123 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3124 if (permName.startsWith(bp.name) && 3125 permName.length() > bp.name.length() && 3126 permName.charAt(bp.name.length()) == '.') { 3127 return bp; 3128 } 3129 } 3130 return null; 3131 } 3132 3133 private BasePermission checkPermissionTreeLP(String permName) { 3134 if (permName != null) { 3135 BasePermission bp = findPermissionTreeLP(permName); 3136 if (bp != null) { 3137 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3138 return bp; 3139 } 3140 throw new SecurityException("Calling uid " 3141 + Binder.getCallingUid() 3142 + " is not allowed to add to permission tree " 3143 + bp.name + " owned by uid " + bp.uid); 3144 } 3145 } 3146 throw new SecurityException("No permission tree found for " + permName); 3147 } 3148 3149 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3150 if (s1 == null) { 3151 return s2 == null; 3152 } 3153 if (s2 == null) { 3154 return false; 3155 } 3156 if (s1.getClass() != s2.getClass()) { 3157 return false; 3158 } 3159 return s1.equals(s2); 3160 } 3161 3162 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3163 if (pi1.icon != pi2.icon) return false; 3164 if (pi1.logo != pi2.logo) return false; 3165 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3166 if (!compareStrings(pi1.name, pi2.name)) return false; 3167 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3168 // We'll take care of setting this one. 3169 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3170 // These are not currently stored in settings. 3171 //if (!compareStrings(pi1.group, pi2.group)) return false; 3172 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3173 //if (pi1.labelRes != pi2.labelRes) return false; 3174 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3175 return true; 3176 } 3177 3178 int permissionInfoFootprint(PermissionInfo info) { 3179 int size = info.name.length(); 3180 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3181 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3182 return size; 3183 } 3184 3185 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3186 int size = 0; 3187 for (BasePermission perm : mSettings.mPermissions.values()) { 3188 if (perm.uid == tree.uid) { 3189 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3190 } 3191 } 3192 return size; 3193 } 3194 3195 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3196 // We calculate the max size of permissions defined by this uid and throw 3197 // if that plus the size of 'info' would exceed our stated maximum. 3198 if (tree.uid != Process.SYSTEM_UID) { 3199 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3200 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3201 throw new SecurityException("Permission tree size cap exceeded"); 3202 } 3203 } 3204 } 3205 3206 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3207 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3208 throw new SecurityException("Label must be specified in permission"); 3209 } 3210 BasePermission tree = checkPermissionTreeLP(info.name); 3211 BasePermission bp = mSettings.mPermissions.get(info.name); 3212 boolean added = bp == null; 3213 boolean changed = true; 3214 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3215 if (added) { 3216 enforcePermissionCapLocked(info, tree); 3217 bp = new BasePermission(info.name, tree.sourcePackage, 3218 BasePermission.TYPE_DYNAMIC); 3219 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3220 throw new SecurityException( 3221 "Not allowed to modify non-dynamic permission " 3222 + info.name); 3223 } else { 3224 if (bp.protectionLevel == fixedLevel 3225 && bp.perm.owner.equals(tree.perm.owner) 3226 && bp.uid == tree.uid 3227 && comparePermissionInfos(bp.perm.info, info)) { 3228 changed = false; 3229 } 3230 } 3231 bp.protectionLevel = fixedLevel; 3232 info = new PermissionInfo(info); 3233 info.protectionLevel = fixedLevel; 3234 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3235 bp.perm.info.packageName = tree.perm.info.packageName; 3236 bp.uid = tree.uid; 3237 if (added) { 3238 mSettings.mPermissions.put(info.name, bp); 3239 } 3240 if (changed) { 3241 if (!async) { 3242 mSettings.writeLPr(); 3243 } else { 3244 scheduleWriteSettingsLocked(); 3245 } 3246 } 3247 return added; 3248 } 3249 3250 @Override 3251 public boolean addPermission(PermissionInfo info) { 3252 synchronized (mPackages) { 3253 return addPermissionLocked(info, false); 3254 } 3255 } 3256 3257 @Override 3258 public boolean addPermissionAsync(PermissionInfo info) { 3259 synchronized (mPackages) { 3260 return addPermissionLocked(info, true); 3261 } 3262 } 3263 3264 @Override 3265 public void removePermission(String name) { 3266 synchronized (mPackages) { 3267 checkPermissionTreeLP(name); 3268 BasePermission bp = mSettings.mPermissions.get(name); 3269 if (bp != null) { 3270 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3271 throw new SecurityException( 3272 "Not allowed to modify non-dynamic permission " 3273 + name); 3274 } 3275 mSettings.mPermissions.remove(name); 3276 mSettings.writeLPr(); 3277 } 3278 } 3279 } 3280 3281 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3282 BasePermission bp) { 3283 int index = pkg.requestedPermissions.indexOf(bp.name); 3284 if (index == -1) { 3285 throw new SecurityException("Package " + pkg.packageName 3286 + " has not requested permission " + bp.name); 3287 } 3288 if (!bp.isRuntime()) { 3289 throw new SecurityException("Permission " + bp.name 3290 + " is not a changeable permission type"); 3291 } 3292 } 3293 3294 @Override 3295 public void grantRuntimePermission(String packageName, String name, final int userId) { 3296 if (!sUserManager.exists(userId)) { 3297 Log.e(TAG, "No such user:" + userId); 3298 return; 3299 } 3300 3301 mContext.enforceCallingOrSelfPermission( 3302 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3303 "grantRuntimePermission"); 3304 3305 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3306 "grantRuntimePermission"); 3307 3308 final int uid; 3309 final SettingBase sb; 3310 3311 synchronized (mPackages) { 3312 final PackageParser.Package pkg = mPackages.get(packageName); 3313 if (pkg == null) { 3314 throw new IllegalArgumentException("Unknown package: " + packageName); 3315 } 3316 3317 final BasePermission bp = mSettings.mPermissions.get(name); 3318 if (bp == null) { 3319 throw new IllegalArgumentException("Unknown permission: " + name); 3320 } 3321 3322 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3323 3324 uid = pkg.applicationInfo.uid; 3325 sb = (SettingBase) pkg.mExtras; 3326 if (sb == null) { 3327 throw new IllegalArgumentException("Unknown package: " + packageName); 3328 } 3329 3330 final PermissionsState permissionsState = sb.getPermissionsState(); 3331 3332 final int flags = permissionsState.getPermissionFlags(name, userId); 3333 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3334 throw new SecurityException("Cannot grant system fixed permission: " 3335 + name + " for package: " + packageName); 3336 } 3337 3338 final int result = permissionsState.grantRuntimePermission(bp, userId); 3339 switch (result) { 3340 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3341 return; 3342 } 3343 3344 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3345 mHandler.post(new Runnable() { 3346 @Override 3347 public void run() { 3348 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3349 } 3350 }); 3351 } break; 3352 } 3353 3354 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3355 3356 // Not critical if that is lost - app has to request again. 3357 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3358 } 3359 3360 if (READ_EXTERNAL_STORAGE.equals(name) 3361 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3362 final long token = Binder.clearCallingIdentity(); 3363 try { 3364 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3365 storage.remountUid(uid); 3366 } finally { 3367 Binder.restoreCallingIdentity(token); 3368 } 3369 } 3370 } 3371 3372 @Override 3373 public void revokeRuntimePermission(String packageName, String name, int userId) { 3374 if (!sUserManager.exists(userId)) { 3375 Log.e(TAG, "No such user:" + userId); 3376 return; 3377 } 3378 3379 mContext.enforceCallingOrSelfPermission( 3380 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3381 "revokeRuntimePermission"); 3382 3383 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3384 "revokeRuntimePermission"); 3385 3386 final SettingBase sb; 3387 3388 synchronized (mPackages) { 3389 final PackageParser.Package pkg = mPackages.get(packageName); 3390 if (pkg == null) { 3391 throw new IllegalArgumentException("Unknown package: " + packageName); 3392 } 3393 3394 final BasePermission bp = mSettings.mPermissions.get(name); 3395 if (bp == null) { 3396 throw new IllegalArgumentException("Unknown permission: " + name); 3397 } 3398 3399 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3400 3401 sb = (SettingBase) pkg.mExtras; 3402 if (sb == null) { 3403 throw new IllegalArgumentException("Unknown package: " + packageName); 3404 } 3405 3406 final PermissionsState permissionsState = sb.getPermissionsState(); 3407 3408 final int flags = permissionsState.getPermissionFlags(name, userId); 3409 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3410 throw new SecurityException("Cannot revoke system fixed permission: " 3411 + name + " for package: " + packageName); 3412 } 3413 3414 if (permissionsState.revokeRuntimePermission(bp, userId) == 3415 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3416 return; 3417 } 3418 3419 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3420 3421 // Critical, after this call app should never have the permission. 3422 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3423 } 3424 3425 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3426 } 3427 3428 @Override 3429 public void resetRuntimePermissions() { 3430 mContext.enforceCallingOrSelfPermission( 3431 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3432 "revokeRuntimePermission"); 3433 3434 int callingUid = Binder.getCallingUid(); 3435 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3436 mContext.enforceCallingOrSelfPermission( 3437 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3438 "resetRuntimePermissions"); 3439 } 3440 3441 final int[] userIds; 3442 3443 synchronized (mPackages) { 3444 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3445 final int userCount = UserManagerService.getInstance().getUserIds().length; 3446 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3447 } 3448 3449 for (int userId : userIds) { 3450 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3451 } 3452 } 3453 3454 @Override 3455 public int getPermissionFlags(String name, String packageName, int userId) { 3456 if (!sUserManager.exists(userId)) { 3457 return 0; 3458 } 3459 3460 mContext.enforceCallingOrSelfPermission( 3461 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3462 "getPermissionFlags"); 3463 3464 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3465 "getPermissionFlags"); 3466 3467 synchronized (mPackages) { 3468 final PackageParser.Package pkg = mPackages.get(packageName); 3469 if (pkg == null) { 3470 throw new IllegalArgumentException("Unknown package: " + packageName); 3471 } 3472 3473 final BasePermission bp = mSettings.mPermissions.get(name); 3474 if (bp == null) { 3475 throw new IllegalArgumentException("Unknown permission: " + name); 3476 } 3477 3478 SettingBase sb = (SettingBase) pkg.mExtras; 3479 if (sb == null) { 3480 throw new IllegalArgumentException("Unknown package: " + packageName); 3481 } 3482 3483 PermissionsState permissionsState = sb.getPermissionsState(); 3484 return permissionsState.getPermissionFlags(name, userId); 3485 } 3486 } 3487 3488 @Override 3489 public void updatePermissionFlags(String name, String packageName, int flagMask, 3490 int flagValues, int userId) { 3491 if (!sUserManager.exists(userId)) { 3492 return; 3493 } 3494 3495 mContext.enforceCallingOrSelfPermission( 3496 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3497 "updatePermissionFlags"); 3498 3499 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3500 "updatePermissionFlags"); 3501 3502 // Only the system can change system fixed flags. 3503 if (getCallingUid() != Process.SYSTEM_UID) { 3504 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3505 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3506 } 3507 3508 synchronized (mPackages) { 3509 final PackageParser.Package pkg = mPackages.get(packageName); 3510 if (pkg == null) { 3511 throw new IllegalArgumentException("Unknown package: " + packageName); 3512 } 3513 3514 final BasePermission bp = mSettings.mPermissions.get(name); 3515 if (bp == null) { 3516 throw new IllegalArgumentException("Unknown permission: " + name); 3517 } 3518 3519 SettingBase sb = (SettingBase) pkg.mExtras; 3520 if (sb == null) { 3521 throw new IllegalArgumentException("Unknown package: " + packageName); 3522 } 3523 3524 PermissionsState permissionsState = sb.getPermissionsState(); 3525 3526 // Only the package manager can change flags for system component permissions. 3527 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3528 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3529 return; 3530 } 3531 3532 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3533 3534 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3535 // Install and runtime permissions are stored in different places, 3536 // so figure out what permission changed and persist the change. 3537 if (permissionsState.getInstallPermissionState(name) != null) { 3538 scheduleWriteSettingsLocked(); 3539 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3540 || hadState) { 3541 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3542 } 3543 } 3544 } 3545 } 3546 3547 /** 3548 * Update the permission flags for all packages and runtime permissions of a user in order 3549 * to allow device or profile owner to remove POLICY_FIXED. 3550 */ 3551 @Override 3552 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3553 if (!sUserManager.exists(userId)) { 3554 return; 3555 } 3556 3557 mContext.enforceCallingOrSelfPermission( 3558 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3559 "updatePermissionFlagsForAllApps"); 3560 3561 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3562 "updatePermissionFlagsForAllApps"); 3563 3564 // Only the system can change system fixed flags. 3565 if (getCallingUid() != Process.SYSTEM_UID) { 3566 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3567 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3568 } 3569 3570 synchronized (mPackages) { 3571 boolean changed = false; 3572 final int packageCount = mPackages.size(); 3573 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3574 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3575 SettingBase sb = (SettingBase) pkg.mExtras; 3576 if (sb == null) { 3577 continue; 3578 } 3579 PermissionsState permissionsState = sb.getPermissionsState(); 3580 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3581 userId, flagMask, flagValues); 3582 } 3583 if (changed) { 3584 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3585 } 3586 } 3587 } 3588 3589 @Override 3590 public boolean shouldShowRequestPermissionRationale(String permissionName, 3591 String packageName, int userId) { 3592 if (UserHandle.getCallingUserId() != userId) { 3593 mContext.enforceCallingPermission( 3594 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3595 "canShowRequestPermissionRationale for user " + userId); 3596 } 3597 3598 final int uid = getPackageUid(packageName, userId); 3599 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3600 return false; 3601 } 3602 3603 if (checkPermission(permissionName, packageName, userId) 3604 == PackageManager.PERMISSION_GRANTED) { 3605 return false; 3606 } 3607 3608 final int flags; 3609 3610 final long identity = Binder.clearCallingIdentity(); 3611 try { 3612 flags = getPermissionFlags(permissionName, 3613 packageName, userId); 3614 } finally { 3615 Binder.restoreCallingIdentity(identity); 3616 } 3617 3618 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3619 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3620 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3621 3622 if ((flags & fixedFlags) != 0) { 3623 return false; 3624 } 3625 3626 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3627 } 3628 3629 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3630 BasePermission bp = mSettings.mPermissions.get(permission); 3631 if (bp == null) { 3632 throw new SecurityException("Missing " + permission + " permission"); 3633 } 3634 3635 SettingBase sb = (SettingBase) pkg.mExtras; 3636 PermissionsState permissionsState = sb.getPermissionsState(); 3637 3638 if (permissionsState.grantInstallPermission(bp) != 3639 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3640 scheduleWriteSettingsLocked(); 3641 } 3642 } 3643 3644 @Override 3645 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3646 mContext.enforceCallingOrSelfPermission( 3647 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3648 "addOnPermissionsChangeListener"); 3649 3650 synchronized (mPackages) { 3651 mOnPermissionChangeListeners.addListenerLocked(listener); 3652 } 3653 } 3654 3655 @Override 3656 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3657 synchronized (mPackages) { 3658 mOnPermissionChangeListeners.removeListenerLocked(listener); 3659 } 3660 } 3661 3662 @Override 3663 public boolean isProtectedBroadcast(String actionName) { 3664 synchronized (mPackages) { 3665 return mProtectedBroadcasts.contains(actionName); 3666 } 3667 } 3668 3669 @Override 3670 public int checkSignatures(String pkg1, String pkg2) { 3671 synchronized (mPackages) { 3672 final PackageParser.Package p1 = mPackages.get(pkg1); 3673 final PackageParser.Package p2 = mPackages.get(pkg2); 3674 if (p1 == null || p1.mExtras == null 3675 || p2 == null || p2.mExtras == null) { 3676 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3677 } 3678 return compareSignatures(p1.mSignatures, p2.mSignatures); 3679 } 3680 } 3681 3682 @Override 3683 public int checkUidSignatures(int uid1, int uid2) { 3684 // Map to base uids. 3685 uid1 = UserHandle.getAppId(uid1); 3686 uid2 = UserHandle.getAppId(uid2); 3687 // reader 3688 synchronized (mPackages) { 3689 Signature[] s1; 3690 Signature[] s2; 3691 Object obj = mSettings.getUserIdLPr(uid1); 3692 if (obj != null) { 3693 if (obj instanceof SharedUserSetting) { 3694 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3695 } else if (obj instanceof PackageSetting) { 3696 s1 = ((PackageSetting)obj).signatures.mSignatures; 3697 } else { 3698 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3699 } 3700 } else { 3701 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3702 } 3703 obj = mSettings.getUserIdLPr(uid2); 3704 if (obj != null) { 3705 if (obj instanceof SharedUserSetting) { 3706 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3707 } else if (obj instanceof PackageSetting) { 3708 s2 = ((PackageSetting)obj).signatures.mSignatures; 3709 } else { 3710 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3711 } 3712 } else { 3713 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3714 } 3715 return compareSignatures(s1, s2); 3716 } 3717 } 3718 3719 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3720 final long identity = Binder.clearCallingIdentity(); 3721 try { 3722 if (sb instanceof SharedUserSetting) { 3723 SharedUserSetting sus = (SharedUserSetting) sb; 3724 final int packageCount = sus.packages.size(); 3725 for (int i = 0; i < packageCount; i++) { 3726 PackageSetting susPs = sus.packages.valueAt(i); 3727 if (userId == UserHandle.USER_ALL) { 3728 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3729 } else { 3730 final int uid = UserHandle.getUid(userId, susPs.appId); 3731 killUid(uid, reason); 3732 } 3733 } 3734 } else if (sb instanceof PackageSetting) { 3735 PackageSetting ps = (PackageSetting) sb; 3736 if (userId == UserHandle.USER_ALL) { 3737 killApplication(ps.pkg.packageName, ps.appId, reason); 3738 } else { 3739 final int uid = UserHandle.getUid(userId, ps.appId); 3740 killUid(uid, reason); 3741 } 3742 } 3743 } finally { 3744 Binder.restoreCallingIdentity(identity); 3745 } 3746 } 3747 3748 private static void killUid(int uid, String reason) { 3749 IActivityManager am = ActivityManagerNative.getDefault(); 3750 if (am != null) { 3751 try { 3752 am.killUid(uid, reason); 3753 } catch (RemoteException e) { 3754 /* ignore - same process */ 3755 } 3756 } 3757 } 3758 3759 /** 3760 * Compares two sets of signatures. Returns: 3761 * <br /> 3762 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3763 * <br /> 3764 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3765 * <br /> 3766 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3767 * <br /> 3768 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3769 * <br /> 3770 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3771 */ 3772 static int compareSignatures(Signature[] s1, Signature[] s2) { 3773 if (s1 == null) { 3774 return s2 == null 3775 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3776 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3777 } 3778 3779 if (s2 == null) { 3780 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3781 } 3782 3783 if (s1.length != s2.length) { 3784 return PackageManager.SIGNATURE_NO_MATCH; 3785 } 3786 3787 // Since both signature sets are of size 1, we can compare without HashSets. 3788 if (s1.length == 1) { 3789 return s1[0].equals(s2[0]) ? 3790 PackageManager.SIGNATURE_MATCH : 3791 PackageManager.SIGNATURE_NO_MATCH; 3792 } 3793 3794 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3795 for (Signature sig : s1) { 3796 set1.add(sig); 3797 } 3798 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3799 for (Signature sig : s2) { 3800 set2.add(sig); 3801 } 3802 // Make sure s2 contains all signatures in s1. 3803 if (set1.equals(set2)) { 3804 return PackageManager.SIGNATURE_MATCH; 3805 } 3806 return PackageManager.SIGNATURE_NO_MATCH; 3807 } 3808 3809 /** 3810 * If the database version for this type of package (internal storage or 3811 * external storage) is less than the version where package signatures 3812 * were updated, return true. 3813 */ 3814 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3815 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3816 DatabaseVersion.SIGNATURE_END_ENTITY)) 3817 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3818 DatabaseVersion.SIGNATURE_END_ENTITY)); 3819 } 3820 3821 /** 3822 * Used for backward compatibility to make sure any packages with 3823 * certificate chains get upgraded to the new style. {@code existingSigs} 3824 * will be in the old format (since they were stored on disk from before the 3825 * system upgrade) and {@code scannedSigs} will be in the newer format. 3826 */ 3827 private int compareSignaturesCompat(PackageSignatures existingSigs, 3828 PackageParser.Package scannedPkg) { 3829 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3830 return PackageManager.SIGNATURE_NO_MATCH; 3831 } 3832 3833 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3834 for (Signature sig : existingSigs.mSignatures) { 3835 existingSet.add(sig); 3836 } 3837 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3838 for (Signature sig : scannedPkg.mSignatures) { 3839 try { 3840 Signature[] chainSignatures = sig.getChainSignatures(); 3841 for (Signature chainSig : chainSignatures) { 3842 scannedCompatSet.add(chainSig); 3843 } 3844 } catch (CertificateEncodingException e) { 3845 scannedCompatSet.add(sig); 3846 } 3847 } 3848 /* 3849 * Make sure the expanded scanned set contains all signatures in the 3850 * existing one. 3851 */ 3852 if (scannedCompatSet.equals(existingSet)) { 3853 // Migrate the old signatures to the new scheme. 3854 existingSigs.assignSignatures(scannedPkg.mSignatures); 3855 // The new KeySets will be re-added later in the scanning process. 3856 synchronized (mPackages) { 3857 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3858 } 3859 return PackageManager.SIGNATURE_MATCH; 3860 } 3861 return PackageManager.SIGNATURE_NO_MATCH; 3862 } 3863 3864 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3865 if (isExternal(scannedPkg)) { 3866 return mSettings.isExternalDatabaseVersionOlderThan( 3867 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3868 } else { 3869 return mSettings.isInternalDatabaseVersionOlderThan( 3870 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3871 } 3872 } 3873 3874 private int compareSignaturesRecover(PackageSignatures existingSigs, 3875 PackageParser.Package scannedPkg) { 3876 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3877 return PackageManager.SIGNATURE_NO_MATCH; 3878 } 3879 3880 String msg = null; 3881 try { 3882 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3883 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3884 + scannedPkg.packageName); 3885 return PackageManager.SIGNATURE_MATCH; 3886 } 3887 } catch (CertificateException e) { 3888 msg = e.getMessage(); 3889 } 3890 3891 logCriticalInfo(Log.INFO, 3892 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3893 return PackageManager.SIGNATURE_NO_MATCH; 3894 } 3895 3896 @Override 3897 public String[] getPackagesForUid(int uid) { 3898 uid = UserHandle.getAppId(uid); 3899 // reader 3900 synchronized (mPackages) { 3901 Object obj = mSettings.getUserIdLPr(uid); 3902 if (obj instanceof SharedUserSetting) { 3903 final SharedUserSetting sus = (SharedUserSetting) obj; 3904 final int N = sus.packages.size(); 3905 final String[] res = new String[N]; 3906 final Iterator<PackageSetting> it = sus.packages.iterator(); 3907 int i = 0; 3908 while (it.hasNext()) { 3909 res[i++] = it.next().name; 3910 } 3911 return res; 3912 } else if (obj instanceof PackageSetting) { 3913 final PackageSetting ps = (PackageSetting) obj; 3914 return new String[] { ps.name }; 3915 } 3916 } 3917 return null; 3918 } 3919 3920 @Override 3921 public String getNameForUid(int uid) { 3922 // reader 3923 synchronized (mPackages) { 3924 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3925 if (obj instanceof SharedUserSetting) { 3926 final SharedUserSetting sus = (SharedUserSetting) obj; 3927 return sus.name + ":" + sus.userId; 3928 } else if (obj instanceof PackageSetting) { 3929 final PackageSetting ps = (PackageSetting) obj; 3930 return ps.name; 3931 } 3932 } 3933 return null; 3934 } 3935 3936 @Override 3937 public int getUidForSharedUser(String sharedUserName) { 3938 if(sharedUserName == null) { 3939 return -1; 3940 } 3941 // reader 3942 synchronized (mPackages) { 3943 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3944 if (suid == null) { 3945 return -1; 3946 } 3947 return suid.userId; 3948 } 3949 } 3950 3951 @Override 3952 public int getFlagsForUid(int uid) { 3953 synchronized (mPackages) { 3954 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3955 if (obj instanceof SharedUserSetting) { 3956 final SharedUserSetting sus = (SharedUserSetting) obj; 3957 return sus.pkgFlags; 3958 } else if (obj instanceof PackageSetting) { 3959 final PackageSetting ps = (PackageSetting) obj; 3960 return ps.pkgFlags; 3961 } 3962 } 3963 return 0; 3964 } 3965 3966 @Override 3967 public int getPrivateFlagsForUid(int uid) { 3968 synchronized (mPackages) { 3969 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3970 if (obj instanceof SharedUserSetting) { 3971 final SharedUserSetting sus = (SharedUserSetting) obj; 3972 return sus.pkgPrivateFlags; 3973 } else if (obj instanceof PackageSetting) { 3974 final PackageSetting ps = (PackageSetting) obj; 3975 return ps.pkgPrivateFlags; 3976 } 3977 } 3978 return 0; 3979 } 3980 3981 @Override 3982 public boolean isUidPrivileged(int uid) { 3983 uid = UserHandle.getAppId(uid); 3984 // reader 3985 synchronized (mPackages) { 3986 Object obj = mSettings.getUserIdLPr(uid); 3987 if (obj instanceof SharedUserSetting) { 3988 final SharedUserSetting sus = (SharedUserSetting) obj; 3989 final Iterator<PackageSetting> it = sus.packages.iterator(); 3990 while (it.hasNext()) { 3991 if (it.next().isPrivileged()) { 3992 return true; 3993 } 3994 } 3995 } else if (obj instanceof PackageSetting) { 3996 final PackageSetting ps = (PackageSetting) obj; 3997 return ps.isPrivileged(); 3998 } 3999 } 4000 return false; 4001 } 4002 4003 @Override 4004 public String[] getAppOpPermissionPackages(String permissionName) { 4005 synchronized (mPackages) { 4006 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4007 if (pkgs == null) { 4008 return null; 4009 } 4010 return pkgs.toArray(new String[pkgs.size()]); 4011 } 4012 } 4013 4014 @Override 4015 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4016 int flags, int userId) { 4017 if (!sUserManager.exists(userId)) return null; 4018 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4019 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4020 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4021 } 4022 4023 @Override 4024 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4025 IntentFilter filter, int match, ComponentName activity) { 4026 final int userId = UserHandle.getCallingUserId(); 4027 if (DEBUG_PREFERRED) { 4028 Log.v(TAG, "setLastChosenActivity intent=" + intent 4029 + " resolvedType=" + resolvedType 4030 + " flags=" + flags 4031 + " filter=" + filter 4032 + " match=" + match 4033 + " activity=" + activity); 4034 filter.dump(new PrintStreamPrinter(System.out), " "); 4035 } 4036 intent.setComponent(null); 4037 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4038 // Find any earlier preferred or last chosen entries and nuke them 4039 findPreferredActivity(intent, resolvedType, 4040 flags, query, 0, false, true, false, userId); 4041 // Add the new activity as the last chosen for this filter 4042 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4043 "Setting last chosen"); 4044 } 4045 4046 @Override 4047 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4048 final int userId = UserHandle.getCallingUserId(); 4049 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4050 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4051 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4052 false, false, false, userId); 4053 } 4054 4055 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4056 int flags, List<ResolveInfo> query, int userId) { 4057 if (query != null) { 4058 final int N = query.size(); 4059 if (N == 1) { 4060 return query.get(0); 4061 } else if (N > 1) { 4062 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4063 // If there is more than one activity with the same priority, 4064 // then let the user decide between them. 4065 ResolveInfo r0 = query.get(0); 4066 ResolveInfo r1 = query.get(1); 4067 if (DEBUG_INTENT_MATCHING || debug) { 4068 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4069 + r1.activityInfo.name + "=" + r1.priority); 4070 } 4071 // If the first activity has a higher priority, or a different 4072 // default, then it is always desireable to pick it. 4073 if (r0.priority != r1.priority 4074 || r0.preferredOrder != r1.preferredOrder 4075 || r0.isDefault != r1.isDefault) { 4076 return query.get(0); 4077 } 4078 // If we have saved a preference for a preferred activity for 4079 // this Intent, use that. 4080 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4081 flags, query, r0.priority, true, false, debug, userId); 4082 if (ri != null) { 4083 return ri; 4084 } 4085 if (userId != 0) { 4086 ri = new ResolveInfo(mResolveInfo); 4087 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4088 ri.activityInfo.applicationInfo = new ApplicationInfo( 4089 ri.activityInfo.applicationInfo); 4090 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4091 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4092 return ri; 4093 } 4094 return mResolveInfo; 4095 } 4096 } 4097 return null; 4098 } 4099 4100 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4101 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4102 final int N = query.size(); 4103 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4104 .get(userId); 4105 // Get the list of persistent preferred activities that handle the intent 4106 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4107 List<PersistentPreferredActivity> pprefs = ppir != null 4108 ? ppir.queryIntent(intent, resolvedType, 4109 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4110 : null; 4111 if (pprefs != null && pprefs.size() > 0) { 4112 final int M = pprefs.size(); 4113 for (int i=0; i<M; i++) { 4114 final PersistentPreferredActivity ppa = pprefs.get(i); 4115 if (DEBUG_PREFERRED || debug) { 4116 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4117 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4118 + "\n component=" + ppa.mComponent); 4119 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4120 } 4121 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4122 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4123 if (DEBUG_PREFERRED || debug) { 4124 Slog.v(TAG, "Found persistent preferred activity:"); 4125 if (ai != null) { 4126 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4127 } else { 4128 Slog.v(TAG, " null"); 4129 } 4130 } 4131 if (ai == null) { 4132 // This previously registered persistent preferred activity 4133 // component is no longer known. Ignore it and do NOT remove it. 4134 continue; 4135 } 4136 for (int j=0; j<N; j++) { 4137 final ResolveInfo ri = query.get(j); 4138 if (!ri.activityInfo.applicationInfo.packageName 4139 .equals(ai.applicationInfo.packageName)) { 4140 continue; 4141 } 4142 if (!ri.activityInfo.name.equals(ai.name)) { 4143 continue; 4144 } 4145 // Found a persistent preference that can handle the intent. 4146 if (DEBUG_PREFERRED || debug) { 4147 Slog.v(TAG, "Returning persistent preferred activity: " + 4148 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4149 } 4150 return ri; 4151 } 4152 } 4153 } 4154 return null; 4155 } 4156 4157 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4158 List<ResolveInfo> query, int priority, boolean always, 4159 boolean removeMatches, boolean debug, int userId) { 4160 if (!sUserManager.exists(userId)) return null; 4161 // writer 4162 synchronized (mPackages) { 4163 if (intent.getSelector() != null) { 4164 intent = intent.getSelector(); 4165 } 4166 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4167 4168 // Try to find a matching persistent preferred activity. 4169 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4170 debug, userId); 4171 4172 // If a persistent preferred activity matched, use it. 4173 if (pri != null) { 4174 return pri; 4175 } 4176 4177 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4178 // Get the list of preferred activities that handle the intent 4179 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4180 List<PreferredActivity> prefs = pir != null 4181 ? pir.queryIntent(intent, resolvedType, 4182 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4183 : null; 4184 if (prefs != null && prefs.size() > 0) { 4185 boolean changed = false; 4186 try { 4187 // First figure out how good the original match set is. 4188 // We will only allow preferred activities that came 4189 // from the same match quality. 4190 int match = 0; 4191 4192 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4193 4194 final int N = query.size(); 4195 for (int j=0; j<N; j++) { 4196 final ResolveInfo ri = query.get(j); 4197 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4198 + ": 0x" + Integer.toHexString(match)); 4199 if (ri.match > match) { 4200 match = ri.match; 4201 } 4202 } 4203 4204 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4205 + Integer.toHexString(match)); 4206 4207 match &= IntentFilter.MATCH_CATEGORY_MASK; 4208 final int M = prefs.size(); 4209 for (int i=0; i<M; i++) { 4210 final PreferredActivity pa = prefs.get(i); 4211 if (DEBUG_PREFERRED || debug) { 4212 Slog.v(TAG, "Checking PreferredActivity ds=" 4213 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4214 + "\n component=" + pa.mPref.mComponent); 4215 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4216 } 4217 if (pa.mPref.mMatch != match) { 4218 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4219 + Integer.toHexString(pa.mPref.mMatch)); 4220 continue; 4221 } 4222 // If it's not an "always" type preferred activity and that's what we're 4223 // looking for, skip it. 4224 if (always && !pa.mPref.mAlways) { 4225 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4226 continue; 4227 } 4228 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4229 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4230 if (DEBUG_PREFERRED || debug) { 4231 Slog.v(TAG, "Found preferred activity:"); 4232 if (ai != null) { 4233 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4234 } else { 4235 Slog.v(TAG, " null"); 4236 } 4237 } 4238 if (ai == null) { 4239 // This previously registered preferred activity 4240 // component is no longer known. Most likely an update 4241 // to the app was installed and in the new version this 4242 // component no longer exists. Clean it up by removing 4243 // it from the preferred activities list, and skip it. 4244 Slog.w(TAG, "Removing dangling preferred activity: " 4245 + pa.mPref.mComponent); 4246 pir.removeFilter(pa); 4247 changed = true; 4248 continue; 4249 } 4250 for (int j=0; j<N; j++) { 4251 final ResolveInfo ri = query.get(j); 4252 if (!ri.activityInfo.applicationInfo.packageName 4253 .equals(ai.applicationInfo.packageName)) { 4254 continue; 4255 } 4256 if (!ri.activityInfo.name.equals(ai.name)) { 4257 continue; 4258 } 4259 4260 if (removeMatches) { 4261 pir.removeFilter(pa); 4262 changed = true; 4263 if (DEBUG_PREFERRED) { 4264 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4265 } 4266 break; 4267 } 4268 4269 // Okay we found a previously set preferred or last chosen app. 4270 // If the result set is different from when this 4271 // was created, we need to clear it and re-ask the 4272 // user their preference, if we're looking for an "always" type entry. 4273 if (always && !pa.mPref.sameSet(query)) { 4274 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4275 + intent + " type " + resolvedType); 4276 if (DEBUG_PREFERRED) { 4277 Slog.v(TAG, "Removing preferred activity since set changed " 4278 + pa.mPref.mComponent); 4279 } 4280 pir.removeFilter(pa); 4281 // Re-add the filter as a "last chosen" entry (!always) 4282 PreferredActivity lastChosen = new PreferredActivity( 4283 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4284 pir.addFilter(lastChosen); 4285 changed = true; 4286 return null; 4287 } 4288 4289 // Yay! Either the set matched or we're looking for the last chosen 4290 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4291 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4292 return ri; 4293 } 4294 } 4295 } finally { 4296 if (changed) { 4297 if (DEBUG_PREFERRED) { 4298 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4299 } 4300 scheduleWritePackageRestrictionsLocked(userId); 4301 } 4302 } 4303 } 4304 } 4305 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4306 return null; 4307 } 4308 4309 /* 4310 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4311 */ 4312 @Override 4313 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4314 int targetUserId) { 4315 mContext.enforceCallingOrSelfPermission( 4316 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4317 List<CrossProfileIntentFilter> matches = 4318 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4319 if (matches != null) { 4320 int size = matches.size(); 4321 for (int i = 0; i < size; i++) { 4322 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4323 } 4324 } 4325 if (hasWebURI(intent)) { 4326 // cross-profile app linking works only towards the parent. 4327 final UserInfo parent = getProfileParent(sourceUserId); 4328 synchronized(mPackages) { 4329 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4330 parent.id) != null; 4331 } 4332 } 4333 return false; 4334 } 4335 4336 private UserInfo getProfileParent(int userId) { 4337 final long identity = Binder.clearCallingIdentity(); 4338 try { 4339 return sUserManager.getProfileParent(userId); 4340 } finally { 4341 Binder.restoreCallingIdentity(identity); 4342 } 4343 } 4344 4345 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4346 String resolvedType, int userId) { 4347 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4348 if (resolver != null) { 4349 return resolver.queryIntent(intent, resolvedType, false, userId); 4350 } 4351 return null; 4352 } 4353 4354 @Override 4355 public List<ResolveInfo> queryIntentActivities(Intent intent, 4356 String resolvedType, int flags, int userId) { 4357 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4358 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4359 ComponentName comp = intent.getComponent(); 4360 if (comp == null) { 4361 if (intent.getSelector() != null) { 4362 intent = intent.getSelector(); 4363 comp = intent.getComponent(); 4364 } 4365 } 4366 4367 if (comp != null) { 4368 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4369 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4370 if (ai != null) { 4371 final ResolveInfo ri = new ResolveInfo(); 4372 ri.activityInfo = ai; 4373 list.add(ri); 4374 } 4375 return list; 4376 } 4377 4378 // reader 4379 synchronized (mPackages) { 4380 final String pkgName = intent.getPackage(); 4381 if (pkgName == null) { 4382 List<CrossProfileIntentFilter> matchingFilters = 4383 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4384 // Check for results that need to skip the current profile. 4385 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4386 resolvedType, flags, userId); 4387 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4388 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4389 result.add(xpResolveInfo); 4390 return filterIfNotPrimaryUser(result, userId); 4391 } 4392 4393 // Check for results in the current profile. 4394 List<ResolveInfo> result = mActivities.queryIntent( 4395 intent, resolvedType, flags, userId); 4396 4397 // Check for cross profile results. 4398 xpResolveInfo = queryCrossProfileIntents( 4399 matchingFilters, intent, resolvedType, flags, userId); 4400 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4401 result.add(xpResolveInfo); 4402 Collections.sort(result, mResolvePrioritySorter); 4403 } 4404 result = filterIfNotPrimaryUser(result, userId); 4405 if (hasWebURI(intent)) { 4406 CrossProfileDomainInfo xpDomainInfo = null; 4407 final UserInfo parent = getProfileParent(userId); 4408 if (parent != null) { 4409 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4410 flags, userId, parent.id); 4411 } 4412 if (xpDomainInfo != null) { 4413 if (xpResolveInfo != null) { 4414 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4415 // in the result. 4416 result.remove(xpResolveInfo); 4417 } 4418 if (result.size() == 0) { 4419 result.add(xpDomainInfo.resolveInfo); 4420 return result; 4421 } 4422 } else if (result.size() <= 1) { 4423 return result; 4424 } 4425 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4426 xpDomainInfo); 4427 Collections.sort(result, mResolvePrioritySorter); 4428 } 4429 return result; 4430 } 4431 final PackageParser.Package pkg = mPackages.get(pkgName); 4432 if (pkg != null) { 4433 return filterIfNotPrimaryUser( 4434 mActivities.queryIntentForPackage( 4435 intent, resolvedType, flags, pkg.activities, userId), 4436 userId); 4437 } 4438 return new ArrayList<ResolveInfo>(); 4439 } 4440 } 4441 4442 private static class CrossProfileDomainInfo { 4443 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4444 ResolveInfo resolveInfo; 4445 /* Best domain verification status of the activities found in the other profile */ 4446 int bestDomainVerificationStatus; 4447 } 4448 4449 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4450 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4451 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4452 sourceUserId)) { 4453 return null; 4454 } 4455 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4456 resolvedType, flags, parentUserId); 4457 4458 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4459 return null; 4460 } 4461 CrossProfileDomainInfo result = null; 4462 int size = resultTargetUser.size(); 4463 for (int i = 0; i < size; i++) { 4464 ResolveInfo riTargetUser = resultTargetUser.get(i); 4465 // Intent filter verification is only for filters that specify a host. So don't return 4466 // those that handle all web uris. 4467 if (riTargetUser.handleAllWebDataURI) { 4468 continue; 4469 } 4470 String packageName = riTargetUser.activityInfo.packageName; 4471 PackageSetting ps = mSettings.mPackages.get(packageName); 4472 if (ps == null) { 4473 continue; 4474 } 4475 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4476 if (result == null) { 4477 result = new CrossProfileDomainInfo(); 4478 result.resolveInfo = 4479 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4480 result.bestDomainVerificationStatus = status; 4481 } else { 4482 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4483 result.bestDomainVerificationStatus); 4484 } 4485 } 4486 return result; 4487 } 4488 4489 /** 4490 * Verification statuses are ordered from the worse to the best, except for 4491 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4492 */ 4493 private int bestDomainVerificationStatus(int status1, int status2) { 4494 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4495 return status2; 4496 } 4497 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4498 return status1; 4499 } 4500 return (int) MathUtils.max(status1, status2); 4501 } 4502 4503 private boolean isUserEnabled(int userId) { 4504 long callingId = Binder.clearCallingIdentity(); 4505 try { 4506 UserInfo userInfo = sUserManager.getUserInfo(userId); 4507 return userInfo != null && userInfo.isEnabled(); 4508 } finally { 4509 Binder.restoreCallingIdentity(callingId); 4510 } 4511 } 4512 4513 /** 4514 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4515 * 4516 * @return filtered list 4517 */ 4518 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4519 if (userId == UserHandle.USER_OWNER) { 4520 return resolveInfos; 4521 } 4522 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4523 ResolveInfo info = resolveInfos.get(i); 4524 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4525 resolveInfos.remove(i); 4526 } 4527 } 4528 return resolveInfos; 4529 } 4530 4531 private static boolean hasWebURI(Intent intent) { 4532 if (intent.getData() == null) { 4533 return false; 4534 } 4535 final String scheme = intent.getScheme(); 4536 if (TextUtils.isEmpty(scheme)) { 4537 return false; 4538 } 4539 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4540 } 4541 4542 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4543 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4544 if (DEBUG_PREFERRED) { 4545 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4546 candidates.size()); 4547 } 4548 4549 final int userId = UserHandle.getCallingUserId(); 4550 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4551 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4552 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4553 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4554 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4555 4556 synchronized (mPackages) { 4557 final int count = candidates.size(); 4558 // First, try to use the domain preferred app. Partition the candidates into four lists: 4559 // one for the final results, one for the "do not use ever", one for "undefined status" 4560 // and finally one for "Browser App type". 4561 for (int n=0; n<count; n++) { 4562 ResolveInfo info = candidates.get(n); 4563 String packageName = info.activityInfo.packageName; 4564 PackageSetting ps = mSettings.mPackages.get(packageName); 4565 if (ps != null) { 4566 // Add to the special match all list (Browser use case) 4567 if (info.handleAllWebDataURI) { 4568 matchAllList.add(info); 4569 continue; 4570 } 4571 // Try to get the status from User settings first 4572 int status = getDomainVerificationStatusLPr(ps, userId); 4573 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4574 alwaysList.add(info); 4575 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4576 neverList.add(info); 4577 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4578 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4579 undefinedList.add(info); 4580 } 4581 } 4582 } 4583 // First try to add the "always" resolution for the current user if there is any 4584 if (alwaysList.size() > 0) { 4585 result.addAll(alwaysList); 4586 // if there is an "always" for the parent user, add it. 4587 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4588 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4589 result.add(xpDomainInfo.resolveInfo); 4590 } else { 4591 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4592 result.addAll(undefinedList); 4593 if (xpDomainInfo != null && ( 4594 xpDomainInfo.bestDomainVerificationStatus 4595 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4596 || xpDomainInfo.bestDomainVerificationStatus 4597 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4598 result.add(xpDomainInfo.resolveInfo); 4599 } 4600 // Also add Browsers (all of them or only the default one) 4601 if ((flags & MATCH_ALL) != 0) { 4602 result.addAll(matchAllList); 4603 } else { 4604 // Try to add the Default Browser if we can 4605 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4606 UserHandle.myUserId()); 4607 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4608 boolean defaultBrowserFound = false; 4609 final int browserCount = matchAllList.size(); 4610 for (int n=0; n<browserCount; n++) { 4611 ResolveInfo browser = matchAllList.get(n); 4612 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4613 result.add(browser); 4614 defaultBrowserFound = true; 4615 break; 4616 } 4617 } 4618 if (!defaultBrowserFound) { 4619 result.addAll(matchAllList); 4620 } 4621 } else { 4622 result.addAll(matchAllList); 4623 } 4624 } 4625 4626 // If there is nothing selected, add all candidates and remove the ones that the User 4627 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4628 if (result.size() == 0) { 4629 result.addAll(candidates); 4630 result.removeAll(neverList); 4631 } 4632 } 4633 } 4634 if (DEBUG_PREFERRED) { 4635 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4636 result.size()); 4637 } 4638 return result; 4639 } 4640 4641 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4642 int status = ps.getDomainVerificationStatusForUser(userId); 4643 // if none available, get the master status 4644 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4645 if (ps.getIntentFilterVerificationInfo() != null) { 4646 status = ps.getIntentFilterVerificationInfo().getStatus(); 4647 } 4648 } 4649 return status; 4650 } 4651 4652 private ResolveInfo querySkipCurrentProfileIntents( 4653 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4654 int flags, int sourceUserId) { 4655 if (matchingFilters != null) { 4656 int size = matchingFilters.size(); 4657 for (int i = 0; i < size; i ++) { 4658 CrossProfileIntentFilter filter = matchingFilters.get(i); 4659 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4660 // Checking if there are activities in the target user that can handle the 4661 // intent. 4662 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4663 flags, sourceUserId); 4664 if (resolveInfo != null) { 4665 return resolveInfo; 4666 } 4667 } 4668 } 4669 } 4670 return null; 4671 } 4672 4673 // Return matching ResolveInfo if any for skip current profile intent filters. 4674 private ResolveInfo queryCrossProfileIntents( 4675 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4676 int flags, int sourceUserId) { 4677 if (matchingFilters != null) { 4678 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4679 // match the same intent. For performance reasons, it is better not to 4680 // run queryIntent twice for the same userId 4681 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4682 int size = matchingFilters.size(); 4683 for (int i = 0; i < size; i++) { 4684 CrossProfileIntentFilter filter = matchingFilters.get(i); 4685 int targetUserId = filter.getTargetUserId(); 4686 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4687 && !alreadyTriedUserIds.get(targetUserId)) { 4688 // Checking if there are activities in the target user that can handle the 4689 // intent. 4690 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4691 flags, sourceUserId); 4692 if (resolveInfo != null) return resolveInfo; 4693 alreadyTriedUserIds.put(targetUserId, true); 4694 } 4695 } 4696 } 4697 return null; 4698 } 4699 4700 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4701 String resolvedType, int flags, int sourceUserId) { 4702 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4703 resolvedType, flags, filter.getTargetUserId()); 4704 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4705 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4706 } 4707 return null; 4708 } 4709 4710 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4711 int sourceUserId, int targetUserId) { 4712 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4713 String className; 4714 if (targetUserId == UserHandle.USER_OWNER) { 4715 className = FORWARD_INTENT_TO_USER_OWNER; 4716 } else { 4717 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4718 } 4719 ComponentName forwardingActivityComponentName = new ComponentName( 4720 mAndroidApplication.packageName, className); 4721 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4722 sourceUserId); 4723 if (targetUserId == UserHandle.USER_OWNER) { 4724 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4725 forwardingResolveInfo.noResourceId = true; 4726 } 4727 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4728 forwardingResolveInfo.priority = 0; 4729 forwardingResolveInfo.preferredOrder = 0; 4730 forwardingResolveInfo.match = 0; 4731 forwardingResolveInfo.isDefault = true; 4732 forwardingResolveInfo.filter = filter; 4733 forwardingResolveInfo.targetUserId = targetUserId; 4734 return forwardingResolveInfo; 4735 } 4736 4737 @Override 4738 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4739 Intent[] specifics, String[] specificTypes, Intent intent, 4740 String resolvedType, int flags, int userId) { 4741 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4742 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4743 false, "query intent activity options"); 4744 final String resultsAction = intent.getAction(); 4745 4746 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4747 | PackageManager.GET_RESOLVED_FILTER, userId); 4748 4749 if (DEBUG_INTENT_MATCHING) { 4750 Log.v(TAG, "Query " + intent + ": " + results); 4751 } 4752 4753 int specificsPos = 0; 4754 int N; 4755 4756 // todo: note that the algorithm used here is O(N^2). This 4757 // isn't a problem in our current environment, but if we start running 4758 // into situations where we have more than 5 or 10 matches then this 4759 // should probably be changed to something smarter... 4760 4761 // First we go through and resolve each of the specific items 4762 // that were supplied, taking care of removing any corresponding 4763 // duplicate items in the generic resolve list. 4764 if (specifics != null) { 4765 for (int i=0; i<specifics.length; i++) { 4766 final Intent sintent = specifics[i]; 4767 if (sintent == null) { 4768 continue; 4769 } 4770 4771 if (DEBUG_INTENT_MATCHING) { 4772 Log.v(TAG, "Specific #" + i + ": " + sintent); 4773 } 4774 4775 String action = sintent.getAction(); 4776 if (resultsAction != null && resultsAction.equals(action)) { 4777 // If this action was explicitly requested, then don't 4778 // remove things that have it. 4779 action = null; 4780 } 4781 4782 ResolveInfo ri = null; 4783 ActivityInfo ai = null; 4784 4785 ComponentName comp = sintent.getComponent(); 4786 if (comp == null) { 4787 ri = resolveIntent( 4788 sintent, 4789 specificTypes != null ? specificTypes[i] : null, 4790 flags, userId); 4791 if (ri == null) { 4792 continue; 4793 } 4794 if (ri == mResolveInfo) { 4795 // ACK! Must do something better with this. 4796 } 4797 ai = ri.activityInfo; 4798 comp = new ComponentName(ai.applicationInfo.packageName, 4799 ai.name); 4800 } else { 4801 ai = getActivityInfo(comp, flags, userId); 4802 if (ai == null) { 4803 continue; 4804 } 4805 } 4806 4807 // Look for any generic query activities that are duplicates 4808 // of this specific one, and remove them from the results. 4809 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4810 N = results.size(); 4811 int j; 4812 for (j=specificsPos; j<N; j++) { 4813 ResolveInfo sri = results.get(j); 4814 if ((sri.activityInfo.name.equals(comp.getClassName()) 4815 && sri.activityInfo.applicationInfo.packageName.equals( 4816 comp.getPackageName())) 4817 || (action != null && sri.filter.matchAction(action))) { 4818 results.remove(j); 4819 if (DEBUG_INTENT_MATCHING) Log.v( 4820 TAG, "Removing duplicate item from " + j 4821 + " due to specific " + specificsPos); 4822 if (ri == null) { 4823 ri = sri; 4824 } 4825 j--; 4826 N--; 4827 } 4828 } 4829 4830 // Add this specific item to its proper place. 4831 if (ri == null) { 4832 ri = new ResolveInfo(); 4833 ri.activityInfo = ai; 4834 } 4835 results.add(specificsPos, ri); 4836 ri.specificIndex = i; 4837 specificsPos++; 4838 } 4839 } 4840 4841 // Now we go through the remaining generic results and remove any 4842 // duplicate actions that are found here. 4843 N = results.size(); 4844 for (int i=specificsPos; i<N-1; i++) { 4845 final ResolveInfo rii = results.get(i); 4846 if (rii.filter == null) { 4847 continue; 4848 } 4849 4850 // Iterate over all of the actions of this result's intent 4851 // filter... typically this should be just one. 4852 final Iterator<String> it = rii.filter.actionsIterator(); 4853 if (it == null) { 4854 continue; 4855 } 4856 while (it.hasNext()) { 4857 final String action = it.next(); 4858 if (resultsAction != null && resultsAction.equals(action)) { 4859 // If this action was explicitly requested, then don't 4860 // remove things that have it. 4861 continue; 4862 } 4863 for (int j=i+1; j<N; j++) { 4864 final ResolveInfo rij = results.get(j); 4865 if (rij.filter != null && rij.filter.hasAction(action)) { 4866 results.remove(j); 4867 if (DEBUG_INTENT_MATCHING) Log.v( 4868 TAG, "Removing duplicate item from " + j 4869 + " due to action " + action + " at " + i); 4870 j--; 4871 N--; 4872 } 4873 } 4874 } 4875 4876 // If the caller didn't request filter information, drop it now 4877 // so we don't have to marshall/unmarshall it. 4878 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4879 rii.filter = null; 4880 } 4881 } 4882 4883 // Filter out the caller activity if so requested. 4884 if (caller != null) { 4885 N = results.size(); 4886 for (int i=0; i<N; i++) { 4887 ActivityInfo ainfo = results.get(i).activityInfo; 4888 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4889 && caller.getClassName().equals(ainfo.name)) { 4890 results.remove(i); 4891 break; 4892 } 4893 } 4894 } 4895 4896 // If the caller didn't request filter information, 4897 // drop them now so we don't have to 4898 // marshall/unmarshall it. 4899 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4900 N = results.size(); 4901 for (int i=0; i<N; i++) { 4902 results.get(i).filter = null; 4903 } 4904 } 4905 4906 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4907 return results; 4908 } 4909 4910 @Override 4911 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4912 int userId) { 4913 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4914 ComponentName comp = intent.getComponent(); 4915 if (comp == null) { 4916 if (intent.getSelector() != null) { 4917 intent = intent.getSelector(); 4918 comp = intent.getComponent(); 4919 } 4920 } 4921 if (comp != null) { 4922 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4923 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4924 if (ai != null) { 4925 ResolveInfo ri = new ResolveInfo(); 4926 ri.activityInfo = ai; 4927 list.add(ri); 4928 } 4929 return list; 4930 } 4931 4932 // reader 4933 synchronized (mPackages) { 4934 String pkgName = intent.getPackage(); 4935 if (pkgName == null) { 4936 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4937 } 4938 final PackageParser.Package pkg = mPackages.get(pkgName); 4939 if (pkg != null) { 4940 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4941 userId); 4942 } 4943 return null; 4944 } 4945 } 4946 4947 @Override 4948 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4949 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4950 if (!sUserManager.exists(userId)) return null; 4951 if (query != null) { 4952 if (query.size() >= 1) { 4953 // If there is more than one service with the same priority, 4954 // just arbitrarily pick the first one. 4955 return query.get(0); 4956 } 4957 } 4958 return null; 4959 } 4960 4961 @Override 4962 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4963 int userId) { 4964 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4965 ComponentName comp = intent.getComponent(); 4966 if (comp == null) { 4967 if (intent.getSelector() != null) { 4968 intent = intent.getSelector(); 4969 comp = intent.getComponent(); 4970 } 4971 } 4972 if (comp != null) { 4973 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4974 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4975 if (si != null) { 4976 final ResolveInfo ri = new ResolveInfo(); 4977 ri.serviceInfo = si; 4978 list.add(ri); 4979 } 4980 return list; 4981 } 4982 4983 // reader 4984 synchronized (mPackages) { 4985 String pkgName = intent.getPackage(); 4986 if (pkgName == null) { 4987 return mServices.queryIntent(intent, resolvedType, flags, userId); 4988 } 4989 final PackageParser.Package pkg = mPackages.get(pkgName); 4990 if (pkg != null) { 4991 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4992 userId); 4993 } 4994 return null; 4995 } 4996 } 4997 4998 @Override 4999 public List<ResolveInfo> queryIntentContentProviders( 5000 Intent intent, String resolvedType, int flags, int userId) { 5001 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5002 ComponentName comp = intent.getComponent(); 5003 if (comp == null) { 5004 if (intent.getSelector() != null) { 5005 intent = intent.getSelector(); 5006 comp = intent.getComponent(); 5007 } 5008 } 5009 if (comp != null) { 5010 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5011 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5012 if (pi != null) { 5013 final ResolveInfo ri = new ResolveInfo(); 5014 ri.providerInfo = pi; 5015 list.add(ri); 5016 } 5017 return list; 5018 } 5019 5020 // reader 5021 synchronized (mPackages) { 5022 String pkgName = intent.getPackage(); 5023 if (pkgName == null) { 5024 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5025 } 5026 final PackageParser.Package pkg = mPackages.get(pkgName); 5027 if (pkg != null) { 5028 return mProviders.queryIntentForPackage( 5029 intent, resolvedType, flags, pkg.providers, userId); 5030 } 5031 return null; 5032 } 5033 } 5034 5035 @Override 5036 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5037 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5038 5039 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5040 5041 // writer 5042 synchronized (mPackages) { 5043 ArrayList<PackageInfo> list; 5044 if (listUninstalled) { 5045 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5046 for (PackageSetting ps : mSettings.mPackages.values()) { 5047 PackageInfo pi; 5048 if (ps.pkg != null) { 5049 pi = generatePackageInfo(ps.pkg, flags, userId); 5050 } else { 5051 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5052 } 5053 if (pi != null) { 5054 list.add(pi); 5055 } 5056 } 5057 } else { 5058 list = new ArrayList<PackageInfo>(mPackages.size()); 5059 for (PackageParser.Package p : mPackages.values()) { 5060 PackageInfo pi = generatePackageInfo(p, flags, userId); 5061 if (pi != null) { 5062 list.add(pi); 5063 } 5064 } 5065 } 5066 5067 return new ParceledListSlice<PackageInfo>(list); 5068 } 5069 } 5070 5071 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5072 String[] permissions, boolean[] tmp, int flags, int userId) { 5073 int numMatch = 0; 5074 final PermissionsState permissionsState = ps.getPermissionsState(); 5075 for (int i=0; i<permissions.length; i++) { 5076 final String permission = permissions[i]; 5077 if (permissionsState.hasPermission(permission, userId)) { 5078 tmp[i] = true; 5079 numMatch++; 5080 } else { 5081 tmp[i] = false; 5082 } 5083 } 5084 if (numMatch == 0) { 5085 return; 5086 } 5087 PackageInfo pi; 5088 if (ps.pkg != null) { 5089 pi = generatePackageInfo(ps.pkg, flags, userId); 5090 } else { 5091 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5092 } 5093 // The above might return null in cases of uninstalled apps or install-state 5094 // skew across users/profiles. 5095 if (pi != null) { 5096 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5097 if (numMatch == permissions.length) { 5098 pi.requestedPermissions = permissions; 5099 } else { 5100 pi.requestedPermissions = new String[numMatch]; 5101 numMatch = 0; 5102 for (int i=0; i<permissions.length; i++) { 5103 if (tmp[i]) { 5104 pi.requestedPermissions[numMatch] = permissions[i]; 5105 numMatch++; 5106 } 5107 } 5108 } 5109 } 5110 list.add(pi); 5111 } 5112 } 5113 5114 @Override 5115 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5116 String[] permissions, int flags, int userId) { 5117 if (!sUserManager.exists(userId)) return null; 5118 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5119 5120 // writer 5121 synchronized (mPackages) { 5122 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5123 boolean[] tmpBools = new boolean[permissions.length]; 5124 if (listUninstalled) { 5125 for (PackageSetting ps : mSettings.mPackages.values()) { 5126 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5127 } 5128 } else { 5129 for (PackageParser.Package pkg : mPackages.values()) { 5130 PackageSetting ps = (PackageSetting)pkg.mExtras; 5131 if (ps != null) { 5132 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5133 userId); 5134 } 5135 } 5136 } 5137 5138 return new ParceledListSlice<PackageInfo>(list); 5139 } 5140 } 5141 5142 @Override 5143 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5144 if (!sUserManager.exists(userId)) return null; 5145 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5146 5147 // writer 5148 synchronized (mPackages) { 5149 ArrayList<ApplicationInfo> list; 5150 if (listUninstalled) { 5151 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5152 for (PackageSetting ps : mSettings.mPackages.values()) { 5153 ApplicationInfo ai; 5154 if (ps.pkg != null) { 5155 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5156 ps.readUserState(userId), userId); 5157 } else { 5158 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5159 } 5160 if (ai != null) { 5161 list.add(ai); 5162 } 5163 } 5164 } else { 5165 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5166 for (PackageParser.Package p : mPackages.values()) { 5167 if (p.mExtras != null) { 5168 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5169 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5170 if (ai != null) { 5171 list.add(ai); 5172 } 5173 } 5174 } 5175 } 5176 5177 return new ParceledListSlice<ApplicationInfo>(list); 5178 } 5179 } 5180 5181 public List<ApplicationInfo> getPersistentApplications(int flags) { 5182 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5183 5184 // reader 5185 synchronized (mPackages) { 5186 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5187 final int userId = UserHandle.getCallingUserId(); 5188 while (i.hasNext()) { 5189 final PackageParser.Package p = i.next(); 5190 if (p.applicationInfo != null 5191 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5192 && (!mSafeMode || isSystemApp(p))) { 5193 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5194 if (ps != null) { 5195 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5196 ps.readUserState(userId), userId); 5197 if (ai != null) { 5198 finalList.add(ai); 5199 } 5200 } 5201 } 5202 } 5203 } 5204 5205 return finalList; 5206 } 5207 5208 @Override 5209 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5210 if (!sUserManager.exists(userId)) return null; 5211 // reader 5212 synchronized (mPackages) { 5213 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5214 PackageSetting ps = provider != null 5215 ? mSettings.mPackages.get(provider.owner.packageName) 5216 : null; 5217 return ps != null 5218 && mSettings.isEnabledLPr(provider.info, flags, userId) 5219 && (!mSafeMode || (provider.info.applicationInfo.flags 5220 &ApplicationInfo.FLAG_SYSTEM) != 0) 5221 ? PackageParser.generateProviderInfo(provider, flags, 5222 ps.readUserState(userId), userId) 5223 : null; 5224 } 5225 } 5226 5227 /** 5228 * @deprecated 5229 */ 5230 @Deprecated 5231 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5232 // reader 5233 synchronized (mPackages) { 5234 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5235 .entrySet().iterator(); 5236 final int userId = UserHandle.getCallingUserId(); 5237 while (i.hasNext()) { 5238 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5239 PackageParser.Provider p = entry.getValue(); 5240 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5241 5242 if (ps != null && p.syncable 5243 && (!mSafeMode || (p.info.applicationInfo.flags 5244 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5245 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5246 ps.readUserState(userId), userId); 5247 if (info != null) { 5248 outNames.add(entry.getKey()); 5249 outInfo.add(info); 5250 } 5251 } 5252 } 5253 } 5254 } 5255 5256 @Override 5257 public List<ProviderInfo> queryContentProviders(String processName, 5258 int uid, int flags) { 5259 ArrayList<ProviderInfo> finalList = null; 5260 // reader 5261 synchronized (mPackages) { 5262 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5263 final int userId = processName != null ? 5264 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5265 while (i.hasNext()) { 5266 final PackageParser.Provider p = i.next(); 5267 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5268 if (ps != null && p.info.authority != null 5269 && (processName == null 5270 || (p.info.processName.equals(processName) 5271 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5272 && mSettings.isEnabledLPr(p.info, flags, userId) 5273 && (!mSafeMode 5274 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5275 if (finalList == null) { 5276 finalList = new ArrayList<ProviderInfo>(3); 5277 } 5278 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5279 ps.readUserState(userId), userId); 5280 if (info != null) { 5281 finalList.add(info); 5282 } 5283 } 5284 } 5285 } 5286 5287 if (finalList != null) { 5288 Collections.sort(finalList, mProviderInitOrderSorter); 5289 } 5290 5291 return finalList; 5292 } 5293 5294 @Override 5295 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5296 int flags) { 5297 // reader 5298 synchronized (mPackages) { 5299 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5300 return PackageParser.generateInstrumentationInfo(i, flags); 5301 } 5302 } 5303 5304 @Override 5305 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5306 int flags) { 5307 ArrayList<InstrumentationInfo> finalList = 5308 new ArrayList<InstrumentationInfo>(); 5309 5310 // reader 5311 synchronized (mPackages) { 5312 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5313 while (i.hasNext()) { 5314 final PackageParser.Instrumentation p = i.next(); 5315 if (targetPackage == null 5316 || targetPackage.equals(p.info.targetPackage)) { 5317 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5318 flags); 5319 if (ii != null) { 5320 finalList.add(ii); 5321 } 5322 } 5323 } 5324 } 5325 5326 return finalList; 5327 } 5328 5329 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5330 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5331 if (overlays == null) { 5332 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5333 return; 5334 } 5335 for (PackageParser.Package opkg : overlays.values()) { 5336 // Not much to do if idmap fails: we already logged the error 5337 // and we certainly don't want to abort installation of pkg simply 5338 // because an overlay didn't fit properly. For these reasons, 5339 // ignore the return value of createIdmapForPackagePairLI. 5340 createIdmapForPackagePairLI(pkg, opkg); 5341 } 5342 } 5343 5344 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5345 PackageParser.Package opkg) { 5346 if (!opkg.mTrustedOverlay) { 5347 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5348 opkg.baseCodePath + ": overlay not trusted"); 5349 return false; 5350 } 5351 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5352 if (overlaySet == null) { 5353 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5354 opkg.baseCodePath + " but target package has no known overlays"); 5355 return false; 5356 } 5357 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5358 // TODO: generate idmap for split APKs 5359 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5360 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5361 + opkg.baseCodePath); 5362 return false; 5363 } 5364 PackageParser.Package[] overlayArray = 5365 overlaySet.values().toArray(new PackageParser.Package[0]); 5366 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5367 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5368 return p1.mOverlayPriority - p2.mOverlayPriority; 5369 } 5370 }; 5371 Arrays.sort(overlayArray, cmp); 5372 5373 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5374 int i = 0; 5375 for (PackageParser.Package p : overlayArray) { 5376 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5377 } 5378 return true; 5379 } 5380 5381 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5382 final File[] files = dir.listFiles(); 5383 if (ArrayUtils.isEmpty(files)) { 5384 Log.d(TAG, "No files in app dir " + dir); 5385 return; 5386 } 5387 5388 if (DEBUG_PACKAGE_SCANNING) { 5389 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5390 + " flags=0x" + Integer.toHexString(parseFlags)); 5391 } 5392 5393 for (File file : files) { 5394 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5395 && !PackageInstallerService.isStageName(file.getName()); 5396 if (!isPackage) { 5397 // Ignore entries which are not packages 5398 continue; 5399 } 5400 try { 5401 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5402 scanFlags, currentTime, null); 5403 } catch (PackageManagerException e) { 5404 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5405 5406 // Delete invalid userdata apps 5407 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5408 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5409 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5410 if (file.isDirectory()) { 5411 mInstaller.rmPackageDir(file.getAbsolutePath()); 5412 } else { 5413 file.delete(); 5414 } 5415 } 5416 } 5417 } 5418 } 5419 5420 private static File getSettingsProblemFile() { 5421 File dataDir = Environment.getDataDirectory(); 5422 File systemDir = new File(dataDir, "system"); 5423 File fname = new File(systemDir, "uiderrors.txt"); 5424 return fname; 5425 } 5426 5427 static void reportSettingsProblem(int priority, String msg) { 5428 logCriticalInfo(priority, msg); 5429 } 5430 5431 static void logCriticalInfo(int priority, String msg) { 5432 Slog.println(priority, TAG, msg); 5433 EventLogTags.writePmCriticalInfo(msg); 5434 try { 5435 File fname = getSettingsProblemFile(); 5436 FileOutputStream out = new FileOutputStream(fname, true); 5437 PrintWriter pw = new FastPrintWriter(out); 5438 SimpleDateFormat formatter = new SimpleDateFormat(); 5439 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5440 pw.println(dateString + ": " + msg); 5441 pw.close(); 5442 FileUtils.setPermissions( 5443 fname.toString(), 5444 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5445 -1, -1); 5446 } catch (java.io.IOException e) { 5447 } 5448 } 5449 5450 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5451 PackageParser.Package pkg, File srcFile, int parseFlags) 5452 throws PackageManagerException { 5453 if (ps != null 5454 && ps.codePath.equals(srcFile) 5455 && ps.timeStamp == srcFile.lastModified() 5456 && !isCompatSignatureUpdateNeeded(pkg) 5457 && !isRecoverSignatureUpdateNeeded(pkg)) { 5458 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5459 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5460 ArraySet<PublicKey> signingKs; 5461 synchronized (mPackages) { 5462 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5463 } 5464 if (ps.signatures.mSignatures != null 5465 && ps.signatures.mSignatures.length != 0 5466 && signingKs != null) { 5467 // Optimization: reuse the existing cached certificates 5468 // if the package appears to be unchanged. 5469 pkg.mSignatures = ps.signatures.mSignatures; 5470 pkg.mSigningKeys = signingKs; 5471 return; 5472 } 5473 5474 Slog.w(TAG, "PackageSetting for " + ps.name 5475 + " is missing signatures. Collecting certs again to recover them."); 5476 } else { 5477 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5478 } 5479 5480 try { 5481 pp.collectCertificates(pkg, parseFlags); 5482 pp.collectManifestDigest(pkg); 5483 } catch (PackageParserException e) { 5484 throw PackageManagerException.from(e); 5485 } 5486 } 5487 5488 /* 5489 * Scan a package and return the newly parsed package. 5490 * Returns null in case of errors and the error code is stored in mLastScanError 5491 */ 5492 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5493 long currentTime, UserHandle user) throws PackageManagerException { 5494 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5495 parseFlags |= mDefParseFlags; 5496 PackageParser pp = new PackageParser(); 5497 pp.setSeparateProcesses(mSeparateProcesses); 5498 pp.setOnlyCoreApps(mOnlyCore); 5499 pp.setDisplayMetrics(mMetrics); 5500 5501 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5502 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5503 } 5504 5505 final PackageParser.Package pkg; 5506 try { 5507 pkg = pp.parsePackage(scanFile, parseFlags); 5508 } catch (PackageParserException e) { 5509 throw PackageManagerException.from(e); 5510 } 5511 5512 PackageSetting ps = null; 5513 PackageSetting updatedPkg; 5514 // reader 5515 synchronized (mPackages) { 5516 // Look to see if we already know about this package. 5517 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5518 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5519 // This package has been renamed to its original name. Let's 5520 // use that. 5521 ps = mSettings.peekPackageLPr(oldName); 5522 } 5523 // If there was no original package, see one for the real package name. 5524 if (ps == null) { 5525 ps = mSettings.peekPackageLPr(pkg.packageName); 5526 } 5527 // Check to see if this package could be hiding/updating a system 5528 // package. Must look for it either under the original or real 5529 // package name depending on our state. 5530 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5531 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5532 } 5533 boolean updatedPkgBetter = false; 5534 // First check if this is a system package that may involve an update 5535 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5536 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5537 // it needs to drop FLAG_PRIVILEGED. 5538 if (locationIsPrivileged(scanFile)) { 5539 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5540 } else { 5541 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5542 } 5543 5544 if (ps != null && !ps.codePath.equals(scanFile)) { 5545 // The path has changed from what was last scanned... check the 5546 // version of the new path against what we have stored to determine 5547 // what to do. 5548 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5549 if (pkg.mVersionCode <= ps.versionCode) { 5550 // The system package has been updated and the code path does not match 5551 // Ignore entry. Skip it. 5552 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5553 + " ignored: updated version " + ps.versionCode 5554 + " better than this " + pkg.mVersionCode); 5555 if (!updatedPkg.codePath.equals(scanFile)) { 5556 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5557 + ps.name + " changing from " + updatedPkg.codePathString 5558 + " to " + scanFile); 5559 updatedPkg.codePath = scanFile; 5560 updatedPkg.codePathString = scanFile.toString(); 5561 updatedPkg.resourcePath = scanFile; 5562 updatedPkg.resourcePathString = scanFile.toString(); 5563 } 5564 updatedPkg.pkg = pkg; 5565 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5566 } else { 5567 // The current app on the system partition is better than 5568 // what we have updated to on the data partition; switch 5569 // back to the system partition version. 5570 // At this point, its safely assumed that package installation for 5571 // apps in system partition will go through. If not there won't be a working 5572 // version of the app 5573 // writer 5574 synchronized (mPackages) { 5575 // Just remove the loaded entries from package lists. 5576 mPackages.remove(ps.name); 5577 } 5578 5579 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5580 + " reverting from " + ps.codePathString 5581 + ": new version " + pkg.mVersionCode 5582 + " better than installed " + ps.versionCode); 5583 5584 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5585 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5586 synchronized (mInstallLock) { 5587 args.cleanUpResourcesLI(); 5588 } 5589 synchronized (mPackages) { 5590 mSettings.enableSystemPackageLPw(ps.name); 5591 } 5592 updatedPkgBetter = true; 5593 } 5594 } 5595 } 5596 5597 if (updatedPkg != null) { 5598 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5599 // initially 5600 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5601 5602 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5603 // flag set initially 5604 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5605 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5606 } 5607 } 5608 5609 // Verify certificates against what was last scanned 5610 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5611 5612 /* 5613 * A new system app appeared, but we already had a non-system one of the 5614 * same name installed earlier. 5615 */ 5616 boolean shouldHideSystemApp = false; 5617 if (updatedPkg == null && ps != null 5618 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5619 /* 5620 * Check to make sure the signatures match first. If they don't, 5621 * wipe the installed application and its data. 5622 */ 5623 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5624 != PackageManager.SIGNATURE_MATCH) { 5625 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5626 + " signatures don't match existing userdata copy; removing"); 5627 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5628 ps = null; 5629 } else { 5630 /* 5631 * If the newly-added system app is an older version than the 5632 * already installed version, hide it. It will be scanned later 5633 * and re-added like an update. 5634 */ 5635 if (pkg.mVersionCode <= ps.versionCode) { 5636 shouldHideSystemApp = true; 5637 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5638 + " but new version " + pkg.mVersionCode + " better than installed " 5639 + ps.versionCode + "; hiding system"); 5640 } else { 5641 /* 5642 * The newly found system app is a newer version that the 5643 * one previously installed. Simply remove the 5644 * already-installed application and replace it with our own 5645 * while keeping the application data. 5646 */ 5647 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5648 + " reverting from " + ps.codePathString + ": new version " 5649 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5650 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5651 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5652 synchronized (mInstallLock) { 5653 args.cleanUpResourcesLI(); 5654 } 5655 } 5656 } 5657 } 5658 5659 // The apk is forward locked (not public) if its code and resources 5660 // are kept in different files. (except for app in either system or 5661 // vendor path). 5662 // TODO grab this value from PackageSettings 5663 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5664 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5665 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5666 } 5667 } 5668 5669 // TODO: extend to support forward-locked splits 5670 String resourcePath = null; 5671 String baseResourcePath = null; 5672 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5673 if (ps != null && ps.resourcePathString != null) { 5674 resourcePath = ps.resourcePathString; 5675 baseResourcePath = ps.resourcePathString; 5676 } else { 5677 // Should not happen at all. Just log an error. 5678 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5679 } 5680 } else { 5681 resourcePath = pkg.codePath; 5682 baseResourcePath = pkg.baseCodePath; 5683 } 5684 5685 // Set application objects path explicitly. 5686 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5687 pkg.applicationInfo.setCodePath(pkg.codePath); 5688 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5689 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5690 pkg.applicationInfo.setResourcePath(resourcePath); 5691 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5692 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5693 5694 // Note that we invoke the following method only if we are about to unpack an application 5695 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5696 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5697 5698 /* 5699 * If the system app should be overridden by a previously installed 5700 * data, hide the system app now and let the /data/app scan pick it up 5701 * again. 5702 */ 5703 if (shouldHideSystemApp) { 5704 synchronized (mPackages) { 5705 /* 5706 * We have to grant systems permissions before we hide, because 5707 * grantPermissions will assume the package update is trying to 5708 * expand its permissions. 5709 */ 5710 grantPermissionsLPw(pkg, true, pkg.packageName); 5711 mSettings.disableSystemPackageLPw(pkg.packageName); 5712 } 5713 } 5714 5715 return scannedPkg; 5716 } 5717 5718 private static String fixProcessName(String defProcessName, 5719 String processName, int uid) { 5720 if (processName == null) { 5721 return defProcessName; 5722 } 5723 return processName; 5724 } 5725 5726 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5727 throws PackageManagerException { 5728 if (pkgSetting.signatures.mSignatures != null) { 5729 // Already existing package. Make sure signatures match 5730 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5731 == PackageManager.SIGNATURE_MATCH; 5732 if (!match) { 5733 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5734 == PackageManager.SIGNATURE_MATCH; 5735 } 5736 if (!match) { 5737 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5738 == PackageManager.SIGNATURE_MATCH; 5739 } 5740 if (!match) { 5741 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5742 + pkg.packageName + " signatures do not match the " 5743 + "previously installed version; ignoring!"); 5744 } 5745 } 5746 5747 // Check for shared user signatures 5748 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5749 // Already existing package. Make sure signatures match 5750 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5751 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5752 if (!match) { 5753 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5754 == PackageManager.SIGNATURE_MATCH; 5755 } 5756 if (!match) { 5757 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5758 == PackageManager.SIGNATURE_MATCH; 5759 } 5760 if (!match) { 5761 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5762 "Package " + pkg.packageName 5763 + " has no signatures that match those in shared user " 5764 + pkgSetting.sharedUser.name + "; ignoring!"); 5765 } 5766 } 5767 } 5768 5769 /** 5770 * Enforces that only the system UID or root's UID can call a method exposed 5771 * via Binder. 5772 * 5773 * @param message used as message if SecurityException is thrown 5774 * @throws SecurityException if the caller is not system or root 5775 */ 5776 private static final void enforceSystemOrRoot(String message) { 5777 final int uid = Binder.getCallingUid(); 5778 if (uid != Process.SYSTEM_UID && uid != 0) { 5779 throw new SecurityException(message); 5780 } 5781 } 5782 5783 @Override 5784 public void performBootDexOpt() { 5785 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5786 5787 // Before everything else, see whether we need to fstrim. 5788 try { 5789 IMountService ms = PackageHelper.getMountService(); 5790 if (ms != null) { 5791 final boolean isUpgrade = isUpgrade(); 5792 boolean doTrim = isUpgrade; 5793 if (doTrim) { 5794 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5795 } else { 5796 final long interval = android.provider.Settings.Global.getLong( 5797 mContext.getContentResolver(), 5798 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5799 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5800 if (interval > 0) { 5801 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5802 if (timeSinceLast > interval) { 5803 doTrim = true; 5804 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5805 + "; running immediately"); 5806 } 5807 } 5808 } 5809 if (doTrim) { 5810 if (!isFirstBoot()) { 5811 try { 5812 ActivityManagerNative.getDefault().showBootMessage( 5813 mContext.getResources().getString( 5814 R.string.android_upgrading_fstrim), true); 5815 } catch (RemoteException e) { 5816 } 5817 } 5818 ms.runMaintenance(); 5819 } 5820 } else { 5821 Slog.e(TAG, "Mount service unavailable!"); 5822 } 5823 } catch (RemoteException e) { 5824 // Can't happen; MountService is local 5825 } 5826 5827 final ArraySet<PackageParser.Package> pkgs; 5828 synchronized (mPackages) { 5829 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5830 } 5831 5832 if (pkgs != null) { 5833 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5834 // in case the device runs out of space. 5835 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5836 // Give priority to core apps. 5837 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5838 PackageParser.Package pkg = it.next(); 5839 if (pkg.coreApp) { 5840 if (DEBUG_DEXOPT) { 5841 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5842 } 5843 sortedPkgs.add(pkg); 5844 it.remove(); 5845 } 5846 } 5847 // Give priority to system apps that listen for pre boot complete. 5848 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5849 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5850 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5851 PackageParser.Package pkg = it.next(); 5852 if (pkgNames.contains(pkg.packageName)) { 5853 if (DEBUG_DEXOPT) { 5854 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5855 } 5856 sortedPkgs.add(pkg); 5857 it.remove(); 5858 } 5859 } 5860 // Give priority to system apps. 5861 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5862 PackageParser.Package pkg = it.next(); 5863 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5864 if (DEBUG_DEXOPT) { 5865 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5866 } 5867 sortedPkgs.add(pkg); 5868 it.remove(); 5869 } 5870 } 5871 // Give priority to updated system apps. 5872 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5873 PackageParser.Package pkg = it.next(); 5874 if (pkg.isUpdatedSystemApp()) { 5875 if (DEBUG_DEXOPT) { 5876 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5877 } 5878 sortedPkgs.add(pkg); 5879 it.remove(); 5880 } 5881 } 5882 // Give priority to apps that listen for boot complete. 5883 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5884 pkgNames = getPackageNamesForIntent(intent); 5885 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5886 PackageParser.Package pkg = it.next(); 5887 if (pkgNames.contains(pkg.packageName)) { 5888 if (DEBUG_DEXOPT) { 5889 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5890 } 5891 sortedPkgs.add(pkg); 5892 it.remove(); 5893 } 5894 } 5895 // Filter out packages that aren't recently used. 5896 filterRecentlyUsedApps(pkgs); 5897 // Add all remaining apps. 5898 for (PackageParser.Package pkg : pkgs) { 5899 if (DEBUG_DEXOPT) { 5900 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5901 } 5902 sortedPkgs.add(pkg); 5903 } 5904 5905 // If we want to be lazy, filter everything that wasn't recently used. 5906 if (mLazyDexOpt) { 5907 filterRecentlyUsedApps(sortedPkgs); 5908 } 5909 5910 int i = 0; 5911 int total = sortedPkgs.size(); 5912 File dataDir = Environment.getDataDirectory(); 5913 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5914 if (lowThreshold == 0) { 5915 throw new IllegalStateException("Invalid low memory threshold"); 5916 } 5917 for (PackageParser.Package pkg : sortedPkgs) { 5918 long usableSpace = dataDir.getUsableSpace(); 5919 if (usableSpace < lowThreshold) { 5920 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5921 break; 5922 } 5923 performBootDexOpt(pkg, ++i, total); 5924 } 5925 } 5926 } 5927 5928 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5929 // Filter out packages that aren't recently used. 5930 // 5931 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5932 // should do a full dexopt. 5933 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5934 int total = pkgs.size(); 5935 int skipped = 0; 5936 long now = System.currentTimeMillis(); 5937 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5938 PackageParser.Package pkg = i.next(); 5939 long then = pkg.mLastPackageUsageTimeInMills; 5940 if (then + mDexOptLRUThresholdInMills < now) { 5941 if (DEBUG_DEXOPT) { 5942 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5943 ((then == 0) ? "never" : new Date(then))); 5944 } 5945 i.remove(); 5946 skipped++; 5947 } 5948 } 5949 if (DEBUG_DEXOPT) { 5950 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5951 } 5952 } 5953 } 5954 5955 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5956 List<ResolveInfo> ris = null; 5957 try { 5958 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5959 intent, null, 0, UserHandle.USER_OWNER); 5960 } catch (RemoteException e) { 5961 } 5962 ArraySet<String> pkgNames = new ArraySet<String>(); 5963 if (ris != null) { 5964 for (ResolveInfo ri : ris) { 5965 pkgNames.add(ri.activityInfo.packageName); 5966 } 5967 } 5968 return pkgNames; 5969 } 5970 5971 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5972 if (DEBUG_DEXOPT) { 5973 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5974 } 5975 if (!isFirstBoot()) { 5976 try { 5977 ActivityManagerNative.getDefault().showBootMessage( 5978 mContext.getResources().getString(R.string.android_upgrading_apk, 5979 curr, total), true); 5980 } catch (RemoteException e) { 5981 } 5982 } 5983 PackageParser.Package p = pkg; 5984 synchronized (mInstallLock) { 5985 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5986 false /* force dex */, false /* defer */, true /* include dependencies */); 5987 } 5988 } 5989 5990 @Override 5991 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5992 return performDexOpt(packageName, instructionSet, false); 5993 } 5994 5995 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5996 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5997 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5998 if (!dexopt && !updateUsage) { 5999 // We aren't going to dexopt or update usage, so bail early. 6000 return false; 6001 } 6002 PackageParser.Package p; 6003 final String targetInstructionSet; 6004 synchronized (mPackages) { 6005 p = mPackages.get(packageName); 6006 if (p == null) { 6007 return false; 6008 } 6009 if (updateUsage) { 6010 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6011 } 6012 mPackageUsage.write(false); 6013 if (!dexopt) { 6014 // We aren't going to dexopt, so bail early. 6015 return false; 6016 } 6017 6018 targetInstructionSet = instructionSet != null ? instructionSet : 6019 getPrimaryInstructionSet(p.applicationInfo); 6020 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6021 return false; 6022 } 6023 } 6024 6025 synchronized (mInstallLock) { 6026 final String[] instructionSets = new String[] { targetInstructionSet }; 6027 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6028 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6029 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6030 } 6031 } 6032 6033 public ArraySet<String> getPackagesThatNeedDexOpt() { 6034 ArraySet<String> pkgs = null; 6035 synchronized (mPackages) { 6036 for (PackageParser.Package p : mPackages.values()) { 6037 if (DEBUG_DEXOPT) { 6038 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6039 } 6040 if (!p.mDexOptPerformed.isEmpty()) { 6041 continue; 6042 } 6043 if (pkgs == null) { 6044 pkgs = new ArraySet<String>(); 6045 } 6046 pkgs.add(p.packageName); 6047 } 6048 } 6049 return pkgs; 6050 } 6051 6052 public void shutdown() { 6053 mPackageUsage.write(true); 6054 } 6055 6056 @Override 6057 public void forceDexOpt(String packageName) { 6058 enforceSystemOrRoot("forceDexOpt"); 6059 6060 PackageParser.Package pkg; 6061 synchronized (mPackages) { 6062 pkg = mPackages.get(packageName); 6063 if (pkg == null) { 6064 throw new IllegalArgumentException("Missing package: " + packageName); 6065 } 6066 } 6067 6068 synchronized (mInstallLock) { 6069 final String[] instructionSets = new String[] { 6070 getPrimaryInstructionSet(pkg.applicationInfo) }; 6071 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6072 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6073 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6074 throw new IllegalStateException("Failed to dexopt: " + res); 6075 } 6076 } 6077 } 6078 6079 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6080 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6081 Slog.w(TAG, "Unable to update from " + oldPkg.name 6082 + " to " + newPkg.packageName 6083 + ": old package not in system partition"); 6084 return false; 6085 } else if (mPackages.get(oldPkg.name) != null) { 6086 Slog.w(TAG, "Unable to update from " + oldPkg.name 6087 + " to " + newPkg.packageName 6088 + ": old package still exists"); 6089 return false; 6090 } 6091 return true; 6092 } 6093 6094 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6095 int[] users = sUserManager.getUserIds(); 6096 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6097 if (res < 0) { 6098 return res; 6099 } 6100 for (int user : users) { 6101 if (user != 0) { 6102 res = mInstaller.createUserData(volumeUuid, packageName, 6103 UserHandle.getUid(user, uid), user, seinfo); 6104 if (res < 0) { 6105 return res; 6106 } 6107 } 6108 } 6109 return res; 6110 } 6111 6112 private int removeDataDirsLI(String volumeUuid, String packageName) { 6113 int[] users = sUserManager.getUserIds(); 6114 int res = 0; 6115 for (int user : users) { 6116 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6117 if (resInner < 0) { 6118 res = resInner; 6119 } 6120 } 6121 6122 return res; 6123 } 6124 6125 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6126 int[] users = sUserManager.getUserIds(); 6127 int res = 0; 6128 for (int user : users) { 6129 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6130 if (resInner < 0) { 6131 res = resInner; 6132 } 6133 } 6134 return res; 6135 } 6136 6137 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6138 PackageParser.Package changingLib) { 6139 if (file.path != null) { 6140 usesLibraryFiles.add(file.path); 6141 return; 6142 } 6143 PackageParser.Package p = mPackages.get(file.apk); 6144 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6145 // If we are doing this while in the middle of updating a library apk, 6146 // then we need to make sure to use that new apk for determining the 6147 // dependencies here. (We haven't yet finished committing the new apk 6148 // to the package manager state.) 6149 if (p == null || p.packageName.equals(changingLib.packageName)) { 6150 p = changingLib; 6151 } 6152 } 6153 if (p != null) { 6154 usesLibraryFiles.addAll(p.getAllCodePaths()); 6155 } 6156 } 6157 6158 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6159 PackageParser.Package changingLib) throws PackageManagerException { 6160 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6161 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6162 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6163 for (int i=0; i<N; i++) { 6164 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6165 if (file == null) { 6166 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6167 "Package " + pkg.packageName + " requires unavailable shared library " 6168 + pkg.usesLibraries.get(i) + "; failing!"); 6169 } 6170 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6171 } 6172 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6173 for (int i=0; i<N; i++) { 6174 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6175 if (file == null) { 6176 Slog.w(TAG, "Package " + pkg.packageName 6177 + " desires unavailable shared library " 6178 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6179 } else { 6180 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6181 } 6182 } 6183 N = usesLibraryFiles.size(); 6184 if (N > 0) { 6185 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6186 } else { 6187 pkg.usesLibraryFiles = null; 6188 } 6189 } 6190 } 6191 6192 private static boolean hasString(List<String> list, List<String> which) { 6193 if (list == null) { 6194 return false; 6195 } 6196 for (int i=list.size()-1; i>=0; i--) { 6197 for (int j=which.size()-1; j>=0; j--) { 6198 if (which.get(j).equals(list.get(i))) { 6199 return true; 6200 } 6201 } 6202 } 6203 return false; 6204 } 6205 6206 private void updateAllSharedLibrariesLPw() { 6207 for (PackageParser.Package pkg : mPackages.values()) { 6208 try { 6209 updateSharedLibrariesLPw(pkg, null); 6210 } catch (PackageManagerException e) { 6211 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6212 } 6213 } 6214 } 6215 6216 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6217 PackageParser.Package changingPkg) { 6218 ArrayList<PackageParser.Package> res = null; 6219 for (PackageParser.Package pkg : mPackages.values()) { 6220 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6221 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6222 if (res == null) { 6223 res = new ArrayList<PackageParser.Package>(); 6224 } 6225 res.add(pkg); 6226 try { 6227 updateSharedLibrariesLPw(pkg, changingPkg); 6228 } catch (PackageManagerException e) { 6229 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6230 } 6231 } 6232 } 6233 return res; 6234 } 6235 6236 /** 6237 * Derive the value of the {@code cpuAbiOverride} based on the provided 6238 * value and an optional stored value from the package settings. 6239 */ 6240 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6241 String cpuAbiOverride = null; 6242 6243 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6244 cpuAbiOverride = null; 6245 } else if (abiOverride != null) { 6246 cpuAbiOverride = abiOverride; 6247 } else if (settings != null) { 6248 cpuAbiOverride = settings.cpuAbiOverrideString; 6249 } 6250 6251 return cpuAbiOverride; 6252 } 6253 6254 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6255 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6256 boolean success = false; 6257 try { 6258 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6259 currentTime, user); 6260 success = true; 6261 return res; 6262 } finally { 6263 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6264 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6265 } 6266 } 6267 } 6268 6269 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6270 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6271 final File scanFile = new File(pkg.codePath); 6272 if (pkg.applicationInfo.getCodePath() == null || 6273 pkg.applicationInfo.getResourcePath() == null) { 6274 // Bail out. The resource and code paths haven't been set. 6275 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6276 "Code and resource paths haven't been set correctly"); 6277 } 6278 6279 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6280 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6281 } else { 6282 // Only allow system apps to be flagged as core apps. 6283 pkg.coreApp = false; 6284 } 6285 6286 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6287 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6288 } 6289 6290 if (mCustomResolverComponentName != null && 6291 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6292 setUpCustomResolverActivity(pkg); 6293 } 6294 6295 if (pkg.packageName.equals("android")) { 6296 synchronized (mPackages) { 6297 if (mAndroidApplication != null) { 6298 Slog.w(TAG, "*************************************************"); 6299 Slog.w(TAG, "Core android package being redefined. Skipping."); 6300 Slog.w(TAG, " file=" + scanFile); 6301 Slog.w(TAG, "*************************************************"); 6302 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6303 "Core android package being redefined. Skipping."); 6304 } 6305 6306 // Set up information for our fall-back user intent resolution activity. 6307 mPlatformPackage = pkg; 6308 pkg.mVersionCode = mSdkVersion; 6309 mAndroidApplication = pkg.applicationInfo; 6310 6311 if (!mResolverReplaced) { 6312 mResolveActivity.applicationInfo = mAndroidApplication; 6313 mResolveActivity.name = ResolverActivity.class.getName(); 6314 mResolveActivity.packageName = mAndroidApplication.packageName; 6315 mResolveActivity.processName = "system:ui"; 6316 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6317 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6318 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6319 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6320 mResolveActivity.exported = true; 6321 mResolveActivity.enabled = true; 6322 mResolveInfo.activityInfo = mResolveActivity; 6323 mResolveInfo.priority = 0; 6324 mResolveInfo.preferredOrder = 0; 6325 mResolveInfo.match = 0; 6326 mResolveComponentName = new ComponentName( 6327 mAndroidApplication.packageName, mResolveActivity.name); 6328 } 6329 } 6330 } 6331 6332 if (DEBUG_PACKAGE_SCANNING) { 6333 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6334 Log.d(TAG, "Scanning package " + pkg.packageName); 6335 } 6336 6337 if (mPackages.containsKey(pkg.packageName) 6338 || mSharedLibraries.containsKey(pkg.packageName)) { 6339 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6340 "Application package " + pkg.packageName 6341 + " already installed. Skipping duplicate."); 6342 } 6343 6344 // If we're only installing presumed-existing packages, require that the 6345 // scanned APK is both already known and at the path previously established 6346 // for it. Previously unknown packages we pick up normally, but if we have an 6347 // a priori expectation about this package's install presence, enforce it. 6348 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6349 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6350 if (known != null) { 6351 if (DEBUG_PACKAGE_SCANNING) { 6352 Log.d(TAG, "Examining " + pkg.codePath 6353 + " and requiring known paths " + known.codePathString 6354 + " & " + known.resourcePathString); 6355 } 6356 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6357 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6358 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6359 "Application package " + pkg.packageName 6360 + " found at " + pkg.applicationInfo.getCodePath() 6361 + " but expected at " + known.codePathString + "; ignoring."); 6362 } 6363 } 6364 } 6365 6366 // Initialize package source and resource directories 6367 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6368 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6369 6370 SharedUserSetting suid = null; 6371 PackageSetting pkgSetting = null; 6372 6373 if (!isSystemApp(pkg)) { 6374 // Only system apps can use these features. 6375 pkg.mOriginalPackages = null; 6376 pkg.mRealPackage = null; 6377 pkg.mAdoptPermissions = null; 6378 } 6379 6380 // writer 6381 synchronized (mPackages) { 6382 if (pkg.mSharedUserId != null) { 6383 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6384 if (suid == null) { 6385 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6386 "Creating application package " + pkg.packageName 6387 + " for shared user failed"); 6388 } 6389 if (DEBUG_PACKAGE_SCANNING) { 6390 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6391 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6392 + "): packages=" + suid.packages); 6393 } 6394 } 6395 6396 // Check if we are renaming from an original package name. 6397 PackageSetting origPackage = null; 6398 String realName = null; 6399 if (pkg.mOriginalPackages != null) { 6400 // This package may need to be renamed to a previously 6401 // installed name. Let's check on that... 6402 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6403 if (pkg.mOriginalPackages.contains(renamed)) { 6404 // This package had originally been installed as the 6405 // original name, and we have already taken care of 6406 // transitioning to the new one. Just update the new 6407 // one to continue using the old name. 6408 realName = pkg.mRealPackage; 6409 if (!pkg.packageName.equals(renamed)) { 6410 // Callers into this function may have already taken 6411 // care of renaming the package; only do it here if 6412 // it is not already done. 6413 pkg.setPackageName(renamed); 6414 } 6415 6416 } else { 6417 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6418 if ((origPackage = mSettings.peekPackageLPr( 6419 pkg.mOriginalPackages.get(i))) != null) { 6420 // We do have the package already installed under its 6421 // original name... should we use it? 6422 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6423 // New package is not compatible with original. 6424 origPackage = null; 6425 continue; 6426 } else if (origPackage.sharedUser != null) { 6427 // Make sure uid is compatible between packages. 6428 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6429 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6430 + " to " + pkg.packageName + ": old uid " 6431 + origPackage.sharedUser.name 6432 + " differs from " + pkg.mSharedUserId); 6433 origPackage = null; 6434 continue; 6435 } 6436 } else { 6437 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6438 + pkg.packageName + " to old name " + origPackage.name); 6439 } 6440 break; 6441 } 6442 } 6443 } 6444 } 6445 6446 if (mTransferedPackages.contains(pkg.packageName)) { 6447 Slog.w(TAG, "Package " + pkg.packageName 6448 + " was transferred to another, but its .apk remains"); 6449 } 6450 6451 // Just create the setting, don't add it yet. For already existing packages 6452 // the PkgSetting exists already and doesn't have to be created. 6453 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6454 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6455 pkg.applicationInfo.primaryCpuAbi, 6456 pkg.applicationInfo.secondaryCpuAbi, 6457 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6458 user, false); 6459 if (pkgSetting == null) { 6460 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6461 "Creating application package " + pkg.packageName + " failed"); 6462 } 6463 6464 if (pkgSetting.origPackage != null) { 6465 // If we are first transitioning from an original package, 6466 // fix up the new package's name now. We need to do this after 6467 // looking up the package under its new name, so getPackageLP 6468 // can take care of fiddling things correctly. 6469 pkg.setPackageName(origPackage.name); 6470 6471 // File a report about this. 6472 String msg = "New package " + pkgSetting.realName 6473 + " renamed to replace old package " + pkgSetting.name; 6474 reportSettingsProblem(Log.WARN, msg); 6475 6476 // Make a note of it. 6477 mTransferedPackages.add(origPackage.name); 6478 6479 // No longer need to retain this. 6480 pkgSetting.origPackage = null; 6481 } 6482 6483 if (realName != null) { 6484 // Make a note of it. 6485 mTransferedPackages.add(pkg.packageName); 6486 } 6487 6488 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6489 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6490 } 6491 6492 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6493 // Check all shared libraries and map to their actual file path. 6494 // We only do this here for apps not on a system dir, because those 6495 // are the only ones that can fail an install due to this. We 6496 // will take care of the system apps by updating all of their 6497 // library paths after the scan is done. 6498 updateSharedLibrariesLPw(pkg, null); 6499 } 6500 6501 if (mFoundPolicyFile) { 6502 SELinuxMMAC.assignSeinfoValue(pkg); 6503 } 6504 6505 pkg.applicationInfo.uid = pkgSetting.appId; 6506 pkg.mExtras = pkgSetting; 6507 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6508 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6509 // We just determined the app is signed correctly, so bring 6510 // over the latest parsed certs. 6511 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6512 } else { 6513 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6514 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6515 "Package " + pkg.packageName + " upgrade keys do not match the " 6516 + "previously installed version"); 6517 } else { 6518 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6519 String msg = "System package " + pkg.packageName 6520 + " signature changed; retaining data."; 6521 reportSettingsProblem(Log.WARN, msg); 6522 } 6523 } 6524 } else { 6525 try { 6526 verifySignaturesLP(pkgSetting, pkg); 6527 // We just determined the app is signed correctly, so bring 6528 // over the latest parsed certs. 6529 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6530 } catch (PackageManagerException e) { 6531 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6532 throw e; 6533 } 6534 // The signature has changed, but this package is in the system 6535 // image... let's recover! 6536 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6537 // However... if this package is part of a shared user, but it 6538 // doesn't match the signature of the shared user, let's fail. 6539 // What this means is that you can't change the signatures 6540 // associated with an overall shared user, which doesn't seem all 6541 // that unreasonable. 6542 if (pkgSetting.sharedUser != null) { 6543 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6544 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6545 throw new PackageManagerException( 6546 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6547 "Signature mismatch for shared user : " 6548 + pkgSetting.sharedUser); 6549 } 6550 } 6551 // File a report about this. 6552 String msg = "System package " + pkg.packageName 6553 + " signature changed; retaining data."; 6554 reportSettingsProblem(Log.WARN, msg); 6555 } 6556 } 6557 // Verify that this new package doesn't have any content providers 6558 // that conflict with existing packages. Only do this if the 6559 // package isn't already installed, since we don't want to break 6560 // things that are installed. 6561 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6562 final int N = pkg.providers.size(); 6563 int i; 6564 for (i=0; i<N; i++) { 6565 PackageParser.Provider p = pkg.providers.get(i); 6566 if (p.info.authority != null) { 6567 String names[] = p.info.authority.split(";"); 6568 for (int j = 0; j < names.length; j++) { 6569 if (mProvidersByAuthority.containsKey(names[j])) { 6570 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6571 final String otherPackageName = 6572 ((other != null && other.getComponentName() != null) ? 6573 other.getComponentName().getPackageName() : "?"); 6574 throw new PackageManagerException( 6575 INSTALL_FAILED_CONFLICTING_PROVIDER, 6576 "Can't install because provider name " + names[j] 6577 + " (in package " + pkg.applicationInfo.packageName 6578 + ") is already used by " + otherPackageName); 6579 } 6580 } 6581 } 6582 } 6583 } 6584 6585 if (pkg.mAdoptPermissions != null) { 6586 // This package wants to adopt ownership of permissions from 6587 // another package. 6588 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6589 final String origName = pkg.mAdoptPermissions.get(i); 6590 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6591 if (orig != null) { 6592 if (verifyPackageUpdateLPr(orig, pkg)) { 6593 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6594 + pkg.packageName); 6595 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6596 } 6597 } 6598 } 6599 } 6600 } 6601 6602 final String pkgName = pkg.packageName; 6603 6604 final long scanFileTime = scanFile.lastModified(); 6605 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6606 pkg.applicationInfo.processName = fixProcessName( 6607 pkg.applicationInfo.packageName, 6608 pkg.applicationInfo.processName, 6609 pkg.applicationInfo.uid); 6610 6611 File dataPath; 6612 if (mPlatformPackage == pkg) { 6613 // The system package is special. 6614 dataPath = new File(Environment.getDataDirectory(), "system"); 6615 6616 pkg.applicationInfo.dataDir = dataPath.getPath(); 6617 6618 } else { 6619 // This is a normal package, need to make its data directory. 6620 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6621 UserHandle.USER_OWNER); 6622 6623 boolean uidError = false; 6624 if (dataPath.exists()) { 6625 int currentUid = 0; 6626 try { 6627 StructStat stat = Os.stat(dataPath.getPath()); 6628 currentUid = stat.st_uid; 6629 } catch (ErrnoException e) { 6630 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6631 } 6632 6633 // If we have mismatched owners for the data path, we have a problem. 6634 if (currentUid != pkg.applicationInfo.uid) { 6635 boolean recovered = false; 6636 if (currentUid == 0) { 6637 // The directory somehow became owned by root. Wow. 6638 // This is probably because the system was stopped while 6639 // installd was in the middle of messing with its libs 6640 // directory. Ask installd to fix that. 6641 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6642 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6643 if (ret >= 0) { 6644 recovered = true; 6645 String msg = "Package " + pkg.packageName 6646 + " unexpectedly changed to uid 0; recovered to " + 6647 + pkg.applicationInfo.uid; 6648 reportSettingsProblem(Log.WARN, msg); 6649 } 6650 } 6651 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6652 || (scanFlags&SCAN_BOOTING) != 0)) { 6653 // If this is a system app, we can at least delete its 6654 // current data so the application will still work. 6655 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6656 if (ret >= 0) { 6657 // TODO: Kill the processes first 6658 // Old data gone! 6659 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6660 ? "System package " : "Third party package "; 6661 String msg = prefix + pkg.packageName 6662 + " has changed from uid: " 6663 + currentUid + " to " 6664 + pkg.applicationInfo.uid + "; old data erased"; 6665 reportSettingsProblem(Log.WARN, msg); 6666 recovered = true; 6667 6668 // And now re-install the app. 6669 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6670 pkg.applicationInfo.seinfo); 6671 if (ret == -1) { 6672 // Ack should not happen! 6673 msg = prefix + pkg.packageName 6674 + " could not have data directory re-created after delete."; 6675 reportSettingsProblem(Log.WARN, msg); 6676 throw new PackageManagerException( 6677 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6678 } 6679 } 6680 if (!recovered) { 6681 mHasSystemUidErrors = true; 6682 } 6683 } else if (!recovered) { 6684 // If we allow this install to proceed, we will be broken. 6685 // Abort, abort! 6686 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6687 "scanPackageLI"); 6688 } 6689 if (!recovered) { 6690 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6691 + pkg.applicationInfo.uid + "/fs_" 6692 + currentUid; 6693 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6694 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6695 String msg = "Package " + pkg.packageName 6696 + " has mismatched uid: " 6697 + currentUid + " on disk, " 6698 + pkg.applicationInfo.uid + " in settings"; 6699 // writer 6700 synchronized (mPackages) { 6701 mSettings.mReadMessages.append(msg); 6702 mSettings.mReadMessages.append('\n'); 6703 uidError = true; 6704 if (!pkgSetting.uidError) { 6705 reportSettingsProblem(Log.ERROR, msg); 6706 } 6707 } 6708 } 6709 } 6710 pkg.applicationInfo.dataDir = dataPath.getPath(); 6711 if (mShouldRestoreconData) { 6712 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6713 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6714 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6715 } 6716 } else { 6717 if (DEBUG_PACKAGE_SCANNING) { 6718 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6719 Log.v(TAG, "Want this data dir: " + dataPath); 6720 } 6721 //invoke installer to do the actual installation 6722 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6723 pkg.applicationInfo.seinfo); 6724 if (ret < 0) { 6725 // Error from installer 6726 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6727 "Unable to create data dirs [errorCode=" + ret + "]"); 6728 } 6729 6730 if (dataPath.exists()) { 6731 pkg.applicationInfo.dataDir = dataPath.getPath(); 6732 } else { 6733 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6734 pkg.applicationInfo.dataDir = null; 6735 } 6736 } 6737 6738 pkgSetting.uidError = uidError; 6739 } 6740 6741 final String path = scanFile.getPath(); 6742 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6743 6744 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6745 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6746 6747 // Some system apps still use directory structure for native libraries 6748 // in which case we might end up not detecting abi solely based on apk 6749 // structure. Try to detect abi based on directory structure. 6750 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6751 pkg.applicationInfo.primaryCpuAbi == null) { 6752 setBundledAppAbisAndRoots(pkg, pkgSetting); 6753 setNativeLibraryPaths(pkg); 6754 } 6755 6756 } else { 6757 if ((scanFlags & SCAN_MOVE) != 0) { 6758 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6759 // but we already have this packages package info in the PackageSetting. We just 6760 // use that and derive the native library path based on the new codepath. 6761 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6762 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6763 } 6764 6765 // Set native library paths again. For moves, the path will be updated based on the 6766 // ABIs we've determined above. For non-moves, the path will be updated based on the 6767 // ABIs we determined during compilation, but the path will depend on the final 6768 // package path (after the rename away from the stage path). 6769 setNativeLibraryPaths(pkg); 6770 } 6771 6772 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6773 final int[] userIds = sUserManager.getUserIds(); 6774 synchronized (mInstallLock) { 6775 // Create a native library symlink only if we have native libraries 6776 // and if the native libraries are 32 bit libraries. We do not provide 6777 // this symlink for 64 bit libraries. 6778 if (pkg.applicationInfo.primaryCpuAbi != null && 6779 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6780 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6781 for (int userId : userIds) { 6782 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6783 nativeLibPath, userId) < 0) { 6784 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6785 "Failed linking native library dir (user=" + userId + ")"); 6786 } 6787 } 6788 } 6789 } 6790 6791 // This is a special case for the "system" package, where the ABI is 6792 // dictated by the zygote configuration (and init.rc). We should keep track 6793 // of this ABI so that we can deal with "normal" applications that run under 6794 // the same UID correctly. 6795 if (mPlatformPackage == pkg) { 6796 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6797 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6798 } 6799 6800 // If there's a mismatch between the abi-override in the package setting 6801 // and the abiOverride specified for the install. Warn about this because we 6802 // would've already compiled the app without taking the package setting into 6803 // account. 6804 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6805 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6806 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6807 " for package: " + pkg.packageName); 6808 } 6809 } 6810 6811 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6812 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6813 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6814 6815 // Copy the derived override back to the parsed package, so that we can 6816 // update the package settings accordingly. 6817 pkg.cpuAbiOverride = cpuAbiOverride; 6818 6819 if (DEBUG_ABI_SELECTION) { 6820 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6821 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6822 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6823 } 6824 6825 // Push the derived path down into PackageSettings so we know what to 6826 // clean up at uninstall time. 6827 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6828 6829 if (DEBUG_ABI_SELECTION) { 6830 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6831 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6832 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6833 } 6834 6835 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6836 // We don't do this here during boot because we can do it all 6837 // at once after scanning all existing packages. 6838 // 6839 // We also do this *before* we perform dexopt on this package, so that 6840 // we can avoid redundant dexopts, and also to make sure we've got the 6841 // code and package path correct. 6842 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6843 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6844 } 6845 6846 if ((scanFlags & SCAN_NO_DEX) == 0) { 6847 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6848 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6849 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6850 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6851 } 6852 } 6853 if (mFactoryTest && pkg.requestedPermissions.contains( 6854 android.Manifest.permission.FACTORY_TEST)) { 6855 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6856 } 6857 6858 ArrayList<PackageParser.Package> clientLibPkgs = null; 6859 6860 // writer 6861 synchronized (mPackages) { 6862 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6863 // Only system apps can add new shared libraries. 6864 if (pkg.libraryNames != null) { 6865 for (int i=0; i<pkg.libraryNames.size(); i++) { 6866 String name = pkg.libraryNames.get(i); 6867 boolean allowed = false; 6868 if (pkg.isUpdatedSystemApp()) { 6869 // New library entries can only be added through the 6870 // system image. This is important to get rid of a lot 6871 // of nasty edge cases: for example if we allowed a non- 6872 // system update of the app to add a library, then uninstalling 6873 // the update would make the library go away, and assumptions 6874 // we made such as through app install filtering would now 6875 // have allowed apps on the device which aren't compatible 6876 // with it. Better to just have the restriction here, be 6877 // conservative, and create many fewer cases that can negatively 6878 // impact the user experience. 6879 final PackageSetting sysPs = mSettings 6880 .getDisabledSystemPkgLPr(pkg.packageName); 6881 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6882 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6883 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6884 allowed = true; 6885 allowed = true; 6886 break; 6887 } 6888 } 6889 } 6890 } else { 6891 allowed = true; 6892 } 6893 if (allowed) { 6894 if (!mSharedLibraries.containsKey(name)) { 6895 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6896 } else if (!name.equals(pkg.packageName)) { 6897 Slog.w(TAG, "Package " + pkg.packageName + " library " 6898 + name + " already exists; skipping"); 6899 } 6900 } else { 6901 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6902 + name + " that is not declared on system image; skipping"); 6903 } 6904 } 6905 if ((scanFlags&SCAN_BOOTING) == 0) { 6906 // If we are not booting, we need to update any applications 6907 // that are clients of our shared library. If we are booting, 6908 // this will all be done once the scan is complete. 6909 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6910 } 6911 } 6912 } 6913 } 6914 6915 // We also need to dexopt any apps that are dependent on this library. Note that 6916 // if these fail, we should abort the install since installing the library will 6917 // result in some apps being broken. 6918 if (clientLibPkgs != null) { 6919 if ((scanFlags & SCAN_NO_DEX) == 0) { 6920 for (int i = 0; i < clientLibPkgs.size(); i++) { 6921 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6922 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6923 null /* instruction sets */, forceDex, 6924 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6925 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6926 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6927 "scanPackageLI failed to dexopt clientLibPkgs"); 6928 } 6929 } 6930 } 6931 } 6932 6933 // Also need to kill any apps that are dependent on the library. 6934 if (clientLibPkgs != null) { 6935 for (int i=0; i<clientLibPkgs.size(); i++) { 6936 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6937 killApplication(clientPkg.applicationInfo.packageName, 6938 clientPkg.applicationInfo.uid, "update lib"); 6939 } 6940 } 6941 6942 // Make sure we're not adding any bogus keyset info 6943 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6944 ksms.assertScannedPackageValid(pkg); 6945 6946 // writer 6947 synchronized (mPackages) { 6948 // We don't expect installation to fail beyond this point 6949 6950 // Add the new setting to mSettings 6951 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6952 // Add the new setting to mPackages 6953 mPackages.put(pkg.applicationInfo.packageName, pkg); 6954 // Make sure we don't accidentally delete its data. 6955 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6956 while (iter.hasNext()) { 6957 PackageCleanItem item = iter.next(); 6958 if (pkgName.equals(item.packageName)) { 6959 iter.remove(); 6960 } 6961 } 6962 6963 // Take care of first install / last update times. 6964 if (currentTime != 0) { 6965 if (pkgSetting.firstInstallTime == 0) { 6966 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6967 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6968 pkgSetting.lastUpdateTime = currentTime; 6969 } 6970 } else if (pkgSetting.firstInstallTime == 0) { 6971 // We need *something*. Take time time stamp of the file. 6972 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6973 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6974 if (scanFileTime != pkgSetting.timeStamp) { 6975 // A package on the system image has changed; consider this 6976 // to be an update. 6977 pkgSetting.lastUpdateTime = scanFileTime; 6978 } 6979 } 6980 6981 // Add the package's KeySets to the global KeySetManagerService 6982 ksms.addScannedPackageLPw(pkg); 6983 6984 int N = pkg.providers.size(); 6985 StringBuilder r = null; 6986 int i; 6987 for (i=0; i<N; i++) { 6988 PackageParser.Provider p = pkg.providers.get(i); 6989 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6990 p.info.processName, pkg.applicationInfo.uid); 6991 mProviders.addProvider(p); 6992 p.syncable = p.info.isSyncable; 6993 if (p.info.authority != null) { 6994 String names[] = p.info.authority.split(";"); 6995 p.info.authority = null; 6996 for (int j = 0; j < names.length; j++) { 6997 if (j == 1 && p.syncable) { 6998 // We only want the first authority for a provider to possibly be 6999 // syncable, so if we already added this provider using a different 7000 // authority clear the syncable flag. We copy the provider before 7001 // changing it because the mProviders object contains a reference 7002 // to a provider that we don't want to change. 7003 // Only do this for the second authority since the resulting provider 7004 // object can be the same for all future authorities for this provider. 7005 p = new PackageParser.Provider(p); 7006 p.syncable = false; 7007 } 7008 if (!mProvidersByAuthority.containsKey(names[j])) { 7009 mProvidersByAuthority.put(names[j], p); 7010 if (p.info.authority == null) { 7011 p.info.authority = names[j]; 7012 } else { 7013 p.info.authority = p.info.authority + ";" + names[j]; 7014 } 7015 if (DEBUG_PACKAGE_SCANNING) { 7016 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7017 Log.d(TAG, "Registered content provider: " + names[j] 7018 + ", className = " + p.info.name + ", isSyncable = " 7019 + p.info.isSyncable); 7020 } 7021 } else { 7022 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7023 Slog.w(TAG, "Skipping provider name " + names[j] + 7024 " (in package " + pkg.applicationInfo.packageName + 7025 "): name already used by " 7026 + ((other != null && other.getComponentName() != null) 7027 ? other.getComponentName().getPackageName() : "?")); 7028 } 7029 } 7030 } 7031 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7032 if (r == null) { 7033 r = new StringBuilder(256); 7034 } else { 7035 r.append(' '); 7036 } 7037 r.append(p.info.name); 7038 } 7039 } 7040 if (r != null) { 7041 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7042 } 7043 7044 N = pkg.services.size(); 7045 r = null; 7046 for (i=0; i<N; i++) { 7047 PackageParser.Service s = pkg.services.get(i); 7048 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7049 s.info.processName, pkg.applicationInfo.uid); 7050 mServices.addService(s); 7051 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7052 if (r == null) { 7053 r = new StringBuilder(256); 7054 } else { 7055 r.append(' '); 7056 } 7057 r.append(s.info.name); 7058 } 7059 } 7060 if (r != null) { 7061 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7062 } 7063 7064 N = pkg.receivers.size(); 7065 r = null; 7066 for (i=0; i<N; i++) { 7067 PackageParser.Activity a = pkg.receivers.get(i); 7068 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7069 a.info.processName, pkg.applicationInfo.uid); 7070 mReceivers.addActivity(a, "receiver"); 7071 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7072 if (r == null) { 7073 r = new StringBuilder(256); 7074 } else { 7075 r.append(' '); 7076 } 7077 r.append(a.info.name); 7078 } 7079 } 7080 if (r != null) { 7081 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7082 } 7083 7084 N = pkg.activities.size(); 7085 r = null; 7086 for (i=0; i<N; i++) { 7087 PackageParser.Activity a = pkg.activities.get(i); 7088 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7089 a.info.processName, pkg.applicationInfo.uid); 7090 mActivities.addActivity(a, "activity"); 7091 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7092 if (r == null) { 7093 r = new StringBuilder(256); 7094 } else { 7095 r.append(' '); 7096 } 7097 r.append(a.info.name); 7098 } 7099 } 7100 if (r != null) { 7101 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7102 } 7103 7104 N = pkg.permissionGroups.size(); 7105 r = null; 7106 for (i=0; i<N; i++) { 7107 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7108 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7109 if (cur == null) { 7110 mPermissionGroups.put(pg.info.name, pg); 7111 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7112 if (r == null) { 7113 r = new StringBuilder(256); 7114 } else { 7115 r.append(' '); 7116 } 7117 r.append(pg.info.name); 7118 } 7119 } else { 7120 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7121 + pg.info.packageName + " ignored: original from " 7122 + cur.info.packageName); 7123 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7124 if (r == null) { 7125 r = new StringBuilder(256); 7126 } else { 7127 r.append(' '); 7128 } 7129 r.append("DUP:"); 7130 r.append(pg.info.name); 7131 } 7132 } 7133 } 7134 if (r != null) { 7135 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7136 } 7137 7138 N = pkg.permissions.size(); 7139 r = null; 7140 for (i=0; i<N; i++) { 7141 PackageParser.Permission p = pkg.permissions.get(i); 7142 7143 // Now that permission groups have a special meaning, we ignore permission 7144 // groups for legacy apps to prevent unexpected behavior. In particular, 7145 // permissions for one app being granted to someone just becuase they happen 7146 // to be in a group defined by another app (before this had no implications). 7147 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7148 p.group = mPermissionGroups.get(p.info.group); 7149 // Warn for a permission in an unknown group. 7150 if (p.info.group != null && p.group == null) { 7151 Slog.w(TAG, "Permission " + p.info.name + " from package " 7152 + p.info.packageName + " in an unknown group " + p.info.group); 7153 } 7154 } 7155 7156 ArrayMap<String, BasePermission> permissionMap = 7157 p.tree ? mSettings.mPermissionTrees 7158 : mSettings.mPermissions; 7159 BasePermission bp = permissionMap.get(p.info.name); 7160 7161 // Allow system apps to redefine non-system permissions 7162 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7163 final boolean currentOwnerIsSystem = (bp.perm != null 7164 && isSystemApp(bp.perm.owner)); 7165 if (isSystemApp(p.owner)) { 7166 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7167 // It's a built-in permission and no owner, take ownership now 7168 bp.packageSetting = pkgSetting; 7169 bp.perm = p; 7170 bp.uid = pkg.applicationInfo.uid; 7171 bp.sourcePackage = p.info.packageName; 7172 } else if (!currentOwnerIsSystem) { 7173 String msg = "New decl " + p.owner + " of permission " 7174 + p.info.name + " is system; overriding " + bp.sourcePackage; 7175 reportSettingsProblem(Log.WARN, msg); 7176 bp = null; 7177 } 7178 } 7179 } 7180 7181 if (bp == null) { 7182 bp = new BasePermission(p.info.name, p.info.packageName, 7183 BasePermission.TYPE_NORMAL); 7184 permissionMap.put(p.info.name, bp); 7185 } 7186 7187 if (bp.perm == null) { 7188 if (bp.sourcePackage == null 7189 || bp.sourcePackage.equals(p.info.packageName)) { 7190 BasePermission tree = findPermissionTreeLP(p.info.name); 7191 if (tree == null 7192 || tree.sourcePackage.equals(p.info.packageName)) { 7193 bp.packageSetting = pkgSetting; 7194 bp.perm = p; 7195 bp.uid = pkg.applicationInfo.uid; 7196 bp.sourcePackage = p.info.packageName; 7197 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7198 if (r == null) { 7199 r = new StringBuilder(256); 7200 } else { 7201 r.append(' '); 7202 } 7203 r.append(p.info.name); 7204 } 7205 } else { 7206 Slog.w(TAG, "Permission " + p.info.name + " from package " 7207 + p.info.packageName + " ignored: base tree " 7208 + tree.name + " is from package " 7209 + tree.sourcePackage); 7210 } 7211 } else { 7212 Slog.w(TAG, "Permission " + p.info.name + " from package " 7213 + p.info.packageName + " ignored: original from " 7214 + bp.sourcePackage); 7215 } 7216 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7217 if (r == null) { 7218 r = new StringBuilder(256); 7219 } else { 7220 r.append(' '); 7221 } 7222 r.append("DUP:"); 7223 r.append(p.info.name); 7224 } 7225 if (bp.perm == p) { 7226 bp.protectionLevel = p.info.protectionLevel; 7227 } 7228 } 7229 7230 if (r != null) { 7231 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7232 } 7233 7234 N = pkg.instrumentation.size(); 7235 r = null; 7236 for (i=0; i<N; i++) { 7237 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7238 a.info.packageName = pkg.applicationInfo.packageName; 7239 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7240 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7241 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7242 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7243 a.info.dataDir = pkg.applicationInfo.dataDir; 7244 7245 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7246 // need other information about the application, like the ABI and what not ? 7247 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7248 mInstrumentation.put(a.getComponentName(), a); 7249 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7250 if (r == null) { 7251 r = new StringBuilder(256); 7252 } else { 7253 r.append(' '); 7254 } 7255 r.append(a.info.name); 7256 } 7257 } 7258 if (r != null) { 7259 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7260 } 7261 7262 if (pkg.protectedBroadcasts != null) { 7263 N = pkg.protectedBroadcasts.size(); 7264 for (i=0; i<N; i++) { 7265 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7266 } 7267 } 7268 7269 pkgSetting.setTimeStamp(scanFileTime); 7270 7271 // Create idmap files for pairs of (packages, overlay packages). 7272 // Note: "android", ie framework-res.apk, is handled by native layers. 7273 if (pkg.mOverlayTarget != null) { 7274 // This is an overlay package. 7275 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7276 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7277 mOverlays.put(pkg.mOverlayTarget, 7278 new ArrayMap<String, PackageParser.Package>()); 7279 } 7280 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7281 map.put(pkg.packageName, pkg); 7282 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7283 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7284 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7285 "scanPackageLI failed to createIdmap"); 7286 } 7287 } 7288 } else if (mOverlays.containsKey(pkg.packageName) && 7289 !pkg.packageName.equals("android")) { 7290 // This is a regular package, with one or more known overlay packages. 7291 createIdmapsForPackageLI(pkg); 7292 } 7293 } 7294 7295 return pkg; 7296 } 7297 7298 /** 7299 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7300 * is derived purely on the basis of the contents of {@code scanFile} and 7301 * {@code cpuAbiOverride}. 7302 * 7303 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7304 */ 7305 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7306 String cpuAbiOverride, boolean extractLibs) 7307 throws PackageManagerException { 7308 // TODO: We can probably be smarter about this stuff. For installed apps, 7309 // we can calculate this information at install time once and for all. For 7310 // system apps, we can probably assume that this information doesn't change 7311 // after the first boot scan. As things stand, we do lots of unnecessary work. 7312 7313 // Give ourselves some initial paths; we'll come back for another 7314 // pass once we've determined ABI below. 7315 setNativeLibraryPaths(pkg); 7316 7317 // We would never need to extract libs for forward-locked and external packages, 7318 // since the container service will do it for us. We shouldn't attempt to 7319 // extract libs from system app when it was not updated. 7320 if (pkg.isForwardLocked() || isExternal(pkg) || 7321 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7322 extractLibs = false; 7323 } 7324 7325 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7326 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7327 7328 NativeLibraryHelper.Handle handle = null; 7329 try { 7330 handle = NativeLibraryHelper.Handle.create(scanFile); 7331 // TODO(multiArch): This can be null for apps that didn't go through the 7332 // usual installation process. We can calculate it again, like we 7333 // do during install time. 7334 // 7335 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7336 // unnecessary. 7337 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7338 7339 // Null out the abis so that they can be recalculated. 7340 pkg.applicationInfo.primaryCpuAbi = null; 7341 pkg.applicationInfo.secondaryCpuAbi = null; 7342 if (isMultiArch(pkg.applicationInfo)) { 7343 // Warn if we've set an abiOverride for multi-lib packages.. 7344 // By definition, we need to copy both 32 and 64 bit libraries for 7345 // such packages. 7346 if (pkg.cpuAbiOverride != null 7347 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7348 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7349 } 7350 7351 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7352 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7353 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7354 if (extractLibs) { 7355 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7356 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7357 useIsaSpecificSubdirs); 7358 } else { 7359 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7360 } 7361 } 7362 7363 maybeThrowExceptionForMultiArchCopy( 7364 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7365 7366 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7367 if (extractLibs) { 7368 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7369 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7370 useIsaSpecificSubdirs); 7371 } else { 7372 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7373 } 7374 } 7375 7376 maybeThrowExceptionForMultiArchCopy( 7377 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7378 7379 if (abi64 >= 0) { 7380 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7381 } 7382 7383 if (abi32 >= 0) { 7384 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7385 if (abi64 >= 0) { 7386 pkg.applicationInfo.secondaryCpuAbi = abi; 7387 } else { 7388 pkg.applicationInfo.primaryCpuAbi = abi; 7389 } 7390 } 7391 } else { 7392 String[] abiList = (cpuAbiOverride != null) ? 7393 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7394 7395 // Enable gross and lame hacks for apps that are built with old 7396 // SDK tools. We must scan their APKs for renderscript bitcode and 7397 // not launch them if it's present. Don't bother checking on devices 7398 // that don't have 64 bit support. 7399 boolean needsRenderScriptOverride = false; 7400 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7401 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7402 abiList = Build.SUPPORTED_32_BIT_ABIS; 7403 needsRenderScriptOverride = true; 7404 } 7405 7406 final int copyRet; 7407 if (extractLibs) { 7408 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7409 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7410 } else { 7411 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7412 } 7413 7414 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7415 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7416 "Error unpackaging native libs for app, errorCode=" + copyRet); 7417 } 7418 7419 if (copyRet >= 0) { 7420 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7421 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7422 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7423 } else if (needsRenderScriptOverride) { 7424 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7425 } 7426 } 7427 } catch (IOException ioe) { 7428 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7429 } finally { 7430 IoUtils.closeQuietly(handle); 7431 } 7432 7433 // Now that we've calculated the ABIs and determined if it's an internal app, 7434 // we will go ahead and populate the nativeLibraryPath. 7435 setNativeLibraryPaths(pkg); 7436 } 7437 7438 /** 7439 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7440 * i.e, so that all packages can be run inside a single process if required. 7441 * 7442 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7443 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7444 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7445 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7446 * updating a package that belongs to a shared user. 7447 * 7448 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7449 * adds unnecessary complexity. 7450 */ 7451 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7452 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7453 String requiredInstructionSet = null; 7454 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7455 requiredInstructionSet = VMRuntime.getInstructionSet( 7456 scannedPackage.applicationInfo.primaryCpuAbi); 7457 } 7458 7459 PackageSetting requirer = null; 7460 for (PackageSetting ps : packagesForUser) { 7461 // If packagesForUser contains scannedPackage, we skip it. This will happen 7462 // when scannedPackage is an update of an existing package. Without this check, 7463 // we will never be able to change the ABI of any package belonging to a shared 7464 // user, even if it's compatible with other packages. 7465 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7466 if (ps.primaryCpuAbiString == null) { 7467 continue; 7468 } 7469 7470 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7471 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7472 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7473 // this but there's not much we can do. 7474 String errorMessage = "Instruction set mismatch, " 7475 + ((requirer == null) ? "[caller]" : requirer) 7476 + " requires " + requiredInstructionSet + " whereas " + ps 7477 + " requires " + instructionSet; 7478 Slog.w(TAG, errorMessage); 7479 } 7480 7481 if (requiredInstructionSet == null) { 7482 requiredInstructionSet = instructionSet; 7483 requirer = ps; 7484 } 7485 } 7486 } 7487 7488 if (requiredInstructionSet != null) { 7489 String adjustedAbi; 7490 if (requirer != null) { 7491 // requirer != null implies that either scannedPackage was null or that scannedPackage 7492 // did not require an ABI, in which case we have to adjust scannedPackage to match 7493 // the ABI of the set (which is the same as requirer's ABI) 7494 adjustedAbi = requirer.primaryCpuAbiString; 7495 if (scannedPackage != null) { 7496 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7497 } 7498 } else { 7499 // requirer == null implies that we're updating all ABIs in the set to 7500 // match scannedPackage. 7501 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7502 } 7503 7504 for (PackageSetting ps : packagesForUser) { 7505 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7506 if (ps.primaryCpuAbiString != null) { 7507 continue; 7508 } 7509 7510 ps.primaryCpuAbiString = adjustedAbi; 7511 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7512 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7513 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7514 7515 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7516 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7517 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7518 ps.primaryCpuAbiString = null; 7519 ps.pkg.applicationInfo.primaryCpuAbi = null; 7520 return; 7521 } else { 7522 mInstaller.rmdex(ps.codePathString, 7523 getDexCodeInstructionSet(getPreferredInstructionSet())); 7524 } 7525 } 7526 } 7527 } 7528 } 7529 } 7530 7531 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7532 synchronized (mPackages) { 7533 mResolverReplaced = true; 7534 // Set up information for custom user intent resolution activity. 7535 mResolveActivity.applicationInfo = pkg.applicationInfo; 7536 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7537 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7538 mResolveActivity.processName = pkg.applicationInfo.packageName; 7539 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7540 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7541 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7542 mResolveActivity.theme = 0; 7543 mResolveActivity.exported = true; 7544 mResolveActivity.enabled = true; 7545 mResolveInfo.activityInfo = mResolveActivity; 7546 mResolveInfo.priority = 0; 7547 mResolveInfo.preferredOrder = 0; 7548 mResolveInfo.match = 0; 7549 mResolveComponentName = mCustomResolverComponentName; 7550 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7551 mResolveComponentName); 7552 } 7553 } 7554 7555 private static String calculateBundledApkRoot(final String codePathString) { 7556 final File codePath = new File(codePathString); 7557 final File codeRoot; 7558 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7559 codeRoot = Environment.getRootDirectory(); 7560 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7561 codeRoot = Environment.getOemDirectory(); 7562 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7563 codeRoot = Environment.getVendorDirectory(); 7564 } else { 7565 // Unrecognized code path; take its top real segment as the apk root: 7566 // e.g. /something/app/blah.apk => /something 7567 try { 7568 File f = codePath.getCanonicalFile(); 7569 File parent = f.getParentFile(); // non-null because codePath is a file 7570 File tmp; 7571 while ((tmp = parent.getParentFile()) != null) { 7572 f = parent; 7573 parent = tmp; 7574 } 7575 codeRoot = f; 7576 Slog.w(TAG, "Unrecognized code path " 7577 + codePath + " - using " + codeRoot); 7578 } catch (IOException e) { 7579 // Can't canonicalize the code path -- shenanigans? 7580 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7581 return Environment.getRootDirectory().getPath(); 7582 } 7583 } 7584 return codeRoot.getPath(); 7585 } 7586 7587 /** 7588 * Derive and set the location of native libraries for the given package, 7589 * which varies depending on where and how the package was installed. 7590 */ 7591 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7592 final ApplicationInfo info = pkg.applicationInfo; 7593 final String codePath = pkg.codePath; 7594 final File codeFile = new File(codePath); 7595 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7596 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7597 7598 info.nativeLibraryRootDir = null; 7599 info.nativeLibraryRootRequiresIsa = false; 7600 info.nativeLibraryDir = null; 7601 info.secondaryNativeLibraryDir = null; 7602 7603 if (isApkFile(codeFile)) { 7604 // Monolithic install 7605 if (bundledApp) { 7606 // If "/system/lib64/apkname" exists, assume that is the per-package 7607 // native library directory to use; otherwise use "/system/lib/apkname". 7608 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7609 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7610 getPrimaryInstructionSet(info)); 7611 7612 // This is a bundled system app so choose the path based on the ABI. 7613 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7614 // is just the default path. 7615 final String apkName = deriveCodePathName(codePath); 7616 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7617 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7618 apkName).getAbsolutePath(); 7619 7620 if (info.secondaryCpuAbi != null) { 7621 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7622 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7623 secondaryLibDir, apkName).getAbsolutePath(); 7624 } 7625 } else if (asecApp) { 7626 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7627 .getAbsolutePath(); 7628 } else { 7629 final String apkName = deriveCodePathName(codePath); 7630 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7631 .getAbsolutePath(); 7632 } 7633 7634 info.nativeLibraryRootRequiresIsa = false; 7635 info.nativeLibraryDir = info.nativeLibraryRootDir; 7636 } else { 7637 // Cluster install 7638 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7639 info.nativeLibraryRootRequiresIsa = true; 7640 7641 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7642 getPrimaryInstructionSet(info)).getAbsolutePath(); 7643 7644 if (info.secondaryCpuAbi != null) { 7645 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7646 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7647 } 7648 } 7649 } 7650 7651 /** 7652 * Calculate the abis and roots for a bundled app. These can uniquely 7653 * be determined from the contents of the system partition, i.e whether 7654 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7655 * of this information, and instead assume that the system was built 7656 * sensibly. 7657 */ 7658 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7659 PackageSetting pkgSetting) { 7660 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7661 7662 // If "/system/lib64/apkname" exists, assume that is the per-package 7663 // native library directory to use; otherwise use "/system/lib/apkname". 7664 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7665 setBundledAppAbi(pkg, apkRoot, apkName); 7666 // pkgSetting might be null during rescan following uninstall of updates 7667 // to a bundled app, so accommodate that possibility. The settings in 7668 // that case will be established later from the parsed package. 7669 // 7670 // If the settings aren't null, sync them up with what we've just derived. 7671 // note that apkRoot isn't stored in the package settings. 7672 if (pkgSetting != null) { 7673 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7674 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7675 } 7676 } 7677 7678 /** 7679 * Deduces the ABI of a bundled app and sets the relevant fields on the 7680 * parsed pkg object. 7681 * 7682 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7683 * under which system libraries are installed. 7684 * @param apkName the name of the installed package. 7685 */ 7686 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7687 final File codeFile = new File(pkg.codePath); 7688 7689 final boolean has64BitLibs; 7690 final boolean has32BitLibs; 7691 if (isApkFile(codeFile)) { 7692 // Monolithic install 7693 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7694 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7695 } else { 7696 // Cluster install 7697 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7698 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7699 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7700 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7701 has64BitLibs = (new File(rootDir, isa)).exists(); 7702 } else { 7703 has64BitLibs = false; 7704 } 7705 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7706 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7707 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7708 has32BitLibs = (new File(rootDir, isa)).exists(); 7709 } else { 7710 has32BitLibs = false; 7711 } 7712 } 7713 7714 if (has64BitLibs && !has32BitLibs) { 7715 // The package has 64 bit libs, but not 32 bit libs. Its primary 7716 // ABI should be 64 bit. We can safely assume here that the bundled 7717 // native libraries correspond to the most preferred ABI in the list. 7718 7719 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7720 pkg.applicationInfo.secondaryCpuAbi = null; 7721 } else if (has32BitLibs && !has64BitLibs) { 7722 // The package has 32 bit libs but not 64 bit libs. Its primary 7723 // ABI should be 32 bit. 7724 7725 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7726 pkg.applicationInfo.secondaryCpuAbi = null; 7727 } else if (has32BitLibs && has64BitLibs) { 7728 // The application has both 64 and 32 bit bundled libraries. We check 7729 // here that the app declares multiArch support, and warn if it doesn't. 7730 // 7731 // We will be lenient here and record both ABIs. The primary will be the 7732 // ABI that's higher on the list, i.e, a device that's configured to prefer 7733 // 64 bit apps will see a 64 bit primary ABI, 7734 7735 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7736 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7737 } 7738 7739 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7740 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7741 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7742 } else { 7743 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7744 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7745 } 7746 } else { 7747 pkg.applicationInfo.primaryCpuAbi = null; 7748 pkg.applicationInfo.secondaryCpuAbi = null; 7749 } 7750 } 7751 7752 private void killApplication(String pkgName, int appId, String reason) { 7753 // Request the ActivityManager to kill the process(only for existing packages) 7754 // so that we do not end up in a confused state while the user is still using the older 7755 // version of the application while the new one gets installed. 7756 IActivityManager am = ActivityManagerNative.getDefault(); 7757 if (am != null) { 7758 try { 7759 am.killApplicationWithAppId(pkgName, appId, reason); 7760 } catch (RemoteException e) { 7761 } 7762 } 7763 } 7764 7765 void removePackageLI(PackageSetting ps, boolean chatty) { 7766 if (DEBUG_INSTALL) { 7767 if (chatty) 7768 Log.d(TAG, "Removing package " + ps.name); 7769 } 7770 7771 // writer 7772 synchronized (mPackages) { 7773 mPackages.remove(ps.name); 7774 final PackageParser.Package pkg = ps.pkg; 7775 if (pkg != null) { 7776 cleanPackageDataStructuresLILPw(pkg, chatty); 7777 } 7778 } 7779 } 7780 7781 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7782 if (DEBUG_INSTALL) { 7783 if (chatty) 7784 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7785 } 7786 7787 // writer 7788 synchronized (mPackages) { 7789 mPackages.remove(pkg.applicationInfo.packageName); 7790 cleanPackageDataStructuresLILPw(pkg, chatty); 7791 } 7792 } 7793 7794 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7795 int N = pkg.providers.size(); 7796 StringBuilder r = null; 7797 int i; 7798 for (i=0; i<N; i++) { 7799 PackageParser.Provider p = pkg.providers.get(i); 7800 mProviders.removeProvider(p); 7801 if (p.info.authority == null) { 7802 7803 /* There was another ContentProvider with this authority when 7804 * this app was installed so this authority is null, 7805 * Ignore it as we don't have to unregister the provider. 7806 */ 7807 continue; 7808 } 7809 String names[] = p.info.authority.split(";"); 7810 for (int j = 0; j < names.length; j++) { 7811 if (mProvidersByAuthority.get(names[j]) == p) { 7812 mProvidersByAuthority.remove(names[j]); 7813 if (DEBUG_REMOVE) { 7814 if (chatty) 7815 Log.d(TAG, "Unregistered content provider: " + names[j] 7816 + ", className = " + p.info.name + ", isSyncable = " 7817 + p.info.isSyncable); 7818 } 7819 } 7820 } 7821 if (DEBUG_REMOVE && chatty) { 7822 if (r == null) { 7823 r = new StringBuilder(256); 7824 } else { 7825 r.append(' '); 7826 } 7827 r.append(p.info.name); 7828 } 7829 } 7830 if (r != null) { 7831 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7832 } 7833 7834 N = pkg.services.size(); 7835 r = null; 7836 for (i=0; i<N; i++) { 7837 PackageParser.Service s = pkg.services.get(i); 7838 mServices.removeService(s); 7839 if (chatty) { 7840 if (r == null) { 7841 r = new StringBuilder(256); 7842 } else { 7843 r.append(' '); 7844 } 7845 r.append(s.info.name); 7846 } 7847 } 7848 if (r != null) { 7849 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7850 } 7851 7852 N = pkg.receivers.size(); 7853 r = null; 7854 for (i=0; i<N; i++) { 7855 PackageParser.Activity a = pkg.receivers.get(i); 7856 mReceivers.removeActivity(a, "receiver"); 7857 if (DEBUG_REMOVE && chatty) { 7858 if (r == null) { 7859 r = new StringBuilder(256); 7860 } else { 7861 r.append(' '); 7862 } 7863 r.append(a.info.name); 7864 } 7865 } 7866 if (r != null) { 7867 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7868 } 7869 7870 N = pkg.activities.size(); 7871 r = null; 7872 for (i=0; i<N; i++) { 7873 PackageParser.Activity a = pkg.activities.get(i); 7874 mActivities.removeActivity(a, "activity"); 7875 if (DEBUG_REMOVE && chatty) { 7876 if (r == null) { 7877 r = new StringBuilder(256); 7878 } else { 7879 r.append(' '); 7880 } 7881 r.append(a.info.name); 7882 } 7883 } 7884 if (r != null) { 7885 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7886 } 7887 7888 N = pkg.permissions.size(); 7889 r = null; 7890 for (i=0; i<N; i++) { 7891 PackageParser.Permission p = pkg.permissions.get(i); 7892 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7893 if (bp == null) { 7894 bp = mSettings.mPermissionTrees.get(p.info.name); 7895 } 7896 if (bp != null && bp.perm == p) { 7897 bp.perm = null; 7898 if (DEBUG_REMOVE && chatty) { 7899 if (r == null) { 7900 r = new StringBuilder(256); 7901 } else { 7902 r.append(' '); 7903 } 7904 r.append(p.info.name); 7905 } 7906 } 7907 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7908 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7909 if (appOpPerms != null) { 7910 appOpPerms.remove(pkg.packageName); 7911 } 7912 } 7913 } 7914 if (r != null) { 7915 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7916 } 7917 7918 N = pkg.requestedPermissions.size(); 7919 r = null; 7920 for (i=0; i<N; i++) { 7921 String perm = pkg.requestedPermissions.get(i); 7922 BasePermission bp = mSettings.mPermissions.get(perm); 7923 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7924 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7925 if (appOpPerms != null) { 7926 appOpPerms.remove(pkg.packageName); 7927 if (appOpPerms.isEmpty()) { 7928 mAppOpPermissionPackages.remove(perm); 7929 } 7930 } 7931 } 7932 } 7933 if (r != null) { 7934 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7935 } 7936 7937 N = pkg.instrumentation.size(); 7938 r = null; 7939 for (i=0; i<N; i++) { 7940 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7941 mInstrumentation.remove(a.getComponentName()); 7942 if (DEBUG_REMOVE && chatty) { 7943 if (r == null) { 7944 r = new StringBuilder(256); 7945 } else { 7946 r.append(' '); 7947 } 7948 r.append(a.info.name); 7949 } 7950 } 7951 if (r != null) { 7952 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7953 } 7954 7955 r = null; 7956 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7957 // Only system apps can hold shared libraries. 7958 if (pkg.libraryNames != null) { 7959 for (i=0; i<pkg.libraryNames.size(); i++) { 7960 String name = pkg.libraryNames.get(i); 7961 SharedLibraryEntry cur = mSharedLibraries.get(name); 7962 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7963 mSharedLibraries.remove(name); 7964 if (DEBUG_REMOVE && chatty) { 7965 if (r == null) { 7966 r = new StringBuilder(256); 7967 } else { 7968 r.append(' '); 7969 } 7970 r.append(name); 7971 } 7972 } 7973 } 7974 } 7975 } 7976 if (r != null) { 7977 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7978 } 7979 } 7980 7981 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7982 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7983 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7984 return true; 7985 } 7986 } 7987 return false; 7988 } 7989 7990 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7991 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7992 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7993 7994 private void updatePermissionsLPw(String changingPkg, 7995 PackageParser.Package pkgInfo, int flags) { 7996 // Make sure there are no dangling permission trees. 7997 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7998 while (it.hasNext()) { 7999 final BasePermission bp = it.next(); 8000 if (bp.packageSetting == null) { 8001 // We may not yet have parsed the package, so just see if 8002 // we still know about its settings. 8003 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8004 } 8005 if (bp.packageSetting == null) { 8006 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8007 + " from package " + bp.sourcePackage); 8008 it.remove(); 8009 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8010 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8011 Slog.i(TAG, "Removing old permission tree: " + bp.name 8012 + " from package " + bp.sourcePackage); 8013 flags |= UPDATE_PERMISSIONS_ALL; 8014 it.remove(); 8015 } 8016 } 8017 } 8018 8019 // Make sure all dynamic permissions have been assigned to a package, 8020 // and make sure there are no dangling permissions. 8021 it = mSettings.mPermissions.values().iterator(); 8022 while (it.hasNext()) { 8023 final BasePermission bp = it.next(); 8024 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8025 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8026 + bp.name + " pkg=" + bp.sourcePackage 8027 + " info=" + bp.pendingInfo); 8028 if (bp.packageSetting == null && bp.pendingInfo != null) { 8029 final BasePermission tree = findPermissionTreeLP(bp.name); 8030 if (tree != null && tree.perm != null) { 8031 bp.packageSetting = tree.packageSetting; 8032 bp.perm = new PackageParser.Permission(tree.perm.owner, 8033 new PermissionInfo(bp.pendingInfo)); 8034 bp.perm.info.packageName = tree.perm.info.packageName; 8035 bp.perm.info.name = bp.name; 8036 bp.uid = tree.uid; 8037 } 8038 } 8039 } 8040 if (bp.packageSetting == null) { 8041 // We may not yet have parsed the package, so just see if 8042 // we still know about its settings. 8043 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8044 } 8045 if (bp.packageSetting == null) { 8046 Slog.w(TAG, "Removing dangling permission: " + bp.name 8047 + " from package " + bp.sourcePackage); 8048 it.remove(); 8049 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8050 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8051 Slog.i(TAG, "Removing old permission: " + bp.name 8052 + " from package " + bp.sourcePackage); 8053 flags |= UPDATE_PERMISSIONS_ALL; 8054 it.remove(); 8055 } 8056 } 8057 } 8058 8059 // Now update the permissions for all packages, in particular 8060 // replace the granted permissions of the system packages. 8061 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8062 for (PackageParser.Package pkg : mPackages.values()) { 8063 if (pkg != pkgInfo) { 8064 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8065 changingPkg); 8066 } 8067 } 8068 } 8069 8070 if (pkgInfo != null) { 8071 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8072 } 8073 } 8074 8075 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8076 String packageOfInterest) { 8077 // IMPORTANT: There are two types of permissions: install and runtime. 8078 // Install time permissions are granted when the app is installed to 8079 // all device users and users added in the future. Runtime permissions 8080 // are granted at runtime explicitly to specific users. Normal and signature 8081 // protected permissions are install time permissions. Dangerous permissions 8082 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8083 // otherwise they are runtime permissions. This function does not manage 8084 // runtime permissions except for the case an app targeting Lollipop MR1 8085 // being upgraded to target a newer SDK, in which case dangerous permissions 8086 // are transformed from install time to runtime ones. 8087 8088 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8089 if (ps == null) { 8090 return; 8091 } 8092 8093 PermissionsState permissionsState = ps.getPermissionsState(); 8094 PermissionsState origPermissions = permissionsState; 8095 8096 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8097 8098 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8099 8100 boolean changedInstallPermission = false; 8101 8102 if (replace) { 8103 ps.installPermissionsFixed = false; 8104 if (!ps.isSharedUser()) { 8105 origPermissions = new PermissionsState(permissionsState); 8106 permissionsState.reset(); 8107 } 8108 } 8109 8110 permissionsState.setGlobalGids(mGlobalGids); 8111 8112 final int N = pkg.requestedPermissions.size(); 8113 for (int i=0; i<N; i++) { 8114 final String name = pkg.requestedPermissions.get(i); 8115 final BasePermission bp = mSettings.mPermissions.get(name); 8116 8117 if (DEBUG_INSTALL) { 8118 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8119 } 8120 8121 if (bp == null || bp.packageSetting == null) { 8122 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8123 Slog.w(TAG, "Unknown permission " + name 8124 + " in package " + pkg.packageName); 8125 } 8126 continue; 8127 } 8128 8129 final String perm = bp.name; 8130 boolean allowedSig = false; 8131 int grant = GRANT_DENIED; 8132 8133 // Keep track of app op permissions. 8134 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8135 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8136 if (pkgs == null) { 8137 pkgs = new ArraySet<>(); 8138 mAppOpPermissionPackages.put(bp.name, pkgs); 8139 } 8140 pkgs.add(pkg.packageName); 8141 } 8142 8143 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8144 switch (level) { 8145 case PermissionInfo.PROTECTION_NORMAL: { 8146 // For all apps normal permissions are install time ones. 8147 grant = GRANT_INSTALL; 8148 } break; 8149 8150 case PermissionInfo.PROTECTION_DANGEROUS: { 8151 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8152 // For legacy apps dangerous permissions are install time ones. 8153 grant = GRANT_INSTALL_LEGACY; 8154 } else if (origPermissions.hasInstallPermission(bp.name)) { 8155 // For legacy apps that became modern, install becomes runtime. 8156 grant = GRANT_UPGRADE; 8157 } else { 8158 // For modern apps keep runtime permissions unchanged. 8159 grant = GRANT_RUNTIME; 8160 } 8161 } break; 8162 8163 case PermissionInfo.PROTECTION_SIGNATURE: { 8164 // For all apps signature permissions are install time ones. 8165 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8166 if (allowedSig) { 8167 grant = GRANT_INSTALL; 8168 } 8169 } break; 8170 } 8171 8172 if (DEBUG_INSTALL) { 8173 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8174 } 8175 8176 if (grant != GRANT_DENIED) { 8177 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8178 // If this is an existing, non-system package, then 8179 // we can't add any new permissions to it. 8180 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8181 // Except... if this is a permission that was added 8182 // to the platform (note: need to only do this when 8183 // updating the platform). 8184 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8185 grant = GRANT_DENIED; 8186 } 8187 } 8188 } 8189 8190 switch (grant) { 8191 case GRANT_INSTALL: { 8192 // Revoke this as runtime permission to handle the case of 8193 // a runtime permission being downgraded to an install one. 8194 for (int userId : UserManagerService.getInstance().getUserIds()) { 8195 if (origPermissions.getRuntimePermissionState( 8196 bp.name, userId) != null) { 8197 // Revoke the runtime permission and clear the flags. 8198 origPermissions.revokeRuntimePermission(bp, userId); 8199 origPermissions.updatePermissionFlags(bp, userId, 8200 PackageManager.MASK_PERMISSION_FLAGS, 0); 8201 // If we revoked a permission permission, we have to write. 8202 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8203 changedRuntimePermissionUserIds, userId); 8204 } 8205 } 8206 // Grant an install permission. 8207 if (permissionsState.grantInstallPermission(bp) != 8208 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8209 changedInstallPermission = true; 8210 } 8211 } break; 8212 8213 case GRANT_INSTALL_LEGACY: { 8214 // Grant an install permission. 8215 if (permissionsState.grantInstallPermission(bp) != 8216 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8217 changedInstallPermission = true; 8218 } 8219 } break; 8220 8221 case GRANT_RUNTIME: { 8222 // Grant previously granted runtime permissions. 8223 for (int userId : UserManagerService.getInstance().getUserIds()) { 8224 PermissionState permissionState = origPermissions 8225 .getRuntimePermissionState(bp.name, userId); 8226 final int flags = permissionState != null 8227 ? permissionState.getFlags() : 0; 8228 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8229 if (permissionsState.grantRuntimePermission(bp, userId) == 8230 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8231 // If we cannot put the permission as it was, we have to write. 8232 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8233 changedRuntimePermissionUserIds, userId); 8234 } 8235 } 8236 // Propagate the permission flags. 8237 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8238 } 8239 } break; 8240 8241 case GRANT_UPGRADE: { 8242 // Grant runtime permissions for a previously held install permission. 8243 PermissionState permissionState = origPermissions 8244 .getInstallPermissionState(bp.name); 8245 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8246 8247 if (origPermissions.revokeInstallPermission(bp) 8248 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8249 // We will be transferring the permission flags, so clear them. 8250 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8251 PackageManager.MASK_PERMISSION_FLAGS, 0); 8252 changedInstallPermission = true; 8253 } 8254 8255 // If the permission is not to be promoted to runtime we ignore it and 8256 // also its other flags as they are not applicable to install permissions. 8257 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8258 for (int userId : currentUserIds) { 8259 if (permissionsState.grantRuntimePermission(bp, userId) != 8260 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8261 // Transfer the permission flags. 8262 permissionsState.updatePermissionFlags(bp, userId, 8263 flags, flags); 8264 // If we granted the permission, we have to write. 8265 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8266 changedRuntimePermissionUserIds, userId); 8267 } 8268 } 8269 } 8270 } break; 8271 8272 default: { 8273 if (packageOfInterest == null 8274 || packageOfInterest.equals(pkg.packageName)) { 8275 Slog.w(TAG, "Not granting permission " + perm 8276 + " to package " + pkg.packageName 8277 + " because it was previously installed without"); 8278 } 8279 } break; 8280 } 8281 } else { 8282 if (permissionsState.revokeInstallPermission(bp) != 8283 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8284 // Also drop the permission flags. 8285 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8286 PackageManager.MASK_PERMISSION_FLAGS, 0); 8287 changedInstallPermission = true; 8288 Slog.i(TAG, "Un-granting permission " + perm 8289 + " from package " + pkg.packageName 8290 + " (protectionLevel=" + bp.protectionLevel 8291 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8292 + ")"); 8293 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8294 // Don't print warning for app op permissions, since it is fine for them 8295 // not to be granted, there is a UI for the user to decide. 8296 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8297 Slog.w(TAG, "Not granting permission " + perm 8298 + " to package " + pkg.packageName 8299 + " (protectionLevel=" + bp.protectionLevel 8300 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8301 + ")"); 8302 } 8303 } 8304 } 8305 } 8306 8307 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8308 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8309 // This is the first that we have heard about this package, so the 8310 // permissions we have now selected are fixed until explicitly 8311 // changed. 8312 ps.installPermissionsFixed = true; 8313 } 8314 8315 // Persist the runtime permissions state for users with changes. 8316 for (int userId : changedRuntimePermissionUserIds) { 8317 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8318 } 8319 } 8320 8321 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8322 boolean allowed = false; 8323 final int NP = PackageParser.NEW_PERMISSIONS.length; 8324 for (int ip=0; ip<NP; ip++) { 8325 final PackageParser.NewPermissionInfo npi 8326 = PackageParser.NEW_PERMISSIONS[ip]; 8327 if (npi.name.equals(perm) 8328 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8329 allowed = true; 8330 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8331 + pkg.packageName); 8332 break; 8333 } 8334 } 8335 return allowed; 8336 } 8337 8338 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8339 BasePermission bp, PermissionsState origPermissions) { 8340 boolean allowed; 8341 allowed = (compareSignatures( 8342 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8343 == PackageManager.SIGNATURE_MATCH) 8344 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8345 == PackageManager.SIGNATURE_MATCH); 8346 if (!allowed && (bp.protectionLevel 8347 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8348 if (isSystemApp(pkg)) { 8349 // For updated system applications, a system permission 8350 // is granted only if it had been defined by the original application. 8351 if (pkg.isUpdatedSystemApp()) { 8352 final PackageSetting sysPs = mSettings 8353 .getDisabledSystemPkgLPr(pkg.packageName); 8354 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8355 // If the original was granted this permission, we take 8356 // that grant decision as read and propagate it to the 8357 // update. 8358 if (sysPs.isPrivileged()) { 8359 allowed = true; 8360 } 8361 } else { 8362 // The system apk may have been updated with an older 8363 // version of the one on the data partition, but which 8364 // granted a new system permission that it didn't have 8365 // before. In this case we do want to allow the app to 8366 // now get the new permission if the ancestral apk is 8367 // privileged to get it. 8368 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8369 for (int j=0; 8370 j<sysPs.pkg.requestedPermissions.size(); j++) { 8371 if (perm.equals( 8372 sysPs.pkg.requestedPermissions.get(j))) { 8373 allowed = true; 8374 break; 8375 } 8376 } 8377 } 8378 } 8379 } else { 8380 allowed = isPrivilegedApp(pkg); 8381 } 8382 } 8383 } 8384 if (!allowed && (bp.protectionLevel 8385 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8386 // For development permissions, a development permission 8387 // is granted only if it was already granted. 8388 allowed = origPermissions.hasInstallPermission(perm); 8389 } 8390 return allowed; 8391 } 8392 8393 final class ActivityIntentResolver 8394 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8395 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8396 boolean defaultOnly, int userId) { 8397 if (!sUserManager.exists(userId)) return null; 8398 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8399 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8400 } 8401 8402 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8403 int userId) { 8404 if (!sUserManager.exists(userId)) return null; 8405 mFlags = flags; 8406 return super.queryIntent(intent, resolvedType, 8407 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8408 } 8409 8410 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8411 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8412 if (!sUserManager.exists(userId)) return null; 8413 if (packageActivities == null) { 8414 return null; 8415 } 8416 mFlags = flags; 8417 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8418 final int N = packageActivities.size(); 8419 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8420 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8421 8422 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8423 for (int i = 0; i < N; ++i) { 8424 intentFilters = packageActivities.get(i).intents; 8425 if (intentFilters != null && intentFilters.size() > 0) { 8426 PackageParser.ActivityIntentInfo[] array = 8427 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8428 intentFilters.toArray(array); 8429 listCut.add(array); 8430 } 8431 } 8432 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8433 } 8434 8435 public final void addActivity(PackageParser.Activity a, String type) { 8436 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8437 mActivities.put(a.getComponentName(), a); 8438 if (DEBUG_SHOW_INFO) 8439 Log.v( 8440 TAG, " " + type + " " + 8441 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8442 if (DEBUG_SHOW_INFO) 8443 Log.v(TAG, " Class=" + a.info.name); 8444 final int NI = a.intents.size(); 8445 for (int j=0; j<NI; j++) { 8446 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8447 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8448 intent.setPriority(0); 8449 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8450 + a.className + " with priority > 0, forcing to 0"); 8451 } 8452 if (DEBUG_SHOW_INFO) { 8453 Log.v(TAG, " IntentFilter:"); 8454 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8455 } 8456 if (!intent.debugCheck()) { 8457 Log.w(TAG, "==> For Activity " + a.info.name); 8458 } 8459 addFilter(intent); 8460 } 8461 } 8462 8463 public final void removeActivity(PackageParser.Activity a, String type) { 8464 mActivities.remove(a.getComponentName()); 8465 if (DEBUG_SHOW_INFO) { 8466 Log.v(TAG, " " + type + " " 8467 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8468 : a.info.name) + ":"); 8469 Log.v(TAG, " Class=" + a.info.name); 8470 } 8471 final int NI = a.intents.size(); 8472 for (int j=0; j<NI; j++) { 8473 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8474 if (DEBUG_SHOW_INFO) { 8475 Log.v(TAG, " IntentFilter:"); 8476 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8477 } 8478 removeFilter(intent); 8479 } 8480 } 8481 8482 @Override 8483 protected boolean allowFilterResult( 8484 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8485 ActivityInfo filterAi = filter.activity.info; 8486 for (int i=dest.size()-1; i>=0; i--) { 8487 ActivityInfo destAi = dest.get(i).activityInfo; 8488 if (destAi.name == filterAi.name 8489 && destAi.packageName == filterAi.packageName) { 8490 return false; 8491 } 8492 } 8493 return true; 8494 } 8495 8496 @Override 8497 protected ActivityIntentInfo[] newArray(int size) { 8498 return new ActivityIntentInfo[size]; 8499 } 8500 8501 @Override 8502 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8503 if (!sUserManager.exists(userId)) return true; 8504 PackageParser.Package p = filter.activity.owner; 8505 if (p != null) { 8506 PackageSetting ps = (PackageSetting)p.mExtras; 8507 if (ps != null) { 8508 // System apps are never considered stopped for purposes of 8509 // filtering, because there may be no way for the user to 8510 // actually re-launch them. 8511 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8512 && ps.getStopped(userId); 8513 } 8514 } 8515 return false; 8516 } 8517 8518 @Override 8519 protected boolean isPackageForFilter(String packageName, 8520 PackageParser.ActivityIntentInfo info) { 8521 return packageName.equals(info.activity.owner.packageName); 8522 } 8523 8524 @Override 8525 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8526 int match, int userId) { 8527 if (!sUserManager.exists(userId)) return null; 8528 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8529 return null; 8530 } 8531 final PackageParser.Activity activity = info.activity; 8532 if (mSafeMode && (activity.info.applicationInfo.flags 8533 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8534 return null; 8535 } 8536 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8537 if (ps == null) { 8538 return null; 8539 } 8540 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8541 ps.readUserState(userId), userId); 8542 if (ai == null) { 8543 return null; 8544 } 8545 final ResolveInfo res = new ResolveInfo(); 8546 res.activityInfo = ai; 8547 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8548 res.filter = info; 8549 } 8550 if (info != null) { 8551 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8552 } 8553 res.priority = info.getPriority(); 8554 res.preferredOrder = activity.owner.mPreferredOrder; 8555 //System.out.println("Result: " + res.activityInfo.className + 8556 // " = " + res.priority); 8557 res.match = match; 8558 res.isDefault = info.hasDefault; 8559 res.labelRes = info.labelRes; 8560 res.nonLocalizedLabel = info.nonLocalizedLabel; 8561 if (userNeedsBadging(userId)) { 8562 res.noResourceId = true; 8563 } else { 8564 res.icon = info.icon; 8565 } 8566 res.iconResourceId = info.icon; 8567 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8568 return res; 8569 } 8570 8571 @Override 8572 protected void sortResults(List<ResolveInfo> results) { 8573 Collections.sort(results, mResolvePrioritySorter); 8574 } 8575 8576 @Override 8577 protected void dumpFilter(PrintWriter out, String prefix, 8578 PackageParser.ActivityIntentInfo filter) { 8579 out.print(prefix); out.print( 8580 Integer.toHexString(System.identityHashCode(filter.activity))); 8581 out.print(' '); 8582 filter.activity.printComponentShortName(out); 8583 out.print(" filter "); 8584 out.println(Integer.toHexString(System.identityHashCode(filter))); 8585 } 8586 8587 @Override 8588 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8589 return filter.activity; 8590 } 8591 8592 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8593 PackageParser.Activity activity = (PackageParser.Activity)label; 8594 out.print(prefix); out.print( 8595 Integer.toHexString(System.identityHashCode(activity))); 8596 out.print(' '); 8597 activity.printComponentShortName(out); 8598 if (count > 1) { 8599 out.print(" ("); out.print(count); out.print(" filters)"); 8600 } 8601 out.println(); 8602 } 8603 8604// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8605// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8606// final List<ResolveInfo> retList = Lists.newArrayList(); 8607// while (i.hasNext()) { 8608// final ResolveInfo resolveInfo = i.next(); 8609// if (isEnabledLP(resolveInfo.activityInfo)) { 8610// retList.add(resolveInfo); 8611// } 8612// } 8613// return retList; 8614// } 8615 8616 // Keys are String (activity class name), values are Activity. 8617 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8618 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8619 private int mFlags; 8620 } 8621 8622 private final class ServiceIntentResolver 8623 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8624 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8625 boolean defaultOnly, int userId) { 8626 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8627 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8628 } 8629 8630 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8631 int userId) { 8632 if (!sUserManager.exists(userId)) return null; 8633 mFlags = flags; 8634 return super.queryIntent(intent, resolvedType, 8635 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8636 } 8637 8638 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8639 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8640 if (!sUserManager.exists(userId)) return null; 8641 if (packageServices == null) { 8642 return null; 8643 } 8644 mFlags = flags; 8645 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8646 final int N = packageServices.size(); 8647 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8648 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8649 8650 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8651 for (int i = 0; i < N; ++i) { 8652 intentFilters = packageServices.get(i).intents; 8653 if (intentFilters != null && intentFilters.size() > 0) { 8654 PackageParser.ServiceIntentInfo[] array = 8655 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8656 intentFilters.toArray(array); 8657 listCut.add(array); 8658 } 8659 } 8660 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8661 } 8662 8663 public final void addService(PackageParser.Service s) { 8664 mServices.put(s.getComponentName(), s); 8665 if (DEBUG_SHOW_INFO) { 8666 Log.v(TAG, " " 8667 + (s.info.nonLocalizedLabel != null 8668 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8669 Log.v(TAG, " Class=" + s.info.name); 8670 } 8671 final int NI = s.intents.size(); 8672 int j; 8673 for (j=0; j<NI; j++) { 8674 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8675 if (DEBUG_SHOW_INFO) { 8676 Log.v(TAG, " IntentFilter:"); 8677 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8678 } 8679 if (!intent.debugCheck()) { 8680 Log.w(TAG, "==> For Service " + s.info.name); 8681 } 8682 addFilter(intent); 8683 } 8684 } 8685 8686 public final void removeService(PackageParser.Service s) { 8687 mServices.remove(s.getComponentName()); 8688 if (DEBUG_SHOW_INFO) { 8689 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8690 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8691 Log.v(TAG, " Class=" + s.info.name); 8692 } 8693 final int NI = s.intents.size(); 8694 int j; 8695 for (j=0; j<NI; j++) { 8696 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8697 if (DEBUG_SHOW_INFO) { 8698 Log.v(TAG, " IntentFilter:"); 8699 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8700 } 8701 removeFilter(intent); 8702 } 8703 } 8704 8705 @Override 8706 protected boolean allowFilterResult( 8707 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8708 ServiceInfo filterSi = filter.service.info; 8709 for (int i=dest.size()-1; i>=0; i--) { 8710 ServiceInfo destAi = dest.get(i).serviceInfo; 8711 if (destAi.name == filterSi.name 8712 && destAi.packageName == filterSi.packageName) { 8713 return false; 8714 } 8715 } 8716 return true; 8717 } 8718 8719 @Override 8720 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8721 return new PackageParser.ServiceIntentInfo[size]; 8722 } 8723 8724 @Override 8725 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8726 if (!sUserManager.exists(userId)) return true; 8727 PackageParser.Package p = filter.service.owner; 8728 if (p != null) { 8729 PackageSetting ps = (PackageSetting)p.mExtras; 8730 if (ps != null) { 8731 // System apps are never considered stopped for purposes of 8732 // filtering, because there may be no way for the user to 8733 // actually re-launch them. 8734 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8735 && ps.getStopped(userId); 8736 } 8737 } 8738 return false; 8739 } 8740 8741 @Override 8742 protected boolean isPackageForFilter(String packageName, 8743 PackageParser.ServiceIntentInfo info) { 8744 return packageName.equals(info.service.owner.packageName); 8745 } 8746 8747 @Override 8748 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8749 int match, int userId) { 8750 if (!sUserManager.exists(userId)) return null; 8751 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8752 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8753 return null; 8754 } 8755 final PackageParser.Service service = info.service; 8756 if (mSafeMode && (service.info.applicationInfo.flags 8757 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8758 return null; 8759 } 8760 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8761 if (ps == null) { 8762 return null; 8763 } 8764 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8765 ps.readUserState(userId), userId); 8766 if (si == null) { 8767 return null; 8768 } 8769 final ResolveInfo res = new ResolveInfo(); 8770 res.serviceInfo = si; 8771 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8772 res.filter = filter; 8773 } 8774 res.priority = info.getPriority(); 8775 res.preferredOrder = service.owner.mPreferredOrder; 8776 res.match = match; 8777 res.isDefault = info.hasDefault; 8778 res.labelRes = info.labelRes; 8779 res.nonLocalizedLabel = info.nonLocalizedLabel; 8780 res.icon = info.icon; 8781 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8782 return res; 8783 } 8784 8785 @Override 8786 protected void sortResults(List<ResolveInfo> results) { 8787 Collections.sort(results, mResolvePrioritySorter); 8788 } 8789 8790 @Override 8791 protected void dumpFilter(PrintWriter out, String prefix, 8792 PackageParser.ServiceIntentInfo filter) { 8793 out.print(prefix); out.print( 8794 Integer.toHexString(System.identityHashCode(filter.service))); 8795 out.print(' '); 8796 filter.service.printComponentShortName(out); 8797 out.print(" filter "); 8798 out.println(Integer.toHexString(System.identityHashCode(filter))); 8799 } 8800 8801 @Override 8802 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8803 return filter.service; 8804 } 8805 8806 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8807 PackageParser.Service service = (PackageParser.Service)label; 8808 out.print(prefix); out.print( 8809 Integer.toHexString(System.identityHashCode(service))); 8810 out.print(' '); 8811 service.printComponentShortName(out); 8812 if (count > 1) { 8813 out.print(" ("); out.print(count); out.print(" filters)"); 8814 } 8815 out.println(); 8816 } 8817 8818// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8819// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8820// final List<ResolveInfo> retList = Lists.newArrayList(); 8821// while (i.hasNext()) { 8822// final ResolveInfo resolveInfo = (ResolveInfo) i; 8823// if (isEnabledLP(resolveInfo.serviceInfo)) { 8824// retList.add(resolveInfo); 8825// } 8826// } 8827// return retList; 8828// } 8829 8830 // Keys are String (activity class name), values are Activity. 8831 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8832 = new ArrayMap<ComponentName, PackageParser.Service>(); 8833 private int mFlags; 8834 }; 8835 8836 private final class ProviderIntentResolver 8837 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8838 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8839 boolean defaultOnly, int userId) { 8840 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8841 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8842 } 8843 8844 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8845 int userId) { 8846 if (!sUserManager.exists(userId)) 8847 return null; 8848 mFlags = flags; 8849 return super.queryIntent(intent, resolvedType, 8850 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8851 } 8852 8853 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8854 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8855 if (!sUserManager.exists(userId)) 8856 return null; 8857 if (packageProviders == null) { 8858 return null; 8859 } 8860 mFlags = flags; 8861 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8862 final int N = packageProviders.size(); 8863 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8864 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8865 8866 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8867 for (int i = 0; i < N; ++i) { 8868 intentFilters = packageProviders.get(i).intents; 8869 if (intentFilters != null && intentFilters.size() > 0) { 8870 PackageParser.ProviderIntentInfo[] array = 8871 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8872 intentFilters.toArray(array); 8873 listCut.add(array); 8874 } 8875 } 8876 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8877 } 8878 8879 public final void addProvider(PackageParser.Provider p) { 8880 if (mProviders.containsKey(p.getComponentName())) { 8881 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8882 return; 8883 } 8884 8885 mProviders.put(p.getComponentName(), p); 8886 if (DEBUG_SHOW_INFO) { 8887 Log.v(TAG, " " 8888 + (p.info.nonLocalizedLabel != null 8889 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8890 Log.v(TAG, " Class=" + p.info.name); 8891 } 8892 final int NI = p.intents.size(); 8893 int j; 8894 for (j = 0; j < NI; j++) { 8895 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8896 if (DEBUG_SHOW_INFO) { 8897 Log.v(TAG, " IntentFilter:"); 8898 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8899 } 8900 if (!intent.debugCheck()) { 8901 Log.w(TAG, "==> For Provider " + p.info.name); 8902 } 8903 addFilter(intent); 8904 } 8905 } 8906 8907 public final void removeProvider(PackageParser.Provider p) { 8908 mProviders.remove(p.getComponentName()); 8909 if (DEBUG_SHOW_INFO) { 8910 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8911 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8912 Log.v(TAG, " Class=" + p.info.name); 8913 } 8914 final int NI = p.intents.size(); 8915 int j; 8916 for (j = 0; j < NI; j++) { 8917 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8918 if (DEBUG_SHOW_INFO) { 8919 Log.v(TAG, " IntentFilter:"); 8920 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8921 } 8922 removeFilter(intent); 8923 } 8924 } 8925 8926 @Override 8927 protected boolean allowFilterResult( 8928 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8929 ProviderInfo filterPi = filter.provider.info; 8930 for (int i = dest.size() - 1; i >= 0; i--) { 8931 ProviderInfo destPi = dest.get(i).providerInfo; 8932 if (destPi.name == filterPi.name 8933 && destPi.packageName == filterPi.packageName) { 8934 return false; 8935 } 8936 } 8937 return true; 8938 } 8939 8940 @Override 8941 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8942 return new PackageParser.ProviderIntentInfo[size]; 8943 } 8944 8945 @Override 8946 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8947 if (!sUserManager.exists(userId)) 8948 return true; 8949 PackageParser.Package p = filter.provider.owner; 8950 if (p != null) { 8951 PackageSetting ps = (PackageSetting) p.mExtras; 8952 if (ps != null) { 8953 // System apps are never considered stopped for purposes of 8954 // filtering, because there may be no way for the user to 8955 // actually re-launch them. 8956 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8957 && ps.getStopped(userId); 8958 } 8959 } 8960 return false; 8961 } 8962 8963 @Override 8964 protected boolean isPackageForFilter(String packageName, 8965 PackageParser.ProviderIntentInfo info) { 8966 return packageName.equals(info.provider.owner.packageName); 8967 } 8968 8969 @Override 8970 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8971 int match, int userId) { 8972 if (!sUserManager.exists(userId)) 8973 return null; 8974 final PackageParser.ProviderIntentInfo info = filter; 8975 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8976 return null; 8977 } 8978 final PackageParser.Provider provider = info.provider; 8979 if (mSafeMode && (provider.info.applicationInfo.flags 8980 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8981 return null; 8982 } 8983 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8984 if (ps == null) { 8985 return null; 8986 } 8987 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8988 ps.readUserState(userId), userId); 8989 if (pi == null) { 8990 return null; 8991 } 8992 final ResolveInfo res = new ResolveInfo(); 8993 res.providerInfo = pi; 8994 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8995 res.filter = filter; 8996 } 8997 res.priority = info.getPriority(); 8998 res.preferredOrder = provider.owner.mPreferredOrder; 8999 res.match = match; 9000 res.isDefault = info.hasDefault; 9001 res.labelRes = info.labelRes; 9002 res.nonLocalizedLabel = info.nonLocalizedLabel; 9003 res.icon = info.icon; 9004 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9005 return res; 9006 } 9007 9008 @Override 9009 protected void sortResults(List<ResolveInfo> results) { 9010 Collections.sort(results, mResolvePrioritySorter); 9011 } 9012 9013 @Override 9014 protected void dumpFilter(PrintWriter out, String prefix, 9015 PackageParser.ProviderIntentInfo filter) { 9016 out.print(prefix); 9017 out.print( 9018 Integer.toHexString(System.identityHashCode(filter.provider))); 9019 out.print(' '); 9020 filter.provider.printComponentShortName(out); 9021 out.print(" filter "); 9022 out.println(Integer.toHexString(System.identityHashCode(filter))); 9023 } 9024 9025 @Override 9026 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9027 return filter.provider; 9028 } 9029 9030 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9031 PackageParser.Provider provider = (PackageParser.Provider)label; 9032 out.print(prefix); out.print( 9033 Integer.toHexString(System.identityHashCode(provider))); 9034 out.print(' '); 9035 provider.printComponentShortName(out); 9036 if (count > 1) { 9037 out.print(" ("); out.print(count); out.print(" filters)"); 9038 } 9039 out.println(); 9040 } 9041 9042 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9043 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9044 private int mFlags; 9045 }; 9046 9047 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9048 new Comparator<ResolveInfo>() { 9049 public int compare(ResolveInfo r1, ResolveInfo r2) { 9050 int v1 = r1.priority; 9051 int v2 = r2.priority; 9052 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9053 if (v1 != v2) { 9054 return (v1 > v2) ? -1 : 1; 9055 } 9056 v1 = r1.preferredOrder; 9057 v2 = r2.preferredOrder; 9058 if (v1 != v2) { 9059 return (v1 > v2) ? -1 : 1; 9060 } 9061 if (r1.isDefault != r2.isDefault) { 9062 return r1.isDefault ? -1 : 1; 9063 } 9064 v1 = r1.match; 9065 v2 = r2.match; 9066 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9067 if (v1 != v2) { 9068 return (v1 > v2) ? -1 : 1; 9069 } 9070 if (r1.system != r2.system) { 9071 return r1.system ? -1 : 1; 9072 } 9073 return 0; 9074 } 9075 }; 9076 9077 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9078 new Comparator<ProviderInfo>() { 9079 public int compare(ProviderInfo p1, ProviderInfo p2) { 9080 final int v1 = p1.initOrder; 9081 final int v2 = p2.initOrder; 9082 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9083 } 9084 }; 9085 9086 final void sendPackageBroadcast(final String action, final String pkg, 9087 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9088 final int[] userIds) { 9089 mHandler.post(new Runnable() { 9090 @Override 9091 public void run() { 9092 try { 9093 final IActivityManager am = ActivityManagerNative.getDefault(); 9094 if (am == null) return; 9095 final int[] resolvedUserIds; 9096 if (userIds == null) { 9097 resolvedUserIds = am.getRunningUserIds(); 9098 } else { 9099 resolvedUserIds = userIds; 9100 } 9101 for (int id : resolvedUserIds) { 9102 final Intent intent = new Intent(action, 9103 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9104 if (extras != null) { 9105 intent.putExtras(extras); 9106 } 9107 if (targetPkg != null) { 9108 intent.setPackage(targetPkg); 9109 } 9110 // Modify the UID when posting to other users 9111 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9112 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9113 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9114 intent.putExtra(Intent.EXTRA_UID, uid); 9115 } 9116 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9117 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9118 if (DEBUG_BROADCASTS) { 9119 RuntimeException here = new RuntimeException("here"); 9120 here.fillInStackTrace(); 9121 Slog.d(TAG, "Sending to user " + id + ": " 9122 + intent.toShortString(false, true, false, false) 9123 + " " + intent.getExtras(), here); 9124 } 9125 am.broadcastIntent(null, intent, null, finishedReceiver, 9126 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9127 null, finishedReceiver != null, false, id); 9128 } 9129 } catch (RemoteException ex) { 9130 } 9131 } 9132 }); 9133 } 9134 9135 /** 9136 * Check if the external storage media is available. This is true if there 9137 * is a mounted external storage medium or if the external storage is 9138 * emulated. 9139 */ 9140 private boolean isExternalMediaAvailable() { 9141 return mMediaMounted || Environment.isExternalStorageEmulated(); 9142 } 9143 9144 @Override 9145 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9146 // writer 9147 synchronized (mPackages) { 9148 if (!isExternalMediaAvailable()) { 9149 // If the external storage is no longer mounted at this point, 9150 // the caller may not have been able to delete all of this 9151 // packages files and can not delete any more. Bail. 9152 return null; 9153 } 9154 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9155 if (lastPackage != null) { 9156 pkgs.remove(lastPackage); 9157 } 9158 if (pkgs.size() > 0) { 9159 return pkgs.get(0); 9160 } 9161 } 9162 return null; 9163 } 9164 9165 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9166 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9167 userId, andCode ? 1 : 0, packageName); 9168 if (mSystemReady) { 9169 msg.sendToTarget(); 9170 } else { 9171 if (mPostSystemReadyMessages == null) { 9172 mPostSystemReadyMessages = new ArrayList<>(); 9173 } 9174 mPostSystemReadyMessages.add(msg); 9175 } 9176 } 9177 9178 void startCleaningPackages() { 9179 // reader 9180 synchronized (mPackages) { 9181 if (!isExternalMediaAvailable()) { 9182 return; 9183 } 9184 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9185 return; 9186 } 9187 } 9188 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9189 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9190 IActivityManager am = ActivityManagerNative.getDefault(); 9191 if (am != null) { 9192 try { 9193 am.startService(null, intent, null, UserHandle.USER_OWNER); 9194 } catch (RemoteException e) { 9195 } 9196 } 9197 } 9198 9199 @Override 9200 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9201 int installFlags, String installerPackageName, VerificationParams verificationParams, 9202 String packageAbiOverride) { 9203 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9204 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9205 } 9206 9207 @Override 9208 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9209 int installFlags, String installerPackageName, VerificationParams verificationParams, 9210 String packageAbiOverride, int userId) { 9211 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9212 9213 final int callingUid = Binder.getCallingUid(); 9214 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9215 9216 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9217 try { 9218 if (observer != null) { 9219 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9220 } 9221 } catch (RemoteException re) { 9222 } 9223 return; 9224 } 9225 9226 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9227 installFlags |= PackageManager.INSTALL_FROM_ADB; 9228 9229 } else { 9230 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9231 // about installerPackageName. 9232 9233 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9234 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9235 } 9236 9237 UserHandle user; 9238 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9239 user = UserHandle.ALL; 9240 } else { 9241 user = new UserHandle(userId); 9242 } 9243 9244 // Only system components can circumvent runtime permissions when installing. 9245 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9246 && mContext.checkCallingOrSelfPermission(Manifest.permission 9247 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9248 throw new SecurityException("You need the " 9249 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9250 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9251 } 9252 9253 verificationParams.setInstallerUid(callingUid); 9254 9255 final File originFile = new File(originPath); 9256 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9257 9258 final Message msg = mHandler.obtainMessage(INIT_COPY); 9259 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9260 null, verificationParams, user, packageAbiOverride); 9261 mHandler.sendMessage(msg); 9262 } 9263 9264 void installStage(String packageName, File stagedDir, String stagedCid, 9265 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9266 String installerPackageName, int installerUid, UserHandle user) { 9267 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9268 params.referrerUri, installerUid, null); 9269 verifParams.setInstallerUid(installerUid); 9270 9271 final OriginInfo origin; 9272 if (stagedDir != null) { 9273 origin = OriginInfo.fromStagedFile(stagedDir); 9274 } else { 9275 origin = OriginInfo.fromStagedContainer(stagedCid); 9276 } 9277 9278 final Message msg = mHandler.obtainMessage(INIT_COPY); 9279 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9280 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9281 mHandler.sendMessage(msg); 9282 } 9283 9284 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9285 Bundle extras = new Bundle(1); 9286 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9287 9288 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9289 packageName, extras, null, null, new int[] {userId}); 9290 try { 9291 IActivityManager am = ActivityManagerNative.getDefault(); 9292 final boolean isSystem = 9293 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9294 if (isSystem && am.isUserRunning(userId, false)) { 9295 // The just-installed/enabled app is bundled on the system, so presumed 9296 // to be able to run automatically without needing an explicit launch. 9297 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9298 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9299 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9300 .setPackage(packageName); 9301 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9302 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9303 } 9304 } catch (RemoteException e) { 9305 // shouldn't happen 9306 Slog.w(TAG, "Unable to bootstrap installed package", e); 9307 } 9308 } 9309 9310 @Override 9311 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9312 int userId) { 9313 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9314 PackageSetting pkgSetting; 9315 final int uid = Binder.getCallingUid(); 9316 enforceCrossUserPermission(uid, userId, true, true, 9317 "setApplicationHiddenSetting for user " + userId); 9318 9319 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9320 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9321 return false; 9322 } 9323 9324 long callingId = Binder.clearCallingIdentity(); 9325 try { 9326 boolean sendAdded = false; 9327 boolean sendRemoved = false; 9328 // writer 9329 synchronized (mPackages) { 9330 pkgSetting = mSettings.mPackages.get(packageName); 9331 if (pkgSetting == null) { 9332 return false; 9333 } 9334 if (pkgSetting.getHidden(userId) != hidden) { 9335 pkgSetting.setHidden(hidden, userId); 9336 mSettings.writePackageRestrictionsLPr(userId); 9337 if (hidden) { 9338 sendRemoved = true; 9339 } else { 9340 sendAdded = true; 9341 } 9342 } 9343 } 9344 if (sendAdded) { 9345 sendPackageAddedForUser(packageName, pkgSetting, userId); 9346 return true; 9347 } 9348 if (sendRemoved) { 9349 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9350 "hiding pkg"); 9351 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9352 } 9353 } finally { 9354 Binder.restoreCallingIdentity(callingId); 9355 } 9356 return false; 9357 } 9358 9359 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9360 int userId) { 9361 final PackageRemovedInfo info = new PackageRemovedInfo(); 9362 info.removedPackage = packageName; 9363 info.removedUsers = new int[] {userId}; 9364 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9365 info.sendBroadcast(false, false, false); 9366 } 9367 9368 /** 9369 * Returns true if application is not found or there was an error. Otherwise it returns 9370 * the hidden state of the package for the given user. 9371 */ 9372 @Override 9373 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9374 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9375 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9376 false, "getApplicationHidden for user " + userId); 9377 PackageSetting pkgSetting; 9378 long callingId = Binder.clearCallingIdentity(); 9379 try { 9380 // writer 9381 synchronized (mPackages) { 9382 pkgSetting = mSettings.mPackages.get(packageName); 9383 if (pkgSetting == null) { 9384 return true; 9385 } 9386 return pkgSetting.getHidden(userId); 9387 } 9388 } finally { 9389 Binder.restoreCallingIdentity(callingId); 9390 } 9391 } 9392 9393 /** 9394 * @hide 9395 */ 9396 @Override 9397 public int installExistingPackageAsUser(String packageName, int userId) { 9398 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9399 null); 9400 PackageSetting pkgSetting; 9401 final int uid = Binder.getCallingUid(); 9402 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9403 + userId); 9404 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9405 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9406 } 9407 9408 long callingId = Binder.clearCallingIdentity(); 9409 try { 9410 boolean sendAdded = false; 9411 9412 // writer 9413 synchronized (mPackages) { 9414 pkgSetting = mSettings.mPackages.get(packageName); 9415 if (pkgSetting == null) { 9416 return PackageManager.INSTALL_FAILED_INVALID_URI; 9417 } 9418 if (!pkgSetting.getInstalled(userId)) { 9419 pkgSetting.setInstalled(true, userId); 9420 pkgSetting.setHidden(false, userId); 9421 mSettings.writePackageRestrictionsLPr(userId); 9422 sendAdded = true; 9423 } 9424 } 9425 9426 if (sendAdded) { 9427 sendPackageAddedForUser(packageName, pkgSetting, userId); 9428 } 9429 } finally { 9430 Binder.restoreCallingIdentity(callingId); 9431 } 9432 9433 return PackageManager.INSTALL_SUCCEEDED; 9434 } 9435 9436 boolean isUserRestricted(int userId, String restrictionKey) { 9437 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9438 if (restrictions.getBoolean(restrictionKey, false)) { 9439 Log.w(TAG, "User is restricted: " + restrictionKey); 9440 return true; 9441 } 9442 return false; 9443 } 9444 9445 @Override 9446 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9447 mContext.enforceCallingOrSelfPermission( 9448 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9449 "Only package verification agents can verify applications"); 9450 9451 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9452 final PackageVerificationResponse response = new PackageVerificationResponse( 9453 verificationCode, Binder.getCallingUid()); 9454 msg.arg1 = id; 9455 msg.obj = response; 9456 mHandler.sendMessage(msg); 9457 } 9458 9459 @Override 9460 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9461 long millisecondsToDelay) { 9462 mContext.enforceCallingOrSelfPermission( 9463 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9464 "Only package verification agents can extend verification timeouts"); 9465 9466 final PackageVerificationState state = mPendingVerification.get(id); 9467 final PackageVerificationResponse response = new PackageVerificationResponse( 9468 verificationCodeAtTimeout, Binder.getCallingUid()); 9469 9470 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9471 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9472 } 9473 if (millisecondsToDelay < 0) { 9474 millisecondsToDelay = 0; 9475 } 9476 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9477 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9478 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9479 } 9480 9481 if ((state != null) && !state.timeoutExtended()) { 9482 state.extendTimeout(); 9483 9484 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9485 msg.arg1 = id; 9486 msg.obj = response; 9487 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9488 } 9489 } 9490 9491 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9492 int verificationCode, UserHandle user) { 9493 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9494 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9495 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9496 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9497 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9498 9499 mContext.sendBroadcastAsUser(intent, user, 9500 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9501 } 9502 9503 private ComponentName matchComponentForVerifier(String packageName, 9504 List<ResolveInfo> receivers) { 9505 ActivityInfo targetReceiver = null; 9506 9507 final int NR = receivers.size(); 9508 for (int i = 0; i < NR; i++) { 9509 final ResolveInfo info = receivers.get(i); 9510 if (info.activityInfo == null) { 9511 continue; 9512 } 9513 9514 if (packageName.equals(info.activityInfo.packageName)) { 9515 targetReceiver = info.activityInfo; 9516 break; 9517 } 9518 } 9519 9520 if (targetReceiver == null) { 9521 return null; 9522 } 9523 9524 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9525 } 9526 9527 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9528 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9529 if (pkgInfo.verifiers.length == 0) { 9530 return null; 9531 } 9532 9533 final int N = pkgInfo.verifiers.length; 9534 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9535 for (int i = 0; i < N; i++) { 9536 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9537 9538 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9539 receivers); 9540 if (comp == null) { 9541 continue; 9542 } 9543 9544 final int verifierUid = getUidForVerifier(verifierInfo); 9545 if (verifierUid == -1) { 9546 continue; 9547 } 9548 9549 if (DEBUG_VERIFY) { 9550 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9551 + " with the correct signature"); 9552 } 9553 sufficientVerifiers.add(comp); 9554 verificationState.addSufficientVerifier(verifierUid); 9555 } 9556 9557 return sufficientVerifiers; 9558 } 9559 9560 private int getUidForVerifier(VerifierInfo verifierInfo) { 9561 synchronized (mPackages) { 9562 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9563 if (pkg == null) { 9564 return -1; 9565 } else if (pkg.mSignatures.length != 1) { 9566 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9567 + " has more than one signature; ignoring"); 9568 return -1; 9569 } 9570 9571 /* 9572 * If the public key of the package's signature does not match 9573 * our expected public key, then this is a different package and 9574 * we should skip. 9575 */ 9576 9577 final byte[] expectedPublicKey; 9578 try { 9579 final Signature verifierSig = pkg.mSignatures[0]; 9580 final PublicKey publicKey = verifierSig.getPublicKey(); 9581 expectedPublicKey = publicKey.getEncoded(); 9582 } catch (CertificateException e) { 9583 return -1; 9584 } 9585 9586 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9587 9588 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9589 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9590 + " does not have the expected public key; ignoring"); 9591 return -1; 9592 } 9593 9594 return pkg.applicationInfo.uid; 9595 } 9596 } 9597 9598 @Override 9599 public void finishPackageInstall(int token) { 9600 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9601 9602 if (DEBUG_INSTALL) { 9603 Slog.v(TAG, "BM finishing package install for " + token); 9604 } 9605 9606 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9607 mHandler.sendMessage(msg); 9608 } 9609 9610 /** 9611 * Get the verification agent timeout. 9612 * 9613 * @return verification timeout in milliseconds 9614 */ 9615 private long getVerificationTimeout() { 9616 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9617 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9618 DEFAULT_VERIFICATION_TIMEOUT); 9619 } 9620 9621 /** 9622 * Get the default verification agent response code. 9623 * 9624 * @return default verification response code 9625 */ 9626 private int getDefaultVerificationResponse() { 9627 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9628 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9629 DEFAULT_VERIFICATION_RESPONSE); 9630 } 9631 9632 /** 9633 * Check whether or not package verification has been enabled. 9634 * 9635 * @return true if verification should be performed 9636 */ 9637 private boolean isVerificationEnabled(int userId, int installFlags) { 9638 if (!DEFAULT_VERIFY_ENABLE) { 9639 return false; 9640 } 9641 9642 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9643 9644 // Check if installing from ADB 9645 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9646 // Do not run verification in a test harness environment 9647 if (ActivityManager.isRunningInTestHarness()) { 9648 return false; 9649 } 9650 if (ensureVerifyAppsEnabled) { 9651 return true; 9652 } 9653 // Check if the developer does not want package verification for ADB installs 9654 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9655 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9656 return false; 9657 } 9658 } 9659 9660 if (ensureVerifyAppsEnabled) { 9661 return true; 9662 } 9663 9664 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9665 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9666 } 9667 9668 @Override 9669 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9670 throws RemoteException { 9671 mContext.enforceCallingOrSelfPermission( 9672 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9673 "Only intentfilter verification agents can verify applications"); 9674 9675 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9676 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9677 Binder.getCallingUid(), verificationCode, failedDomains); 9678 msg.arg1 = id; 9679 msg.obj = response; 9680 mHandler.sendMessage(msg); 9681 } 9682 9683 @Override 9684 public int getIntentVerificationStatus(String packageName, int userId) { 9685 synchronized (mPackages) { 9686 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9687 } 9688 } 9689 9690 @Override 9691 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9692 mContext.enforceCallingOrSelfPermission( 9693 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9694 9695 boolean result = false; 9696 synchronized (mPackages) { 9697 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9698 } 9699 if (result) { 9700 scheduleWritePackageRestrictionsLocked(userId); 9701 } 9702 return result; 9703 } 9704 9705 @Override 9706 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9707 synchronized (mPackages) { 9708 return mSettings.getIntentFilterVerificationsLPr(packageName); 9709 } 9710 } 9711 9712 @Override 9713 public List<IntentFilter> getAllIntentFilters(String packageName) { 9714 if (TextUtils.isEmpty(packageName)) { 9715 return Collections.<IntentFilter>emptyList(); 9716 } 9717 synchronized (mPackages) { 9718 PackageParser.Package pkg = mPackages.get(packageName); 9719 if (pkg == null || pkg.activities == null) { 9720 return Collections.<IntentFilter>emptyList(); 9721 } 9722 final int count = pkg.activities.size(); 9723 ArrayList<IntentFilter> result = new ArrayList<>(); 9724 for (int n=0; n<count; n++) { 9725 PackageParser.Activity activity = pkg.activities.get(n); 9726 if (activity.intents != null || activity.intents.size() > 0) { 9727 result.addAll(activity.intents); 9728 } 9729 } 9730 return result; 9731 } 9732 } 9733 9734 @Override 9735 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9736 mContext.enforceCallingOrSelfPermission( 9737 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9738 9739 synchronized (mPackages) { 9740 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9741 if (packageName != null) { 9742 result |= updateIntentVerificationStatus(packageName, 9743 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9744 UserHandle.myUserId()); 9745 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9746 packageName, userId); 9747 } 9748 return result; 9749 } 9750 } 9751 9752 @Override 9753 public String getDefaultBrowserPackageName(int userId) { 9754 synchronized (mPackages) { 9755 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9756 } 9757 } 9758 9759 /** 9760 * Get the "allow unknown sources" setting. 9761 * 9762 * @return the current "allow unknown sources" setting 9763 */ 9764 private int getUnknownSourcesSettings() { 9765 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9766 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9767 -1); 9768 } 9769 9770 @Override 9771 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9772 final int uid = Binder.getCallingUid(); 9773 // writer 9774 synchronized (mPackages) { 9775 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9776 if (targetPackageSetting == null) { 9777 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9778 } 9779 9780 PackageSetting installerPackageSetting; 9781 if (installerPackageName != null) { 9782 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9783 if (installerPackageSetting == null) { 9784 throw new IllegalArgumentException("Unknown installer package: " 9785 + installerPackageName); 9786 } 9787 } else { 9788 installerPackageSetting = null; 9789 } 9790 9791 Signature[] callerSignature; 9792 Object obj = mSettings.getUserIdLPr(uid); 9793 if (obj != null) { 9794 if (obj instanceof SharedUserSetting) { 9795 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9796 } else if (obj instanceof PackageSetting) { 9797 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9798 } else { 9799 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9800 } 9801 } else { 9802 throw new SecurityException("Unknown calling uid " + uid); 9803 } 9804 9805 // Verify: can't set installerPackageName to a package that is 9806 // not signed with the same cert as the caller. 9807 if (installerPackageSetting != null) { 9808 if (compareSignatures(callerSignature, 9809 installerPackageSetting.signatures.mSignatures) 9810 != PackageManager.SIGNATURE_MATCH) { 9811 throw new SecurityException( 9812 "Caller does not have same cert as new installer package " 9813 + installerPackageName); 9814 } 9815 } 9816 9817 // Verify: if target already has an installer package, it must 9818 // be signed with the same cert as the caller. 9819 if (targetPackageSetting.installerPackageName != null) { 9820 PackageSetting setting = mSettings.mPackages.get( 9821 targetPackageSetting.installerPackageName); 9822 // If the currently set package isn't valid, then it's always 9823 // okay to change it. 9824 if (setting != null) { 9825 if (compareSignatures(callerSignature, 9826 setting.signatures.mSignatures) 9827 != PackageManager.SIGNATURE_MATCH) { 9828 throw new SecurityException( 9829 "Caller does not have same cert as old installer package " 9830 + targetPackageSetting.installerPackageName); 9831 } 9832 } 9833 } 9834 9835 // Okay! 9836 targetPackageSetting.installerPackageName = installerPackageName; 9837 scheduleWriteSettingsLocked(); 9838 } 9839 } 9840 9841 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9842 // Queue up an async operation since the package installation may take a little while. 9843 mHandler.post(new Runnable() { 9844 public void run() { 9845 mHandler.removeCallbacks(this); 9846 // Result object to be returned 9847 PackageInstalledInfo res = new PackageInstalledInfo(); 9848 res.returnCode = currentStatus; 9849 res.uid = -1; 9850 res.pkg = null; 9851 res.removedInfo = new PackageRemovedInfo(); 9852 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9853 args.doPreInstall(res.returnCode); 9854 synchronized (mInstallLock) { 9855 installPackageLI(args, res); 9856 } 9857 args.doPostInstall(res.returnCode, res.uid); 9858 } 9859 9860 // A restore should be performed at this point if (a) the install 9861 // succeeded, (b) the operation is not an update, and (c) the new 9862 // package has not opted out of backup participation. 9863 final boolean update = res.removedInfo.removedPackage != null; 9864 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9865 boolean doRestore = !update 9866 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9867 9868 // Set up the post-install work request bookkeeping. This will be used 9869 // and cleaned up by the post-install event handling regardless of whether 9870 // there's a restore pass performed. Token values are >= 1. 9871 int token; 9872 if (mNextInstallToken < 0) mNextInstallToken = 1; 9873 token = mNextInstallToken++; 9874 9875 PostInstallData data = new PostInstallData(args, res); 9876 mRunningInstalls.put(token, data); 9877 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9878 9879 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9880 // Pass responsibility to the Backup Manager. It will perform a 9881 // restore if appropriate, then pass responsibility back to the 9882 // Package Manager to run the post-install observer callbacks 9883 // and broadcasts. 9884 IBackupManager bm = IBackupManager.Stub.asInterface( 9885 ServiceManager.getService(Context.BACKUP_SERVICE)); 9886 if (bm != null) { 9887 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9888 + " to BM for possible restore"); 9889 try { 9890 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9891 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9892 } else { 9893 doRestore = false; 9894 } 9895 } catch (RemoteException e) { 9896 // can't happen; the backup manager is local 9897 } catch (Exception e) { 9898 Slog.e(TAG, "Exception trying to enqueue restore", e); 9899 doRestore = false; 9900 } 9901 } else { 9902 Slog.e(TAG, "Backup Manager not found!"); 9903 doRestore = false; 9904 } 9905 } 9906 9907 if (!doRestore) { 9908 // No restore possible, or the Backup Manager was mysteriously not 9909 // available -- just fire the post-install work request directly. 9910 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9911 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9912 mHandler.sendMessage(msg); 9913 } 9914 } 9915 }); 9916 } 9917 9918 private abstract class HandlerParams { 9919 private static final int MAX_RETRIES = 4; 9920 9921 /** 9922 * Number of times startCopy() has been attempted and had a non-fatal 9923 * error. 9924 */ 9925 private int mRetries = 0; 9926 9927 /** User handle for the user requesting the information or installation. */ 9928 private final UserHandle mUser; 9929 9930 HandlerParams(UserHandle user) { 9931 mUser = user; 9932 } 9933 9934 UserHandle getUser() { 9935 return mUser; 9936 } 9937 9938 final boolean startCopy() { 9939 boolean res; 9940 try { 9941 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9942 9943 if (++mRetries > MAX_RETRIES) { 9944 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9945 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9946 handleServiceError(); 9947 return false; 9948 } else { 9949 handleStartCopy(); 9950 res = true; 9951 } 9952 } catch (RemoteException e) { 9953 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9954 mHandler.sendEmptyMessage(MCS_RECONNECT); 9955 res = false; 9956 } 9957 handleReturnCode(); 9958 return res; 9959 } 9960 9961 final void serviceError() { 9962 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9963 handleServiceError(); 9964 handleReturnCode(); 9965 } 9966 9967 abstract void handleStartCopy() throws RemoteException; 9968 abstract void handleServiceError(); 9969 abstract void handleReturnCode(); 9970 } 9971 9972 class MeasureParams extends HandlerParams { 9973 private final PackageStats mStats; 9974 private boolean mSuccess; 9975 9976 private final IPackageStatsObserver mObserver; 9977 9978 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9979 super(new UserHandle(stats.userHandle)); 9980 mObserver = observer; 9981 mStats = stats; 9982 } 9983 9984 @Override 9985 public String toString() { 9986 return "MeasureParams{" 9987 + Integer.toHexString(System.identityHashCode(this)) 9988 + " " + mStats.packageName + "}"; 9989 } 9990 9991 @Override 9992 void handleStartCopy() throws RemoteException { 9993 synchronized (mInstallLock) { 9994 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9995 } 9996 9997 if (mSuccess) { 9998 final boolean mounted; 9999 if (Environment.isExternalStorageEmulated()) { 10000 mounted = true; 10001 } else { 10002 final String status = Environment.getExternalStorageState(); 10003 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10004 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10005 } 10006 10007 if (mounted) { 10008 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10009 10010 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10011 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10012 10013 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10014 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10015 10016 // Always subtract cache size, since it's a subdirectory 10017 mStats.externalDataSize -= mStats.externalCacheSize; 10018 10019 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10020 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10021 10022 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10023 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10024 } 10025 } 10026 } 10027 10028 @Override 10029 void handleReturnCode() { 10030 if (mObserver != null) { 10031 try { 10032 mObserver.onGetStatsCompleted(mStats, mSuccess); 10033 } catch (RemoteException e) { 10034 Slog.i(TAG, "Observer no longer exists."); 10035 } 10036 } 10037 } 10038 10039 @Override 10040 void handleServiceError() { 10041 Slog.e(TAG, "Could not measure application " + mStats.packageName 10042 + " external storage"); 10043 } 10044 } 10045 10046 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10047 throws RemoteException { 10048 long result = 0; 10049 for (File path : paths) { 10050 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10051 } 10052 return result; 10053 } 10054 10055 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10056 for (File path : paths) { 10057 try { 10058 mcs.clearDirectory(path.getAbsolutePath()); 10059 } catch (RemoteException e) { 10060 } 10061 } 10062 } 10063 10064 static class OriginInfo { 10065 /** 10066 * Location where install is coming from, before it has been 10067 * copied/renamed into place. This could be a single monolithic APK 10068 * file, or a cluster directory. This location may be untrusted. 10069 */ 10070 final File file; 10071 final String cid; 10072 10073 /** 10074 * Flag indicating that {@link #file} or {@link #cid} has already been 10075 * staged, meaning downstream users don't need to defensively copy the 10076 * contents. 10077 */ 10078 final boolean staged; 10079 10080 /** 10081 * Flag indicating that {@link #file} or {@link #cid} is an already 10082 * installed app that is being moved. 10083 */ 10084 final boolean existing; 10085 10086 final String resolvedPath; 10087 final File resolvedFile; 10088 10089 static OriginInfo fromNothing() { 10090 return new OriginInfo(null, null, false, false); 10091 } 10092 10093 static OriginInfo fromUntrustedFile(File file) { 10094 return new OriginInfo(file, null, false, false); 10095 } 10096 10097 static OriginInfo fromExistingFile(File file) { 10098 return new OriginInfo(file, null, false, true); 10099 } 10100 10101 static OriginInfo fromStagedFile(File file) { 10102 return new OriginInfo(file, null, true, false); 10103 } 10104 10105 static OriginInfo fromStagedContainer(String cid) { 10106 return new OriginInfo(null, cid, true, false); 10107 } 10108 10109 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10110 this.file = file; 10111 this.cid = cid; 10112 this.staged = staged; 10113 this.existing = existing; 10114 10115 if (cid != null) { 10116 resolvedPath = PackageHelper.getSdDir(cid); 10117 resolvedFile = new File(resolvedPath); 10118 } else if (file != null) { 10119 resolvedPath = file.getAbsolutePath(); 10120 resolvedFile = file; 10121 } else { 10122 resolvedPath = null; 10123 resolvedFile = null; 10124 } 10125 } 10126 } 10127 10128 class MoveInfo { 10129 final int moveId; 10130 final String fromUuid; 10131 final String toUuid; 10132 final String packageName; 10133 final String dataAppName; 10134 final int appId; 10135 final String seinfo; 10136 10137 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10138 String dataAppName, int appId, String seinfo) { 10139 this.moveId = moveId; 10140 this.fromUuid = fromUuid; 10141 this.toUuid = toUuid; 10142 this.packageName = packageName; 10143 this.dataAppName = dataAppName; 10144 this.appId = appId; 10145 this.seinfo = seinfo; 10146 } 10147 } 10148 10149 class InstallParams extends HandlerParams { 10150 final OriginInfo origin; 10151 final MoveInfo move; 10152 final IPackageInstallObserver2 observer; 10153 int installFlags; 10154 final String installerPackageName; 10155 final String volumeUuid; 10156 final VerificationParams verificationParams; 10157 private InstallArgs mArgs; 10158 private int mRet; 10159 final String packageAbiOverride; 10160 10161 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10162 int installFlags, String installerPackageName, String volumeUuid, 10163 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10164 super(user); 10165 this.origin = origin; 10166 this.move = move; 10167 this.observer = observer; 10168 this.installFlags = installFlags; 10169 this.installerPackageName = installerPackageName; 10170 this.volumeUuid = volumeUuid; 10171 this.verificationParams = verificationParams; 10172 this.packageAbiOverride = packageAbiOverride; 10173 } 10174 10175 @Override 10176 public String toString() { 10177 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10178 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10179 } 10180 10181 public ManifestDigest getManifestDigest() { 10182 if (verificationParams == null) { 10183 return null; 10184 } 10185 return verificationParams.getManifestDigest(); 10186 } 10187 10188 private int installLocationPolicy(PackageInfoLite pkgLite) { 10189 String packageName = pkgLite.packageName; 10190 int installLocation = pkgLite.installLocation; 10191 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10192 // reader 10193 synchronized (mPackages) { 10194 PackageParser.Package pkg = mPackages.get(packageName); 10195 if (pkg != null) { 10196 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10197 // Check for downgrading. 10198 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10199 try { 10200 checkDowngrade(pkg, pkgLite); 10201 } catch (PackageManagerException e) { 10202 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10203 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10204 } 10205 } 10206 // Check for updated system application. 10207 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10208 if (onSd) { 10209 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10210 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10211 } 10212 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10213 } else { 10214 if (onSd) { 10215 // Install flag overrides everything. 10216 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10217 } 10218 // If current upgrade specifies particular preference 10219 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10220 // Application explicitly specified internal. 10221 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10222 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10223 // App explictly prefers external. Let policy decide 10224 } else { 10225 // Prefer previous location 10226 if (isExternal(pkg)) { 10227 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10228 } 10229 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10230 } 10231 } 10232 } else { 10233 // Invalid install. Return error code 10234 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10235 } 10236 } 10237 } 10238 // All the special cases have been taken care of. 10239 // Return result based on recommended install location. 10240 if (onSd) { 10241 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10242 } 10243 return pkgLite.recommendedInstallLocation; 10244 } 10245 10246 /* 10247 * Invoke remote method to get package information and install 10248 * location values. Override install location based on default 10249 * policy if needed and then create install arguments based 10250 * on the install location. 10251 */ 10252 public void handleStartCopy() throws RemoteException { 10253 int ret = PackageManager.INSTALL_SUCCEEDED; 10254 10255 // If we're already staged, we've firmly committed to an install location 10256 if (origin.staged) { 10257 if (origin.file != null) { 10258 installFlags |= PackageManager.INSTALL_INTERNAL; 10259 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10260 } else if (origin.cid != null) { 10261 installFlags |= PackageManager.INSTALL_EXTERNAL; 10262 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10263 } else { 10264 throw new IllegalStateException("Invalid stage location"); 10265 } 10266 } 10267 10268 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10269 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10270 10271 PackageInfoLite pkgLite = null; 10272 10273 if (onInt && onSd) { 10274 // Check if both bits are set. 10275 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10276 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10277 } else { 10278 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10279 packageAbiOverride); 10280 10281 /* 10282 * If we have too little free space, try to free cache 10283 * before giving up. 10284 */ 10285 if (!origin.staged && pkgLite.recommendedInstallLocation 10286 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10287 // TODO: focus freeing disk space on the target device 10288 final StorageManager storage = StorageManager.from(mContext); 10289 final long lowThreshold = storage.getStorageLowBytes( 10290 Environment.getDataDirectory()); 10291 10292 final long sizeBytes = mContainerService.calculateInstalledSize( 10293 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10294 10295 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10296 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10297 installFlags, packageAbiOverride); 10298 } 10299 10300 /* 10301 * The cache free must have deleted the file we 10302 * downloaded to install. 10303 * 10304 * TODO: fix the "freeCache" call to not delete 10305 * the file we care about. 10306 */ 10307 if (pkgLite.recommendedInstallLocation 10308 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10309 pkgLite.recommendedInstallLocation 10310 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10311 } 10312 } 10313 } 10314 10315 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10316 int loc = pkgLite.recommendedInstallLocation; 10317 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10318 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10319 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10320 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10321 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10322 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10323 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10324 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10325 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10326 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10327 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10328 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10329 } else { 10330 // Override with defaults if needed. 10331 loc = installLocationPolicy(pkgLite); 10332 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10333 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10334 } else if (!onSd && !onInt) { 10335 // Override install location with flags 10336 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10337 // Set the flag to install on external media. 10338 installFlags |= PackageManager.INSTALL_EXTERNAL; 10339 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10340 } else { 10341 // Make sure the flag for installing on external 10342 // media is unset 10343 installFlags |= PackageManager.INSTALL_INTERNAL; 10344 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10345 } 10346 } 10347 } 10348 } 10349 10350 final InstallArgs args = createInstallArgs(this); 10351 mArgs = args; 10352 10353 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10354 /* 10355 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10356 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10357 */ 10358 int userIdentifier = getUser().getIdentifier(); 10359 if (userIdentifier == UserHandle.USER_ALL 10360 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10361 userIdentifier = UserHandle.USER_OWNER; 10362 } 10363 10364 /* 10365 * Determine if we have any installed package verifiers. If we 10366 * do, then we'll defer to them to verify the packages. 10367 */ 10368 final int requiredUid = mRequiredVerifierPackage == null ? -1 10369 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10370 if (!origin.existing && requiredUid != -1 10371 && isVerificationEnabled(userIdentifier, installFlags)) { 10372 final Intent verification = new Intent( 10373 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10374 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10375 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10376 PACKAGE_MIME_TYPE); 10377 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10378 10379 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10380 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10381 0 /* TODO: Which userId? */); 10382 10383 if (DEBUG_VERIFY) { 10384 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10385 + verification.toString() + " with " + pkgLite.verifiers.length 10386 + " optional verifiers"); 10387 } 10388 10389 final int verificationId = mPendingVerificationToken++; 10390 10391 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10392 10393 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10394 installerPackageName); 10395 10396 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10397 installFlags); 10398 10399 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10400 pkgLite.packageName); 10401 10402 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10403 pkgLite.versionCode); 10404 10405 if (verificationParams != null) { 10406 if (verificationParams.getVerificationURI() != null) { 10407 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10408 verificationParams.getVerificationURI()); 10409 } 10410 if (verificationParams.getOriginatingURI() != null) { 10411 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10412 verificationParams.getOriginatingURI()); 10413 } 10414 if (verificationParams.getReferrer() != null) { 10415 verification.putExtra(Intent.EXTRA_REFERRER, 10416 verificationParams.getReferrer()); 10417 } 10418 if (verificationParams.getOriginatingUid() >= 0) { 10419 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10420 verificationParams.getOriginatingUid()); 10421 } 10422 if (verificationParams.getInstallerUid() >= 0) { 10423 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10424 verificationParams.getInstallerUid()); 10425 } 10426 } 10427 10428 final PackageVerificationState verificationState = new PackageVerificationState( 10429 requiredUid, args); 10430 10431 mPendingVerification.append(verificationId, verificationState); 10432 10433 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10434 receivers, verificationState); 10435 10436 /* 10437 * If any sufficient verifiers were listed in the package 10438 * manifest, attempt to ask them. 10439 */ 10440 if (sufficientVerifiers != null) { 10441 final int N = sufficientVerifiers.size(); 10442 if (N == 0) { 10443 Slog.i(TAG, "Additional verifiers required, but none installed."); 10444 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10445 } else { 10446 for (int i = 0; i < N; i++) { 10447 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10448 10449 final Intent sufficientIntent = new Intent(verification); 10450 sufficientIntent.setComponent(verifierComponent); 10451 10452 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10453 } 10454 } 10455 } 10456 10457 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10458 mRequiredVerifierPackage, receivers); 10459 if (ret == PackageManager.INSTALL_SUCCEEDED 10460 && mRequiredVerifierPackage != null) { 10461 /* 10462 * Send the intent to the required verification agent, 10463 * but only start the verification timeout after the 10464 * target BroadcastReceivers have run. 10465 */ 10466 verification.setComponent(requiredVerifierComponent); 10467 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10468 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10469 new BroadcastReceiver() { 10470 @Override 10471 public void onReceive(Context context, Intent intent) { 10472 final Message msg = mHandler 10473 .obtainMessage(CHECK_PENDING_VERIFICATION); 10474 msg.arg1 = verificationId; 10475 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10476 } 10477 }, null, 0, null, null); 10478 10479 /* 10480 * We don't want the copy to proceed until verification 10481 * succeeds, so null out this field. 10482 */ 10483 mArgs = null; 10484 } 10485 } else { 10486 /* 10487 * No package verification is enabled, so immediately start 10488 * the remote call to initiate copy using temporary file. 10489 */ 10490 ret = args.copyApk(mContainerService, true); 10491 } 10492 } 10493 10494 mRet = ret; 10495 } 10496 10497 @Override 10498 void handleReturnCode() { 10499 // If mArgs is null, then MCS couldn't be reached. When it 10500 // reconnects, it will try again to install. At that point, this 10501 // will succeed. 10502 if (mArgs != null) { 10503 processPendingInstall(mArgs, mRet); 10504 } 10505 } 10506 10507 @Override 10508 void handleServiceError() { 10509 mArgs = createInstallArgs(this); 10510 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10511 } 10512 10513 public boolean isForwardLocked() { 10514 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10515 } 10516 } 10517 10518 /** 10519 * Used during creation of InstallArgs 10520 * 10521 * @param installFlags package installation flags 10522 * @return true if should be installed on external storage 10523 */ 10524 private static boolean installOnExternalAsec(int installFlags) { 10525 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10526 return false; 10527 } 10528 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10529 return true; 10530 } 10531 return false; 10532 } 10533 10534 /** 10535 * Used during creation of InstallArgs 10536 * 10537 * @param installFlags package installation flags 10538 * @return true if should be installed as forward locked 10539 */ 10540 private static boolean installForwardLocked(int installFlags) { 10541 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10542 } 10543 10544 private InstallArgs createInstallArgs(InstallParams params) { 10545 if (params.move != null) { 10546 return new MoveInstallArgs(params); 10547 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10548 return new AsecInstallArgs(params); 10549 } else { 10550 return new FileInstallArgs(params); 10551 } 10552 } 10553 10554 /** 10555 * Create args that describe an existing installed package. Typically used 10556 * when cleaning up old installs, or used as a move source. 10557 */ 10558 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10559 String resourcePath, String[] instructionSets) { 10560 final boolean isInAsec; 10561 if (installOnExternalAsec(installFlags)) { 10562 /* Apps on SD card are always in ASEC containers. */ 10563 isInAsec = true; 10564 } else if (installForwardLocked(installFlags) 10565 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10566 /* 10567 * Forward-locked apps are only in ASEC containers if they're the 10568 * new style 10569 */ 10570 isInAsec = true; 10571 } else { 10572 isInAsec = false; 10573 } 10574 10575 if (isInAsec) { 10576 return new AsecInstallArgs(codePath, instructionSets, 10577 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10578 } else { 10579 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10580 } 10581 } 10582 10583 static abstract class InstallArgs { 10584 /** @see InstallParams#origin */ 10585 final OriginInfo origin; 10586 /** @see InstallParams#move */ 10587 final MoveInfo move; 10588 10589 final IPackageInstallObserver2 observer; 10590 // Always refers to PackageManager flags only 10591 final int installFlags; 10592 final String installerPackageName; 10593 final String volumeUuid; 10594 final ManifestDigest manifestDigest; 10595 final UserHandle user; 10596 final String abiOverride; 10597 10598 // The list of instruction sets supported by this app. This is currently 10599 // only used during the rmdex() phase to clean up resources. We can get rid of this 10600 // if we move dex files under the common app path. 10601 /* nullable */ String[] instructionSets; 10602 10603 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10604 int installFlags, String installerPackageName, String volumeUuid, 10605 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10606 String abiOverride) { 10607 this.origin = origin; 10608 this.move = move; 10609 this.installFlags = installFlags; 10610 this.observer = observer; 10611 this.installerPackageName = installerPackageName; 10612 this.volumeUuid = volumeUuid; 10613 this.manifestDigest = manifestDigest; 10614 this.user = user; 10615 this.instructionSets = instructionSets; 10616 this.abiOverride = abiOverride; 10617 } 10618 10619 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10620 abstract int doPreInstall(int status); 10621 10622 /** 10623 * Rename package into final resting place. All paths on the given 10624 * scanned package should be updated to reflect the rename. 10625 */ 10626 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10627 abstract int doPostInstall(int status, int uid); 10628 10629 /** @see PackageSettingBase#codePathString */ 10630 abstract String getCodePath(); 10631 /** @see PackageSettingBase#resourcePathString */ 10632 abstract String getResourcePath(); 10633 10634 // Need installer lock especially for dex file removal. 10635 abstract void cleanUpResourcesLI(); 10636 abstract boolean doPostDeleteLI(boolean delete); 10637 10638 /** 10639 * Called before the source arguments are copied. This is used mostly 10640 * for MoveParams when it needs to read the source file to put it in the 10641 * destination. 10642 */ 10643 int doPreCopy() { 10644 return PackageManager.INSTALL_SUCCEEDED; 10645 } 10646 10647 /** 10648 * Called after the source arguments are copied. This is used mostly for 10649 * MoveParams when it needs to read the source file to put it in the 10650 * destination. 10651 * 10652 * @return 10653 */ 10654 int doPostCopy(int uid) { 10655 return PackageManager.INSTALL_SUCCEEDED; 10656 } 10657 10658 protected boolean isFwdLocked() { 10659 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10660 } 10661 10662 protected boolean isExternalAsec() { 10663 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10664 } 10665 10666 UserHandle getUser() { 10667 return user; 10668 } 10669 } 10670 10671 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10672 if (!allCodePaths.isEmpty()) { 10673 if (instructionSets == null) { 10674 throw new IllegalStateException("instructionSet == null"); 10675 } 10676 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10677 for (String codePath : allCodePaths) { 10678 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10679 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10680 if (retCode < 0) { 10681 Slog.w(TAG, "Couldn't remove dex file for package: " 10682 + " at location " + codePath + ", retcode=" + retCode); 10683 // we don't consider this to be a failure of the core package deletion 10684 } 10685 } 10686 } 10687 } 10688 } 10689 10690 /** 10691 * Logic to handle installation of non-ASEC applications, including copying 10692 * and renaming logic. 10693 */ 10694 class FileInstallArgs extends InstallArgs { 10695 private File codeFile; 10696 private File resourceFile; 10697 10698 // Example topology: 10699 // /data/app/com.example/base.apk 10700 // /data/app/com.example/split_foo.apk 10701 // /data/app/com.example/lib/arm/libfoo.so 10702 // /data/app/com.example/lib/arm64/libfoo.so 10703 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10704 10705 /** New install */ 10706 FileInstallArgs(InstallParams params) { 10707 super(params.origin, params.move, params.observer, params.installFlags, 10708 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10709 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10710 if (isFwdLocked()) { 10711 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10712 } 10713 } 10714 10715 /** Existing install */ 10716 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10717 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10718 null); 10719 this.codeFile = (codePath != null) ? new File(codePath) : null; 10720 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10721 } 10722 10723 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10724 if (origin.staged) { 10725 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10726 codeFile = origin.file; 10727 resourceFile = origin.file; 10728 return PackageManager.INSTALL_SUCCEEDED; 10729 } 10730 10731 try { 10732 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10733 codeFile = tempDir; 10734 resourceFile = tempDir; 10735 } catch (IOException e) { 10736 Slog.w(TAG, "Failed to create copy file: " + e); 10737 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10738 } 10739 10740 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10741 @Override 10742 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10743 if (!FileUtils.isValidExtFilename(name)) { 10744 throw new IllegalArgumentException("Invalid filename: " + name); 10745 } 10746 try { 10747 final File file = new File(codeFile, name); 10748 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10749 O_RDWR | O_CREAT, 0644); 10750 Os.chmod(file.getAbsolutePath(), 0644); 10751 return new ParcelFileDescriptor(fd); 10752 } catch (ErrnoException e) { 10753 throw new RemoteException("Failed to open: " + e.getMessage()); 10754 } 10755 } 10756 }; 10757 10758 int ret = PackageManager.INSTALL_SUCCEEDED; 10759 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10760 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10761 Slog.e(TAG, "Failed to copy package"); 10762 return ret; 10763 } 10764 10765 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10766 NativeLibraryHelper.Handle handle = null; 10767 try { 10768 handle = NativeLibraryHelper.Handle.create(codeFile); 10769 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10770 abiOverride); 10771 } catch (IOException e) { 10772 Slog.e(TAG, "Copying native libraries failed", e); 10773 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10774 } finally { 10775 IoUtils.closeQuietly(handle); 10776 } 10777 10778 return ret; 10779 } 10780 10781 int doPreInstall(int status) { 10782 if (status != PackageManager.INSTALL_SUCCEEDED) { 10783 cleanUp(); 10784 } 10785 return status; 10786 } 10787 10788 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10789 if (status != PackageManager.INSTALL_SUCCEEDED) { 10790 cleanUp(); 10791 return false; 10792 } 10793 10794 final File targetDir = codeFile.getParentFile(); 10795 final File beforeCodeFile = codeFile; 10796 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10797 10798 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10799 try { 10800 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10801 } catch (ErrnoException e) { 10802 Slog.w(TAG, "Failed to rename", e); 10803 return false; 10804 } 10805 10806 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10807 Slog.w(TAG, "Failed to restorecon"); 10808 return false; 10809 } 10810 10811 // Reflect the rename internally 10812 codeFile = afterCodeFile; 10813 resourceFile = afterCodeFile; 10814 10815 // Reflect the rename in scanned details 10816 pkg.codePath = afterCodeFile.getAbsolutePath(); 10817 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10818 pkg.baseCodePath); 10819 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10820 pkg.splitCodePaths); 10821 10822 // Reflect the rename in app info 10823 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10824 pkg.applicationInfo.setCodePath(pkg.codePath); 10825 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10826 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10827 pkg.applicationInfo.setResourcePath(pkg.codePath); 10828 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10829 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10830 10831 return true; 10832 } 10833 10834 int doPostInstall(int status, int uid) { 10835 if (status != PackageManager.INSTALL_SUCCEEDED) { 10836 cleanUp(); 10837 } 10838 return status; 10839 } 10840 10841 @Override 10842 String getCodePath() { 10843 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10844 } 10845 10846 @Override 10847 String getResourcePath() { 10848 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10849 } 10850 10851 private boolean cleanUp() { 10852 if (codeFile == null || !codeFile.exists()) { 10853 return false; 10854 } 10855 10856 if (codeFile.isDirectory()) { 10857 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10858 } else { 10859 codeFile.delete(); 10860 } 10861 10862 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10863 resourceFile.delete(); 10864 } 10865 10866 return true; 10867 } 10868 10869 void cleanUpResourcesLI() { 10870 // Try enumerating all code paths before deleting 10871 List<String> allCodePaths = Collections.EMPTY_LIST; 10872 if (codeFile != null && codeFile.exists()) { 10873 try { 10874 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10875 allCodePaths = pkg.getAllCodePaths(); 10876 } catch (PackageParserException e) { 10877 // Ignored; we tried our best 10878 } 10879 } 10880 10881 cleanUp(); 10882 removeDexFiles(allCodePaths, instructionSets); 10883 } 10884 10885 boolean doPostDeleteLI(boolean delete) { 10886 // XXX err, shouldn't we respect the delete flag? 10887 cleanUpResourcesLI(); 10888 return true; 10889 } 10890 } 10891 10892 private boolean isAsecExternal(String cid) { 10893 final String asecPath = PackageHelper.getSdFilesystem(cid); 10894 return !asecPath.startsWith(mAsecInternalPath); 10895 } 10896 10897 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10898 PackageManagerException { 10899 if (copyRet < 0) { 10900 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10901 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10902 throw new PackageManagerException(copyRet, message); 10903 } 10904 } 10905 } 10906 10907 /** 10908 * Extract the MountService "container ID" from the full code path of an 10909 * .apk. 10910 */ 10911 static String cidFromCodePath(String fullCodePath) { 10912 int eidx = fullCodePath.lastIndexOf("/"); 10913 String subStr1 = fullCodePath.substring(0, eidx); 10914 int sidx = subStr1.lastIndexOf("/"); 10915 return subStr1.substring(sidx+1, eidx); 10916 } 10917 10918 /** 10919 * Logic to handle installation of ASEC applications, including copying and 10920 * renaming logic. 10921 */ 10922 class AsecInstallArgs extends InstallArgs { 10923 static final String RES_FILE_NAME = "pkg.apk"; 10924 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10925 10926 String cid; 10927 String packagePath; 10928 String resourcePath; 10929 10930 /** New install */ 10931 AsecInstallArgs(InstallParams params) { 10932 super(params.origin, params.move, params.observer, params.installFlags, 10933 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10934 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10935 } 10936 10937 /** Existing install */ 10938 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10939 boolean isExternal, boolean isForwardLocked) { 10940 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10941 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10942 instructionSets, null); 10943 // Hackily pretend we're still looking at a full code path 10944 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10945 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10946 } 10947 10948 // Extract cid from fullCodePath 10949 int eidx = fullCodePath.lastIndexOf("/"); 10950 String subStr1 = fullCodePath.substring(0, eidx); 10951 int sidx = subStr1.lastIndexOf("/"); 10952 cid = subStr1.substring(sidx+1, eidx); 10953 setMountPath(subStr1); 10954 } 10955 10956 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10957 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10958 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10959 instructionSets, null); 10960 this.cid = cid; 10961 setMountPath(PackageHelper.getSdDir(cid)); 10962 } 10963 10964 void createCopyFile() { 10965 cid = mInstallerService.allocateExternalStageCidLegacy(); 10966 } 10967 10968 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10969 if (origin.staged) { 10970 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10971 cid = origin.cid; 10972 setMountPath(PackageHelper.getSdDir(cid)); 10973 return PackageManager.INSTALL_SUCCEEDED; 10974 } 10975 10976 if (temp) { 10977 createCopyFile(); 10978 } else { 10979 /* 10980 * Pre-emptively destroy the container since it's destroyed if 10981 * copying fails due to it existing anyway. 10982 */ 10983 PackageHelper.destroySdDir(cid); 10984 } 10985 10986 final String newMountPath = imcs.copyPackageToContainer( 10987 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10988 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10989 10990 if (newMountPath != null) { 10991 setMountPath(newMountPath); 10992 return PackageManager.INSTALL_SUCCEEDED; 10993 } else { 10994 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10995 } 10996 } 10997 10998 @Override 10999 String getCodePath() { 11000 return packagePath; 11001 } 11002 11003 @Override 11004 String getResourcePath() { 11005 return resourcePath; 11006 } 11007 11008 int doPreInstall(int status) { 11009 if (status != PackageManager.INSTALL_SUCCEEDED) { 11010 // Destroy container 11011 PackageHelper.destroySdDir(cid); 11012 } else { 11013 boolean mounted = PackageHelper.isContainerMounted(cid); 11014 if (!mounted) { 11015 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11016 Process.SYSTEM_UID); 11017 if (newMountPath != null) { 11018 setMountPath(newMountPath); 11019 } else { 11020 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11021 } 11022 } 11023 } 11024 return status; 11025 } 11026 11027 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11028 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11029 String newMountPath = null; 11030 if (PackageHelper.isContainerMounted(cid)) { 11031 // Unmount the container 11032 if (!PackageHelper.unMountSdDir(cid)) { 11033 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11034 return false; 11035 } 11036 } 11037 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11038 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11039 " which might be stale. Will try to clean up."); 11040 // Clean up the stale container and proceed to recreate. 11041 if (!PackageHelper.destroySdDir(newCacheId)) { 11042 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11043 return false; 11044 } 11045 // Successfully cleaned up stale container. Try to rename again. 11046 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11047 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11048 + " inspite of cleaning it up."); 11049 return false; 11050 } 11051 } 11052 if (!PackageHelper.isContainerMounted(newCacheId)) { 11053 Slog.w(TAG, "Mounting container " + newCacheId); 11054 newMountPath = PackageHelper.mountSdDir(newCacheId, 11055 getEncryptKey(), Process.SYSTEM_UID); 11056 } else { 11057 newMountPath = PackageHelper.getSdDir(newCacheId); 11058 } 11059 if (newMountPath == null) { 11060 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11061 return false; 11062 } 11063 Log.i(TAG, "Succesfully renamed " + cid + 11064 " to " + newCacheId + 11065 " at new path: " + newMountPath); 11066 cid = newCacheId; 11067 11068 final File beforeCodeFile = new File(packagePath); 11069 setMountPath(newMountPath); 11070 final File afterCodeFile = new File(packagePath); 11071 11072 // Reflect the rename in scanned details 11073 pkg.codePath = afterCodeFile.getAbsolutePath(); 11074 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11075 pkg.baseCodePath); 11076 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11077 pkg.splitCodePaths); 11078 11079 // Reflect the rename in app info 11080 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11081 pkg.applicationInfo.setCodePath(pkg.codePath); 11082 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11083 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11084 pkg.applicationInfo.setResourcePath(pkg.codePath); 11085 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11086 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11087 11088 return true; 11089 } 11090 11091 private void setMountPath(String mountPath) { 11092 final File mountFile = new File(mountPath); 11093 11094 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11095 if (monolithicFile.exists()) { 11096 packagePath = monolithicFile.getAbsolutePath(); 11097 if (isFwdLocked()) { 11098 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11099 } else { 11100 resourcePath = packagePath; 11101 } 11102 } else { 11103 packagePath = mountFile.getAbsolutePath(); 11104 resourcePath = packagePath; 11105 } 11106 } 11107 11108 int doPostInstall(int status, int uid) { 11109 if (status != PackageManager.INSTALL_SUCCEEDED) { 11110 cleanUp(); 11111 } else { 11112 final int groupOwner; 11113 final String protectedFile; 11114 if (isFwdLocked()) { 11115 groupOwner = UserHandle.getSharedAppGid(uid); 11116 protectedFile = RES_FILE_NAME; 11117 } else { 11118 groupOwner = -1; 11119 protectedFile = null; 11120 } 11121 11122 if (uid < Process.FIRST_APPLICATION_UID 11123 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11124 Slog.e(TAG, "Failed to finalize " + cid); 11125 PackageHelper.destroySdDir(cid); 11126 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11127 } 11128 11129 boolean mounted = PackageHelper.isContainerMounted(cid); 11130 if (!mounted) { 11131 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11132 } 11133 } 11134 return status; 11135 } 11136 11137 private void cleanUp() { 11138 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11139 11140 // Destroy secure container 11141 PackageHelper.destroySdDir(cid); 11142 } 11143 11144 private List<String> getAllCodePaths() { 11145 final File codeFile = new File(getCodePath()); 11146 if (codeFile != null && codeFile.exists()) { 11147 try { 11148 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11149 return pkg.getAllCodePaths(); 11150 } catch (PackageParserException e) { 11151 // Ignored; we tried our best 11152 } 11153 } 11154 return Collections.EMPTY_LIST; 11155 } 11156 11157 void cleanUpResourcesLI() { 11158 // Enumerate all code paths before deleting 11159 cleanUpResourcesLI(getAllCodePaths()); 11160 } 11161 11162 private void cleanUpResourcesLI(List<String> allCodePaths) { 11163 cleanUp(); 11164 removeDexFiles(allCodePaths, instructionSets); 11165 } 11166 11167 String getPackageName() { 11168 return getAsecPackageName(cid); 11169 } 11170 11171 boolean doPostDeleteLI(boolean delete) { 11172 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11173 final List<String> allCodePaths = getAllCodePaths(); 11174 boolean mounted = PackageHelper.isContainerMounted(cid); 11175 if (mounted) { 11176 // Unmount first 11177 if (PackageHelper.unMountSdDir(cid)) { 11178 mounted = false; 11179 } 11180 } 11181 if (!mounted && delete) { 11182 cleanUpResourcesLI(allCodePaths); 11183 } 11184 return !mounted; 11185 } 11186 11187 @Override 11188 int doPreCopy() { 11189 if (isFwdLocked()) { 11190 if (!PackageHelper.fixSdPermissions(cid, 11191 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11192 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11193 } 11194 } 11195 11196 return PackageManager.INSTALL_SUCCEEDED; 11197 } 11198 11199 @Override 11200 int doPostCopy(int uid) { 11201 if (isFwdLocked()) { 11202 if (uid < Process.FIRST_APPLICATION_UID 11203 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11204 RES_FILE_NAME)) { 11205 Slog.e(TAG, "Failed to finalize " + cid); 11206 PackageHelper.destroySdDir(cid); 11207 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11208 } 11209 } 11210 11211 return PackageManager.INSTALL_SUCCEEDED; 11212 } 11213 } 11214 11215 /** 11216 * Logic to handle movement of existing installed applications. 11217 */ 11218 class MoveInstallArgs extends InstallArgs { 11219 private File codeFile; 11220 private File resourceFile; 11221 11222 /** New install */ 11223 MoveInstallArgs(InstallParams params) { 11224 super(params.origin, params.move, params.observer, params.installFlags, 11225 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11226 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11227 } 11228 11229 int copyApk(IMediaContainerService imcs, boolean temp) { 11230 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11231 + move.fromUuid + " to " + move.toUuid); 11232 synchronized (mInstaller) { 11233 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11234 move.dataAppName, move.appId, move.seinfo) != 0) { 11235 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11236 } 11237 } 11238 11239 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11240 resourceFile = codeFile; 11241 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11242 11243 return PackageManager.INSTALL_SUCCEEDED; 11244 } 11245 11246 int doPreInstall(int status) { 11247 if (status != PackageManager.INSTALL_SUCCEEDED) { 11248 cleanUp(); 11249 } 11250 return status; 11251 } 11252 11253 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11254 if (status != PackageManager.INSTALL_SUCCEEDED) { 11255 cleanUp(); 11256 return false; 11257 } 11258 11259 // Reflect the move in app info 11260 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11261 pkg.applicationInfo.setCodePath(pkg.codePath); 11262 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11263 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11264 pkg.applicationInfo.setResourcePath(pkg.codePath); 11265 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11266 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11267 11268 return true; 11269 } 11270 11271 int doPostInstall(int status, int uid) { 11272 if (status != PackageManager.INSTALL_SUCCEEDED) { 11273 cleanUp(); 11274 } 11275 return status; 11276 } 11277 11278 @Override 11279 String getCodePath() { 11280 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11281 } 11282 11283 @Override 11284 String getResourcePath() { 11285 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11286 } 11287 11288 private boolean cleanUp() { 11289 if (codeFile == null || !codeFile.exists()) { 11290 return false; 11291 } 11292 11293 if (codeFile.isDirectory()) { 11294 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11295 } else { 11296 codeFile.delete(); 11297 } 11298 11299 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11300 resourceFile.delete(); 11301 } 11302 11303 return true; 11304 } 11305 11306 void cleanUpResourcesLI() { 11307 cleanUp(); 11308 } 11309 11310 boolean doPostDeleteLI(boolean delete) { 11311 // XXX err, shouldn't we respect the delete flag? 11312 cleanUpResourcesLI(); 11313 return true; 11314 } 11315 } 11316 11317 static String getAsecPackageName(String packageCid) { 11318 int idx = packageCid.lastIndexOf("-"); 11319 if (idx == -1) { 11320 return packageCid; 11321 } 11322 return packageCid.substring(0, idx); 11323 } 11324 11325 // Utility method used to create code paths based on package name and available index. 11326 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11327 String idxStr = ""; 11328 int idx = 1; 11329 // Fall back to default value of idx=1 if prefix is not 11330 // part of oldCodePath 11331 if (oldCodePath != null) { 11332 String subStr = oldCodePath; 11333 // Drop the suffix right away 11334 if (suffix != null && subStr.endsWith(suffix)) { 11335 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11336 } 11337 // If oldCodePath already contains prefix find out the 11338 // ending index to either increment or decrement. 11339 int sidx = subStr.lastIndexOf(prefix); 11340 if (sidx != -1) { 11341 subStr = subStr.substring(sidx + prefix.length()); 11342 if (subStr != null) { 11343 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11344 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11345 } 11346 try { 11347 idx = Integer.parseInt(subStr); 11348 if (idx <= 1) { 11349 idx++; 11350 } else { 11351 idx--; 11352 } 11353 } catch(NumberFormatException e) { 11354 } 11355 } 11356 } 11357 } 11358 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11359 return prefix + idxStr; 11360 } 11361 11362 private File getNextCodePath(File targetDir, String packageName) { 11363 int suffix = 1; 11364 File result; 11365 do { 11366 result = new File(targetDir, packageName + "-" + suffix); 11367 suffix++; 11368 } while (result.exists()); 11369 return result; 11370 } 11371 11372 // Utility method that returns the relative package path with respect 11373 // to the installation directory. Like say for /data/data/com.test-1.apk 11374 // string com.test-1 is returned. 11375 static String deriveCodePathName(String codePath) { 11376 if (codePath == null) { 11377 return null; 11378 } 11379 final File codeFile = new File(codePath); 11380 final String name = codeFile.getName(); 11381 if (codeFile.isDirectory()) { 11382 return name; 11383 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11384 final int lastDot = name.lastIndexOf('.'); 11385 return name.substring(0, lastDot); 11386 } else { 11387 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11388 return null; 11389 } 11390 } 11391 11392 class PackageInstalledInfo { 11393 String name; 11394 int uid; 11395 // The set of users that originally had this package installed. 11396 int[] origUsers; 11397 // The set of users that now have this package installed. 11398 int[] newUsers; 11399 PackageParser.Package pkg; 11400 int returnCode; 11401 String returnMsg; 11402 PackageRemovedInfo removedInfo; 11403 11404 public void setError(int code, String msg) { 11405 returnCode = code; 11406 returnMsg = msg; 11407 Slog.w(TAG, msg); 11408 } 11409 11410 public void setError(String msg, PackageParserException e) { 11411 returnCode = e.error; 11412 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11413 Slog.w(TAG, msg, e); 11414 } 11415 11416 public void setError(String msg, PackageManagerException e) { 11417 returnCode = e.error; 11418 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11419 Slog.w(TAG, msg, e); 11420 } 11421 11422 // In some error cases we want to convey more info back to the observer 11423 String origPackage; 11424 String origPermission; 11425 } 11426 11427 /* 11428 * Install a non-existing package. 11429 */ 11430 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11431 UserHandle user, String installerPackageName, String volumeUuid, 11432 PackageInstalledInfo res) { 11433 // Remember this for later, in case we need to rollback this install 11434 String pkgName = pkg.packageName; 11435 11436 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11437 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11438 UserHandle.USER_OWNER).exists(); 11439 synchronized(mPackages) { 11440 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11441 // A package with the same name is already installed, though 11442 // it has been renamed to an older name. The package we 11443 // are trying to install should be installed as an update to 11444 // the existing one, but that has not been requested, so bail. 11445 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11446 + " without first uninstalling package running as " 11447 + mSettings.mRenamedPackages.get(pkgName)); 11448 return; 11449 } 11450 if (mPackages.containsKey(pkgName)) { 11451 // Don't allow installation over an existing package with the same name. 11452 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11453 + " without first uninstalling."); 11454 return; 11455 } 11456 } 11457 11458 try { 11459 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11460 System.currentTimeMillis(), user); 11461 11462 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11463 // delete the partially installed application. the data directory will have to be 11464 // restored if it was already existing 11465 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11466 // remove package from internal structures. Note that we want deletePackageX to 11467 // delete the package data and cache directories that it created in 11468 // scanPackageLocked, unless those directories existed before we even tried to 11469 // install. 11470 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11471 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11472 res.removedInfo, true); 11473 } 11474 11475 } catch (PackageManagerException e) { 11476 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11477 } 11478 } 11479 11480 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11481 // Can't rotate keys during boot or if sharedUser. 11482 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11483 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11484 return false; 11485 } 11486 // app is using upgradeKeySets; make sure all are valid 11487 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11488 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11489 for (int i = 0; i < upgradeKeySets.length; i++) { 11490 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11491 Slog.wtf(TAG, "Package " 11492 + (oldPs.name != null ? oldPs.name : "<null>") 11493 + " contains upgrade-key-set reference to unknown key-set: " 11494 + upgradeKeySets[i] 11495 + " reverting to signatures check."); 11496 return false; 11497 } 11498 } 11499 return true; 11500 } 11501 11502 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11503 // Upgrade keysets are being used. Determine if new package has a superset of the 11504 // required keys. 11505 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11506 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11507 for (int i = 0; i < upgradeKeySets.length; i++) { 11508 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11509 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11510 return true; 11511 } 11512 } 11513 return false; 11514 } 11515 11516 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11517 UserHandle user, String installerPackageName, String volumeUuid, 11518 PackageInstalledInfo res) { 11519 final PackageParser.Package oldPackage; 11520 final String pkgName = pkg.packageName; 11521 final int[] allUsers; 11522 final boolean[] perUserInstalled; 11523 final boolean weFroze; 11524 11525 // First find the old package info and check signatures 11526 synchronized(mPackages) { 11527 oldPackage = mPackages.get(pkgName); 11528 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11529 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11530 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11531 if(!checkUpgradeKeySetLP(ps, pkg)) { 11532 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11533 "New package not signed by keys specified by upgrade-keysets: " 11534 + pkgName); 11535 return; 11536 } 11537 } else { 11538 // default to original signature matching 11539 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11540 != PackageManager.SIGNATURE_MATCH) { 11541 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11542 "New package has a different signature: " + pkgName); 11543 return; 11544 } 11545 } 11546 11547 // In case of rollback, remember per-user/profile install state 11548 allUsers = sUserManager.getUserIds(); 11549 perUserInstalled = new boolean[allUsers.length]; 11550 for (int i = 0; i < allUsers.length; i++) { 11551 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11552 } 11553 11554 // Mark the app as frozen to prevent launching during the upgrade 11555 // process, and then kill all running instances 11556 if (!ps.frozen) { 11557 ps.frozen = true; 11558 weFroze = true; 11559 } else { 11560 weFroze = false; 11561 } 11562 } 11563 11564 // Now that we're guarded by frozen state, kill app during upgrade 11565 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11566 11567 try { 11568 boolean sysPkg = (isSystemApp(oldPackage)); 11569 if (sysPkg) { 11570 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11571 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11572 } else { 11573 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11574 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11575 } 11576 } finally { 11577 // Regardless of success or failure of upgrade steps above, always 11578 // unfreeze the package if we froze it 11579 if (weFroze) { 11580 unfreezePackage(pkgName); 11581 } 11582 } 11583 } 11584 11585 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11586 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11587 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11588 String volumeUuid, PackageInstalledInfo res) { 11589 String pkgName = deletedPackage.packageName; 11590 boolean deletedPkg = true; 11591 boolean updatedSettings = false; 11592 11593 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11594 + deletedPackage); 11595 long origUpdateTime; 11596 if (pkg.mExtras != null) { 11597 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11598 } else { 11599 origUpdateTime = 0; 11600 } 11601 11602 // First delete the existing package while retaining the data directory 11603 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11604 res.removedInfo, true)) { 11605 // If the existing package wasn't successfully deleted 11606 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11607 deletedPkg = false; 11608 } else { 11609 // Successfully deleted the old package; proceed with replace. 11610 11611 // If deleted package lived in a container, give users a chance to 11612 // relinquish resources before killing. 11613 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11614 if (DEBUG_INSTALL) { 11615 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11616 } 11617 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11618 final ArrayList<String> pkgList = new ArrayList<String>(1); 11619 pkgList.add(deletedPackage.applicationInfo.packageName); 11620 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11621 } 11622 11623 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11624 try { 11625 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11626 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11627 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11628 perUserInstalled, res, user); 11629 updatedSettings = true; 11630 } catch (PackageManagerException e) { 11631 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11632 } 11633 } 11634 11635 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11636 // remove package from internal structures. Note that we want deletePackageX to 11637 // delete the package data and cache directories that it created in 11638 // scanPackageLocked, unless those directories existed before we even tried to 11639 // install. 11640 if(updatedSettings) { 11641 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11642 deletePackageLI( 11643 pkgName, null, true, allUsers, perUserInstalled, 11644 PackageManager.DELETE_KEEP_DATA, 11645 res.removedInfo, true); 11646 } 11647 // Since we failed to install the new package we need to restore the old 11648 // package that we deleted. 11649 if (deletedPkg) { 11650 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11651 File restoreFile = new File(deletedPackage.codePath); 11652 // Parse old package 11653 boolean oldExternal = isExternal(deletedPackage); 11654 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11655 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11656 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11657 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11658 try { 11659 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11660 } catch (PackageManagerException e) { 11661 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11662 + e.getMessage()); 11663 return; 11664 } 11665 // Restore of old package succeeded. Update permissions. 11666 // writer 11667 synchronized (mPackages) { 11668 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11669 UPDATE_PERMISSIONS_ALL); 11670 // can downgrade to reader 11671 mSettings.writeLPr(); 11672 } 11673 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11674 } 11675 } 11676 } 11677 11678 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11679 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11680 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11681 String volumeUuid, PackageInstalledInfo res) { 11682 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11683 + ", old=" + deletedPackage); 11684 boolean disabledSystem = false; 11685 boolean updatedSettings = false; 11686 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11687 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11688 != 0) { 11689 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11690 } 11691 String packageName = deletedPackage.packageName; 11692 if (packageName == null) { 11693 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11694 "Attempt to delete null packageName."); 11695 return; 11696 } 11697 PackageParser.Package oldPkg; 11698 PackageSetting oldPkgSetting; 11699 // reader 11700 synchronized (mPackages) { 11701 oldPkg = mPackages.get(packageName); 11702 oldPkgSetting = mSettings.mPackages.get(packageName); 11703 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11704 (oldPkgSetting == null)) { 11705 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11706 "Couldn't find package:" + packageName + " information"); 11707 return; 11708 } 11709 } 11710 11711 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11712 res.removedInfo.removedPackage = packageName; 11713 // Remove existing system package 11714 removePackageLI(oldPkgSetting, true); 11715 // writer 11716 synchronized (mPackages) { 11717 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11718 if (!disabledSystem && deletedPackage != null) { 11719 // We didn't need to disable the .apk as a current system package, 11720 // which means we are replacing another update that is already 11721 // installed. We need to make sure to delete the older one's .apk. 11722 res.removedInfo.args = createInstallArgsForExisting(0, 11723 deletedPackage.applicationInfo.getCodePath(), 11724 deletedPackage.applicationInfo.getResourcePath(), 11725 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11726 } else { 11727 res.removedInfo.args = null; 11728 } 11729 } 11730 11731 // Successfully disabled the old package. Now proceed with re-installation 11732 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11733 11734 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11735 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11736 11737 PackageParser.Package newPackage = null; 11738 try { 11739 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11740 if (newPackage.mExtras != null) { 11741 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11742 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11743 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11744 11745 // is the update attempting to change shared user? that isn't going to work... 11746 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11747 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11748 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11749 + " to " + newPkgSetting.sharedUser); 11750 updatedSettings = true; 11751 } 11752 } 11753 11754 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11755 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11756 perUserInstalled, res, user); 11757 updatedSettings = true; 11758 } 11759 11760 } catch (PackageManagerException e) { 11761 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11762 } 11763 11764 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11765 // Re installation failed. Restore old information 11766 // Remove new pkg information 11767 if (newPackage != null) { 11768 removeInstalledPackageLI(newPackage, true); 11769 } 11770 // Add back the old system package 11771 try { 11772 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11773 } catch (PackageManagerException e) { 11774 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11775 } 11776 // Restore the old system information in Settings 11777 synchronized (mPackages) { 11778 if (disabledSystem) { 11779 mSettings.enableSystemPackageLPw(packageName); 11780 } 11781 if (updatedSettings) { 11782 mSettings.setInstallerPackageName(packageName, 11783 oldPkgSetting.installerPackageName); 11784 } 11785 mSettings.writeLPr(); 11786 } 11787 } 11788 } 11789 11790 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11791 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11792 UserHandle user) { 11793 String pkgName = newPackage.packageName; 11794 synchronized (mPackages) { 11795 //write settings. the installStatus will be incomplete at this stage. 11796 //note that the new package setting would have already been 11797 //added to mPackages. It hasn't been persisted yet. 11798 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11799 mSettings.writeLPr(); 11800 } 11801 11802 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11803 11804 synchronized (mPackages) { 11805 updatePermissionsLPw(newPackage.packageName, newPackage, 11806 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11807 ? UPDATE_PERMISSIONS_ALL : 0)); 11808 // For system-bundled packages, we assume that installing an upgraded version 11809 // of the package implies that the user actually wants to run that new code, 11810 // so we enable the package. 11811 PackageSetting ps = mSettings.mPackages.get(pkgName); 11812 if (ps != null) { 11813 if (isSystemApp(newPackage)) { 11814 // NB: implicit assumption that system package upgrades apply to all users 11815 if (DEBUG_INSTALL) { 11816 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11817 } 11818 if (res.origUsers != null) { 11819 for (int userHandle : res.origUsers) { 11820 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11821 userHandle, installerPackageName); 11822 } 11823 } 11824 // Also convey the prior install/uninstall state 11825 if (allUsers != null && perUserInstalled != null) { 11826 for (int i = 0; i < allUsers.length; i++) { 11827 if (DEBUG_INSTALL) { 11828 Slog.d(TAG, " user " + allUsers[i] 11829 + " => " + perUserInstalled[i]); 11830 } 11831 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11832 } 11833 // these install state changes will be persisted in the 11834 // upcoming call to mSettings.writeLPr(). 11835 } 11836 } 11837 // It's implied that when a user requests installation, they want the app to be 11838 // installed and enabled. 11839 int userId = user.getIdentifier(); 11840 if (userId != UserHandle.USER_ALL) { 11841 ps.setInstalled(true, userId); 11842 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11843 } 11844 } 11845 res.name = pkgName; 11846 res.uid = newPackage.applicationInfo.uid; 11847 res.pkg = newPackage; 11848 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11849 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11850 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11851 //to update install status 11852 mSettings.writeLPr(); 11853 } 11854 } 11855 11856 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11857 final int installFlags = args.installFlags; 11858 final String installerPackageName = args.installerPackageName; 11859 final String volumeUuid = args.volumeUuid; 11860 final File tmpPackageFile = new File(args.getCodePath()); 11861 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11862 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11863 || (args.volumeUuid != null)); 11864 boolean replace = false; 11865 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11866 if (args.move != null) { 11867 // moving a complete application; perfom an initial scan on the new install location 11868 scanFlags |= SCAN_INITIAL; 11869 } 11870 // Result object to be returned 11871 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11872 11873 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11874 // Retrieve PackageSettings and parse package 11875 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11876 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11877 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11878 PackageParser pp = new PackageParser(); 11879 pp.setSeparateProcesses(mSeparateProcesses); 11880 pp.setDisplayMetrics(mMetrics); 11881 11882 final PackageParser.Package pkg; 11883 try { 11884 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11885 } catch (PackageParserException e) { 11886 res.setError("Failed parse during installPackageLI", e); 11887 return; 11888 } 11889 11890 // Mark that we have an install time CPU ABI override. 11891 pkg.cpuAbiOverride = args.abiOverride; 11892 11893 String pkgName = res.name = pkg.packageName; 11894 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11895 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11896 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11897 return; 11898 } 11899 } 11900 11901 try { 11902 pp.collectCertificates(pkg, parseFlags); 11903 pp.collectManifestDigest(pkg); 11904 } catch (PackageParserException e) { 11905 res.setError("Failed collect during installPackageLI", e); 11906 return; 11907 } 11908 11909 /* If the installer passed in a manifest digest, compare it now. */ 11910 if (args.manifestDigest != null) { 11911 if (DEBUG_INSTALL) { 11912 final String parsedManifest = pkg.manifestDigest == null ? "null" 11913 : pkg.manifestDigest.toString(); 11914 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11915 + parsedManifest); 11916 } 11917 11918 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11919 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11920 return; 11921 } 11922 } else if (DEBUG_INSTALL) { 11923 final String parsedManifest = pkg.manifestDigest == null 11924 ? "null" : pkg.manifestDigest.toString(); 11925 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11926 } 11927 11928 // Get rid of all references to package scan path via parser. 11929 pp = null; 11930 String oldCodePath = null; 11931 boolean systemApp = false; 11932 synchronized (mPackages) { 11933 // Check if installing already existing package 11934 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11935 String oldName = mSettings.mRenamedPackages.get(pkgName); 11936 if (pkg.mOriginalPackages != null 11937 && pkg.mOriginalPackages.contains(oldName) 11938 && mPackages.containsKey(oldName)) { 11939 // This package is derived from an original package, 11940 // and this device has been updating from that original 11941 // name. We must continue using the original name, so 11942 // rename the new package here. 11943 pkg.setPackageName(oldName); 11944 pkgName = pkg.packageName; 11945 replace = true; 11946 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11947 + oldName + " pkgName=" + pkgName); 11948 } else if (mPackages.containsKey(pkgName)) { 11949 // This package, under its official name, already exists 11950 // on the device; we should replace it. 11951 replace = true; 11952 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11953 } 11954 11955 // Prevent apps opting out from runtime permissions 11956 if (replace) { 11957 PackageParser.Package oldPackage = mPackages.get(pkgName); 11958 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11959 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11960 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11961 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11962 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11963 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11964 + " doesn't support runtime permissions but the old" 11965 + " target SDK " + oldTargetSdk + " does."); 11966 return; 11967 } 11968 } 11969 } 11970 11971 PackageSetting ps = mSettings.mPackages.get(pkgName); 11972 if (ps != null) { 11973 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11974 11975 // Quick sanity check that we're signed correctly if updating; 11976 // we'll check this again later when scanning, but we want to 11977 // bail early here before tripping over redefined permissions. 11978 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11979 if (!checkUpgradeKeySetLP(ps, pkg)) { 11980 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11981 + pkg.packageName + " upgrade keys do not match the " 11982 + "previously installed version"); 11983 return; 11984 } 11985 } else { 11986 try { 11987 verifySignaturesLP(ps, pkg); 11988 } catch (PackageManagerException e) { 11989 res.setError(e.error, e.getMessage()); 11990 return; 11991 } 11992 } 11993 11994 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11995 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11996 systemApp = (ps.pkg.applicationInfo.flags & 11997 ApplicationInfo.FLAG_SYSTEM) != 0; 11998 } 11999 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12000 } 12001 12002 // Check whether the newly-scanned package wants to define an already-defined perm 12003 int N = pkg.permissions.size(); 12004 for (int i = N-1; i >= 0; i--) { 12005 PackageParser.Permission perm = pkg.permissions.get(i); 12006 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12007 if (bp != null) { 12008 // If the defining package is signed with our cert, it's okay. This 12009 // also includes the "updating the same package" case, of course. 12010 // "updating same package" could also involve key-rotation. 12011 final boolean sigsOk; 12012 if (bp.sourcePackage.equals(pkg.packageName) 12013 && (bp.packageSetting instanceof PackageSetting) 12014 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12015 scanFlags))) { 12016 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12017 } else { 12018 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12019 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12020 } 12021 if (!sigsOk) { 12022 // If the owning package is the system itself, we log but allow 12023 // install to proceed; we fail the install on all other permission 12024 // redefinitions. 12025 if (!bp.sourcePackage.equals("android")) { 12026 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12027 + pkg.packageName + " attempting to redeclare permission " 12028 + perm.info.name + " already owned by " + bp.sourcePackage); 12029 res.origPermission = perm.info.name; 12030 res.origPackage = bp.sourcePackage; 12031 return; 12032 } else { 12033 Slog.w(TAG, "Package " + pkg.packageName 12034 + " attempting to redeclare system permission " 12035 + perm.info.name + "; ignoring new declaration"); 12036 pkg.permissions.remove(i); 12037 } 12038 } 12039 } 12040 } 12041 12042 } 12043 12044 if (systemApp && onExternal) { 12045 // Disable updates to system apps on sdcard 12046 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12047 "Cannot install updates to system apps on sdcard"); 12048 return; 12049 } 12050 12051 if (args.move != null) { 12052 // We did an in-place move, so dex is ready to roll 12053 scanFlags |= SCAN_NO_DEX; 12054 scanFlags |= SCAN_MOVE; 12055 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12056 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12057 scanFlags |= SCAN_NO_DEX; 12058 12059 try { 12060 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12061 true /* extract libs */); 12062 } catch (PackageManagerException pme) { 12063 Slog.e(TAG, "Error deriving application ABI", pme); 12064 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12065 return; 12066 } 12067 12068 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12069 int result = mPackageDexOptimizer 12070 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12071 false /* defer */, false /* inclDependencies */); 12072 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12073 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12074 return; 12075 } 12076 } 12077 12078 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12079 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12080 return; 12081 } 12082 12083 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12084 12085 if (replace) { 12086 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12087 installerPackageName, volumeUuid, res); 12088 } else { 12089 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12090 args.user, installerPackageName, volumeUuid, res); 12091 } 12092 synchronized (mPackages) { 12093 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12094 if (ps != null) { 12095 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12096 } 12097 } 12098 } 12099 12100 private void startIntentFilterVerifications(int userId, boolean replacing, 12101 PackageParser.Package pkg) { 12102 if (mIntentFilterVerifierComponent == null) { 12103 Slog.w(TAG, "No IntentFilter verification will not be done as " 12104 + "there is no IntentFilterVerifier available!"); 12105 return; 12106 } 12107 12108 final int verifierUid = getPackageUid( 12109 mIntentFilterVerifierComponent.getPackageName(), 12110 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12111 12112 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12113 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12114 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12115 mHandler.sendMessage(msg); 12116 } 12117 12118 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12119 PackageParser.Package pkg) { 12120 int size = pkg.activities.size(); 12121 if (size == 0) { 12122 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12123 "No activity, so no need to verify any IntentFilter!"); 12124 return; 12125 } 12126 12127 final boolean hasDomainURLs = hasDomainURLs(pkg); 12128 if (!hasDomainURLs) { 12129 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12130 "No domain URLs, so no need to verify any IntentFilter!"); 12131 return; 12132 } 12133 12134 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12135 + " if any IntentFilter from the " + size 12136 + " Activities needs verification ..."); 12137 12138 int count = 0; 12139 final String packageName = pkg.packageName; 12140 12141 synchronized (mPackages) { 12142 // If this is a new install and we see that we've already run verification for this 12143 // package, we have nothing to do: it means the state was restored from backup. 12144 if (!replacing) { 12145 IntentFilterVerificationInfo ivi = 12146 mSettings.getIntentFilterVerificationLPr(packageName); 12147 if (ivi != null) { 12148 if (DEBUG_DOMAIN_VERIFICATION) { 12149 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12150 + ivi.getStatusString()); 12151 } 12152 return; 12153 } 12154 } 12155 12156 // If any filters need to be verified, then all need to be. 12157 boolean needToVerify = false; 12158 for (PackageParser.Activity a : pkg.activities) { 12159 for (ActivityIntentInfo filter : a.intents) { 12160 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12161 if (DEBUG_DOMAIN_VERIFICATION) { 12162 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12163 } 12164 needToVerify = true; 12165 break; 12166 } 12167 } 12168 } 12169 12170 if (needToVerify) { 12171 final int verificationId = mIntentFilterVerificationToken++; 12172 for (PackageParser.Activity a : pkg.activities) { 12173 for (ActivityIntentInfo filter : a.intents) { 12174 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12175 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12176 "Verification needed for IntentFilter:" + filter.toString()); 12177 mIntentFilterVerifier.addOneIntentFilterVerification( 12178 verifierUid, userId, verificationId, filter, packageName); 12179 count++; 12180 } 12181 } 12182 } 12183 } 12184 } 12185 12186 if (count > 0) { 12187 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12188 + " IntentFilter verification" + (count > 1 ? "s" : "") 12189 + " for userId:" + userId); 12190 mIntentFilterVerifier.startVerifications(userId); 12191 } else { 12192 if (DEBUG_DOMAIN_VERIFICATION) { 12193 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12194 } 12195 } 12196 } 12197 12198 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12199 final ComponentName cn = filter.activity.getComponentName(); 12200 final String packageName = cn.getPackageName(); 12201 12202 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12203 packageName); 12204 if (ivi == null) { 12205 return true; 12206 } 12207 int status = ivi.getStatus(); 12208 switch (status) { 12209 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12210 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12211 return true; 12212 12213 default: 12214 // Nothing to do 12215 return false; 12216 } 12217 } 12218 12219 private static boolean isMultiArch(PackageSetting ps) { 12220 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12221 } 12222 12223 private static boolean isMultiArch(ApplicationInfo info) { 12224 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12225 } 12226 12227 private static boolean isExternal(PackageParser.Package pkg) { 12228 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12229 } 12230 12231 private static boolean isExternal(PackageSetting ps) { 12232 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12233 } 12234 12235 private static boolean isExternal(ApplicationInfo info) { 12236 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12237 } 12238 12239 private static boolean isSystemApp(PackageParser.Package pkg) { 12240 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12241 } 12242 12243 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12244 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12245 } 12246 12247 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12248 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12249 } 12250 12251 private static boolean isSystemApp(PackageSetting ps) { 12252 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12253 } 12254 12255 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12256 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12257 } 12258 12259 private int packageFlagsToInstallFlags(PackageSetting ps) { 12260 int installFlags = 0; 12261 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12262 // This existing package was an external ASEC install when we have 12263 // the external flag without a UUID 12264 installFlags |= PackageManager.INSTALL_EXTERNAL; 12265 } 12266 if (ps.isForwardLocked()) { 12267 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12268 } 12269 return installFlags; 12270 } 12271 12272 private void deleteTempPackageFiles() { 12273 final FilenameFilter filter = new FilenameFilter() { 12274 public boolean accept(File dir, String name) { 12275 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12276 } 12277 }; 12278 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12279 file.delete(); 12280 } 12281 } 12282 12283 @Override 12284 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12285 int flags) { 12286 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12287 flags); 12288 } 12289 12290 @Override 12291 public void deletePackage(final String packageName, 12292 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12293 mContext.enforceCallingOrSelfPermission( 12294 android.Manifest.permission.DELETE_PACKAGES, null); 12295 final int uid = Binder.getCallingUid(); 12296 if (UserHandle.getUserId(uid) != userId) { 12297 mContext.enforceCallingPermission( 12298 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12299 "deletePackage for user " + userId); 12300 } 12301 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12302 try { 12303 observer.onPackageDeleted(packageName, 12304 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12305 } catch (RemoteException re) { 12306 } 12307 return; 12308 } 12309 12310 boolean uninstallBlocked = false; 12311 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12312 int[] users = sUserManager.getUserIds(); 12313 for (int i = 0; i < users.length; ++i) { 12314 if (getBlockUninstallForUser(packageName, users[i])) { 12315 uninstallBlocked = true; 12316 break; 12317 } 12318 } 12319 } else { 12320 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12321 } 12322 if (uninstallBlocked) { 12323 try { 12324 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12325 null); 12326 } catch (RemoteException re) { 12327 } 12328 return; 12329 } 12330 12331 if (DEBUG_REMOVE) { 12332 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12333 } 12334 // Queue up an async operation since the package deletion may take a little while. 12335 mHandler.post(new Runnable() { 12336 public void run() { 12337 mHandler.removeCallbacks(this); 12338 final int returnCode = deletePackageX(packageName, userId, flags); 12339 if (observer != null) { 12340 try { 12341 observer.onPackageDeleted(packageName, returnCode, null); 12342 } catch (RemoteException e) { 12343 Log.i(TAG, "Observer no longer exists."); 12344 } //end catch 12345 } //end if 12346 } //end run 12347 }); 12348 } 12349 12350 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12351 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12352 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12353 try { 12354 if (dpm != null) { 12355 if (dpm.isDeviceOwner(packageName)) { 12356 return true; 12357 } 12358 int[] users; 12359 if (userId == UserHandle.USER_ALL) { 12360 users = sUserManager.getUserIds(); 12361 } else { 12362 users = new int[]{userId}; 12363 } 12364 for (int i = 0; i < users.length; ++i) { 12365 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12366 return true; 12367 } 12368 } 12369 } 12370 } catch (RemoteException e) { 12371 } 12372 return false; 12373 } 12374 12375 /** 12376 * This method is an internal method that could be get invoked either 12377 * to delete an installed package or to clean up a failed installation. 12378 * After deleting an installed package, a broadcast is sent to notify any 12379 * listeners that the package has been installed. For cleaning up a failed 12380 * installation, the broadcast is not necessary since the package's 12381 * installation wouldn't have sent the initial broadcast either 12382 * The key steps in deleting a package are 12383 * deleting the package information in internal structures like mPackages, 12384 * deleting the packages base directories through installd 12385 * updating mSettings to reflect current status 12386 * persisting settings for later use 12387 * sending a broadcast if necessary 12388 */ 12389 private int deletePackageX(String packageName, int userId, int flags) { 12390 final PackageRemovedInfo info = new PackageRemovedInfo(); 12391 final boolean res; 12392 12393 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12394 ? UserHandle.ALL : new UserHandle(userId); 12395 12396 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12397 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12398 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12399 } 12400 12401 boolean removedForAllUsers = false; 12402 boolean systemUpdate = false; 12403 12404 // for the uninstall-updates case and restricted profiles, remember the per- 12405 // userhandle installed state 12406 int[] allUsers; 12407 boolean[] perUserInstalled; 12408 synchronized (mPackages) { 12409 PackageSetting ps = mSettings.mPackages.get(packageName); 12410 allUsers = sUserManager.getUserIds(); 12411 perUserInstalled = new boolean[allUsers.length]; 12412 for (int i = 0; i < allUsers.length; i++) { 12413 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12414 } 12415 } 12416 12417 synchronized (mInstallLock) { 12418 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12419 res = deletePackageLI(packageName, removeForUser, 12420 true, allUsers, perUserInstalled, 12421 flags | REMOVE_CHATTY, info, true); 12422 systemUpdate = info.isRemovedPackageSystemUpdate; 12423 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12424 removedForAllUsers = true; 12425 } 12426 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12427 + " removedForAllUsers=" + removedForAllUsers); 12428 } 12429 12430 if (res) { 12431 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12432 12433 // If the removed package was a system update, the old system package 12434 // was re-enabled; we need to broadcast this information 12435 if (systemUpdate) { 12436 Bundle extras = new Bundle(1); 12437 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12438 ? info.removedAppId : info.uid); 12439 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12440 12441 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12442 extras, null, null, null); 12443 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12444 extras, null, null, null); 12445 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12446 null, packageName, null, null); 12447 } 12448 } 12449 // Force a gc here. 12450 Runtime.getRuntime().gc(); 12451 // Delete the resources here after sending the broadcast to let 12452 // other processes clean up before deleting resources. 12453 if (info.args != null) { 12454 synchronized (mInstallLock) { 12455 info.args.doPostDeleteLI(true); 12456 } 12457 } 12458 12459 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12460 } 12461 12462 class PackageRemovedInfo { 12463 String removedPackage; 12464 int uid = -1; 12465 int removedAppId = -1; 12466 int[] removedUsers = null; 12467 boolean isRemovedPackageSystemUpdate = false; 12468 // Clean up resources deleted packages. 12469 InstallArgs args = null; 12470 12471 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12472 Bundle extras = new Bundle(1); 12473 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12474 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12475 if (replacing) { 12476 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12477 } 12478 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12479 if (removedPackage != null) { 12480 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12481 extras, null, null, removedUsers); 12482 if (fullRemove && !replacing) { 12483 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12484 extras, null, null, removedUsers); 12485 } 12486 } 12487 if (removedAppId >= 0) { 12488 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12489 removedUsers); 12490 } 12491 } 12492 } 12493 12494 /* 12495 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12496 * flag is not set, the data directory is removed as well. 12497 * make sure this flag is set for partially installed apps. If not its meaningless to 12498 * delete a partially installed application. 12499 */ 12500 private void removePackageDataLI(PackageSetting ps, 12501 int[] allUserHandles, boolean[] perUserInstalled, 12502 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12503 String packageName = ps.name; 12504 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12505 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12506 // Retrieve object to delete permissions for shared user later on 12507 final PackageSetting deletedPs; 12508 // reader 12509 synchronized (mPackages) { 12510 deletedPs = mSettings.mPackages.get(packageName); 12511 if (outInfo != null) { 12512 outInfo.removedPackage = packageName; 12513 outInfo.removedUsers = deletedPs != null 12514 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12515 : null; 12516 } 12517 } 12518 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12519 removeDataDirsLI(ps.volumeUuid, packageName); 12520 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12521 } 12522 // writer 12523 synchronized (mPackages) { 12524 if (deletedPs != null) { 12525 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12526 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12527 clearDefaultBrowserIfNeeded(packageName); 12528 if (outInfo != null) { 12529 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12530 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12531 } 12532 updatePermissionsLPw(deletedPs.name, null, 0); 12533 if (deletedPs.sharedUser != null) { 12534 // Remove permissions associated with package. Since runtime 12535 // permissions are per user we have to kill the removed package 12536 // or packages running under the shared user of the removed 12537 // package if revoking the permissions requested only by the removed 12538 // package is successful and this causes a change in gids. 12539 for (int userId : UserManagerService.getInstance().getUserIds()) { 12540 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12541 userId); 12542 if (userIdToKill == UserHandle.USER_ALL 12543 || userIdToKill >= UserHandle.USER_OWNER) { 12544 // If gids changed for this user, kill all affected packages. 12545 mHandler.post(new Runnable() { 12546 @Override 12547 public void run() { 12548 // This has to happen with no lock held. 12549 killSettingPackagesForUser(deletedPs, userIdToKill, 12550 KILL_APP_REASON_GIDS_CHANGED); 12551 } 12552 }); 12553 break; 12554 } 12555 } 12556 } 12557 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12558 } 12559 // make sure to preserve per-user disabled state if this removal was just 12560 // a downgrade of a system app to the factory package 12561 if (allUserHandles != null && perUserInstalled != null) { 12562 if (DEBUG_REMOVE) { 12563 Slog.d(TAG, "Propagating install state across downgrade"); 12564 } 12565 for (int i = 0; i < allUserHandles.length; i++) { 12566 if (DEBUG_REMOVE) { 12567 Slog.d(TAG, " user " + allUserHandles[i] 12568 + " => " + perUserInstalled[i]); 12569 } 12570 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12571 } 12572 } 12573 } 12574 // can downgrade to reader 12575 if (writeSettings) { 12576 // Save settings now 12577 mSettings.writeLPr(); 12578 } 12579 } 12580 if (outInfo != null) { 12581 // A user ID was deleted here. Go through all users and remove it 12582 // from KeyStore. 12583 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12584 } 12585 } 12586 12587 static boolean locationIsPrivileged(File path) { 12588 try { 12589 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12590 .getCanonicalPath(); 12591 return path.getCanonicalPath().startsWith(privilegedAppDir); 12592 } catch (IOException e) { 12593 Slog.e(TAG, "Unable to access code path " + path); 12594 } 12595 return false; 12596 } 12597 12598 /* 12599 * Tries to delete system package. 12600 */ 12601 private boolean deleteSystemPackageLI(PackageSetting newPs, 12602 int[] allUserHandles, boolean[] perUserInstalled, 12603 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12604 final boolean applyUserRestrictions 12605 = (allUserHandles != null) && (perUserInstalled != null); 12606 PackageSetting disabledPs = null; 12607 // Confirm if the system package has been updated 12608 // An updated system app can be deleted. This will also have to restore 12609 // the system pkg from system partition 12610 // reader 12611 synchronized (mPackages) { 12612 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12613 } 12614 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12615 + " disabledPs=" + disabledPs); 12616 if (disabledPs == null) { 12617 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12618 return false; 12619 } else if (DEBUG_REMOVE) { 12620 Slog.d(TAG, "Deleting system pkg from data partition"); 12621 } 12622 if (DEBUG_REMOVE) { 12623 if (applyUserRestrictions) { 12624 Slog.d(TAG, "Remembering install states:"); 12625 for (int i = 0; i < allUserHandles.length; i++) { 12626 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12627 } 12628 } 12629 } 12630 // Delete the updated package 12631 outInfo.isRemovedPackageSystemUpdate = true; 12632 if (disabledPs.versionCode < newPs.versionCode) { 12633 // Delete data for downgrades 12634 flags &= ~PackageManager.DELETE_KEEP_DATA; 12635 } else { 12636 // Preserve data by setting flag 12637 flags |= PackageManager.DELETE_KEEP_DATA; 12638 } 12639 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12640 allUserHandles, perUserInstalled, outInfo, writeSettings); 12641 if (!ret) { 12642 return false; 12643 } 12644 // writer 12645 synchronized (mPackages) { 12646 // Reinstate the old system package 12647 mSettings.enableSystemPackageLPw(newPs.name); 12648 // Remove any native libraries from the upgraded package. 12649 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12650 } 12651 // Install the system package 12652 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12653 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12654 if (locationIsPrivileged(disabledPs.codePath)) { 12655 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12656 } 12657 12658 final PackageParser.Package newPkg; 12659 try { 12660 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12661 } catch (PackageManagerException e) { 12662 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12663 return false; 12664 } 12665 12666 // writer 12667 synchronized (mPackages) { 12668 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12669 updatePermissionsLPw(newPkg.packageName, newPkg, 12670 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12671 if (applyUserRestrictions) { 12672 if (DEBUG_REMOVE) { 12673 Slog.d(TAG, "Propagating install state across reinstall"); 12674 } 12675 for (int i = 0; i < allUserHandles.length; i++) { 12676 if (DEBUG_REMOVE) { 12677 Slog.d(TAG, " user " + allUserHandles[i] 12678 + " => " + perUserInstalled[i]); 12679 } 12680 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12681 } 12682 // Regardless of writeSettings we need to ensure that this restriction 12683 // state propagation is persisted 12684 mSettings.writeAllUsersPackageRestrictionsLPr(); 12685 } 12686 // can downgrade to reader here 12687 if (writeSettings) { 12688 mSettings.writeLPr(); 12689 } 12690 } 12691 return true; 12692 } 12693 12694 private boolean deleteInstalledPackageLI(PackageSetting ps, 12695 boolean deleteCodeAndResources, int flags, 12696 int[] allUserHandles, boolean[] perUserInstalled, 12697 PackageRemovedInfo outInfo, boolean writeSettings) { 12698 if (outInfo != null) { 12699 outInfo.uid = ps.appId; 12700 } 12701 12702 // Delete package data from internal structures and also remove data if flag is set 12703 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12704 12705 // Delete application code and resources 12706 if (deleteCodeAndResources && (outInfo != null)) { 12707 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12708 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12709 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12710 } 12711 return true; 12712 } 12713 12714 @Override 12715 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12716 int userId) { 12717 mContext.enforceCallingOrSelfPermission( 12718 android.Manifest.permission.DELETE_PACKAGES, null); 12719 synchronized (mPackages) { 12720 PackageSetting ps = mSettings.mPackages.get(packageName); 12721 if (ps == null) { 12722 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12723 return false; 12724 } 12725 if (!ps.getInstalled(userId)) { 12726 // Can't block uninstall for an app that is not installed or enabled. 12727 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12728 return false; 12729 } 12730 ps.setBlockUninstall(blockUninstall, userId); 12731 mSettings.writePackageRestrictionsLPr(userId); 12732 } 12733 return true; 12734 } 12735 12736 @Override 12737 public boolean getBlockUninstallForUser(String packageName, int userId) { 12738 synchronized (mPackages) { 12739 PackageSetting ps = mSettings.mPackages.get(packageName); 12740 if (ps == null) { 12741 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12742 return false; 12743 } 12744 return ps.getBlockUninstall(userId); 12745 } 12746 } 12747 12748 /* 12749 * This method handles package deletion in general 12750 */ 12751 private boolean deletePackageLI(String packageName, UserHandle user, 12752 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12753 int flags, PackageRemovedInfo outInfo, 12754 boolean writeSettings) { 12755 if (packageName == null) { 12756 Slog.w(TAG, "Attempt to delete null packageName."); 12757 return false; 12758 } 12759 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12760 PackageSetting ps; 12761 boolean dataOnly = false; 12762 int removeUser = -1; 12763 int appId = -1; 12764 synchronized (mPackages) { 12765 ps = mSettings.mPackages.get(packageName); 12766 if (ps == null) { 12767 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12768 return false; 12769 } 12770 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12771 && user.getIdentifier() != UserHandle.USER_ALL) { 12772 // The caller is asking that the package only be deleted for a single 12773 // user. To do this, we just mark its uninstalled state and delete 12774 // its data. If this is a system app, we only allow this to happen if 12775 // they have set the special DELETE_SYSTEM_APP which requests different 12776 // semantics than normal for uninstalling system apps. 12777 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12778 ps.setUserState(user.getIdentifier(), 12779 COMPONENT_ENABLED_STATE_DEFAULT, 12780 false, //installed 12781 true, //stopped 12782 true, //notLaunched 12783 false, //hidden 12784 null, null, null, 12785 false, // blockUninstall 12786 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12787 if (!isSystemApp(ps)) { 12788 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12789 // Other user still have this package installed, so all 12790 // we need to do is clear this user's data and save that 12791 // it is uninstalled. 12792 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12793 removeUser = user.getIdentifier(); 12794 appId = ps.appId; 12795 scheduleWritePackageRestrictionsLocked(removeUser); 12796 } else { 12797 // We need to set it back to 'installed' so the uninstall 12798 // broadcasts will be sent correctly. 12799 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12800 ps.setInstalled(true, user.getIdentifier()); 12801 } 12802 } else { 12803 // This is a system app, so we assume that the 12804 // other users still have this package installed, so all 12805 // we need to do is clear this user's data and save that 12806 // it is uninstalled. 12807 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12808 removeUser = user.getIdentifier(); 12809 appId = ps.appId; 12810 scheduleWritePackageRestrictionsLocked(removeUser); 12811 } 12812 } 12813 } 12814 12815 if (removeUser >= 0) { 12816 // From above, we determined that we are deleting this only 12817 // for a single user. Continue the work here. 12818 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12819 if (outInfo != null) { 12820 outInfo.removedPackage = packageName; 12821 outInfo.removedAppId = appId; 12822 outInfo.removedUsers = new int[] {removeUser}; 12823 } 12824 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12825 removeKeystoreDataIfNeeded(removeUser, appId); 12826 schedulePackageCleaning(packageName, removeUser, false); 12827 synchronized (mPackages) { 12828 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12829 scheduleWritePackageRestrictionsLocked(removeUser); 12830 } 12831 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12832 removeUser); 12833 } 12834 return true; 12835 } 12836 12837 if (dataOnly) { 12838 // Delete application data first 12839 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12840 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12841 return true; 12842 } 12843 12844 boolean ret = false; 12845 if (isSystemApp(ps)) { 12846 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12847 // When an updated system application is deleted we delete the existing resources as well and 12848 // fall back to existing code in system partition 12849 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12850 flags, outInfo, writeSettings); 12851 } else { 12852 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12853 // Kill application pre-emptively especially for apps on sd. 12854 killApplication(packageName, ps.appId, "uninstall pkg"); 12855 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12856 allUserHandles, perUserInstalled, 12857 outInfo, writeSettings); 12858 } 12859 12860 return ret; 12861 } 12862 12863 private final class ClearStorageConnection implements ServiceConnection { 12864 IMediaContainerService mContainerService; 12865 12866 @Override 12867 public void onServiceConnected(ComponentName name, IBinder service) { 12868 synchronized (this) { 12869 mContainerService = IMediaContainerService.Stub.asInterface(service); 12870 notifyAll(); 12871 } 12872 } 12873 12874 @Override 12875 public void onServiceDisconnected(ComponentName name) { 12876 } 12877 } 12878 12879 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12880 final boolean mounted; 12881 if (Environment.isExternalStorageEmulated()) { 12882 mounted = true; 12883 } else { 12884 final String status = Environment.getExternalStorageState(); 12885 12886 mounted = status.equals(Environment.MEDIA_MOUNTED) 12887 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12888 } 12889 12890 if (!mounted) { 12891 return; 12892 } 12893 12894 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12895 int[] users; 12896 if (userId == UserHandle.USER_ALL) { 12897 users = sUserManager.getUserIds(); 12898 } else { 12899 users = new int[] { userId }; 12900 } 12901 final ClearStorageConnection conn = new ClearStorageConnection(); 12902 if (mContext.bindServiceAsUser( 12903 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12904 try { 12905 for (int curUser : users) { 12906 long timeout = SystemClock.uptimeMillis() + 5000; 12907 synchronized (conn) { 12908 long now = SystemClock.uptimeMillis(); 12909 while (conn.mContainerService == null && now < timeout) { 12910 try { 12911 conn.wait(timeout - now); 12912 } catch (InterruptedException e) { 12913 } 12914 } 12915 } 12916 if (conn.mContainerService == null) { 12917 return; 12918 } 12919 12920 final UserEnvironment userEnv = new UserEnvironment(curUser); 12921 clearDirectory(conn.mContainerService, 12922 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12923 if (allData) { 12924 clearDirectory(conn.mContainerService, 12925 userEnv.buildExternalStorageAppDataDirs(packageName)); 12926 clearDirectory(conn.mContainerService, 12927 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12928 } 12929 } 12930 } finally { 12931 mContext.unbindService(conn); 12932 } 12933 } 12934 } 12935 12936 @Override 12937 public void clearApplicationUserData(final String packageName, 12938 final IPackageDataObserver observer, final int userId) { 12939 mContext.enforceCallingOrSelfPermission( 12940 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12941 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12942 // Queue up an async operation since the package deletion may take a little while. 12943 mHandler.post(new Runnable() { 12944 public void run() { 12945 mHandler.removeCallbacks(this); 12946 final boolean succeeded; 12947 synchronized (mInstallLock) { 12948 succeeded = clearApplicationUserDataLI(packageName, userId); 12949 } 12950 clearExternalStorageDataSync(packageName, userId, true); 12951 if (succeeded) { 12952 // invoke DeviceStorageMonitor's update method to clear any notifications 12953 DeviceStorageMonitorInternal 12954 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12955 if (dsm != null) { 12956 dsm.checkMemory(); 12957 } 12958 } 12959 if(observer != null) { 12960 try { 12961 observer.onRemoveCompleted(packageName, succeeded); 12962 } catch (RemoteException e) { 12963 Log.i(TAG, "Observer no longer exists."); 12964 } 12965 } //end if observer 12966 } //end run 12967 }); 12968 } 12969 12970 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12971 if (packageName == null) { 12972 Slog.w(TAG, "Attempt to delete null packageName."); 12973 return false; 12974 } 12975 12976 // Try finding details about the requested package 12977 PackageParser.Package pkg; 12978 synchronized (mPackages) { 12979 pkg = mPackages.get(packageName); 12980 if (pkg == null) { 12981 final PackageSetting ps = mSettings.mPackages.get(packageName); 12982 if (ps != null) { 12983 pkg = ps.pkg; 12984 } 12985 } 12986 12987 if (pkg == null) { 12988 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12989 return false; 12990 } 12991 12992 PackageSetting ps = (PackageSetting) pkg.mExtras; 12993 PermissionsState permissionsState = ps.getPermissionsState(); 12994 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12995 } 12996 12997 // Always delete data directories for package, even if we found no other 12998 // record of app. This helps users recover from UID mismatches without 12999 // resorting to a full data wipe. 13000 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13001 if (retCode < 0) { 13002 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13003 return false; 13004 } 13005 13006 final int appId = pkg.applicationInfo.uid; 13007 removeKeystoreDataIfNeeded(userId, appId); 13008 13009 // Create a native library symlink only if we have native libraries 13010 // and if the native libraries are 32 bit libraries. We do not provide 13011 // this symlink for 64 bit libraries. 13012 if (pkg.applicationInfo.primaryCpuAbi != null && 13013 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13014 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13015 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13016 nativeLibPath, userId) < 0) { 13017 Slog.w(TAG, "Failed linking native library dir"); 13018 return false; 13019 } 13020 } 13021 13022 return true; 13023 } 13024 13025 13026 /** 13027 * Revokes granted runtime permissions and clears resettable flags 13028 * which are flags that can be set by a user interaction. 13029 * 13030 * @param permissionsState The permission state to reset. 13031 * @param userId The device user for which to do a reset. 13032 */ 13033 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 13034 PermissionsState permissionsState, int userId) { 13035 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 13036 | PackageManager.FLAG_PERMISSION_USER_FIXED 13037 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13038 13039 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 13040 } 13041 13042 /** 13043 * Revokes granted runtime permissions and clears all flags. 13044 * 13045 * @param permissionsState The permission state to reset. 13046 * @param userId The device user for which to do a reset. 13047 */ 13048 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 13049 PermissionsState permissionsState, int userId) { 13050 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 13051 PackageManager.MASK_PERMISSION_FLAGS); 13052 } 13053 13054 /** 13055 * Revokes granted runtime permissions and clears certain flags. 13056 * 13057 * @param permissionsState The permission state to reset. 13058 * @param userId The device user for which to do a reset. 13059 * @param flags The flags that is going to be reset. 13060 */ 13061 private void revokeRuntimePermissionsAndClearFlagsLocked( 13062 PermissionsState permissionsState, final int userId, int flags) { 13063 boolean needsWrite = false; 13064 13065 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 13066 BasePermission bp = mSettings.mPermissions.get(state.getName()); 13067 if (bp != null) { 13068 permissionsState.revokeRuntimePermission(bp, userId); 13069 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 13070 needsWrite = true; 13071 } 13072 } 13073 13074 // Ensure default permissions are never cleared. 13075 mHandler.post(new Runnable() { 13076 @Override 13077 public void run() { 13078 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13079 } 13080 }); 13081 13082 if (needsWrite) { 13083 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13084 } 13085 } 13086 13087 /** 13088 * Remove entries from the keystore daemon. Will only remove it if the 13089 * {@code appId} is valid. 13090 */ 13091 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13092 if (appId < 0) { 13093 return; 13094 } 13095 13096 final KeyStore keyStore = KeyStore.getInstance(); 13097 if (keyStore != null) { 13098 if (userId == UserHandle.USER_ALL) { 13099 for (final int individual : sUserManager.getUserIds()) { 13100 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13101 } 13102 } else { 13103 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13104 } 13105 } else { 13106 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13107 } 13108 } 13109 13110 @Override 13111 public void deleteApplicationCacheFiles(final String packageName, 13112 final IPackageDataObserver observer) { 13113 mContext.enforceCallingOrSelfPermission( 13114 android.Manifest.permission.DELETE_CACHE_FILES, null); 13115 // Queue up an async operation since the package deletion may take a little while. 13116 final int userId = UserHandle.getCallingUserId(); 13117 mHandler.post(new Runnable() { 13118 public void run() { 13119 mHandler.removeCallbacks(this); 13120 final boolean succeded; 13121 synchronized (mInstallLock) { 13122 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13123 } 13124 clearExternalStorageDataSync(packageName, userId, false); 13125 if (observer != null) { 13126 try { 13127 observer.onRemoveCompleted(packageName, succeded); 13128 } catch (RemoteException e) { 13129 Log.i(TAG, "Observer no longer exists."); 13130 } 13131 } //end if observer 13132 } //end run 13133 }); 13134 } 13135 13136 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13137 if (packageName == null) { 13138 Slog.w(TAG, "Attempt to delete null packageName."); 13139 return false; 13140 } 13141 PackageParser.Package p; 13142 synchronized (mPackages) { 13143 p = mPackages.get(packageName); 13144 } 13145 if (p == null) { 13146 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13147 return false; 13148 } 13149 final ApplicationInfo applicationInfo = p.applicationInfo; 13150 if (applicationInfo == null) { 13151 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13152 return false; 13153 } 13154 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13155 if (retCode < 0) { 13156 Slog.w(TAG, "Couldn't remove cache files for package: " 13157 + packageName + " u" + userId); 13158 return false; 13159 } 13160 return true; 13161 } 13162 13163 @Override 13164 public void getPackageSizeInfo(final String packageName, int userHandle, 13165 final IPackageStatsObserver observer) { 13166 mContext.enforceCallingOrSelfPermission( 13167 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13168 if (packageName == null) { 13169 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13170 } 13171 13172 PackageStats stats = new PackageStats(packageName, userHandle); 13173 13174 /* 13175 * Queue up an async operation since the package measurement may take a 13176 * little while. 13177 */ 13178 Message msg = mHandler.obtainMessage(INIT_COPY); 13179 msg.obj = new MeasureParams(stats, observer); 13180 mHandler.sendMessage(msg); 13181 } 13182 13183 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13184 PackageStats pStats) { 13185 if (packageName == null) { 13186 Slog.w(TAG, "Attempt to get size of null packageName."); 13187 return false; 13188 } 13189 PackageParser.Package p; 13190 boolean dataOnly = false; 13191 String libDirRoot = null; 13192 String asecPath = null; 13193 PackageSetting ps = null; 13194 synchronized (mPackages) { 13195 p = mPackages.get(packageName); 13196 ps = mSettings.mPackages.get(packageName); 13197 if(p == null) { 13198 dataOnly = true; 13199 if((ps == null) || (ps.pkg == null)) { 13200 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13201 return false; 13202 } 13203 p = ps.pkg; 13204 } 13205 if (ps != null) { 13206 libDirRoot = ps.legacyNativeLibraryPathString; 13207 } 13208 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13209 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13210 if (secureContainerId != null) { 13211 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13212 } 13213 } 13214 } 13215 String publicSrcDir = null; 13216 if(!dataOnly) { 13217 final ApplicationInfo applicationInfo = p.applicationInfo; 13218 if (applicationInfo == null) { 13219 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13220 return false; 13221 } 13222 if (p.isForwardLocked()) { 13223 publicSrcDir = applicationInfo.getBaseResourcePath(); 13224 } 13225 } 13226 // TODO: extend to measure size of split APKs 13227 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13228 // not just the first level. 13229 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13230 // just the primary. 13231 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13232 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13233 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13234 if (res < 0) { 13235 return false; 13236 } 13237 13238 // Fix-up for forward-locked applications in ASEC containers. 13239 if (!isExternal(p)) { 13240 pStats.codeSize += pStats.externalCodeSize; 13241 pStats.externalCodeSize = 0L; 13242 } 13243 13244 return true; 13245 } 13246 13247 13248 @Override 13249 public void addPackageToPreferred(String packageName) { 13250 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13251 } 13252 13253 @Override 13254 public void removePackageFromPreferred(String packageName) { 13255 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13256 } 13257 13258 @Override 13259 public List<PackageInfo> getPreferredPackages(int flags) { 13260 return new ArrayList<PackageInfo>(); 13261 } 13262 13263 private int getUidTargetSdkVersionLockedLPr(int uid) { 13264 Object obj = mSettings.getUserIdLPr(uid); 13265 if (obj instanceof SharedUserSetting) { 13266 final SharedUserSetting sus = (SharedUserSetting) obj; 13267 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13268 final Iterator<PackageSetting> it = sus.packages.iterator(); 13269 while (it.hasNext()) { 13270 final PackageSetting ps = it.next(); 13271 if (ps.pkg != null) { 13272 int v = ps.pkg.applicationInfo.targetSdkVersion; 13273 if (v < vers) vers = v; 13274 } 13275 } 13276 return vers; 13277 } else if (obj instanceof PackageSetting) { 13278 final PackageSetting ps = (PackageSetting) obj; 13279 if (ps.pkg != null) { 13280 return ps.pkg.applicationInfo.targetSdkVersion; 13281 } 13282 } 13283 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13284 } 13285 13286 @Override 13287 public void addPreferredActivity(IntentFilter filter, int match, 13288 ComponentName[] set, ComponentName activity, int userId) { 13289 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13290 "Adding preferred"); 13291 } 13292 13293 private void addPreferredActivityInternal(IntentFilter filter, int match, 13294 ComponentName[] set, ComponentName activity, boolean always, int userId, 13295 String opname) { 13296 // writer 13297 int callingUid = Binder.getCallingUid(); 13298 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13299 if (filter.countActions() == 0) { 13300 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13301 return; 13302 } 13303 synchronized (mPackages) { 13304 if (mContext.checkCallingOrSelfPermission( 13305 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13306 != PackageManager.PERMISSION_GRANTED) { 13307 if (getUidTargetSdkVersionLockedLPr(callingUid) 13308 < Build.VERSION_CODES.FROYO) { 13309 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13310 + callingUid); 13311 return; 13312 } 13313 mContext.enforceCallingOrSelfPermission( 13314 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13315 } 13316 13317 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13318 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13319 + userId + ":"); 13320 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13321 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13322 scheduleWritePackageRestrictionsLocked(userId); 13323 } 13324 } 13325 13326 @Override 13327 public void replacePreferredActivity(IntentFilter filter, int match, 13328 ComponentName[] set, ComponentName activity, int userId) { 13329 if (filter.countActions() != 1) { 13330 throw new IllegalArgumentException( 13331 "replacePreferredActivity expects filter to have only 1 action."); 13332 } 13333 if (filter.countDataAuthorities() != 0 13334 || filter.countDataPaths() != 0 13335 || filter.countDataSchemes() > 1 13336 || filter.countDataTypes() != 0) { 13337 throw new IllegalArgumentException( 13338 "replacePreferredActivity expects filter to have no data authorities, " + 13339 "paths, or types; and at most one scheme."); 13340 } 13341 13342 final int callingUid = Binder.getCallingUid(); 13343 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13344 synchronized (mPackages) { 13345 if (mContext.checkCallingOrSelfPermission( 13346 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13347 != PackageManager.PERMISSION_GRANTED) { 13348 if (getUidTargetSdkVersionLockedLPr(callingUid) 13349 < Build.VERSION_CODES.FROYO) { 13350 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13351 + Binder.getCallingUid()); 13352 return; 13353 } 13354 mContext.enforceCallingOrSelfPermission( 13355 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13356 } 13357 13358 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13359 if (pir != null) { 13360 // Get all of the existing entries that exactly match this filter. 13361 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13362 if (existing != null && existing.size() == 1) { 13363 PreferredActivity cur = existing.get(0); 13364 if (DEBUG_PREFERRED) { 13365 Slog.i(TAG, "Checking replace of preferred:"); 13366 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13367 if (!cur.mPref.mAlways) { 13368 Slog.i(TAG, " -- CUR; not mAlways!"); 13369 } else { 13370 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13371 Slog.i(TAG, " -- CUR: mSet=" 13372 + Arrays.toString(cur.mPref.mSetComponents)); 13373 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13374 Slog.i(TAG, " -- NEW: mMatch=" 13375 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13376 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13377 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13378 } 13379 } 13380 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13381 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13382 && cur.mPref.sameSet(set)) { 13383 // Setting the preferred activity to what it happens to be already 13384 if (DEBUG_PREFERRED) { 13385 Slog.i(TAG, "Replacing with same preferred activity " 13386 + cur.mPref.mShortComponent + " for user " 13387 + userId + ":"); 13388 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13389 } 13390 return; 13391 } 13392 } 13393 13394 if (existing != null) { 13395 if (DEBUG_PREFERRED) { 13396 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13397 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13398 } 13399 for (int i = 0; i < existing.size(); i++) { 13400 PreferredActivity pa = existing.get(i); 13401 if (DEBUG_PREFERRED) { 13402 Slog.i(TAG, "Removing existing preferred activity " 13403 + pa.mPref.mComponent + ":"); 13404 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13405 } 13406 pir.removeFilter(pa); 13407 } 13408 } 13409 } 13410 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13411 "Replacing preferred"); 13412 } 13413 } 13414 13415 @Override 13416 public void clearPackagePreferredActivities(String packageName) { 13417 final int uid = Binder.getCallingUid(); 13418 // writer 13419 synchronized (mPackages) { 13420 PackageParser.Package pkg = mPackages.get(packageName); 13421 if (pkg == null || pkg.applicationInfo.uid != uid) { 13422 if (mContext.checkCallingOrSelfPermission( 13423 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13424 != PackageManager.PERMISSION_GRANTED) { 13425 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13426 < Build.VERSION_CODES.FROYO) { 13427 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13428 + Binder.getCallingUid()); 13429 return; 13430 } 13431 mContext.enforceCallingOrSelfPermission( 13432 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13433 } 13434 } 13435 13436 int user = UserHandle.getCallingUserId(); 13437 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13438 scheduleWritePackageRestrictionsLocked(user); 13439 } 13440 } 13441 } 13442 13443 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13444 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13445 ArrayList<PreferredActivity> removed = null; 13446 boolean changed = false; 13447 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13448 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13449 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13450 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13451 continue; 13452 } 13453 Iterator<PreferredActivity> it = pir.filterIterator(); 13454 while (it.hasNext()) { 13455 PreferredActivity pa = it.next(); 13456 // Mark entry for removal only if it matches the package name 13457 // and the entry is of type "always". 13458 if (packageName == null || 13459 (pa.mPref.mComponent.getPackageName().equals(packageName) 13460 && pa.mPref.mAlways)) { 13461 if (removed == null) { 13462 removed = new ArrayList<PreferredActivity>(); 13463 } 13464 removed.add(pa); 13465 } 13466 } 13467 if (removed != null) { 13468 for (int j=0; j<removed.size(); j++) { 13469 PreferredActivity pa = removed.get(j); 13470 pir.removeFilter(pa); 13471 } 13472 changed = true; 13473 } 13474 } 13475 return changed; 13476 } 13477 13478 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13479 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13480 if (userId == UserHandle.USER_ALL) { 13481 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13482 sUserManager.getUserIds())) { 13483 for (int oneUserId : sUserManager.getUserIds()) { 13484 scheduleWritePackageRestrictionsLocked(oneUserId); 13485 } 13486 } 13487 } else { 13488 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13489 scheduleWritePackageRestrictionsLocked(userId); 13490 } 13491 } 13492 } 13493 13494 13495 void clearDefaultBrowserIfNeeded(String packageName) { 13496 for (int oneUserId : sUserManager.getUserIds()) { 13497 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13498 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13499 if (packageName.equals(defaultBrowserPackageName)) { 13500 setDefaultBrowserPackageName(null, oneUserId); 13501 } 13502 } 13503 } 13504 13505 @Override 13506 public void resetPreferredActivities(int userId) { 13507 mContext.enforceCallingOrSelfPermission( 13508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13509 // writer 13510 synchronized (mPackages) { 13511 clearPackagePreferredActivitiesLPw(null, userId); 13512 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13513 applyFactoryDefaultBrowserLPw(userId); 13514 13515 scheduleWritePackageRestrictionsLocked(userId); 13516 } 13517 } 13518 13519 @Override 13520 public int getPreferredActivities(List<IntentFilter> outFilters, 13521 List<ComponentName> outActivities, String packageName) { 13522 13523 int num = 0; 13524 final int userId = UserHandle.getCallingUserId(); 13525 // reader 13526 synchronized (mPackages) { 13527 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13528 if (pir != null) { 13529 final Iterator<PreferredActivity> it = pir.filterIterator(); 13530 while (it.hasNext()) { 13531 final PreferredActivity pa = it.next(); 13532 if (packageName == null 13533 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13534 && pa.mPref.mAlways)) { 13535 if (outFilters != null) { 13536 outFilters.add(new IntentFilter(pa)); 13537 } 13538 if (outActivities != null) { 13539 outActivities.add(pa.mPref.mComponent); 13540 } 13541 } 13542 } 13543 } 13544 } 13545 13546 return num; 13547 } 13548 13549 @Override 13550 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13551 int userId) { 13552 int callingUid = Binder.getCallingUid(); 13553 if (callingUid != Process.SYSTEM_UID) { 13554 throw new SecurityException( 13555 "addPersistentPreferredActivity can only be run by the system"); 13556 } 13557 if (filter.countActions() == 0) { 13558 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13559 return; 13560 } 13561 synchronized (mPackages) { 13562 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13563 " :"); 13564 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13565 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13566 new PersistentPreferredActivity(filter, activity)); 13567 scheduleWritePackageRestrictionsLocked(userId); 13568 } 13569 } 13570 13571 @Override 13572 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13573 int callingUid = Binder.getCallingUid(); 13574 if (callingUid != Process.SYSTEM_UID) { 13575 throw new SecurityException( 13576 "clearPackagePersistentPreferredActivities can only be run by the system"); 13577 } 13578 ArrayList<PersistentPreferredActivity> removed = null; 13579 boolean changed = false; 13580 synchronized (mPackages) { 13581 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13582 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13583 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13584 .valueAt(i); 13585 if (userId != thisUserId) { 13586 continue; 13587 } 13588 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13589 while (it.hasNext()) { 13590 PersistentPreferredActivity ppa = it.next(); 13591 // Mark entry for removal only if it matches the package name. 13592 if (ppa.mComponent.getPackageName().equals(packageName)) { 13593 if (removed == null) { 13594 removed = new ArrayList<PersistentPreferredActivity>(); 13595 } 13596 removed.add(ppa); 13597 } 13598 } 13599 if (removed != null) { 13600 for (int j=0; j<removed.size(); j++) { 13601 PersistentPreferredActivity ppa = removed.get(j); 13602 ppir.removeFilter(ppa); 13603 } 13604 changed = true; 13605 } 13606 } 13607 13608 if (changed) { 13609 scheduleWritePackageRestrictionsLocked(userId); 13610 } 13611 } 13612 } 13613 13614 /** 13615 * Common machinery for picking apart a restored XML blob and passing 13616 * it to a caller-supplied functor to be applied to the running system. 13617 */ 13618 private void restoreFromXml(XmlPullParser parser, int userId, 13619 String expectedStartTag, BlobXmlRestorer functor) 13620 throws IOException, XmlPullParserException { 13621 int type; 13622 while ((type = parser.next()) != XmlPullParser.START_TAG 13623 && type != XmlPullParser.END_DOCUMENT) { 13624 } 13625 if (type != XmlPullParser.START_TAG) { 13626 // oops didn't find a start tag?! 13627 if (DEBUG_BACKUP) { 13628 Slog.e(TAG, "Didn't find start tag during restore"); 13629 } 13630 return; 13631 } 13632 13633 // this is supposed to be TAG_PREFERRED_BACKUP 13634 if (!expectedStartTag.equals(parser.getName())) { 13635 if (DEBUG_BACKUP) { 13636 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13637 } 13638 return; 13639 } 13640 13641 // skip interfering stuff, then we're aligned with the backing implementation 13642 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13643 functor.apply(parser, userId); 13644 } 13645 13646 private interface BlobXmlRestorer { 13647 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13648 } 13649 13650 /** 13651 * Non-Binder method, support for the backup/restore mechanism: write the 13652 * full set of preferred activities in its canonical XML format. Returns the 13653 * XML output as a byte array, or null if there is none. 13654 */ 13655 @Override 13656 public byte[] getPreferredActivityBackup(int userId) { 13657 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13658 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13659 } 13660 13661 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13662 try { 13663 final XmlSerializer serializer = new FastXmlSerializer(); 13664 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13665 serializer.startDocument(null, true); 13666 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13667 13668 synchronized (mPackages) { 13669 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13670 } 13671 13672 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13673 serializer.endDocument(); 13674 serializer.flush(); 13675 } catch (Exception e) { 13676 if (DEBUG_BACKUP) { 13677 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13678 } 13679 return null; 13680 } 13681 13682 return dataStream.toByteArray(); 13683 } 13684 13685 @Override 13686 public void restorePreferredActivities(byte[] backup, int userId) { 13687 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13688 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13689 } 13690 13691 try { 13692 final XmlPullParser parser = Xml.newPullParser(); 13693 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13694 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13695 new BlobXmlRestorer() { 13696 @Override 13697 public void apply(XmlPullParser parser, int userId) 13698 throws XmlPullParserException, IOException { 13699 synchronized (mPackages) { 13700 mSettings.readPreferredActivitiesLPw(parser, userId); 13701 } 13702 } 13703 } ); 13704 } catch (Exception e) { 13705 if (DEBUG_BACKUP) { 13706 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13707 } 13708 } 13709 } 13710 13711 /** 13712 * Non-Binder method, support for the backup/restore mechanism: write the 13713 * default browser (etc) settings in its canonical XML format. Returns the default 13714 * browser XML representation as a byte array, or null if there is none. 13715 */ 13716 @Override 13717 public byte[] getDefaultAppsBackup(int userId) { 13718 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13719 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13720 } 13721 13722 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13723 try { 13724 final XmlSerializer serializer = new FastXmlSerializer(); 13725 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13726 serializer.startDocument(null, true); 13727 serializer.startTag(null, TAG_DEFAULT_APPS); 13728 13729 synchronized (mPackages) { 13730 mSettings.writeDefaultAppsLPr(serializer, userId); 13731 } 13732 13733 serializer.endTag(null, TAG_DEFAULT_APPS); 13734 serializer.endDocument(); 13735 serializer.flush(); 13736 } catch (Exception e) { 13737 if (DEBUG_BACKUP) { 13738 Slog.e(TAG, "Unable to write default apps for backup", e); 13739 } 13740 return null; 13741 } 13742 13743 return dataStream.toByteArray(); 13744 } 13745 13746 @Override 13747 public void restoreDefaultApps(byte[] backup, int userId) { 13748 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13749 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13750 } 13751 13752 try { 13753 final XmlPullParser parser = Xml.newPullParser(); 13754 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13755 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13756 new BlobXmlRestorer() { 13757 @Override 13758 public void apply(XmlPullParser parser, int userId) 13759 throws XmlPullParserException, IOException { 13760 synchronized (mPackages) { 13761 mSettings.readDefaultAppsLPw(parser, userId); 13762 } 13763 } 13764 } ); 13765 } catch (Exception e) { 13766 if (DEBUG_BACKUP) { 13767 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13768 } 13769 } 13770 } 13771 13772 @Override 13773 public byte[] getIntentFilterVerificationBackup(int userId) { 13774 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13775 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13776 } 13777 13778 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13779 try { 13780 final XmlSerializer serializer = new FastXmlSerializer(); 13781 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13782 serializer.startDocument(null, true); 13783 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13784 13785 synchronized (mPackages) { 13786 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13787 } 13788 13789 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13790 serializer.endDocument(); 13791 serializer.flush(); 13792 } catch (Exception e) { 13793 if (DEBUG_BACKUP) { 13794 Slog.e(TAG, "Unable to write default apps for backup", e); 13795 } 13796 return null; 13797 } 13798 13799 return dataStream.toByteArray(); 13800 } 13801 13802 @Override 13803 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13804 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13805 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13806 } 13807 13808 try { 13809 final XmlPullParser parser = Xml.newPullParser(); 13810 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13811 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13812 new BlobXmlRestorer() { 13813 @Override 13814 public void apply(XmlPullParser parser, int userId) 13815 throws XmlPullParserException, IOException { 13816 synchronized (mPackages) { 13817 mSettings.readAllDomainVerificationsLPr(parser, userId); 13818 mSettings.writeLPr(); 13819 } 13820 } 13821 } ); 13822 } catch (Exception e) { 13823 if (DEBUG_BACKUP) { 13824 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13825 } 13826 } 13827 } 13828 13829 @Override 13830 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13831 int sourceUserId, int targetUserId, int flags) { 13832 mContext.enforceCallingOrSelfPermission( 13833 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13834 int callingUid = Binder.getCallingUid(); 13835 enforceOwnerRights(ownerPackage, callingUid); 13836 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13837 if (intentFilter.countActions() == 0) { 13838 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13839 return; 13840 } 13841 synchronized (mPackages) { 13842 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13843 ownerPackage, targetUserId, flags); 13844 CrossProfileIntentResolver resolver = 13845 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13846 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13847 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13848 if (existing != null) { 13849 int size = existing.size(); 13850 for (int i = 0; i < size; i++) { 13851 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13852 return; 13853 } 13854 } 13855 } 13856 resolver.addFilter(newFilter); 13857 scheduleWritePackageRestrictionsLocked(sourceUserId); 13858 } 13859 } 13860 13861 @Override 13862 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13863 mContext.enforceCallingOrSelfPermission( 13864 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13865 int callingUid = Binder.getCallingUid(); 13866 enforceOwnerRights(ownerPackage, callingUid); 13867 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13868 synchronized (mPackages) { 13869 CrossProfileIntentResolver resolver = 13870 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13871 ArraySet<CrossProfileIntentFilter> set = 13872 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13873 for (CrossProfileIntentFilter filter : set) { 13874 if (filter.getOwnerPackage().equals(ownerPackage)) { 13875 resolver.removeFilter(filter); 13876 } 13877 } 13878 scheduleWritePackageRestrictionsLocked(sourceUserId); 13879 } 13880 } 13881 13882 // Enforcing that callingUid is owning pkg on userId 13883 private void enforceOwnerRights(String pkg, int callingUid) { 13884 // The system owns everything. 13885 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13886 return; 13887 } 13888 int callingUserId = UserHandle.getUserId(callingUid); 13889 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13890 if (pi == null) { 13891 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13892 + callingUserId); 13893 } 13894 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13895 throw new SecurityException("Calling uid " + callingUid 13896 + " does not own package " + pkg); 13897 } 13898 } 13899 13900 @Override 13901 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13902 Intent intent = new Intent(Intent.ACTION_MAIN); 13903 intent.addCategory(Intent.CATEGORY_HOME); 13904 13905 final int callingUserId = UserHandle.getCallingUserId(); 13906 List<ResolveInfo> list = queryIntentActivities(intent, null, 13907 PackageManager.GET_META_DATA, callingUserId); 13908 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13909 true, false, false, callingUserId); 13910 13911 allHomeCandidates.clear(); 13912 if (list != null) { 13913 for (ResolveInfo ri : list) { 13914 allHomeCandidates.add(ri); 13915 } 13916 } 13917 return (preferred == null || preferred.activityInfo == null) 13918 ? null 13919 : new ComponentName(preferred.activityInfo.packageName, 13920 preferred.activityInfo.name); 13921 } 13922 13923 @Override 13924 public void setApplicationEnabledSetting(String appPackageName, 13925 int newState, int flags, int userId, String callingPackage) { 13926 if (!sUserManager.exists(userId)) return; 13927 if (callingPackage == null) { 13928 callingPackage = Integer.toString(Binder.getCallingUid()); 13929 } 13930 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13931 } 13932 13933 @Override 13934 public void setComponentEnabledSetting(ComponentName componentName, 13935 int newState, int flags, int userId) { 13936 if (!sUserManager.exists(userId)) return; 13937 setEnabledSetting(componentName.getPackageName(), 13938 componentName.getClassName(), newState, flags, userId, null); 13939 } 13940 13941 private void setEnabledSetting(final String packageName, String className, int newState, 13942 final int flags, int userId, String callingPackage) { 13943 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13944 || newState == COMPONENT_ENABLED_STATE_ENABLED 13945 || newState == COMPONENT_ENABLED_STATE_DISABLED 13946 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13947 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13948 throw new IllegalArgumentException("Invalid new component state: " 13949 + newState); 13950 } 13951 PackageSetting pkgSetting; 13952 final int uid = Binder.getCallingUid(); 13953 final int permission = mContext.checkCallingOrSelfPermission( 13954 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13955 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13956 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13957 boolean sendNow = false; 13958 boolean isApp = (className == null); 13959 String componentName = isApp ? packageName : className; 13960 int packageUid = -1; 13961 ArrayList<String> components; 13962 13963 // writer 13964 synchronized (mPackages) { 13965 pkgSetting = mSettings.mPackages.get(packageName); 13966 if (pkgSetting == null) { 13967 if (className == null) { 13968 throw new IllegalArgumentException( 13969 "Unknown package: " + packageName); 13970 } 13971 throw new IllegalArgumentException( 13972 "Unknown component: " + packageName 13973 + "/" + className); 13974 } 13975 // Allow root and verify that userId is not being specified by a different user 13976 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13977 throw new SecurityException( 13978 "Permission Denial: attempt to change component state from pid=" 13979 + Binder.getCallingPid() 13980 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13981 } 13982 if (className == null) { 13983 // We're dealing with an application/package level state change 13984 if (pkgSetting.getEnabled(userId) == newState) { 13985 // Nothing to do 13986 return; 13987 } 13988 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13989 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13990 // Don't care about who enables an app. 13991 callingPackage = null; 13992 } 13993 pkgSetting.setEnabled(newState, userId, callingPackage); 13994 // pkgSetting.pkg.mSetEnabled = newState; 13995 } else { 13996 // We're dealing with a component level state change 13997 // First, verify that this is a valid class name. 13998 PackageParser.Package pkg = pkgSetting.pkg; 13999 if (pkg == null || !pkg.hasComponentClassName(className)) { 14000 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14001 throw new IllegalArgumentException("Component class " + className 14002 + " does not exist in " + packageName); 14003 } else { 14004 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14005 + className + " does not exist in " + packageName); 14006 } 14007 } 14008 switch (newState) { 14009 case COMPONENT_ENABLED_STATE_ENABLED: 14010 if (!pkgSetting.enableComponentLPw(className, userId)) { 14011 return; 14012 } 14013 break; 14014 case COMPONENT_ENABLED_STATE_DISABLED: 14015 if (!pkgSetting.disableComponentLPw(className, userId)) { 14016 return; 14017 } 14018 break; 14019 case COMPONENT_ENABLED_STATE_DEFAULT: 14020 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14021 return; 14022 } 14023 break; 14024 default: 14025 Slog.e(TAG, "Invalid new component state: " + newState); 14026 return; 14027 } 14028 } 14029 scheduleWritePackageRestrictionsLocked(userId); 14030 components = mPendingBroadcasts.get(userId, packageName); 14031 final boolean newPackage = components == null; 14032 if (newPackage) { 14033 components = new ArrayList<String>(); 14034 } 14035 if (!components.contains(componentName)) { 14036 components.add(componentName); 14037 } 14038 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14039 sendNow = true; 14040 // Purge entry from pending broadcast list if another one exists already 14041 // since we are sending one right away. 14042 mPendingBroadcasts.remove(userId, packageName); 14043 } else { 14044 if (newPackage) { 14045 mPendingBroadcasts.put(userId, packageName, components); 14046 } 14047 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14048 // Schedule a message 14049 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14050 } 14051 } 14052 } 14053 14054 long callingId = Binder.clearCallingIdentity(); 14055 try { 14056 if (sendNow) { 14057 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14058 sendPackageChangedBroadcast(packageName, 14059 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14060 } 14061 } finally { 14062 Binder.restoreCallingIdentity(callingId); 14063 } 14064 } 14065 14066 private void sendPackageChangedBroadcast(String packageName, 14067 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14068 if (DEBUG_INSTALL) 14069 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14070 + componentNames); 14071 Bundle extras = new Bundle(4); 14072 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14073 String nameList[] = new String[componentNames.size()]; 14074 componentNames.toArray(nameList); 14075 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14076 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14077 extras.putInt(Intent.EXTRA_UID, packageUid); 14078 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14079 new int[] {UserHandle.getUserId(packageUid)}); 14080 } 14081 14082 @Override 14083 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14084 if (!sUserManager.exists(userId)) return; 14085 final int uid = Binder.getCallingUid(); 14086 final int permission = mContext.checkCallingOrSelfPermission( 14087 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14088 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14089 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14090 // writer 14091 synchronized (mPackages) { 14092 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14093 allowedByPermission, uid, userId)) { 14094 scheduleWritePackageRestrictionsLocked(userId); 14095 } 14096 } 14097 } 14098 14099 @Override 14100 public String getInstallerPackageName(String packageName) { 14101 // reader 14102 synchronized (mPackages) { 14103 return mSettings.getInstallerPackageNameLPr(packageName); 14104 } 14105 } 14106 14107 @Override 14108 public int getApplicationEnabledSetting(String packageName, int userId) { 14109 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14110 int uid = Binder.getCallingUid(); 14111 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14112 // reader 14113 synchronized (mPackages) { 14114 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14115 } 14116 } 14117 14118 @Override 14119 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14120 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14121 int uid = Binder.getCallingUid(); 14122 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14123 // reader 14124 synchronized (mPackages) { 14125 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14126 } 14127 } 14128 14129 @Override 14130 public void enterSafeMode() { 14131 enforceSystemOrRoot("Only the system can request entering safe mode"); 14132 14133 if (!mSystemReady) { 14134 mSafeMode = true; 14135 } 14136 } 14137 14138 @Override 14139 public void systemReady() { 14140 mSystemReady = true; 14141 14142 // Read the compatibilty setting when the system is ready. 14143 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14144 mContext.getContentResolver(), 14145 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14146 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14147 if (DEBUG_SETTINGS) { 14148 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14149 } 14150 14151 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14152 14153 synchronized (mPackages) { 14154 // Verify that all of the preferred activity components actually 14155 // exist. It is possible for applications to be updated and at 14156 // that point remove a previously declared activity component that 14157 // had been set as a preferred activity. We try to clean this up 14158 // the next time we encounter that preferred activity, but it is 14159 // possible for the user flow to never be able to return to that 14160 // situation so here we do a sanity check to make sure we haven't 14161 // left any junk around. 14162 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14163 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14164 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14165 removed.clear(); 14166 for (PreferredActivity pa : pir.filterSet()) { 14167 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14168 removed.add(pa); 14169 } 14170 } 14171 if (removed.size() > 0) { 14172 for (int r=0; r<removed.size(); r++) { 14173 PreferredActivity pa = removed.get(r); 14174 Slog.w(TAG, "Removing dangling preferred activity: " 14175 + pa.mPref.mComponent); 14176 pir.removeFilter(pa); 14177 } 14178 mSettings.writePackageRestrictionsLPr( 14179 mSettings.mPreferredActivities.keyAt(i)); 14180 } 14181 } 14182 14183 for (int userId : UserManagerService.getInstance().getUserIds()) { 14184 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14185 grantPermissionsUserIds = ArrayUtils.appendInt( 14186 grantPermissionsUserIds, userId); 14187 } 14188 } 14189 } 14190 sUserManager.systemReady(); 14191 14192 // If we upgraded grant all default permissions before kicking off. 14193 for (int userId : grantPermissionsUserIds) { 14194 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14195 } 14196 14197 // Kick off any messages waiting for system ready 14198 if (mPostSystemReadyMessages != null) { 14199 for (Message msg : mPostSystemReadyMessages) { 14200 msg.sendToTarget(); 14201 } 14202 mPostSystemReadyMessages = null; 14203 } 14204 14205 // Watch for external volumes that come and go over time 14206 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14207 storage.registerListener(mStorageListener); 14208 14209 mInstallerService.systemReady(); 14210 mPackageDexOptimizer.systemReady(); 14211 } 14212 14213 @Override 14214 public boolean isSafeMode() { 14215 return mSafeMode; 14216 } 14217 14218 @Override 14219 public boolean hasSystemUidErrors() { 14220 return mHasSystemUidErrors; 14221 } 14222 14223 static String arrayToString(int[] array) { 14224 StringBuffer buf = new StringBuffer(128); 14225 buf.append('['); 14226 if (array != null) { 14227 for (int i=0; i<array.length; i++) { 14228 if (i > 0) buf.append(", "); 14229 buf.append(array[i]); 14230 } 14231 } 14232 buf.append(']'); 14233 return buf.toString(); 14234 } 14235 14236 static class DumpState { 14237 public static final int DUMP_LIBS = 1 << 0; 14238 public static final int DUMP_FEATURES = 1 << 1; 14239 public static final int DUMP_RESOLVERS = 1 << 2; 14240 public static final int DUMP_PERMISSIONS = 1 << 3; 14241 public static final int DUMP_PACKAGES = 1 << 4; 14242 public static final int DUMP_SHARED_USERS = 1 << 5; 14243 public static final int DUMP_MESSAGES = 1 << 6; 14244 public static final int DUMP_PROVIDERS = 1 << 7; 14245 public static final int DUMP_VERIFIERS = 1 << 8; 14246 public static final int DUMP_PREFERRED = 1 << 9; 14247 public static final int DUMP_PREFERRED_XML = 1 << 10; 14248 public static final int DUMP_KEYSETS = 1 << 11; 14249 public static final int DUMP_VERSION = 1 << 12; 14250 public static final int DUMP_INSTALLS = 1 << 13; 14251 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14252 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14253 14254 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14255 14256 private int mTypes; 14257 14258 private int mOptions; 14259 14260 private boolean mTitlePrinted; 14261 14262 private SharedUserSetting mSharedUser; 14263 14264 public boolean isDumping(int type) { 14265 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14266 return true; 14267 } 14268 14269 return (mTypes & type) != 0; 14270 } 14271 14272 public void setDump(int type) { 14273 mTypes |= type; 14274 } 14275 14276 public boolean isOptionEnabled(int option) { 14277 return (mOptions & option) != 0; 14278 } 14279 14280 public void setOptionEnabled(int option) { 14281 mOptions |= option; 14282 } 14283 14284 public boolean onTitlePrinted() { 14285 final boolean printed = mTitlePrinted; 14286 mTitlePrinted = true; 14287 return printed; 14288 } 14289 14290 public boolean getTitlePrinted() { 14291 return mTitlePrinted; 14292 } 14293 14294 public void setTitlePrinted(boolean enabled) { 14295 mTitlePrinted = enabled; 14296 } 14297 14298 public SharedUserSetting getSharedUser() { 14299 return mSharedUser; 14300 } 14301 14302 public void setSharedUser(SharedUserSetting user) { 14303 mSharedUser = user; 14304 } 14305 } 14306 14307 @Override 14308 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14309 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14310 != PackageManager.PERMISSION_GRANTED) { 14311 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14312 + Binder.getCallingPid() 14313 + ", uid=" + Binder.getCallingUid() 14314 + " without permission " 14315 + android.Manifest.permission.DUMP); 14316 return; 14317 } 14318 14319 DumpState dumpState = new DumpState(); 14320 boolean fullPreferred = false; 14321 boolean checkin = false; 14322 14323 String packageName = null; 14324 ArraySet<String> permissionNames = null; 14325 14326 int opti = 0; 14327 while (opti < args.length) { 14328 String opt = args[opti]; 14329 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14330 break; 14331 } 14332 opti++; 14333 14334 if ("-a".equals(opt)) { 14335 // Right now we only know how to print all. 14336 } else if ("-h".equals(opt)) { 14337 pw.println("Package manager dump options:"); 14338 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14339 pw.println(" --checkin: dump for a checkin"); 14340 pw.println(" -f: print details of intent filters"); 14341 pw.println(" -h: print this help"); 14342 pw.println(" cmd may be one of:"); 14343 pw.println(" l[ibraries]: list known shared libraries"); 14344 pw.println(" f[ibraries]: list device features"); 14345 pw.println(" k[eysets]: print known keysets"); 14346 pw.println(" r[esolvers]: dump intent resolvers"); 14347 pw.println(" perm[issions]: dump permissions"); 14348 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14349 pw.println(" pref[erred]: print preferred package settings"); 14350 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14351 pw.println(" prov[iders]: dump content providers"); 14352 pw.println(" p[ackages]: dump installed packages"); 14353 pw.println(" s[hared-users]: dump shared user IDs"); 14354 pw.println(" m[essages]: print collected runtime messages"); 14355 pw.println(" v[erifiers]: print package verifier info"); 14356 pw.println(" version: print database version info"); 14357 pw.println(" write: write current settings now"); 14358 pw.println(" <package.name>: info about given package"); 14359 pw.println(" installs: details about install sessions"); 14360 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14361 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14362 return; 14363 } else if ("--checkin".equals(opt)) { 14364 checkin = true; 14365 } else if ("-f".equals(opt)) { 14366 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14367 } else { 14368 pw.println("Unknown argument: " + opt + "; use -h for help"); 14369 } 14370 } 14371 14372 // Is the caller requesting to dump a particular piece of data? 14373 if (opti < args.length) { 14374 String cmd = args[opti]; 14375 opti++; 14376 // Is this a package name? 14377 if ("android".equals(cmd) || cmd.contains(".")) { 14378 packageName = cmd; 14379 // When dumping a single package, we always dump all of its 14380 // filter information since the amount of data will be reasonable. 14381 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14382 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14383 dumpState.setDump(DumpState.DUMP_LIBS); 14384 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14385 dumpState.setDump(DumpState.DUMP_FEATURES); 14386 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14387 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14388 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14389 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14390 } else if ("permission".equals(cmd)) { 14391 if (opti >= args.length) { 14392 pw.println("Error: permission requires permission name"); 14393 return; 14394 } 14395 permissionNames = new ArraySet<>(); 14396 while (opti < args.length) { 14397 permissionNames.add(args[opti]); 14398 opti++; 14399 } 14400 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14401 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14402 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14403 dumpState.setDump(DumpState.DUMP_PREFERRED); 14404 } else if ("preferred-xml".equals(cmd)) { 14405 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14406 if (opti < args.length && "--full".equals(args[opti])) { 14407 fullPreferred = true; 14408 opti++; 14409 } 14410 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14411 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14412 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14413 dumpState.setDump(DumpState.DUMP_PACKAGES); 14414 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14415 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14416 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14417 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14418 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14419 dumpState.setDump(DumpState.DUMP_MESSAGES); 14420 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14421 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14422 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14423 || "intent-filter-verifiers".equals(cmd)) { 14424 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14425 } else if ("version".equals(cmd)) { 14426 dumpState.setDump(DumpState.DUMP_VERSION); 14427 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14428 dumpState.setDump(DumpState.DUMP_KEYSETS); 14429 } else if ("installs".equals(cmd)) { 14430 dumpState.setDump(DumpState.DUMP_INSTALLS); 14431 } else if ("write".equals(cmd)) { 14432 synchronized (mPackages) { 14433 mSettings.writeLPr(); 14434 pw.println("Settings written."); 14435 return; 14436 } 14437 } 14438 } 14439 14440 if (checkin) { 14441 pw.println("vers,1"); 14442 } 14443 14444 // reader 14445 synchronized (mPackages) { 14446 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14447 if (!checkin) { 14448 if (dumpState.onTitlePrinted()) 14449 pw.println(); 14450 pw.println("Database versions:"); 14451 pw.print(" SDK Version:"); 14452 pw.print(" internal="); 14453 pw.print(mSettings.mInternalSdkPlatform); 14454 pw.print(" external="); 14455 pw.println(mSettings.mExternalSdkPlatform); 14456 pw.print(" DB Version:"); 14457 pw.print(" internal="); 14458 pw.print(mSettings.mInternalDatabaseVersion); 14459 pw.print(" external="); 14460 pw.println(mSettings.mExternalDatabaseVersion); 14461 } 14462 } 14463 14464 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14465 if (!checkin) { 14466 if (dumpState.onTitlePrinted()) 14467 pw.println(); 14468 pw.println("Verifiers:"); 14469 pw.print(" Required: "); 14470 pw.print(mRequiredVerifierPackage); 14471 pw.print(" (uid="); 14472 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14473 pw.println(")"); 14474 } else if (mRequiredVerifierPackage != null) { 14475 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14476 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14477 } 14478 } 14479 14480 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14481 packageName == null) { 14482 if (mIntentFilterVerifierComponent != null) { 14483 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14484 if (!checkin) { 14485 if (dumpState.onTitlePrinted()) 14486 pw.println(); 14487 pw.println("Intent Filter Verifier:"); 14488 pw.print(" Using: "); 14489 pw.print(verifierPackageName); 14490 pw.print(" (uid="); 14491 pw.print(getPackageUid(verifierPackageName, 0)); 14492 pw.println(")"); 14493 } else if (verifierPackageName != null) { 14494 pw.print("ifv,"); pw.print(verifierPackageName); 14495 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14496 } 14497 } else { 14498 pw.println(); 14499 pw.println("No Intent Filter Verifier available!"); 14500 } 14501 } 14502 14503 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14504 boolean printedHeader = false; 14505 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14506 while (it.hasNext()) { 14507 String name = it.next(); 14508 SharedLibraryEntry ent = mSharedLibraries.get(name); 14509 if (!checkin) { 14510 if (!printedHeader) { 14511 if (dumpState.onTitlePrinted()) 14512 pw.println(); 14513 pw.println("Libraries:"); 14514 printedHeader = true; 14515 } 14516 pw.print(" "); 14517 } else { 14518 pw.print("lib,"); 14519 } 14520 pw.print(name); 14521 if (!checkin) { 14522 pw.print(" -> "); 14523 } 14524 if (ent.path != null) { 14525 if (!checkin) { 14526 pw.print("(jar) "); 14527 pw.print(ent.path); 14528 } else { 14529 pw.print(",jar,"); 14530 pw.print(ent.path); 14531 } 14532 } else { 14533 if (!checkin) { 14534 pw.print("(apk) "); 14535 pw.print(ent.apk); 14536 } else { 14537 pw.print(",apk,"); 14538 pw.print(ent.apk); 14539 } 14540 } 14541 pw.println(); 14542 } 14543 } 14544 14545 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14546 if (dumpState.onTitlePrinted()) 14547 pw.println(); 14548 if (!checkin) { 14549 pw.println("Features:"); 14550 } 14551 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14552 while (it.hasNext()) { 14553 String name = it.next(); 14554 if (!checkin) { 14555 pw.print(" "); 14556 } else { 14557 pw.print("feat,"); 14558 } 14559 pw.println(name); 14560 } 14561 } 14562 14563 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14564 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14565 : "Activity Resolver Table:", " ", packageName, 14566 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14567 dumpState.setTitlePrinted(true); 14568 } 14569 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14570 : "Receiver Resolver Table:", " ", packageName, 14571 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14572 dumpState.setTitlePrinted(true); 14573 } 14574 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14575 : "Service Resolver Table:", " ", packageName, 14576 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14577 dumpState.setTitlePrinted(true); 14578 } 14579 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14580 : "Provider Resolver Table:", " ", packageName, 14581 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14582 dumpState.setTitlePrinted(true); 14583 } 14584 } 14585 14586 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14587 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14588 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14589 int user = mSettings.mPreferredActivities.keyAt(i); 14590 if (pir.dump(pw, 14591 dumpState.getTitlePrinted() 14592 ? "\nPreferred Activities User " + user + ":" 14593 : "Preferred Activities User " + user + ":", " ", 14594 packageName, true, false)) { 14595 dumpState.setTitlePrinted(true); 14596 } 14597 } 14598 } 14599 14600 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14601 pw.flush(); 14602 FileOutputStream fout = new FileOutputStream(fd); 14603 BufferedOutputStream str = new BufferedOutputStream(fout); 14604 XmlSerializer serializer = new FastXmlSerializer(); 14605 try { 14606 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14607 serializer.startDocument(null, true); 14608 serializer.setFeature( 14609 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14610 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14611 serializer.endDocument(); 14612 serializer.flush(); 14613 } catch (IllegalArgumentException e) { 14614 pw.println("Failed writing: " + e); 14615 } catch (IllegalStateException e) { 14616 pw.println("Failed writing: " + e); 14617 } catch (IOException e) { 14618 pw.println("Failed writing: " + e); 14619 } 14620 } 14621 14622 if (!checkin 14623 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14624 && packageName == null) { 14625 pw.println(); 14626 int count = mSettings.mPackages.size(); 14627 if (count == 0) { 14628 pw.println("No domain preferred apps!"); 14629 pw.println(); 14630 } else { 14631 final String prefix = " "; 14632 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14633 if (allPackageSettings.size() == 0) { 14634 pw.println("No domain preferred apps!"); 14635 pw.println(); 14636 } else { 14637 pw.println("Domain preferred apps status:"); 14638 pw.println(); 14639 count = 0; 14640 for (PackageSetting ps : allPackageSettings) { 14641 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14642 if (ivi == null || ivi.getPackageName() == null) continue; 14643 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14644 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14645 pw.println(prefix + "Status: " + ivi.getStatusString()); 14646 pw.println(); 14647 count++; 14648 } 14649 if (count == 0) { 14650 pw.println(prefix + "No domain preferred app status!"); 14651 pw.println(); 14652 } 14653 for (int userId : sUserManager.getUserIds()) { 14654 pw.println("Domain preferred apps for User " + userId + ":"); 14655 pw.println(); 14656 count = 0; 14657 for (PackageSetting ps : allPackageSettings) { 14658 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14659 if (ivi == null || ivi.getPackageName() == null) { 14660 continue; 14661 } 14662 final int status = ps.getDomainVerificationStatusForUser(userId); 14663 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14664 continue; 14665 } 14666 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14667 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14668 String statusStr = IntentFilterVerificationInfo. 14669 getStatusStringFromValue(status); 14670 pw.println(prefix + "Status: " + statusStr); 14671 pw.println(); 14672 count++; 14673 } 14674 if (count == 0) { 14675 pw.println(prefix + "No domain preferred apps!"); 14676 pw.println(); 14677 } 14678 } 14679 } 14680 } 14681 } 14682 14683 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14684 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14685 if (packageName == null && permissionNames == null) { 14686 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14687 if (iperm == 0) { 14688 if (dumpState.onTitlePrinted()) 14689 pw.println(); 14690 pw.println("AppOp Permissions:"); 14691 } 14692 pw.print(" AppOp Permission "); 14693 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14694 pw.println(":"); 14695 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14696 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14697 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14698 } 14699 } 14700 } 14701 } 14702 14703 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14704 boolean printedSomething = false; 14705 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14706 if (packageName != null && !packageName.equals(p.info.packageName)) { 14707 continue; 14708 } 14709 if (!printedSomething) { 14710 if (dumpState.onTitlePrinted()) 14711 pw.println(); 14712 pw.println("Registered ContentProviders:"); 14713 printedSomething = true; 14714 } 14715 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14716 pw.print(" "); pw.println(p.toString()); 14717 } 14718 printedSomething = false; 14719 for (Map.Entry<String, PackageParser.Provider> entry : 14720 mProvidersByAuthority.entrySet()) { 14721 PackageParser.Provider p = entry.getValue(); 14722 if (packageName != null && !packageName.equals(p.info.packageName)) { 14723 continue; 14724 } 14725 if (!printedSomething) { 14726 if (dumpState.onTitlePrinted()) 14727 pw.println(); 14728 pw.println("ContentProvider Authorities:"); 14729 printedSomething = true; 14730 } 14731 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14732 pw.print(" "); pw.println(p.toString()); 14733 if (p.info != null && p.info.applicationInfo != null) { 14734 final String appInfo = p.info.applicationInfo.toString(); 14735 pw.print(" applicationInfo="); pw.println(appInfo); 14736 } 14737 } 14738 } 14739 14740 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14741 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14742 } 14743 14744 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14745 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14746 } 14747 14748 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14749 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14750 } 14751 14752 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14753 // XXX should handle packageName != null by dumping only install data that 14754 // the given package is involved with. 14755 if (dumpState.onTitlePrinted()) pw.println(); 14756 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14757 } 14758 14759 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14760 if (dumpState.onTitlePrinted()) pw.println(); 14761 mSettings.dumpReadMessagesLPr(pw, dumpState); 14762 14763 pw.println(); 14764 pw.println("Package warning messages:"); 14765 BufferedReader in = null; 14766 String line = null; 14767 try { 14768 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14769 while ((line = in.readLine()) != null) { 14770 if (line.contains("ignored: updated version")) continue; 14771 pw.println(line); 14772 } 14773 } catch (IOException ignored) { 14774 } finally { 14775 IoUtils.closeQuietly(in); 14776 } 14777 } 14778 14779 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14780 BufferedReader in = null; 14781 String line = null; 14782 try { 14783 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14784 while ((line = in.readLine()) != null) { 14785 if (line.contains("ignored: updated version")) continue; 14786 pw.print("msg,"); 14787 pw.println(line); 14788 } 14789 } catch (IOException ignored) { 14790 } finally { 14791 IoUtils.closeQuietly(in); 14792 } 14793 } 14794 } 14795 } 14796 14797 // ------- apps on sdcard specific code ------- 14798 static final boolean DEBUG_SD_INSTALL = false; 14799 14800 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14801 14802 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14803 14804 private boolean mMediaMounted = false; 14805 14806 static String getEncryptKey() { 14807 try { 14808 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14809 SD_ENCRYPTION_KEYSTORE_NAME); 14810 if (sdEncKey == null) { 14811 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14812 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14813 if (sdEncKey == null) { 14814 Slog.e(TAG, "Failed to create encryption keys"); 14815 return null; 14816 } 14817 } 14818 return sdEncKey; 14819 } catch (NoSuchAlgorithmException nsae) { 14820 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14821 return null; 14822 } catch (IOException ioe) { 14823 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14824 return null; 14825 } 14826 } 14827 14828 /* 14829 * Update media status on PackageManager. 14830 */ 14831 @Override 14832 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14833 int callingUid = Binder.getCallingUid(); 14834 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14835 throw new SecurityException("Media status can only be updated by the system"); 14836 } 14837 // reader; this apparently protects mMediaMounted, but should probably 14838 // be a different lock in that case. 14839 synchronized (mPackages) { 14840 Log.i(TAG, "Updating external media status from " 14841 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14842 + (mediaStatus ? "mounted" : "unmounted")); 14843 if (DEBUG_SD_INSTALL) 14844 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14845 + ", mMediaMounted=" + mMediaMounted); 14846 if (mediaStatus == mMediaMounted) { 14847 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14848 : 0, -1); 14849 mHandler.sendMessage(msg); 14850 return; 14851 } 14852 mMediaMounted = mediaStatus; 14853 } 14854 // Queue up an async operation since the package installation may take a 14855 // little while. 14856 mHandler.post(new Runnable() { 14857 public void run() { 14858 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14859 } 14860 }); 14861 } 14862 14863 /** 14864 * Called by MountService when the initial ASECs to scan are available. 14865 * Should block until all the ASEC containers are finished being scanned. 14866 */ 14867 public void scanAvailableAsecs() { 14868 updateExternalMediaStatusInner(true, false, false); 14869 if (mShouldRestoreconData) { 14870 SELinuxMMAC.setRestoreconDone(); 14871 mShouldRestoreconData = false; 14872 } 14873 } 14874 14875 /* 14876 * Collect information of applications on external media, map them against 14877 * existing containers and update information based on current mount status. 14878 * Please note that we always have to report status if reportStatus has been 14879 * set to true especially when unloading packages. 14880 */ 14881 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14882 boolean externalStorage) { 14883 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14884 int[] uidArr = EmptyArray.INT; 14885 14886 final String[] list = PackageHelper.getSecureContainerList(); 14887 if (ArrayUtils.isEmpty(list)) { 14888 Log.i(TAG, "No secure containers found"); 14889 } else { 14890 // Process list of secure containers and categorize them 14891 // as active or stale based on their package internal state. 14892 14893 // reader 14894 synchronized (mPackages) { 14895 for (String cid : list) { 14896 // Leave stages untouched for now; installer service owns them 14897 if (PackageInstallerService.isStageName(cid)) continue; 14898 14899 if (DEBUG_SD_INSTALL) 14900 Log.i(TAG, "Processing container " + cid); 14901 String pkgName = getAsecPackageName(cid); 14902 if (pkgName == null) { 14903 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14904 continue; 14905 } 14906 if (DEBUG_SD_INSTALL) 14907 Log.i(TAG, "Looking for pkg : " + pkgName); 14908 14909 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14910 if (ps == null) { 14911 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14912 continue; 14913 } 14914 14915 /* 14916 * Skip packages that are not external if we're unmounting 14917 * external storage. 14918 */ 14919 if (externalStorage && !isMounted && !isExternal(ps)) { 14920 continue; 14921 } 14922 14923 final AsecInstallArgs args = new AsecInstallArgs(cid, 14924 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14925 // The package status is changed only if the code path 14926 // matches between settings and the container id. 14927 if (ps.codePathString != null 14928 && ps.codePathString.startsWith(args.getCodePath())) { 14929 if (DEBUG_SD_INSTALL) { 14930 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14931 + " at code path: " + ps.codePathString); 14932 } 14933 14934 // We do have a valid package installed on sdcard 14935 processCids.put(args, ps.codePathString); 14936 final int uid = ps.appId; 14937 if (uid != -1) { 14938 uidArr = ArrayUtils.appendInt(uidArr, uid); 14939 } 14940 } else { 14941 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14942 + ps.codePathString); 14943 } 14944 } 14945 } 14946 14947 Arrays.sort(uidArr); 14948 } 14949 14950 // Process packages with valid entries. 14951 if (isMounted) { 14952 if (DEBUG_SD_INSTALL) 14953 Log.i(TAG, "Loading packages"); 14954 loadMediaPackages(processCids, uidArr); 14955 startCleaningPackages(); 14956 mInstallerService.onSecureContainersAvailable(); 14957 } else { 14958 if (DEBUG_SD_INSTALL) 14959 Log.i(TAG, "Unloading packages"); 14960 unloadMediaPackages(processCids, uidArr, reportStatus); 14961 } 14962 } 14963 14964 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14965 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14966 final int size = infos.size(); 14967 final String[] packageNames = new String[size]; 14968 final int[] packageUids = new int[size]; 14969 for (int i = 0; i < size; i++) { 14970 final ApplicationInfo info = infos.get(i); 14971 packageNames[i] = info.packageName; 14972 packageUids[i] = info.uid; 14973 } 14974 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14975 finishedReceiver); 14976 } 14977 14978 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14979 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14980 sendResourcesChangedBroadcast(mediaStatus, replacing, 14981 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14982 } 14983 14984 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14985 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14986 int size = pkgList.length; 14987 if (size > 0) { 14988 // Send broadcasts here 14989 Bundle extras = new Bundle(); 14990 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14991 if (uidArr != null) { 14992 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14993 } 14994 if (replacing) { 14995 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14996 } 14997 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14998 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14999 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15000 } 15001 } 15002 15003 /* 15004 * Look at potentially valid container ids from processCids If package 15005 * information doesn't match the one on record or package scanning fails, 15006 * the cid is added to list of removeCids. We currently don't delete stale 15007 * containers. 15008 */ 15009 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15010 ArrayList<String> pkgList = new ArrayList<String>(); 15011 Set<AsecInstallArgs> keys = processCids.keySet(); 15012 15013 for (AsecInstallArgs args : keys) { 15014 String codePath = processCids.get(args); 15015 if (DEBUG_SD_INSTALL) 15016 Log.i(TAG, "Loading container : " + args.cid); 15017 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15018 try { 15019 // Make sure there are no container errors first. 15020 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15021 Slog.e(TAG, "Failed to mount cid : " + args.cid 15022 + " when installing from sdcard"); 15023 continue; 15024 } 15025 // Check code path here. 15026 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15027 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15028 + " does not match one in settings " + codePath); 15029 continue; 15030 } 15031 // Parse package 15032 int parseFlags = mDefParseFlags; 15033 if (args.isExternalAsec()) { 15034 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15035 } 15036 if (args.isFwdLocked()) { 15037 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15038 } 15039 15040 synchronized (mInstallLock) { 15041 PackageParser.Package pkg = null; 15042 try { 15043 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15044 } catch (PackageManagerException e) { 15045 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15046 } 15047 // Scan the package 15048 if (pkg != null) { 15049 /* 15050 * TODO why is the lock being held? doPostInstall is 15051 * called in other places without the lock. This needs 15052 * to be straightened out. 15053 */ 15054 // writer 15055 synchronized (mPackages) { 15056 retCode = PackageManager.INSTALL_SUCCEEDED; 15057 pkgList.add(pkg.packageName); 15058 // Post process args 15059 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15060 pkg.applicationInfo.uid); 15061 } 15062 } else { 15063 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15064 } 15065 } 15066 15067 } finally { 15068 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15069 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15070 } 15071 } 15072 } 15073 // writer 15074 synchronized (mPackages) { 15075 // If the platform SDK has changed since the last time we booted, 15076 // we need to re-grant app permission to catch any new ones that 15077 // appear. This is really a hack, and means that apps can in some 15078 // cases get permissions that the user didn't initially explicitly 15079 // allow... it would be nice to have some better way to handle 15080 // this situation. 15081 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15082 if (regrantPermissions) 15083 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15084 + mSdkVersion + "; regranting permissions for external storage"); 15085 mSettings.mExternalSdkPlatform = mSdkVersion; 15086 15087 // Make sure group IDs have been assigned, and any permission 15088 // changes in other apps are accounted for 15089 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15090 | (regrantPermissions 15091 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15092 : 0)); 15093 15094 mSettings.updateExternalDatabaseVersion(); 15095 15096 // can downgrade to reader 15097 // Persist settings 15098 mSettings.writeLPr(); 15099 } 15100 // Send a broadcast to let everyone know we are done processing 15101 if (pkgList.size() > 0) { 15102 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15103 } 15104 } 15105 15106 /* 15107 * Utility method to unload a list of specified containers 15108 */ 15109 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15110 // Just unmount all valid containers. 15111 for (AsecInstallArgs arg : cidArgs) { 15112 synchronized (mInstallLock) { 15113 arg.doPostDeleteLI(false); 15114 } 15115 } 15116 } 15117 15118 /* 15119 * Unload packages mounted on external media. This involves deleting package 15120 * data from internal structures, sending broadcasts about diabled packages, 15121 * gc'ing to free up references, unmounting all secure containers 15122 * corresponding to packages on external media, and posting a 15123 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15124 * that we always have to post this message if status has been requested no 15125 * matter what. 15126 */ 15127 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15128 final boolean reportStatus) { 15129 if (DEBUG_SD_INSTALL) 15130 Log.i(TAG, "unloading media packages"); 15131 ArrayList<String> pkgList = new ArrayList<String>(); 15132 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15133 final Set<AsecInstallArgs> keys = processCids.keySet(); 15134 for (AsecInstallArgs args : keys) { 15135 String pkgName = args.getPackageName(); 15136 if (DEBUG_SD_INSTALL) 15137 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15138 // Delete package internally 15139 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15140 synchronized (mInstallLock) { 15141 boolean res = deletePackageLI(pkgName, null, false, null, null, 15142 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15143 if (res) { 15144 pkgList.add(pkgName); 15145 } else { 15146 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15147 failedList.add(args); 15148 } 15149 } 15150 } 15151 15152 // reader 15153 synchronized (mPackages) { 15154 // We didn't update the settings after removing each package; 15155 // write them now for all packages. 15156 mSettings.writeLPr(); 15157 } 15158 15159 // We have to absolutely send UPDATED_MEDIA_STATUS only 15160 // after confirming that all the receivers processed the ordered 15161 // broadcast when packages get disabled, force a gc to clean things up. 15162 // and unload all the containers. 15163 if (pkgList.size() > 0) { 15164 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15165 new IIntentReceiver.Stub() { 15166 public void performReceive(Intent intent, int resultCode, String data, 15167 Bundle extras, boolean ordered, boolean sticky, 15168 int sendingUser) throws RemoteException { 15169 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15170 reportStatus ? 1 : 0, 1, keys); 15171 mHandler.sendMessage(msg); 15172 } 15173 }); 15174 } else { 15175 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15176 keys); 15177 mHandler.sendMessage(msg); 15178 } 15179 } 15180 15181 private void loadPrivatePackages(VolumeInfo vol) { 15182 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15183 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15184 synchronized (mInstallLock) { 15185 synchronized (mPackages) { 15186 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15187 for (PackageSetting ps : packages) { 15188 final PackageParser.Package pkg; 15189 try { 15190 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15191 loaded.add(pkg.applicationInfo); 15192 } catch (PackageManagerException e) { 15193 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15194 } 15195 } 15196 15197 // TODO: regrant any permissions that changed based since original install 15198 15199 mSettings.writeLPr(); 15200 } 15201 } 15202 15203 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15204 sendResourcesChangedBroadcast(true, false, loaded, null); 15205 } 15206 15207 private void unloadPrivatePackages(VolumeInfo vol) { 15208 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15209 synchronized (mInstallLock) { 15210 synchronized (mPackages) { 15211 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15212 for (PackageSetting ps : packages) { 15213 if (ps.pkg == null) continue; 15214 15215 final ApplicationInfo info = ps.pkg.applicationInfo; 15216 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15217 if (deletePackageLI(ps.name, null, false, null, null, 15218 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15219 unloaded.add(info); 15220 } else { 15221 Slog.w(TAG, "Failed to unload " + ps.codePath); 15222 } 15223 } 15224 15225 mSettings.writeLPr(); 15226 } 15227 } 15228 15229 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15230 sendResourcesChangedBroadcast(false, false, unloaded, null); 15231 } 15232 15233 private void unfreezePackage(String packageName) { 15234 synchronized (mPackages) { 15235 final PackageSetting ps = mSettings.mPackages.get(packageName); 15236 if (ps != null) { 15237 ps.frozen = false; 15238 } 15239 } 15240 } 15241 15242 @Override 15243 public int movePackage(final String packageName, final String volumeUuid) { 15244 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15245 15246 final int moveId = mNextMoveId.getAndIncrement(); 15247 try { 15248 movePackageInternal(packageName, volumeUuid, moveId); 15249 } catch (PackageManagerException e) { 15250 Slog.w(TAG, "Failed to move " + packageName, e); 15251 mMoveCallbacks.notifyStatusChanged(moveId, 15252 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15253 } 15254 return moveId; 15255 } 15256 15257 private void movePackageInternal(final String packageName, final String volumeUuid, 15258 final int moveId) throws PackageManagerException { 15259 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15260 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15261 final PackageManager pm = mContext.getPackageManager(); 15262 15263 final boolean currentAsec; 15264 final String currentVolumeUuid; 15265 final File codeFile; 15266 final String installerPackageName; 15267 final String packageAbiOverride; 15268 final int appId; 15269 final String seinfo; 15270 final String label; 15271 15272 // reader 15273 synchronized (mPackages) { 15274 final PackageParser.Package pkg = mPackages.get(packageName); 15275 final PackageSetting ps = mSettings.mPackages.get(packageName); 15276 if (pkg == null || ps == null) { 15277 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15278 } 15279 15280 if (pkg.applicationInfo.isSystemApp()) { 15281 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15282 "Cannot move system application"); 15283 } 15284 15285 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15286 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15287 "Package already moved to " + volumeUuid); 15288 } 15289 15290 final File probe = new File(pkg.codePath); 15291 final File probeOat = new File(probe, "oat"); 15292 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15293 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15294 "Move only supported for modern cluster style installs"); 15295 } 15296 15297 if (ps.frozen) { 15298 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15299 "Failed to move already frozen package"); 15300 } 15301 ps.frozen = true; 15302 15303 currentAsec = pkg.applicationInfo.isForwardLocked() 15304 || pkg.applicationInfo.isExternalAsec(); 15305 currentVolumeUuid = ps.volumeUuid; 15306 codeFile = new File(pkg.codePath); 15307 installerPackageName = ps.installerPackageName; 15308 packageAbiOverride = ps.cpuAbiOverrideString; 15309 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15310 seinfo = pkg.applicationInfo.seinfo; 15311 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15312 } 15313 15314 // Now that we're guarded by frozen state, kill app during move 15315 killApplication(packageName, appId, "move pkg"); 15316 15317 final Bundle extras = new Bundle(); 15318 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15319 extras.putString(Intent.EXTRA_TITLE, label); 15320 mMoveCallbacks.notifyCreated(moveId, extras); 15321 15322 int installFlags; 15323 final boolean moveCompleteApp; 15324 final File measurePath; 15325 15326 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15327 installFlags = INSTALL_INTERNAL; 15328 moveCompleteApp = !currentAsec; 15329 measurePath = Environment.getDataAppDirectory(volumeUuid); 15330 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15331 installFlags = INSTALL_EXTERNAL; 15332 moveCompleteApp = false; 15333 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15334 } else { 15335 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15336 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15337 || !volume.isMountedWritable()) { 15338 unfreezePackage(packageName); 15339 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15340 "Move location not mounted private volume"); 15341 } 15342 15343 Preconditions.checkState(!currentAsec); 15344 15345 installFlags = INSTALL_INTERNAL; 15346 moveCompleteApp = true; 15347 measurePath = Environment.getDataAppDirectory(volumeUuid); 15348 } 15349 15350 final PackageStats stats = new PackageStats(null, -1); 15351 synchronized (mInstaller) { 15352 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15353 unfreezePackage(packageName); 15354 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15355 "Failed to measure package size"); 15356 } 15357 } 15358 15359 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15360 + stats.dataSize); 15361 15362 final long startFreeBytes = measurePath.getFreeSpace(); 15363 final long sizeBytes; 15364 if (moveCompleteApp) { 15365 sizeBytes = stats.codeSize + stats.dataSize; 15366 } else { 15367 sizeBytes = stats.codeSize; 15368 } 15369 15370 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15371 unfreezePackage(packageName); 15372 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15373 "Not enough free space to move"); 15374 } 15375 15376 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15377 15378 final CountDownLatch installedLatch = new CountDownLatch(1); 15379 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15380 @Override 15381 public void onUserActionRequired(Intent intent) throws RemoteException { 15382 throw new IllegalStateException(); 15383 } 15384 15385 @Override 15386 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15387 Bundle extras) throws RemoteException { 15388 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15389 + PackageManager.installStatusToString(returnCode, msg)); 15390 15391 installedLatch.countDown(); 15392 15393 // Regardless of success or failure of the move operation, 15394 // always unfreeze the package 15395 unfreezePackage(packageName); 15396 15397 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15398 switch (status) { 15399 case PackageInstaller.STATUS_SUCCESS: 15400 mMoveCallbacks.notifyStatusChanged(moveId, 15401 PackageManager.MOVE_SUCCEEDED); 15402 break; 15403 case PackageInstaller.STATUS_FAILURE_STORAGE: 15404 mMoveCallbacks.notifyStatusChanged(moveId, 15405 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15406 break; 15407 default: 15408 mMoveCallbacks.notifyStatusChanged(moveId, 15409 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15410 break; 15411 } 15412 } 15413 }; 15414 15415 final MoveInfo move; 15416 if (moveCompleteApp) { 15417 // Kick off a thread to report progress estimates 15418 new Thread() { 15419 @Override 15420 public void run() { 15421 while (true) { 15422 try { 15423 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15424 break; 15425 } 15426 } catch (InterruptedException ignored) { 15427 } 15428 15429 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15430 final int progress = 10 + (int) MathUtils.constrain( 15431 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15432 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15433 } 15434 } 15435 }.start(); 15436 15437 final String dataAppName = codeFile.getName(); 15438 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15439 dataAppName, appId, seinfo); 15440 } else { 15441 move = null; 15442 } 15443 15444 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15445 15446 final Message msg = mHandler.obtainMessage(INIT_COPY); 15447 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15448 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15449 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15450 mHandler.sendMessage(msg); 15451 } 15452 15453 @Override 15454 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15455 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15456 15457 final int realMoveId = mNextMoveId.getAndIncrement(); 15458 final Bundle extras = new Bundle(); 15459 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15460 mMoveCallbacks.notifyCreated(realMoveId, extras); 15461 15462 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15463 @Override 15464 public void onCreated(int moveId, Bundle extras) { 15465 // Ignored 15466 } 15467 15468 @Override 15469 public void onStatusChanged(int moveId, int status, long estMillis) { 15470 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15471 } 15472 }; 15473 15474 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15475 storage.setPrimaryStorageUuid(volumeUuid, callback); 15476 return realMoveId; 15477 } 15478 15479 @Override 15480 public int getMoveStatus(int moveId) { 15481 mContext.enforceCallingOrSelfPermission( 15482 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15483 return mMoveCallbacks.mLastStatus.get(moveId); 15484 } 15485 15486 @Override 15487 public void registerMoveCallback(IPackageMoveObserver callback) { 15488 mContext.enforceCallingOrSelfPermission( 15489 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15490 mMoveCallbacks.register(callback); 15491 } 15492 15493 @Override 15494 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15495 mContext.enforceCallingOrSelfPermission( 15496 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15497 mMoveCallbacks.unregister(callback); 15498 } 15499 15500 @Override 15501 public boolean setInstallLocation(int loc) { 15502 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15503 null); 15504 if (getInstallLocation() == loc) { 15505 return true; 15506 } 15507 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15508 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15509 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15510 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15511 return true; 15512 } 15513 return false; 15514 } 15515 15516 @Override 15517 public int getInstallLocation() { 15518 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15519 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15520 PackageHelper.APP_INSTALL_AUTO); 15521 } 15522 15523 /** Called by UserManagerService */ 15524 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15525 mDirtyUsers.remove(userHandle); 15526 mSettings.removeUserLPw(userHandle); 15527 mPendingBroadcasts.remove(userHandle); 15528 if (mInstaller != null) { 15529 // Technically, we shouldn't be doing this with the package lock 15530 // held. However, this is very rare, and there is already so much 15531 // other disk I/O going on, that we'll let it slide for now. 15532 final StorageManager storage = StorageManager.from(mContext); 15533 final List<VolumeInfo> vols = storage.getVolumes(); 15534 for (VolumeInfo vol : vols) { 15535 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15536 final String volumeUuid = vol.getFsUuid(); 15537 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15538 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15539 } 15540 } 15541 } 15542 mUserNeedsBadging.delete(userHandle); 15543 removeUnusedPackagesLILPw(userManager, userHandle); 15544 } 15545 15546 /** 15547 * We're removing userHandle and would like to remove any downloaded packages 15548 * that are no longer in use by any other user. 15549 * @param userHandle the user being removed 15550 */ 15551 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15552 final boolean DEBUG_CLEAN_APKS = false; 15553 int [] users = userManager.getUserIdsLPr(); 15554 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15555 while (psit.hasNext()) { 15556 PackageSetting ps = psit.next(); 15557 if (ps.pkg == null) { 15558 continue; 15559 } 15560 final String packageName = ps.pkg.packageName; 15561 // Skip over if system app 15562 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15563 continue; 15564 } 15565 if (DEBUG_CLEAN_APKS) { 15566 Slog.i(TAG, "Checking package " + packageName); 15567 } 15568 boolean keep = false; 15569 for (int i = 0; i < users.length; i++) { 15570 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15571 keep = true; 15572 if (DEBUG_CLEAN_APKS) { 15573 Slog.i(TAG, " Keeping package " + packageName + " for user " 15574 + users[i]); 15575 } 15576 break; 15577 } 15578 } 15579 if (!keep) { 15580 if (DEBUG_CLEAN_APKS) { 15581 Slog.i(TAG, " Removing package " + packageName); 15582 } 15583 mHandler.post(new Runnable() { 15584 public void run() { 15585 deletePackageX(packageName, userHandle, 0); 15586 } //end run 15587 }); 15588 } 15589 } 15590 } 15591 15592 /** Called by UserManagerService */ 15593 void createNewUserLILPw(int userHandle, File path) { 15594 if (mInstaller != null) { 15595 mInstaller.createUserConfig(userHandle); 15596 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15597 applyFactoryDefaultBrowserLPw(userHandle); 15598 } 15599 } 15600 15601 void newUserCreatedLILPw(final int userHandle) { 15602 // We cannot grant the default permissions with a lock held as 15603 // we query providers from other components for default handlers 15604 // such as enabled IMEs, etc. 15605 mHandler.post(new Runnable() { 15606 @Override 15607 public void run() { 15608 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15609 } 15610 }); 15611 } 15612 15613 @Override 15614 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15615 mContext.enforceCallingOrSelfPermission( 15616 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15617 "Only package verification agents can read the verifier device identity"); 15618 15619 synchronized (mPackages) { 15620 return mSettings.getVerifierDeviceIdentityLPw(); 15621 } 15622 } 15623 15624 @Override 15625 public void setPermissionEnforced(String permission, boolean enforced) { 15626 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15627 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15628 synchronized (mPackages) { 15629 if (mSettings.mReadExternalStorageEnforced == null 15630 || mSettings.mReadExternalStorageEnforced != enforced) { 15631 mSettings.mReadExternalStorageEnforced = enforced; 15632 mSettings.writeLPr(); 15633 } 15634 } 15635 // kill any non-foreground processes so we restart them and 15636 // grant/revoke the GID. 15637 final IActivityManager am = ActivityManagerNative.getDefault(); 15638 if (am != null) { 15639 final long token = Binder.clearCallingIdentity(); 15640 try { 15641 am.killProcessesBelowForeground("setPermissionEnforcement"); 15642 } catch (RemoteException e) { 15643 } finally { 15644 Binder.restoreCallingIdentity(token); 15645 } 15646 } 15647 } else { 15648 throw new IllegalArgumentException("No selective enforcement for " + permission); 15649 } 15650 } 15651 15652 @Override 15653 @Deprecated 15654 public boolean isPermissionEnforced(String permission) { 15655 return true; 15656 } 15657 15658 @Override 15659 public boolean isStorageLow() { 15660 final long token = Binder.clearCallingIdentity(); 15661 try { 15662 final DeviceStorageMonitorInternal 15663 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15664 if (dsm != null) { 15665 return dsm.isMemoryLow(); 15666 } else { 15667 return false; 15668 } 15669 } finally { 15670 Binder.restoreCallingIdentity(token); 15671 } 15672 } 15673 15674 @Override 15675 public IPackageInstaller getPackageInstaller() { 15676 return mInstallerService; 15677 } 15678 15679 private boolean userNeedsBadging(int userId) { 15680 int index = mUserNeedsBadging.indexOfKey(userId); 15681 if (index < 0) { 15682 final UserInfo userInfo; 15683 final long token = Binder.clearCallingIdentity(); 15684 try { 15685 userInfo = sUserManager.getUserInfo(userId); 15686 } finally { 15687 Binder.restoreCallingIdentity(token); 15688 } 15689 final boolean b; 15690 if (userInfo != null && userInfo.isManagedProfile()) { 15691 b = true; 15692 } else { 15693 b = false; 15694 } 15695 mUserNeedsBadging.put(userId, b); 15696 return b; 15697 } 15698 return mUserNeedsBadging.valueAt(index); 15699 } 15700 15701 @Override 15702 public KeySet getKeySetByAlias(String packageName, String alias) { 15703 if (packageName == null || alias == null) { 15704 return null; 15705 } 15706 synchronized(mPackages) { 15707 final PackageParser.Package pkg = mPackages.get(packageName); 15708 if (pkg == null) { 15709 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15710 throw new IllegalArgumentException("Unknown package: " + packageName); 15711 } 15712 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15713 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15714 } 15715 } 15716 15717 @Override 15718 public KeySet getSigningKeySet(String packageName) { 15719 if (packageName == null) { 15720 return null; 15721 } 15722 synchronized(mPackages) { 15723 final PackageParser.Package pkg = mPackages.get(packageName); 15724 if (pkg == null) { 15725 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15726 throw new IllegalArgumentException("Unknown package: " + packageName); 15727 } 15728 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15729 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15730 throw new SecurityException("May not access signing KeySet of other apps."); 15731 } 15732 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15733 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15734 } 15735 } 15736 15737 @Override 15738 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15739 if (packageName == null || ks == null) { 15740 return false; 15741 } 15742 synchronized(mPackages) { 15743 final PackageParser.Package pkg = mPackages.get(packageName); 15744 if (pkg == null) { 15745 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15746 throw new IllegalArgumentException("Unknown package: " + packageName); 15747 } 15748 IBinder ksh = ks.getToken(); 15749 if (ksh instanceof KeySetHandle) { 15750 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15751 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15752 } 15753 return false; 15754 } 15755 } 15756 15757 @Override 15758 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15759 if (packageName == null || ks == null) { 15760 return false; 15761 } 15762 synchronized(mPackages) { 15763 final PackageParser.Package pkg = mPackages.get(packageName); 15764 if (pkg == null) { 15765 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15766 throw new IllegalArgumentException("Unknown package: " + packageName); 15767 } 15768 IBinder ksh = ks.getToken(); 15769 if (ksh instanceof KeySetHandle) { 15770 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15771 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15772 } 15773 return false; 15774 } 15775 } 15776 15777 public void getUsageStatsIfNoPackageUsageInfo() { 15778 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15779 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15780 if (usm == null) { 15781 throw new IllegalStateException("UsageStatsManager must be initialized"); 15782 } 15783 long now = System.currentTimeMillis(); 15784 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15785 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15786 String packageName = entry.getKey(); 15787 PackageParser.Package pkg = mPackages.get(packageName); 15788 if (pkg == null) { 15789 continue; 15790 } 15791 UsageStats usage = entry.getValue(); 15792 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15793 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15794 } 15795 } 15796 } 15797 15798 /** 15799 * Check and throw if the given before/after packages would be considered a 15800 * downgrade. 15801 */ 15802 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15803 throws PackageManagerException { 15804 if (after.versionCode < before.mVersionCode) { 15805 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15806 "Update version code " + after.versionCode + " is older than current " 15807 + before.mVersionCode); 15808 } else if (after.versionCode == before.mVersionCode) { 15809 if (after.baseRevisionCode < before.baseRevisionCode) { 15810 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15811 "Update base revision code " + after.baseRevisionCode 15812 + " is older than current " + before.baseRevisionCode); 15813 } 15814 15815 if (!ArrayUtils.isEmpty(after.splitNames)) { 15816 for (int i = 0; i < after.splitNames.length; i++) { 15817 final String splitName = after.splitNames[i]; 15818 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15819 if (j != -1) { 15820 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15821 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15822 "Update split " + splitName + " revision code " 15823 + after.splitRevisionCodes[i] + " is older than current " 15824 + before.splitRevisionCodes[j]); 15825 } 15826 } 15827 } 15828 } 15829 } 15830 } 15831 15832 private static class MoveCallbacks extends Handler { 15833 private static final int MSG_CREATED = 1; 15834 private static final int MSG_STATUS_CHANGED = 2; 15835 15836 private final RemoteCallbackList<IPackageMoveObserver> 15837 mCallbacks = new RemoteCallbackList<>(); 15838 15839 private final SparseIntArray mLastStatus = new SparseIntArray(); 15840 15841 public MoveCallbacks(Looper looper) { 15842 super(looper); 15843 } 15844 15845 public void register(IPackageMoveObserver callback) { 15846 mCallbacks.register(callback); 15847 } 15848 15849 public void unregister(IPackageMoveObserver callback) { 15850 mCallbacks.unregister(callback); 15851 } 15852 15853 @Override 15854 public void handleMessage(Message msg) { 15855 final SomeArgs args = (SomeArgs) msg.obj; 15856 final int n = mCallbacks.beginBroadcast(); 15857 for (int i = 0; i < n; i++) { 15858 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15859 try { 15860 invokeCallback(callback, msg.what, args); 15861 } catch (RemoteException ignored) { 15862 } 15863 } 15864 mCallbacks.finishBroadcast(); 15865 args.recycle(); 15866 } 15867 15868 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15869 throws RemoteException { 15870 switch (what) { 15871 case MSG_CREATED: { 15872 callback.onCreated(args.argi1, (Bundle) args.arg2); 15873 break; 15874 } 15875 case MSG_STATUS_CHANGED: { 15876 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15877 break; 15878 } 15879 } 15880 } 15881 15882 private void notifyCreated(int moveId, Bundle extras) { 15883 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15884 15885 final SomeArgs args = SomeArgs.obtain(); 15886 args.argi1 = moveId; 15887 args.arg2 = extras; 15888 obtainMessage(MSG_CREATED, args).sendToTarget(); 15889 } 15890 15891 private void notifyStatusChanged(int moveId, int status) { 15892 notifyStatusChanged(moveId, status, -1); 15893 } 15894 15895 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15896 Slog.v(TAG, "Move " + moveId + " status " + status); 15897 15898 final SomeArgs args = SomeArgs.obtain(); 15899 args.argi1 = moveId; 15900 args.argi2 = status; 15901 args.arg3 = estMillis; 15902 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15903 15904 synchronized (mLastStatus) { 15905 mLastStatus.put(moveId, status); 15906 } 15907 } 15908 } 15909 15910 private final class OnPermissionChangeListeners extends Handler { 15911 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15912 15913 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15914 new RemoteCallbackList<>(); 15915 15916 public OnPermissionChangeListeners(Looper looper) { 15917 super(looper); 15918 } 15919 15920 @Override 15921 public void handleMessage(Message msg) { 15922 switch (msg.what) { 15923 case MSG_ON_PERMISSIONS_CHANGED: { 15924 final int uid = msg.arg1; 15925 handleOnPermissionsChanged(uid); 15926 } break; 15927 } 15928 } 15929 15930 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15931 mPermissionListeners.register(listener); 15932 15933 } 15934 15935 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15936 mPermissionListeners.unregister(listener); 15937 } 15938 15939 public void onPermissionsChanged(int uid) { 15940 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15941 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15942 } 15943 } 15944 15945 private void handleOnPermissionsChanged(int uid) { 15946 final int count = mPermissionListeners.beginBroadcast(); 15947 try { 15948 for (int i = 0; i < count; i++) { 15949 IOnPermissionsChangeListener callback = mPermissionListeners 15950 .getBroadcastItem(i); 15951 try { 15952 callback.onPermissionsChanged(uid); 15953 } catch (RemoteException e) { 15954 Log.e(TAG, "Permission listener is dead", e); 15955 } 15956 } 15957 } finally { 15958 mPermissionListeners.finishBroadcast(); 15959 } 15960 } 15961 } 15962 15963 private class PackageManagerInternalImpl extends PackageManagerInternal { 15964 @Override 15965 public void setLocationPackagesProvider(PackagesProvider provider) { 15966 synchronized (mPackages) { 15967 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15968 } 15969 } 15970 15971 @Override 15972 public void setImePackagesProvider(PackagesProvider provider) { 15973 synchronized (mPackages) { 15974 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15975 } 15976 } 15977 15978 @Override 15979 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15980 synchronized (mPackages) { 15981 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15982 } 15983 } 15984 15985 @Override 15986 public void setSmsAppPackagesProvider(PackagesProvider provider) { 15987 synchronized (mPackages) { 15988 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 15989 } 15990 } 15991 15992 @Override 15993 public void setDialerAppPackagesProvider(PackagesProvider provider) { 15994 synchronized (mPackages) { 15995 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 15996 } 15997 } 15998 15999 @Override 16000 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16001 synchronized (mPackages) { 16002 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16003 } 16004 } 16005 16006 @Override 16007 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16008 synchronized (mPackages) { 16009 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16010 packageName, userId); 16011 } 16012 } 16013 16014 @Override 16015 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16016 synchronized (mPackages) { 16017 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16018 packageName, userId); 16019 } 16020 } 16021 } 16022 16023 @Override 16024 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16025 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16026 synchronized (mPackages) { 16027 final long identity = Binder.clearCallingIdentity(); 16028 try { 16029 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16030 packageNames, userId); 16031 } finally { 16032 Binder.restoreCallingIdentity(identity); 16033 } 16034 } 16035 } 16036 16037 private static void enforceSystemOrPhoneCaller(String tag) { 16038 int callingUid = Binder.getCallingUid(); 16039 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16040 throw new SecurityException( 16041 "Cannot call " + tag + " from UID " + callingUid); 16042 } 16043 } 16044} 16045