PackageManagerService.java revision 5603e8981cf3a4f7b8590902485bb570d192ccf5
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.Manifest.permission.WRITE_MEDIA_STORAGE; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 28import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 29import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 30import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 37import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 38import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 39import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 40import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 43import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 45import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 47import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 48import static android.content.pm.PackageManager.INSTALL_INTERNAL; 49import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 53import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 54import static android.content.pm.PackageManager.MATCH_ALL; 55import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 56import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 57import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 58import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 59import static android.content.pm.PackageManager.PERMISSION_GRANTED; 60import static android.content.pm.PackageParser.isApkFile; 61import static android.os.Process.PACKAGE_INFO_GID; 62import static android.os.Process.SYSTEM_UID; 63import static android.system.OsConstants.O_CREAT; 64import static android.system.OsConstants.O_RDWR; 65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 66import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 67import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 68import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 69import static com.android.internal.util.ArrayUtils.appendInt; 70import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 72import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 73import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 74import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 75 76import android.Manifest; 77import android.app.ActivityManager; 78import android.app.ActivityManagerNative; 79import android.app.AppGlobals; 80import android.app.IActivityManager; 81import android.app.admin.IDevicePolicyManager; 82import android.app.backup.IBackupManager; 83import android.app.usage.UsageStats; 84import android.app.usage.UsageStatsManager; 85import android.content.BroadcastReceiver; 86import android.content.ComponentName; 87import android.content.Context; 88import android.content.IIntentReceiver; 89import android.content.Intent; 90import android.content.IntentFilter; 91import android.content.IntentSender; 92import android.content.IntentSender.SendIntentException; 93import android.content.ServiceConnection; 94import android.content.pm.ActivityInfo; 95import android.content.pm.ApplicationInfo; 96import android.content.pm.FeatureInfo; 97import android.content.pm.IOnPermissionsChangeListener; 98import android.content.pm.IPackageDataObserver; 99import android.content.pm.IPackageDeleteObserver; 100import android.content.pm.IPackageDeleteObserver2; 101import android.content.pm.IPackageInstallObserver2; 102import android.content.pm.IPackageInstaller; 103import android.content.pm.IPackageManager; 104import android.content.pm.IPackageMoveObserver; 105import android.content.pm.IPackageStatsObserver; 106import android.content.pm.InstrumentationInfo; 107import android.content.pm.IntentFilterVerificationInfo; 108import android.content.pm.KeySet; 109import android.content.pm.ManifestDigest; 110import android.content.pm.PackageCleanItem; 111import android.content.pm.PackageInfo; 112import android.content.pm.PackageInfoLite; 113import android.content.pm.PackageInstaller; 114import android.content.pm.PackageManager; 115import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 116import android.content.pm.PackageManagerInternal; 117import android.content.pm.PackageParser; 118import android.content.pm.PackageParser.ActivityIntentInfo; 119import android.content.pm.PackageParser.PackageLite; 120import android.content.pm.PackageParser.PackageParserException; 121import android.content.pm.PackageStats; 122import android.content.pm.PackageUserState; 123import android.content.pm.ParceledListSlice; 124import android.content.pm.PermissionGroupInfo; 125import android.content.pm.PermissionInfo; 126import android.content.pm.ProviderInfo; 127import android.content.pm.ResolveInfo; 128import android.content.pm.ServiceInfo; 129import android.content.pm.Signature; 130import android.content.pm.UserInfo; 131import android.content.pm.VerificationParams; 132import android.content.pm.VerifierDeviceIdentity; 133import android.content.pm.VerifierInfo; 134import android.content.res.Resources; 135import android.hardware.display.DisplayManager; 136import android.net.Uri; 137import android.os.Binder; 138import android.os.Build; 139import android.os.Bundle; 140import android.os.Debug; 141import android.os.Environment; 142import android.os.Environment.UserEnvironment; 143import android.os.FileUtils; 144import android.os.Handler; 145import android.os.IBinder; 146import android.os.Looper; 147import android.os.Message; 148import android.os.Parcel; 149import android.os.ParcelFileDescriptor; 150import android.os.Process; 151import android.os.RemoteCallbackList; 152import android.os.RemoteException; 153import android.os.SELinux; 154import android.os.ServiceManager; 155import android.os.SystemClock; 156import android.os.SystemProperties; 157import android.os.UserHandle; 158import android.os.UserManager; 159import android.os.storage.IMountService; 160import android.os.storage.StorageEventListener; 161import android.os.storage.StorageManager; 162import android.os.storage.VolumeInfo; 163import android.os.storage.VolumeRecord; 164import android.security.KeyStore; 165import android.security.SystemKeyStore; 166import android.system.ErrnoException; 167import android.system.Os; 168import android.system.StructStat; 169import android.text.TextUtils; 170import android.text.format.DateUtils; 171import android.util.ArrayMap; 172import android.util.ArraySet; 173import android.util.AtomicFile; 174import android.util.DisplayMetrics; 175import android.util.EventLog; 176import android.util.ExceptionUtils; 177import android.util.Log; 178import android.util.LogPrinter; 179import android.util.MathUtils; 180import android.util.PrintStreamPrinter; 181import android.util.Slog; 182import android.util.SparseArray; 183import android.util.SparseBooleanArray; 184import android.util.SparseIntArray; 185import android.util.Xml; 186import android.view.Display; 187 188import dalvik.system.DexFile; 189import dalvik.system.VMRuntime; 190 191import libcore.io.IoUtils; 192import libcore.util.EmptyArray; 193 194import com.android.internal.R; 195import com.android.internal.annotations.GuardedBy; 196import com.android.internal.app.IMediaContainerService; 197import com.android.internal.app.ResolverActivity; 198import com.android.internal.content.NativeLibraryHelper; 199import com.android.internal.content.PackageHelper; 200import com.android.internal.os.IParcelFileDescriptorFactory; 201import com.android.internal.os.SomeArgs; 202import com.android.internal.os.Zygote; 203import com.android.internal.util.ArrayUtils; 204import com.android.internal.util.FastPrintWriter; 205import com.android.internal.util.FastXmlSerializer; 206import com.android.internal.util.IndentingPrintWriter; 207import com.android.internal.util.Preconditions; 208import com.android.server.EventLogTags; 209import com.android.server.FgThread; 210import com.android.server.IntentResolver; 211import com.android.server.LocalServices; 212import com.android.server.ServiceThread; 213import com.android.server.SystemConfig; 214import com.android.server.Watchdog; 215import com.android.server.pm.PermissionsState.PermissionState; 216import com.android.server.pm.Settings.DatabaseVersion; 217import com.android.server.storage.DeviceStorageMonitorInternal; 218 219import org.xmlpull.v1.XmlPullParser; 220import org.xmlpull.v1.XmlPullParserException; 221import org.xmlpull.v1.XmlSerializer; 222 223import java.io.BufferedInputStream; 224import java.io.BufferedOutputStream; 225import java.io.BufferedReader; 226import java.io.ByteArrayInputStream; 227import java.io.ByteArrayOutputStream; 228import java.io.File; 229import java.io.FileDescriptor; 230import java.io.FileNotFoundException; 231import java.io.FileOutputStream; 232import java.io.FileReader; 233import java.io.FilenameFilter; 234import java.io.IOException; 235import java.io.InputStream; 236import java.io.PrintWriter; 237import java.nio.charset.StandardCharsets; 238import java.security.NoSuchAlgorithmException; 239import java.security.PublicKey; 240import java.security.cert.CertificateEncodingException; 241import java.security.cert.CertificateException; 242import java.text.SimpleDateFormat; 243import java.util.ArrayList; 244import java.util.Arrays; 245import java.util.Collection; 246import java.util.Collections; 247import java.util.Comparator; 248import java.util.Date; 249import java.util.Iterator; 250import java.util.List; 251import java.util.Map; 252import java.util.Objects; 253import java.util.Set; 254import java.util.concurrent.CountDownLatch; 255import java.util.concurrent.TimeUnit; 256import java.util.concurrent.atomic.AtomicBoolean; 257import java.util.concurrent.atomic.AtomicInteger; 258import java.util.concurrent.atomic.AtomicLong; 259 260/** 261 * Keep track of all those .apks everywhere. 262 * 263 * This is very central to the platform's security; please run the unit 264 * tests whenever making modifications here: 265 * 266runtest -c android.content.pm.PackageManagerTests frameworks-core 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 @GuardedBy("mInstallLock") 434 final Installer mInstaller; 435 436 /** Directory where installed third-party apps stored */ 437 final File mAppInstallDir; 438 439 /** 440 * Directory to which applications installed internally have their 441 * 32 bit native libraries copied. 442 */ 443 private File mAppLib32InstallDir; 444 445 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 446 // apps. 447 final File mDrmAppPrivateInstallDir; 448 449 // ---------------------------------------------------------------- 450 451 // Lock for state used when installing and doing other long running 452 // operations. Methods that must be called with this lock held have 453 // the suffix "LI". 454 final Object mInstallLock = new Object(); 455 456 // ---------------------------------------------------------------- 457 458 // Keys are String (package name), values are Package. This also serves 459 // as the lock for the global state. Methods that must be called with 460 // this lock held have the prefix "LP". 461 @GuardedBy("mPackages") 462 final ArrayMap<String, PackageParser.Package> mPackages = 463 new ArrayMap<String, PackageParser.Package>(); 464 465 // Tracks available target package names -> overlay package paths. 466 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 467 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 468 469 final Settings mSettings; 470 boolean mRestoredSettings; 471 472 // System configuration read by SystemConfig. 473 final int[] mGlobalGids; 474 final SparseArray<ArraySet<String>> mSystemPermissions; 475 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 476 477 // If mac_permissions.xml was found for seinfo labeling. 478 boolean mFoundPolicyFile; 479 480 // If a recursive restorecon of /data/data/<pkg> is needed. 481 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 482 483 public static final class SharedLibraryEntry { 484 public final String path; 485 public final String apk; 486 487 SharedLibraryEntry(String _path, String _apk) { 488 path = _path; 489 apk = _apk; 490 } 491 } 492 493 // Currently known shared libraries. 494 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 495 new ArrayMap<String, SharedLibraryEntry>(); 496 497 // All available activities, for your resolving pleasure. 498 final ActivityIntentResolver mActivities = 499 new ActivityIntentResolver(); 500 501 // All available receivers, for your resolving pleasure. 502 final ActivityIntentResolver mReceivers = 503 new ActivityIntentResolver(); 504 505 // All available services, for your resolving pleasure. 506 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 507 508 // All available providers, for your resolving pleasure. 509 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 510 511 // Mapping from provider base names (first directory in content URI codePath) 512 // to the provider information. 513 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 514 new ArrayMap<String, PackageParser.Provider>(); 515 516 // Mapping from instrumentation class names to info about them. 517 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 518 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 519 520 // Mapping from permission names to info about them. 521 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 522 new ArrayMap<String, PackageParser.PermissionGroup>(); 523 524 // Packages whose data we have transfered into another package, thus 525 // should no longer exist. 526 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 527 528 // Broadcast actions that are only available to the system. 529 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 530 531 /** List of packages waiting for verification. */ 532 final SparseArray<PackageVerificationState> mPendingVerification 533 = new SparseArray<PackageVerificationState>(); 534 535 /** Set of packages associated with each app op permission. */ 536 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 537 538 final PackageInstallerService mInstallerService; 539 540 private final PackageDexOptimizer mPackageDexOptimizer; 541 542 private AtomicInteger mNextMoveId = new AtomicInteger(); 543 private final MoveCallbacks mMoveCallbacks; 544 545 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 546 547 // Cache of users who need badging. 548 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 549 550 /** Token for keys in mPendingVerification. */ 551 private int mPendingVerificationToken = 0; 552 553 volatile boolean mSystemReady; 554 volatile boolean mSafeMode; 555 volatile boolean mHasSystemUidErrors; 556 557 ApplicationInfo mAndroidApplication; 558 final ActivityInfo mResolveActivity = new ActivityInfo(); 559 final ResolveInfo mResolveInfo = new ResolveInfo(); 560 ComponentName mResolveComponentName; 561 PackageParser.Package mPlatformPackage; 562 ComponentName mCustomResolverComponentName; 563 564 boolean mResolverReplaced = false; 565 566 private final ComponentName mIntentFilterVerifierComponent; 567 private int mIntentFilterVerificationToken = 0; 568 569 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 570 = new SparseArray<IntentFilterVerificationState>(); 571 572 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 573 new DefaultPermissionGrantPolicy(this); 574 575 private static class IFVerificationParams { 576 PackageParser.Package pkg; 577 boolean replacing; 578 int userId; 579 int verifierUid; 580 581 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 582 int _userId, int _verifierUid) { 583 pkg = _pkg; 584 replacing = _replacing; 585 userId = _userId; 586 replacing = _replacing; 587 verifierUid = _verifierUid; 588 } 589 } 590 591 private interface IntentFilterVerifier<T extends IntentFilter> { 592 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 593 T filter, String packageName); 594 void startVerifications(int userId); 595 void receiveVerificationResponse(int verificationId); 596 } 597 598 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 599 private Context mContext; 600 private ComponentName mIntentFilterVerifierComponent; 601 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 602 603 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 604 mContext = context; 605 mIntentFilterVerifierComponent = verifierComponent; 606 } 607 608 private String getDefaultScheme() { 609 return IntentFilter.SCHEME_HTTPS; 610 } 611 612 @Override 613 public void startVerifications(int userId) { 614 // Launch verifications requests 615 int count = mCurrentIntentFilterVerifications.size(); 616 for (int n=0; n<count; n++) { 617 int verificationId = mCurrentIntentFilterVerifications.get(n); 618 final IntentFilterVerificationState ivs = 619 mIntentFilterVerificationStates.get(verificationId); 620 621 String packageName = ivs.getPackageName(); 622 623 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 624 final int filterCount = filters.size(); 625 ArraySet<String> domainsSet = new ArraySet<>(); 626 for (int m=0; m<filterCount; m++) { 627 PackageParser.ActivityIntentInfo filter = filters.get(m); 628 domainsSet.addAll(filter.getHostsList()); 629 } 630 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 631 synchronized (mPackages) { 632 if (mSettings.createIntentFilterVerificationIfNeededLPw( 633 packageName, domainsList) != null) { 634 scheduleWriteSettingsLocked(); 635 } 636 } 637 sendVerificationRequest(userId, verificationId, ivs); 638 } 639 mCurrentIntentFilterVerifications.clear(); 640 } 641 642 private void sendVerificationRequest(int userId, int verificationId, 643 IntentFilterVerificationState ivs) { 644 645 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 646 verificationIntent.putExtra( 647 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 648 verificationId); 649 verificationIntent.putExtra( 650 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 651 getDefaultScheme()); 652 verificationIntent.putExtra( 653 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 654 ivs.getHostsString()); 655 verificationIntent.putExtra( 656 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 657 ivs.getPackageName()); 658 verificationIntent.setComponent(mIntentFilterVerifierComponent); 659 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 660 661 UserHandle user = new UserHandle(userId); 662 mContext.sendBroadcastAsUser(verificationIntent, user); 663 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 664 "Sending IntentFilter verification broadcast"); 665 } 666 667 public void receiveVerificationResponse(int verificationId) { 668 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 669 670 final boolean verified = ivs.isVerified(); 671 672 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 673 final int count = filters.size(); 674 if (DEBUG_DOMAIN_VERIFICATION) { 675 Slog.i(TAG, "Received verification response " + verificationId 676 + " for " + count + " filters, verified=" + verified); 677 } 678 for (int n=0; n<count; n++) { 679 PackageParser.ActivityIntentInfo filter = filters.get(n); 680 filter.setVerified(verified); 681 682 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 683 + " verified with result:" + verified + " and hosts:" 684 + ivs.getHostsString()); 685 } 686 687 mIntentFilterVerificationStates.remove(verificationId); 688 689 final String packageName = ivs.getPackageName(); 690 IntentFilterVerificationInfo ivi = null; 691 692 synchronized (mPackages) { 693 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 694 } 695 if (ivi == null) { 696 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 697 + verificationId + " packageName:" + packageName); 698 return; 699 } 700 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 701 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 702 703 synchronized (mPackages) { 704 if (verified) { 705 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 706 } else { 707 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 708 } 709 scheduleWriteSettingsLocked(); 710 711 final int userId = ivs.getUserId(); 712 if (userId != UserHandle.USER_ALL) { 713 final int userStatus = 714 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 715 716 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 717 boolean needUpdate = false; 718 719 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 720 // already been set by the User thru the Disambiguation dialog 721 switch (userStatus) { 722 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 723 if (verified) { 724 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 725 } else { 726 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 727 } 728 needUpdate = true; 729 break; 730 731 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 732 if (verified) { 733 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 734 needUpdate = true; 735 } 736 break; 737 738 default: 739 // Nothing to do 740 } 741 742 if (needUpdate) { 743 mSettings.updateIntentFilterVerificationStatusLPw( 744 packageName, updatedStatus, userId); 745 scheduleWritePackageRestrictionsLocked(userId); 746 } 747 } 748 } 749 } 750 751 @Override 752 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 753 ActivityIntentInfo filter, String packageName) { 754 if (!hasValidDomains(filter)) { 755 return false; 756 } 757 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 758 if (ivs == null) { 759 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 760 packageName); 761 } 762 if (DEBUG_DOMAIN_VERIFICATION) { 763 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 764 } 765 ivs.addFilter(filter); 766 return true; 767 } 768 769 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 770 int userId, int verificationId, String packageName) { 771 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 772 verifierUid, userId, packageName); 773 ivs.setPendingState(); 774 synchronized (mPackages) { 775 mIntentFilterVerificationStates.append(verificationId, ivs); 776 mCurrentIntentFilterVerifications.add(verificationId); 777 } 778 return ivs; 779 } 780 } 781 782 private static boolean hasValidDomains(ActivityIntentInfo filter) { 783 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 784 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 785 if (!hasHTTPorHTTPS) { 786 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 787 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 788 return false; 789 } 790 return true; 791 } 792 793 private IntentFilterVerifier mIntentFilterVerifier; 794 795 // Set of pending broadcasts for aggregating enable/disable of components. 796 static class PendingPackageBroadcasts { 797 // for each user id, a map of <package name -> components within that package> 798 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 799 800 public PendingPackageBroadcasts() { 801 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 802 } 803 804 public ArrayList<String> get(int userId, String packageName) { 805 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 806 return packages.get(packageName); 807 } 808 809 public void put(int userId, String packageName, ArrayList<String> components) { 810 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 811 packages.put(packageName, components); 812 } 813 814 public void remove(int userId, String packageName) { 815 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 816 if (packages != null) { 817 packages.remove(packageName); 818 } 819 } 820 821 public void remove(int userId) { 822 mUidMap.remove(userId); 823 } 824 825 public int userIdCount() { 826 return mUidMap.size(); 827 } 828 829 public int userIdAt(int n) { 830 return mUidMap.keyAt(n); 831 } 832 833 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 834 return mUidMap.get(userId); 835 } 836 837 public int size() { 838 // total number of pending broadcast entries across all userIds 839 int num = 0; 840 for (int i = 0; i< mUidMap.size(); i++) { 841 num += mUidMap.valueAt(i).size(); 842 } 843 return num; 844 } 845 846 public void clear() { 847 mUidMap.clear(); 848 } 849 850 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 851 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 852 if (map == null) { 853 map = new ArrayMap<String, ArrayList<String>>(); 854 mUidMap.put(userId, map); 855 } 856 return map; 857 } 858 } 859 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 860 861 // Service Connection to remote media container service to copy 862 // package uri's from external media onto secure containers 863 // or internal storage. 864 private IMediaContainerService mContainerService = null; 865 866 static final int SEND_PENDING_BROADCAST = 1; 867 static final int MCS_BOUND = 3; 868 static final int END_COPY = 4; 869 static final int INIT_COPY = 5; 870 static final int MCS_UNBIND = 6; 871 static final int START_CLEANING_PACKAGE = 7; 872 static final int FIND_INSTALL_LOC = 8; 873 static final int POST_INSTALL = 9; 874 static final int MCS_RECONNECT = 10; 875 static final int MCS_GIVE_UP = 11; 876 static final int UPDATED_MEDIA_STATUS = 12; 877 static final int WRITE_SETTINGS = 13; 878 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 879 static final int PACKAGE_VERIFIED = 15; 880 static final int CHECK_PENDING_VERIFICATION = 16; 881 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 882 static final int INTENT_FILTER_VERIFIED = 18; 883 884 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 885 886 // Delay time in millisecs 887 static final int BROADCAST_DELAY = 10 * 1000; 888 889 static UserManagerService sUserManager; 890 891 // Stores a list of users whose package restrictions file needs to be updated 892 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 893 894 final private DefaultContainerConnection mDefContainerConn = 895 new DefaultContainerConnection(); 896 class DefaultContainerConnection implements ServiceConnection { 897 public void onServiceConnected(ComponentName name, IBinder service) { 898 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 899 IMediaContainerService imcs = 900 IMediaContainerService.Stub.asInterface(service); 901 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 902 } 903 904 public void onServiceDisconnected(ComponentName name) { 905 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 906 } 907 } 908 909 // Recordkeeping of restore-after-install operations that are currently in flight 910 // between the Package Manager and the Backup Manager 911 class PostInstallData { 912 public InstallArgs args; 913 public PackageInstalledInfo res; 914 915 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 916 args = _a; 917 res = _r; 918 } 919 } 920 921 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 922 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 923 924 // XML tags for backup/restore of various bits of state 925 private static final String TAG_PREFERRED_BACKUP = "pa"; 926 private static final String TAG_DEFAULT_APPS = "da"; 927 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 928 929 private final String mRequiredVerifierPackage; 930 931 private final PackageUsage mPackageUsage = new PackageUsage(); 932 933 private class PackageUsage { 934 private static final int WRITE_INTERVAL 935 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 936 937 private final Object mFileLock = new Object(); 938 private final AtomicLong mLastWritten = new AtomicLong(0); 939 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 940 941 private boolean mIsHistoricalPackageUsageAvailable = true; 942 943 boolean isHistoricalPackageUsageAvailable() { 944 return mIsHistoricalPackageUsageAvailable; 945 } 946 947 void write(boolean force) { 948 if (force) { 949 writeInternal(); 950 return; 951 } 952 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 953 && !DEBUG_DEXOPT) { 954 return; 955 } 956 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 957 new Thread("PackageUsage_DiskWriter") { 958 @Override 959 public void run() { 960 try { 961 writeInternal(); 962 } finally { 963 mBackgroundWriteRunning.set(false); 964 } 965 } 966 }.start(); 967 } 968 } 969 970 private void writeInternal() { 971 synchronized (mPackages) { 972 synchronized (mFileLock) { 973 AtomicFile file = getFile(); 974 FileOutputStream f = null; 975 try { 976 f = file.startWrite(); 977 BufferedOutputStream out = new BufferedOutputStream(f); 978 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 979 StringBuilder sb = new StringBuilder(); 980 for (PackageParser.Package pkg : mPackages.values()) { 981 if (pkg.mLastPackageUsageTimeInMills == 0) { 982 continue; 983 } 984 sb.setLength(0); 985 sb.append(pkg.packageName); 986 sb.append(' '); 987 sb.append((long)pkg.mLastPackageUsageTimeInMills); 988 sb.append('\n'); 989 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 990 } 991 out.flush(); 992 file.finishWrite(f); 993 } catch (IOException e) { 994 if (f != null) { 995 file.failWrite(f); 996 } 997 Log.e(TAG, "Failed to write package usage times", e); 998 } 999 } 1000 } 1001 mLastWritten.set(SystemClock.elapsedRealtime()); 1002 } 1003 1004 void readLP() { 1005 synchronized (mFileLock) { 1006 AtomicFile file = getFile(); 1007 BufferedInputStream in = null; 1008 try { 1009 in = new BufferedInputStream(file.openRead()); 1010 StringBuffer sb = new StringBuffer(); 1011 while (true) { 1012 String packageName = readToken(in, sb, ' '); 1013 if (packageName == null) { 1014 break; 1015 } 1016 String timeInMillisString = readToken(in, sb, '\n'); 1017 if (timeInMillisString == null) { 1018 throw new IOException("Failed to find last usage time for package " 1019 + packageName); 1020 } 1021 PackageParser.Package pkg = mPackages.get(packageName); 1022 if (pkg == null) { 1023 continue; 1024 } 1025 long timeInMillis; 1026 try { 1027 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1028 } catch (NumberFormatException e) { 1029 throw new IOException("Failed to parse " + timeInMillisString 1030 + " as a long.", e); 1031 } 1032 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1033 } 1034 } catch (FileNotFoundException expected) { 1035 mIsHistoricalPackageUsageAvailable = false; 1036 } catch (IOException e) { 1037 Log.w(TAG, "Failed to read package usage times", e); 1038 } finally { 1039 IoUtils.closeQuietly(in); 1040 } 1041 } 1042 mLastWritten.set(SystemClock.elapsedRealtime()); 1043 } 1044 1045 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1046 throws IOException { 1047 sb.setLength(0); 1048 while (true) { 1049 int ch = in.read(); 1050 if (ch == -1) { 1051 if (sb.length() == 0) { 1052 return null; 1053 } 1054 throw new IOException("Unexpected EOF"); 1055 } 1056 if (ch == endOfToken) { 1057 return sb.toString(); 1058 } 1059 sb.append((char)ch); 1060 } 1061 } 1062 1063 private AtomicFile getFile() { 1064 File dataDir = Environment.getDataDirectory(); 1065 File systemDir = new File(dataDir, "system"); 1066 File fname = new File(systemDir, "package-usage.list"); 1067 return new AtomicFile(fname); 1068 } 1069 } 1070 1071 class PackageHandler extends Handler { 1072 private boolean mBound = false; 1073 final ArrayList<HandlerParams> mPendingInstalls = 1074 new ArrayList<HandlerParams>(); 1075 1076 private boolean connectToService() { 1077 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1078 " DefaultContainerService"); 1079 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1080 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1081 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1082 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1083 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1084 mBound = true; 1085 return true; 1086 } 1087 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1088 return false; 1089 } 1090 1091 private void disconnectService() { 1092 mContainerService = null; 1093 mBound = false; 1094 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1095 mContext.unbindService(mDefContainerConn); 1096 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1097 } 1098 1099 PackageHandler(Looper looper) { 1100 super(looper); 1101 } 1102 1103 public void handleMessage(Message msg) { 1104 try { 1105 doHandleMessage(msg); 1106 } finally { 1107 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1108 } 1109 } 1110 1111 void doHandleMessage(Message msg) { 1112 switch (msg.what) { 1113 case INIT_COPY: { 1114 HandlerParams params = (HandlerParams) msg.obj; 1115 int idx = mPendingInstalls.size(); 1116 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1117 // If a bind was already initiated we dont really 1118 // need to do anything. The pending install 1119 // will be processed later on. 1120 if (!mBound) { 1121 // If this is the only one pending we might 1122 // have to bind to the service again. 1123 if (!connectToService()) { 1124 Slog.e(TAG, "Failed to bind to media container service"); 1125 params.serviceError(); 1126 return; 1127 } else { 1128 // Once we bind to the service, the first 1129 // pending request will be processed. 1130 mPendingInstalls.add(idx, params); 1131 } 1132 } else { 1133 mPendingInstalls.add(idx, params); 1134 // Already bound to the service. Just make 1135 // sure we trigger off processing the first request. 1136 if (idx == 0) { 1137 mHandler.sendEmptyMessage(MCS_BOUND); 1138 } 1139 } 1140 break; 1141 } 1142 case MCS_BOUND: { 1143 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1144 if (msg.obj != null) { 1145 mContainerService = (IMediaContainerService) msg.obj; 1146 } 1147 if (mContainerService == null) { 1148 if (!mBound) { 1149 // Something seriously wrong since we are not bound and we are not 1150 // waiting for connection. Bail out. 1151 Slog.e(TAG, "Cannot bind to media container service"); 1152 for (HandlerParams params : mPendingInstalls) { 1153 // Indicate service bind error 1154 params.serviceError(); 1155 } 1156 mPendingInstalls.clear(); 1157 } else { 1158 Slog.w(TAG, "Waiting to connect to media container service"); 1159 } 1160 } else if (mPendingInstalls.size() > 0) { 1161 HandlerParams params = mPendingInstalls.get(0); 1162 if (params != null) { 1163 if (params.startCopy()) { 1164 // We are done... look for more work or to 1165 // go idle. 1166 if (DEBUG_SD_INSTALL) Log.i(TAG, 1167 "Checking for more work or unbind..."); 1168 // Delete pending install 1169 if (mPendingInstalls.size() > 0) { 1170 mPendingInstalls.remove(0); 1171 } 1172 if (mPendingInstalls.size() == 0) { 1173 if (mBound) { 1174 if (DEBUG_SD_INSTALL) Log.i(TAG, 1175 "Posting delayed MCS_UNBIND"); 1176 removeMessages(MCS_UNBIND); 1177 Message ubmsg = obtainMessage(MCS_UNBIND); 1178 // Unbind after a little delay, to avoid 1179 // continual thrashing. 1180 sendMessageDelayed(ubmsg, 10000); 1181 } 1182 } else { 1183 // There are more pending requests in queue. 1184 // Just post MCS_BOUND message to trigger processing 1185 // of next pending install. 1186 if (DEBUG_SD_INSTALL) Log.i(TAG, 1187 "Posting MCS_BOUND for next work"); 1188 mHandler.sendEmptyMessage(MCS_BOUND); 1189 } 1190 } 1191 } 1192 } else { 1193 // Should never happen ideally. 1194 Slog.w(TAG, "Empty queue"); 1195 } 1196 break; 1197 } 1198 case MCS_RECONNECT: { 1199 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1200 if (mPendingInstalls.size() > 0) { 1201 if (mBound) { 1202 disconnectService(); 1203 } 1204 if (!connectToService()) { 1205 Slog.e(TAG, "Failed to bind to media container service"); 1206 for (HandlerParams params : mPendingInstalls) { 1207 // Indicate service bind error 1208 params.serviceError(); 1209 } 1210 mPendingInstalls.clear(); 1211 } 1212 } 1213 break; 1214 } 1215 case MCS_UNBIND: { 1216 // If there is no actual work left, then time to unbind. 1217 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1218 1219 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1220 if (mBound) { 1221 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1222 1223 disconnectService(); 1224 } 1225 } else if (mPendingInstalls.size() > 0) { 1226 // There are more pending requests in queue. 1227 // Just post MCS_BOUND message to trigger processing 1228 // of next pending install. 1229 mHandler.sendEmptyMessage(MCS_BOUND); 1230 } 1231 1232 break; 1233 } 1234 case MCS_GIVE_UP: { 1235 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1236 mPendingInstalls.remove(0); 1237 break; 1238 } 1239 case SEND_PENDING_BROADCAST: { 1240 String packages[]; 1241 ArrayList<String> components[]; 1242 int size = 0; 1243 int uids[]; 1244 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1245 synchronized (mPackages) { 1246 if (mPendingBroadcasts == null) { 1247 return; 1248 } 1249 size = mPendingBroadcasts.size(); 1250 if (size <= 0) { 1251 // Nothing to be done. Just return 1252 return; 1253 } 1254 packages = new String[size]; 1255 components = new ArrayList[size]; 1256 uids = new int[size]; 1257 int i = 0; // filling out the above arrays 1258 1259 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1260 int packageUserId = mPendingBroadcasts.userIdAt(n); 1261 Iterator<Map.Entry<String, ArrayList<String>>> it 1262 = mPendingBroadcasts.packagesForUserId(packageUserId) 1263 .entrySet().iterator(); 1264 while (it.hasNext() && i < size) { 1265 Map.Entry<String, ArrayList<String>> ent = it.next(); 1266 packages[i] = ent.getKey(); 1267 components[i] = ent.getValue(); 1268 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1269 uids[i] = (ps != null) 1270 ? UserHandle.getUid(packageUserId, ps.appId) 1271 : -1; 1272 i++; 1273 } 1274 } 1275 size = i; 1276 mPendingBroadcasts.clear(); 1277 } 1278 // Send broadcasts 1279 for (int i = 0; i < size; i++) { 1280 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1281 } 1282 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1283 break; 1284 } 1285 case START_CLEANING_PACKAGE: { 1286 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1287 final String packageName = (String)msg.obj; 1288 final int userId = msg.arg1; 1289 final boolean andCode = msg.arg2 != 0; 1290 synchronized (mPackages) { 1291 if (userId == UserHandle.USER_ALL) { 1292 int[] users = sUserManager.getUserIds(); 1293 for (int user : users) { 1294 mSettings.addPackageToCleanLPw( 1295 new PackageCleanItem(user, packageName, andCode)); 1296 } 1297 } else { 1298 mSettings.addPackageToCleanLPw( 1299 new PackageCleanItem(userId, packageName, andCode)); 1300 } 1301 } 1302 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1303 startCleaningPackages(); 1304 } break; 1305 case POST_INSTALL: { 1306 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1307 PostInstallData data = mRunningInstalls.get(msg.arg1); 1308 mRunningInstalls.delete(msg.arg1); 1309 boolean deleteOld = false; 1310 1311 if (data != null) { 1312 InstallArgs args = data.args; 1313 PackageInstalledInfo res = data.res; 1314 1315 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1316 final String packageName = res.pkg.applicationInfo.packageName; 1317 res.removedInfo.sendBroadcast(false, true, false); 1318 Bundle extras = new Bundle(1); 1319 extras.putInt(Intent.EXTRA_UID, res.uid); 1320 1321 // Now that we successfully installed the package, grant runtime 1322 // permissions if requested before broadcasting the install. 1323 if ((args.installFlags 1324 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1325 grantRequestedRuntimePermissions(res.pkg, 1326 args.user.getIdentifier()); 1327 } 1328 1329 // Determine the set of users who are adding this 1330 // package for the first time vs. those who are seeing 1331 // an update. 1332 int[] firstUsers; 1333 int[] updateUsers = new int[0]; 1334 if (res.origUsers == null || res.origUsers.length == 0) { 1335 firstUsers = res.newUsers; 1336 } else { 1337 firstUsers = new int[0]; 1338 for (int i=0; i<res.newUsers.length; i++) { 1339 int user = res.newUsers[i]; 1340 boolean isNew = true; 1341 for (int j=0; j<res.origUsers.length; j++) { 1342 if (res.origUsers[j] == user) { 1343 isNew = false; 1344 break; 1345 } 1346 } 1347 if (isNew) { 1348 int[] newFirst = new int[firstUsers.length+1]; 1349 System.arraycopy(firstUsers, 0, newFirst, 0, 1350 firstUsers.length); 1351 newFirst[firstUsers.length] = user; 1352 firstUsers = newFirst; 1353 } else { 1354 int[] newUpdate = new int[updateUsers.length+1]; 1355 System.arraycopy(updateUsers, 0, newUpdate, 0, 1356 updateUsers.length); 1357 newUpdate[updateUsers.length] = user; 1358 updateUsers = newUpdate; 1359 } 1360 } 1361 } 1362 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1363 packageName, extras, null, null, firstUsers); 1364 final boolean update = res.removedInfo.removedPackage != null; 1365 if (update) { 1366 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1367 } 1368 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1369 packageName, extras, null, null, updateUsers); 1370 if (update) { 1371 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1372 packageName, extras, null, null, updateUsers); 1373 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1374 null, null, packageName, null, updateUsers); 1375 1376 // treat asec-hosted packages like removable media on upgrade 1377 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1378 if (DEBUG_INSTALL) { 1379 Slog.i(TAG, "upgrading pkg " + res.pkg 1380 + " is ASEC-hosted -> AVAILABLE"); 1381 } 1382 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1383 ArrayList<String> pkgList = new ArrayList<String>(1); 1384 pkgList.add(packageName); 1385 sendResourcesChangedBroadcast(true, true, 1386 pkgList,uidArray, null); 1387 } 1388 } 1389 if (res.removedInfo.args != null) { 1390 // Remove the replaced package's older resources safely now 1391 deleteOld = true; 1392 } 1393 1394 // If this app is a browser and it's newly-installed for some 1395 // users, clear any default-browser state in those users 1396 if (firstUsers.length > 0) { 1397 // the app's nature doesn't depend on the user, so we can just 1398 // check its browser nature in any user and generalize. 1399 if (packageIsBrowser(packageName, firstUsers[0])) { 1400 synchronized (mPackages) { 1401 for (int userId : firstUsers) { 1402 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1403 } 1404 } 1405 } 1406 } 1407 // Log current value of "unknown sources" setting 1408 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1409 getUnknownSourcesSettings()); 1410 } 1411 // Force a gc to clear up things 1412 Runtime.getRuntime().gc(); 1413 // We delete after a gc for applications on sdcard. 1414 if (deleteOld) { 1415 synchronized (mInstallLock) { 1416 res.removedInfo.args.doPostDeleteLI(true); 1417 } 1418 } 1419 if (args.observer != null) { 1420 try { 1421 Bundle extras = extrasForInstallResult(res); 1422 args.observer.onPackageInstalled(res.name, res.returnCode, 1423 res.returnMsg, extras); 1424 } catch (RemoteException e) { 1425 Slog.i(TAG, "Observer no longer exists."); 1426 } 1427 } 1428 } else { 1429 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1430 } 1431 } break; 1432 case UPDATED_MEDIA_STATUS: { 1433 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1434 boolean reportStatus = msg.arg1 == 1; 1435 boolean doGc = msg.arg2 == 1; 1436 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1437 if (doGc) { 1438 // Force a gc to clear up stale containers. 1439 Runtime.getRuntime().gc(); 1440 } 1441 if (msg.obj != null) { 1442 @SuppressWarnings("unchecked") 1443 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1444 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1445 // Unload containers 1446 unloadAllContainers(args); 1447 } 1448 if (reportStatus) { 1449 try { 1450 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1451 PackageHelper.getMountService().finishMediaUpdate(); 1452 } catch (RemoteException e) { 1453 Log.e(TAG, "MountService not running?"); 1454 } 1455 } 1456 } break; 1457 case WRITE_SETTINGS: { 1458 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1459 synchronized (mPackages) { 1460 removeMessages(WRITE_SETTINGS); 1461 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1462 mSettings.writeLPr(); 1463 mDirtyUsers.clear(); 1464 } 1465 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1466 } break; 1467 case WRITE_PACKAGE_RESTRICTIONS: { 1468 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1469 synchronized (mPackages) { 1470 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1471 for (int userId : mDirtyUsers) { 1472 mSettings.writePackageRestrictionsLPr(userId); 1473 } 1474 mDirtyUsers.clear(); 1475 } 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1477 } break; 1478 case CHECK_PENDING_VERIFICATION: { 1479 final int verificationId = msg.arg1; 1480 final PackageVerificationState state = mPendingVerification.get(verificationId); 1481 1482 if ((state != null) && !state.timeoutExtended()) { 1483 final InstallArgs args = state.getInstallArgs(); 1484 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1485 1486 Slog.i(TAG, "Verification timed out for " + originUri); 1487 mPendingVerification.remove(verificationId); 1488 1489 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1490 1491 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1492 Slog.i(TAG, "Continuing with installation of " + originUri); 1493 state.setVerifierResponse(Binder.getCallingUid(), 1494 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1495 broadcastPackageVerified(verificationId, originUri, 1496 PackageManager.VERIFICATION_ALLOW, 1497 state.getInstallArgs().getUser()); 1498 try { 1499 ret = args.copyApk(mContainerService, true); 1500 } catch (RemoteException e) { 1501 Slog.e(TAG, "Could not contact the ContainerService"); 1502 } 1503 } else { 1504 broadcastPackageVerified(verificationId, originUri, 1505 PackageManager.VERIFICATION_REJECT, 1506 state.getInstallArgs().getUser()); 1507 } 1508 1509 processPendingInstall(args, ret); 1510 mHandler.sendEmptyMessage(MCS_UNBIND); 1511 } 1512 break; 1513 } 1514 case PACKAGE_VERIFIED: { 1515 final int verificationId = msg.arg1; 1516 1517 final PackageVerificationState state = mPendingVerification.get(verificationId); 1518 if (state == null) { 1519 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1520 break; 1521 } 1522 1523 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1524 1525 state.setVerifierResponse(response.callerUid, response.code); 1526 1527 if (state.isVerificationComplete()) { 1528 mPendingVerification.remove(verificationId); 1529 1530 final InstallArgs args = state.getInstallArgs(); 1531 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1532 1533 int ret; 1534 if (state.isInstallAllowed()) { 1535 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1536 broadcastPackageVerified(verificationId, originUri, 1537 response.code, state.getInstallArgs().getUser()); 1538 try { 1539 ret = args.copyApk(mContainerService, true); 1540 } catch (RemoteException e) { 1541 Slog.e(TAG, "Could not contact the ContainerService"); 1542 } 1543 } else { 1544 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1545 } 1546 1547 processPendingInstall(args, ret); 1548 1549 mHandler.sendEmptyMessage(MCS_UNBIND); 1550 } 1551 1552 break; 1553 } 1554 case START_INTENT_FILTER_VERIFICATIONS: { 1555 IFVerificationParams params = (IFVerificationParams) msg.obj; 1556 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1557 params.replacing, params.pkg); 1558 break; 1559 } 1560 case INTENT_FILTER_VERIFIED: { 1561 final int verificationId = msg.arg1; 1562 1563 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1564 verificationId); 1565 if (state == null) { 1566 Slog.w(TAG, "Invalid IntentFilter verification token " 1567 + verificationId + " received"); 1568 break; 1569 } 1570 1571 final int userId = state.getUserId(); 1572 1573 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1574 "Processing IntentFilter verification with token:" 1575 + verificationId + " and userId:" + userId); 1576 1577 final IntentFilterVerificationResponse response = 1578 (IntentFilterVerificationResponse) msg.obj; 1579 1580 state.setVerifierResponse(response.callerUid, response.code); 1581 1582 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1583 "IntentFilter verification with token:" + verificationId 1584 + " and userId:" + userId 1585 + " is settings verifier response with response code:" 1586 + response.code); 1587 1588 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1589 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1590 + response.getFailedDomainsString()); 1591 } 1592 1593 if (state.isVerificationComplete()) { 1594 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1595 } else { 1596 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1597 "IntentFilter verification with token:" + verificationId 1598 + " was not said to be complete"); 1599 } 1600 1601 break; 1602 } 1603 } 1604 } 1605 } 1606 1607 private StorageEventListener mStorageListener = new StorageEventListener() { 1608 @Override 1609 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1610 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1611 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1612 final String volumeUuid = vol.getFsUuid(); 1613 1614 // Clean up any users or apps that were removed or recreated 1615 // while this volume was missing 1616 reconcileUsers(volumeUuid); 1617 reconcileApps(volumeUuid); 1618 1619 // Clean up any install sessions that expired or were 1620 // cancelled while this volume was missing 1621 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1622 1623 loadPrivatePackages(vol); 1624 1625 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1626 unloadPrivatePackages(vol); 1627 } 1628 } 1629 1630 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1631 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1632 updateExternalMediaStatus(true, false); 1633 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1634 updateExternalMediaStatus(false, false); 1635 } 1636 } 1637 } 1638 1639 @Override 1640 public void onVolumeForgotten(String fsUuid) { 1641 // Remove any apps installed on the forgotten volume 1642 synchronized (mPackages) { 1643 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1644 for (PackageSetting ps : packages) { 1645 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1646 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1647 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1648 } 1649 1650 mSettings.writeLPr(); 1651 } 1652 } 1653 }; 1654 1655 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1656 if (userId >= UserHandle.USER_OWNER) { 1657 grantRequestedRuntimePermissionsForUser(pkg, userId); 1658 } else if (userId == UserHandle.USER_ALL) { 1659 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1660 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1661 } 1662 } 1663 1664 // We could have touched GID membership, so flush out packages.list 1665 synchronized (mPackages) { 1666 mSettings.writePackageListLPr(); 1667 } 1668 } 1669 1670 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1671 SettingBase sb = (SettingBase) pkg.mExtras; 1672 if (sb == null) { 1673 return; 1674 } 1675 1676 PermissionsState permissionsState = sb.getPermissionsState(); 1677 1678 for (String permission : pkg.requestedPermissions) { 1679 BasePermission bp = mSettings.mPermissions.get(permission); 1680 if (bp != null && bp.isRuntime()) { 1681 permissionsState.grantRuntimePermission(bp, userId); 1682 } 1683 } 1684 } 1685 1686 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1687 Bundle extras = null; 1688 switch (res.returnCode) { 1689 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1690 extras = new Bundle(); 1691 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1692 res.origPermission); 1693 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1694 res.origPackage); 1695 break; 1696 } 1697 case PackageManager.INSTALL_SUCCEEDED: { 1698 extras = new Bundle(); 1699 extras.putBoolean(Intent.EXTRA_REPLACING, 1700 res.removedInfo != null && res.removedInfo.removedPackage != null); 1701 break; 1702 } 1703 } 1704 return extras; 1705 } 1706 1707 void scheduleWriteSettingsLocked() { 1708 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1709 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1710 } 1711 } 1712 1713 void scheduleWritePackageRestrictionsLocked(int userId) { 1714 if (!sUserManager.exists(userId)) return; 1715 mDirtyUsers.add(userId); 1716 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1717 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1718 } 1719 } 1720 1721 public static PackageManagerService main(Context context, Installer installer, 1722 boolean factoryTest, boolean onlyCore) { 1723 PackageManagerService m = new PackageManagerService(context, installer, 1724 factoryTest, onlyCore); 1725 ServiceManager.addService("package", m); 1726 return m; 1727 } 1728 1729 static String[] splitString(String str, char sep) { 1730 int count = 1; 1731 int i = 0; 1732 while ((i=str.indexOf(sep, i)) >= 0) { 1733 count++; 1734 i++; 1735 } 1736 1737 String[] res = new String[count]; 1738 i=0; 1739 count = 0; 1740 int lastI=0; 1741 while ((i=str.indexOf(sep, i)) >= 0) { 1742 res[count] = str.substring(lastI, i); 1743 count++; 1744 i++; 1745 lastI = i; 1746 } 1747 res[count] = str.substring(lastI, str.length()); 1748 return res; 1749 } 1750 1751 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1752 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1753 Context.DISPLAY_SERVICE); 1754 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1755 } 1756 1757 public PackageManagerService(Context context, Installer installer, 1758 boolean factoryTest, boolean onlyCore) { 1759 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1760 SystemClock.uptimeMillis()); 1761 1762 if (mSdkVersion <= 0) { 1763 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1764 } 1765 1766 mContext = context; 1767 mFactoryTest = factoryTest; 1768 mOnlyCore = onlyCore; 1769 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1770 mMetrics = new DisplayMetrics(); 1771 mSettings = new Settings(mPackages); 1772 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1773 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1774 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1775 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1776 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1777 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1778 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1779 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1780 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1781 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1782 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1783 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1784 1785 // TODO: add a property to control this? 1786 long dexOptLRUThresholdInMinutes; 1787 if (mLazyDexOpt) { 1788 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1789 } else { 1790 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1791 } 1792 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1793 1794 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1795 if (separateProcesses != null && separateProcesses.length() > 0) { 1796 if ("*".equals(separateProcesses)) { 1797 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1798 mSeparateProcesses = null; 1799 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1800 } else { 1801 mDefParseFlags = 0; 1802 mSeparateProcesses = separateProcesses.split(","); 1803 Slog.w(TAG, "Running with debug.separate_processes: " 1804 + separateProcesses); 1805 } 1806 } else { 1807 mDefParseFlags = 0; 1808 mSeparateProcesses = null; 1809 } 1810 1811 mInstaller = installer; 1812 mPackageDexOptimizer = new PackageDexOptimizer(this); 1813 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1814 1815 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1816 FgThread.get().getLooper()); 1817 1818 getDefaultDisplayMetrics(context, mMetrics); 1819 1820 SystemConfig systemConfig = SystemConfig.getInstance(); 1821 mGlobalGids = systemConfig.getGlobalGids(); 1822 mSystemPermissions = systemConfig.getSystemPermissions(); 1823 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1824 1825 synchronized (mInstallLock) { 1826 // writer 1827 synchronized (mPackages) { 1828 mHandlerThread = new ServiceThread(TAG, 1829 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1830 mHandlerThread.start(); 1831 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1832 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1833 1834 File dataDir = Environment.getDataDirectory(); 1835 mAppDataDir = new File(dataDir, "data"); 1836 mAppInstallDir = new File(dataDir, "app"); 1837 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1838 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1839 mUserAppDataDir = new File(dataDir, "user"); 1840 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1841 1842 sUserManager = new UserManagerService(context, this, 1843 mInstallLock, mPackages); 1844 1845 // Propagate permission configuration in to package manager. 1846 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1847 = systemConfig.getPermissions(); 1848 for (int i=0; i<permConfig.size(); i++) { 1849 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1850 BasePermission bp = mSettings.mPermissions.get(perm.name); 1851 if (bp == null) { 1852 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1853 mSettings.mPermissions.put(perm.name, bp); 1854 } 1855 if (perm.gids != null) { 1856 bp.setGids(perm.gids, perm.perUser); 1857 } 1858 } 1859 1860 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1861 for (int i=0; i<libConfig.size(); i++) { 1862 mSharedLibraries.put(libConfig.keyAt(i), 1863 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1864 } 1865 1866 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1867 1868 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1869 mSdkVersion, mOnlyCore); 1870 1871 String customResolverActivity = Resources.getSystem().getString( 1872 R.string.config_customResolverActivity); 1873 if (TextUtils.isEmpty(customResolverActivity)) { 1874 customResolverActivity = null; 1875 } else { 1876 mCustomResolverComponentName = ComponentName.unflattenFromString( 1877 customResolverActivity); 1878 } 1879 1880 long startTime = SystemClock.uptimeMillis(); 1881 1882 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1883 startTime); 1884 1885 // Set flag to monitor and not change apk file paths when 1886 // scanning install directories. 1887 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1888 1889 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1890 1891 /** 1892 * Add everything in the in the boot class path to the 1893 * list of process files because dexopt will have been run 1894 * if necessary during zygote startup. 1895 */ 1896 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1897 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1898 1899 if (bootClassPath != null) { 1900 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1901 for (String element : bootClassPathElements) { 1902 alreadyDexOpted.add(element); 1903 } 1904 } else { 1905 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1906 } 1907 1908 if (systemServerClassPath != null) { 1909 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1910 for (String element : systemServerClassPathElements) { 1911 alreadyDexOpted.add(element); 1912 } 1913 } else { 1914 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1915 } 1916 1917 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1918 final String[] dexCodeInstructionSets = 1919 getDexCodeInstructionSets( 1920 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1921 1922 /** 1923 * Ensure all external libraries have had dexopt run on them. 1924 */ 1925 if (mSharedLibraries.size() > 0) { 1926 // NOTE: For now, we're compiling these system "shared libraries" 1927 // (and framework jars) into all available architectures. It's possible 1928 // to compile them only when we come across an app that uses them (there's 1929 // already logic for that in scanPackageLI) but that adds some complexity. 1930 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1931 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1932 final String lib = libEntry.path; 1933 if (lib == null) { 1934 continue; 1935 } 1936 1937 try { 1938 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1939 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1940 alreadyDexOpted.add(lib); 1941 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1942 } 1943 } catch (FileNotFoundException e) { 1944 Slog.w(TAG, "Library not found: " + lib); 1945 } catch (IOException e) { 1946 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1947 + e.getMessage()); 1948 } 1949 } 1950 } 1951 } 1952 1953 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1954 1955 // Gross hack for now: we know this file doesn't contain any 1956 // code, so don't dexopt it to avoid the resulting log spew. 1957 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1958 1959 // Gross hack for now: we know this file is only part of 1960 // the boot class path for art, so don't dexopt it to 1961 // avoid the resulting log spew. 1962 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1963 1964 /** 1965 * There are a number of commands implemented in Java, which 1966 * we currently need to do the dexopt on so that they can be 1967 * run from a non-root shell. 1968 */ 1969 String[] frameworkFiles = frameworkDir.list(); 1970 if (frameworkFiles != null) { 1971 // TODO: We could compile these only for the most preferred ABI. We should 1972 // first double check that the dex files for these commands are not referenced 1973 // by other system apps. 1974 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1975 for (int i=0; i<frameworkFiles.length; i++) { 1976 File libPath = new File(frameworkDir, frameworkFiles[i]); 1977 String path = libPath.getPath(); 1978 // Skip the file if we already did it. 1979 if (alreadyDexOpted.contains(path)) { 1980 continue; 1981 } 1982 // Skip the file if it is not a type we want to dexopt. 1983 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1984 continue; 1985 } 1986 try { 1987 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1988 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1989 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1990 } 1991 } catch (FileNotFoundException e) { 1992 Slog.w(TAG, "Jar not found: " + path); 1993 } catch (IOException e) { 1994 Slog.w(TAG, "Exception reading jar: " + path, e); 1995 } 1996 } 1997 } 1998 } 1999 2000 // Collect vendor overlay packages. 2001 // (Do this before scanning any apps.) 2002 // For security and version matching reason, only consider 2003 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2004 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2005 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2006 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2007 2008 // Find base frameworks (resource packages without code). 2009 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2010 | PackageParser.PARSE_IS_SYSTEM_DIR 2011 | PackageParser.PARSE_IS_PRIVILEGED, 2012 scanFlags | SCAN_NO_DEX, 0); 2013 2014 // Collected privileged system packages. 2015 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2016 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2017 | PackageParser.PARSE_IS_SYSTEM_DIR 2018 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2019 2020 // Collect ordinary system packages. 2021 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2022 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2023 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2024 2025 // Collect all vendor packages. 2026 File vendorAppDir = new File("/vendor/app"); 2027 try { 2028 vendorAppDir = vendorAppDir.getCanonicalFile(); 2029 } catch (IOException e) { 2030 // failed to look up canonical path, continue with original one 2031 } 2032 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2033 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2034 2035 // Collect all OEM packages. 2036 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2037 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2038 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2039 2040 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2041 mInstaller.moveFiles(); 2042 2043 // Prune any system packages that no longer exist. 2044 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2045 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2046 if (!mOnlyCore) { 2047 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2048 while (psit.hasNext()) { 2049 PackageSetting ps = psit.next(); 2050 2051 /* 2052 * If this is not a system app, it can't be a 2053 * disable system app. 2054 */ 2055 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2056 continue; 2057 } 2058 2059 /* 2060 * If the package is scanned, it's not erased. 2061 */ 2062 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2063 if (scannedPkg != null) { 2064 /* 2065 * If the system app is both scanned and in the 2066 * disabled packages list, then it must have been 2067 * added via OTA. Remove it from the currently 2068 * scanned package so the previously user-installed 2069 * application can be scanned. 2070 */ 2071 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2072 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2073 + ps.name + "; removing system app. Last known codePath=" 2074 + ps.codePathString + ", installStatus=" + ps.installStatus 2075 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2076 + scannedPkg.mVersionCode); 2077 removePackageLI(ps, true); 2078 expectingBetter.put(ps.name, ps.codePath); 2079 } 2080 2081 continue; 2082 } 2083 2084 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2085 psit.remove(); 2086 logCriticalInfo(Log.WARN, "System package " + ps.name 2087 + " no longer exists; wiping its data"); 2088 removeDataDirsLI(null, ps.name); 2089 } else { 2090 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2091 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2092 possiblyDeletedUpdatedSystemApps.add(ps.name); 2093 } 2094 } 2095 } 2096 } 2097 2098 //look for any incomplete package installations 2099 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2100 //clean up list 2101 for(int i = 0; i < deletePkgsList.size(); i++) { 2102 //clean up here 2103 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2104 } 2105 //delete tmp files 2106 deleteTempPackageFiles(); 2107 2108 // Remove any shared userIDs that have no associated packages 2109 mSettings.pruneSharedUsersLPw(); 2110 2111 if (!mOnlyCore) { 2112 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2113 SystemClock.uptimeMillis()); 2114 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2115 2116 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2117 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2118 2119 /** 2120 * Remove disable package settings for any updated system 2121 * apps that were removed via an OTA. If they're not a 2122 * previously-updated app, remove them completely. 2123 * Otherwise, just revoke their system-level permissions. 2124 */ 2125 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2126 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2127 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2128 2129 String msg; 2130 if (deletedPkg == null) { 2131 msg = "Updated system package " + deletedAppName 2132 + " no longer exists; wiping its data"; 2133 removeDataDirsLI(null, deletedAppName); 2134 } else { 2135 msg = "Updated system app + " + deletedAppName 2136 + " no longer present; removing system privileges for " 2137 + deletedAppName; 2138 2139 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2140 2141 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2142 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2143 } 2144 logCriticalInfo(Log.WARN, msg); 2145 } 2146 2147 /** 2148 * Make sure all system apps that we expected to appear on 2149 * the userdata partition actually showed up. If they never 2150 * appeared, crawl back and revive the system version. 2151 */ 2152 for (int i = 0; i < expectingBetter.size(); i++) { 2153 final String packageName = expectingBetter.keyAt(i); 2154 if (!mPackages.containsKey(packageName)) { 2155 final File scanFile = expectingBetter.valueAt(i); 2156 2157 logCriticalInfo(Log.WARN, "Expected better " + packageName 2158 + " but never showed up; reverting to system"); 2159 2160 final int reparseFlags; 2161 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2162 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2163 | PackageParser.PARSE_IS_SYSTEM_DIR 2164 | PackageParser.PARSE_IS_PRIVILEGED; 2165 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2166 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2167 | PackageParser.PARSE_IS_SYSTEM_DIR; 2168 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2169 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2170 | PackageParser.PARSE_IS_SYSTEM_DIR; 2171 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2172 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2173 | PackageParser.PARSE_IS_SYSTEM_DIR; 2174 } else { 2175 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2176 continue; 2177 } 2178 2179 mSettings.enableSystemPackageLPw(packageName); 2180 2181 try { 2182 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2183 } catch (PackageManagerException e) { 2184 Slog.e(TAG, "Failed to parse original system package: " 2185 + e.getMessage()); 2186 } 2187 } 2188 } 2189 } 2190 2191 // Now that we know all of the shared libraries, update all clients to have 2192 // the correct library paths. 2193 updateAllSharedLibrariesLPw(); 2194 2195 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2196 // NOTE: We ignore potential failures here during a system scan (like 2197 // the rest of the commands above) because there's precious little we 2198 // can do about it. A settings error is reported, though. 2199 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2200 false /* force dexopt */, false /* defer dexopt */); 2201 } 2202 2203 // Now that we know all the packages we are keeping, 2204 // read and update their last usage times. 2205 mPackageUsage.readLP(); 2206 2207 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2208 SystemClock.uptimeMillis()); 2209 Slog.i(TAG, "Time to scan packages: " 2210 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2211 + " seconds"); 2212 2213 // If the platform SDK has changed since the last time we booted, 2214 // we need to re-grant app permission to catch any new ones that 2215 // appear. This is really a hack, and means that apps can in some 2216 // cases get permissions that the user didn't initially explicitly 2217 // allow... it would be nice to have some better way to handle 2218 // this situation. 2219 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2220 != mSdkVersion; 2221 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2222 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2223 + "; regranting permissions for internal storage"); 2224 mSettings.mInternalSdkPlatform = mSdkVersion; 2225 2226 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2227 | (regrantPermissions 2228 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2229 : 0)); 2230 2231 // If this is the first boot, and it is a normal boot, then 2232 // we need to initialize the default preferred apps. 2233 if (!mRestoredSettings && !onlyCore) { 2234 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2235 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2236 } 2237 2238 // If this is first boot after an OTA, and a normal boot, then 2239 // we need to clear code cache directories. 2240 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2241 if (mIsUpgrade && !onlyCore) { 2242 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2243 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2244 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2245 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2246 } 2247 mSettings.mFingerprint = Build.FINGERPRINT; 2248 } 2249 2250 primeDomainVerificationsLPw(); 2251 checkDefaultBrowser(); 2252 2253 // All the changes are done during package scanning. 2254 mSettings.updateInternalDatabaseVersion(); 2255 2256 // can downgrade to reader 2257 mSettings.writeLPr(); 2258 2259 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2260 SystemClock.uptimeMillis()); 2261 2262 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2263 2264 mInstallerService = new PackageInstallerService(context, this); 2265 2266 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2267 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2268 mIntentFilterVerifierComponent); 2269 2270 } // synchronized (mPackages) 2271 } // synchronized (mInstallLock) 2272 2273 // Now after opening every single application zip, make sure they 2274 // are all flushed. Not really needed, but keeps things nice and 2275 // tidy. 2276 Runtime.getRuntime().gc(); 2277 2278 // Expose private service for system components to use. 2279 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2280 } 2281 2282 @Override 2283 public boolean isFirstBoot() { 2284 return !mRestoredSettings; 2285 } 2286 2287 @Override 2288 public boolean isOnlyCoreApps() { 2289 return mOnlyCore; 2290 } 2291 2292 @Override 2293 public boolean isUpgrade() { 2294 return mIsUpgrade; 2295 } 2296 2297 private String getRequiredVerifierLPr() { 2298 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2299 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2300 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2301 2302 String requiredVerifier = null; 2303 2304 final int N = receivers.size(); 2305 for (int i = 0; i < N; i++) { 2306 final ResolveInfo info = receivers.get(i); 2307 2308 if (info.activityInfo == null) { 2309 continue; 2310 } 2311 2312 final String packageName = info.activityInfo.packageName; 2313 2314 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2315 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2316 continue; 2317 } 2318 2319 if (requiredVerifier != null) { 2320 throw new RuntimeException("There can be only one required verifier"); 2321 } 2322 2323 requiredVerifier = packageName; 2324 } 2325 2326 return requiredVerifier; 2327 } 2328 2329 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2330 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2331 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2332 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2333 2334 ComponentName verifierComponentName = null; 2335 2336 int priority = -1000; 2337 final int N = receivers.size(); 2338 for (int i = 0; i < N; i++) { 2339 final ResolveInfo info = receivers.get(i); 2340 2341 if (info.activityInfo == null) { 2342 continue; 2343 } 2344 2345 final String packageName = info.activityInfo.packageName; 2346 2347 final PackageSetting ps = mSettings.mPackages.get(packageName); 2348 if (ps == null) { 2349 continue; 2350 } 2351 2352 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2353 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2354 continue; 2355 } 2356 2357 // Select the IntentFilterVerifier with the highest priority 2358 if (priority < info.priority) { 2359 priority = info.priority; 2360 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2361 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2362 + verifierComponentName + " with priority: " + info.priority); 2363 } 2364 } 2365 2366 return verifierComponentName; 2367 } 2368 2369 private void primeDomainVerificationsLPw() { 2370 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2371 boolean updated = false; 2372 ArraySet<String> allHostsSet = new ArraySet<>(); 2373 for (PackageParser.Package pkg : mPackages.values()) { 2374 final String packageName = pkg.packageName; 2375 if (!hasDomainURLs(pkg)) { 2376 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2377 "package with no domain URLs: " + packageName); 2378 continue; 2379 } 2380 if (!pkg.isSystemApp()) { 2381 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2382 "No priming domain verifications for a non system package : " + 2383 packageName); 2384 continue; 2385 } 2386 for (PackageParser.Activity a : pkg.activities) { 2387 for (ActivityIntentInfo filter : a.intents) { 2388 if (hasValidDomains(filter)) { 2389 allHostsSet.addAll(filter.getHostsList()); 2390 } 2391 } 2392 } 2393 if (allHostsSet.size() == 0) { 2394 allHostsSet.add("*"); 2395 } 2396 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2397 IntentFilterVerificationInfo ivi = 2398 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2399 if (ivi != null) { 2400 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2401 "Priming domain verifications for package: " + packageName + 2402 " with hosts:" + ivi.getDomainsString()); 2403 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2404 updated = true; 2405 } 2406 else { 2407 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2408 "No priming domain verifications for package: " + packageName); 2409 } 2410 allHostsSet.clear(); 2411 } 2412 if (updated) { 2413 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2414 "Will need to write primed domain verifications"); 2415 } 2416 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2417 } 2418 2419 private void applyFactoryDefaultBrowserLPw(int userId) { 2420 // The default browser app's package name is stored in a string resource, 2421 // with a product-specific overlay used for vendor customization. 2422 String browserPkg = mContext.getResources().getString( 2423 com.android.internal.R.string.default_browser); 2424 if (browserPkg != null) { 2425 // non-empty string => required to be a known package 2426 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2427 if (ps == null) { 2428 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2429 browserPkg = null; 2430 } else { 2431 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2432 } 2433 } 2434 2435 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2436 // default. If there's more than one, just leave everything alone. 2437 if (browserPkg == null) { 2438 calculateDefaultBrowserLPw(userId); 2439 } 2440 } 2441 2442 private void calculateDefaultBrowserLPw(int userId) { 2443 List<String> allBrowsers = resolveAllBrowserApps(userId); 2444 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2445 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2446 } 2447 2448 private List<String> resolveAllBrowserApps(int userId) { 2449 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2450 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2451 PackageManager.MATCH_ALL, userId); 2452 2453 final int count = list.size(); 2454 List<String> result = new ArrayList<String>(count); 2455 for (int i=0; i<count; i++) { 2456 ResolveInfo info = list.get(i); 2457 if (info.activityInfo == null 2458 || !info.handleAllWebDataURI 2459 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2460 || result.contains(info.activityInfo.packageName)) { 2461 continue; 2462 } 2463 result.add(info.activityInfo.packageName); 2464 } 2465 2466 return result; 2467 } 2468 2469 private boolean packageIsBrowser(String packageName, int userId) { 2470 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2471 PackageManager.MATCH_ALL, userId); 2472 final int N = list.size(); 2473 for (int i = 0; i < N; i++) { 2474 ResolveInfo info = list.get(i); 2475 if (packageName.equals(info.activityInfo.packageName)) { 2476 return true; 2477 } 2478 } 2479 return false; 2480 } 2481 2482 private void checkDefaultBrowser() { 2483 final int myUserId = UserHandle.myUserId(); 2484 final String packageName = getDefaultBrowserPackageName(myUserId); 2485 if (packageName != null) { 2486 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2487 if (info == null) { 2488 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2489 synchronized (mPackages) { 2490 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2491 } 2492 } 2493 } 2494 } 2495 2496 @Override 2497 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2498 throws RemoteException { 2499 try { 2500 return super.onTransact(code, data, reply, flags); 2501 } catch (RuntimeException e) { 2502 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2503 Slog.wtf(TAG, "Package Manager Crash", e); 2504 } 2505 throw e; 2506 } 2507 } 2508 2509 void cleanupInstallFailedPackage(PackageSetting ps) { 2510 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2511 2512 removeDataDirsLI(ps.volumeUuid, ps.name); 2513 if (ps.codePath != null) { 2514 if (ps.codePath.isDirectory()) { 2515 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2516 } else { 2517 ps.codePath.delete(); 2518 } 2519 } 2520 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2521 if (ps.resourcePath.isDirectory()) { 2522 FileUtils.deleteContents(ps.resourcePath); 2523 } 2524 ps.resourcePath.delete(); 2525 } 2526 mSettings.removePackageLPw(ps.name); 2527 } 2528 2529 static int[] appendInts(int[] cur, int[] add) { 2530 if (add == null) return cur; 2531 if (cur == null) return add; 2532 final int N = add.length; 2533 for (int i=0; i<N; i++) { 2534 cur = appendInt(cur, add[i]); 2535 } 2536 return cur; 2537 } 2538 2539 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2540 if (!sUserManager.exists(userId)) return null; 2541 final PackageSetting ps = (PackageSetting) p.mExtras; 2542 if (ps == null) { 2543 return null; 2544 } 2545 2546 final PermissionsState permissionsState = ps.getPermissionsState(); 2547 2548 final int[] gids = permissionsState.computeGids(userId); 2549 final Set<String> permissions = permissionsState.getPermissions(userId); 2550 final PackageUserState state = ps.readUserState(userId); 2551 2552 return PackageParser.generatePackageInfo(p, gids, flags, 2553 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2554 } 2555 2556 @Override 2557 public boolean isPackageFrozen(String packageName) { 2558 synchronized (mPackages) { 2559 final PackageSetting ps = mSettings.mPackages.get(packageName); 2560 if (ps != null) { 2561 return ps.frozen; 2562 } 2563 } 2564 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2565 return true; 2566 } 2567 2568 @Override 2569 public boolean isPackageAvailable(String packageName, int userId) { 2570 if (!sUserManager.exists(userId)) return false; 2571 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2572 synchronized (mPackages) { 2573 PackageParser.Package p = mPackages.get(packageName); 2574 if (p != null) { 2575 final PackageSetting ps = (PackageSetting) p.mExtras; 2576 if (ps != null) { 2577 final PackageUserState state = ps.readUserState(userId); 2578 if (state != null) { 2579 return PackageParser.isAvailable(state); 2580 } 2581 } 2582 } 2583 } 2584 return false; 2585 } 2586 2587 @Override 2588 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2589 if (!sUserManager.exists(userId)) return null; 2590 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2591 // reader 2592 synchronized (mPackages) { 2593 PackageParser.Package p = mPackages.get(packageName); 2594 if (DEBUG_PACKAGE_INFO) 2595 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2596 if (p != null) { 2597 return generatePackageInfo(p, flags, userId); 2598 } 2599 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2600 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2601 } 2602 } 2603 return null; 2604 } 2605 2606 @Override 2607 public String[] currentToCanonicalPackageNames(String[] names) { 2608 String[] out = new String[names.length]; 2609 // reader 2610 synchronized (mPackages) { 2611 for (int i=names.length-1; i>=0; i--) { 2612 PackageSetting ps = mSettings.mPackages.get(names[i]); 2613 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2614 } 2615 } 2616 return out; 2617 } 2618 2619 @Override 2620 public String[] canonicalToCurrentPackageNames(String[] names) { 2621 String[] out = new String[names.length]; 2622 // reader 2623 synchronized (mPackages) { 2624 for (int i=names.length-1; i>=0; i--) { 2625 String cur = mSettings.mRenamedPackages.get(names[i]); 2626 out[i] = cur != null ? cur : names[i]; 2627 } 2628 } 2629 return out; 2630 } 2631 2632 @Override 2633 public int getPackageUid(String packageName, int userId) { 2634 if (!sUserManager.exists(userId)) return -1; 2635 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2636 2637 // reader 2638 synchronized (mPackages) { 2639 PackageParser.Package p = mPackages.get(packageName); 2640 if(p != null) { 2641 return UserHandle.getUid(userId, p.applicationInfo.uid); 2642 } 2643 PackageSetting ps = mSettings.mPackages.get(packageName); 2644 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2645 return -1; 2646 } 2647 p = ps.pkg; 2648 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2649 } 2650 } 2651 2652 @Override 2653 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2654 if (!sUserManager.exists(userId)) { 2655 return null; 2656 } 2657 2658 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2659 "getPackageGids"); 2660 2661 // reader 2662 synchronized (mPackages) { 2663 PackageParser.Package p = mPackages.get(packageName); 2664 if (DEBUG_PACKAGE_INFO) { 2665 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2666 } 2667 if (p != null) { 2668 PackageSetting ps = (PackageSetting) p.mExtras; 2669 return ps.getPermissionsState().computeGids(userId); 2670 } 2671 } 2672 2673 return null; 2674 } 2675 2676 @Override 2677 public int getMountExternalMode(int uid) { 2678 if (Process.isIsolated(uid)) { 2679 return Zygote.MOUNT_EXTERNAL_NONE; 2680 } else { 2681 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 2682 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2683 } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2684 return Zygote.MOUNT_EXTERNAL_WRITE; 2685 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2686 return Zygote.MOUNT_EXTERNAL_READ; 2687 } else { 2688 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2689 } 2690 } 2691 } 2692 2693 static PermissionInfo generatePermissionInfo( 2694 BasePermission bp, int flags) { 2695 if (bp.perm != null) { 2696 return PackageParser.generatePermissionInfo(bp.perm, flags); 2697 } 2698 PermissionInfo pi = new PermissionInfo(); 2699 pi.name = bp.name; 2700 pi.packageName = bp.sourcePackage; 2701 pi.nonLocalizedLabel = bp.name; 2702 pi.protectionLevel = bp.protectionLevel; 2703 return pi; 2704 } 2705 2706 @Override 2707 public PermissionInfo getPermissionInfo(String name, int flags) { 2708 // reader 2709 synchronized (mPackages) { 2710 final BasePermission p = mSettings.mPermissions.get(name); 2711 if (p != null) { 2712 return generatePermissionInfo(p, flags); 2713 } 2714 return null; 2715 } 2716 } 2717 2718 @Override 2719 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2720 // reader 2721 synchronized (mPackages) { 2722 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2723 for (BasePermission p : mSettings.mPermissions.values()) { 2724 if (group == null) { 2725 if (p.perm == null || p.perm.info.group == null) { 2726 out.add(generatePermissionInfo(p, flags)); 2727 } 2728 } else { 2729 if (p.perm != null && group.equals(p.perm.info.group)) { 2730 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2731 } 2732 } 2733 } 2734 2735 if (out.size() > 0) { 2736 return out; 2737 } 2738 return mPermissionGroups.containsKey(group) ? out : null; 2739 } 2740 } 2741 2742 @Override 2743 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2744 // reader 2745 synchronized (mPackages) { 2746 return PackageParser.generatePermissionGroupInfo( 2747 mPermissionGroups.get(name), flags); 2748 } 2749 } 2750 2751 @Override 2752 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2753 // reader 2754 synchronized (mPackages) { 2755 final int N = mPermissionGroups.size(); 2756 ArrayList<PermissionGroupInfo> out 2757 = new ArrayList<PermissionGroupInfo>(N); 2758 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2759 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2760 } 2761 return out; 2762 } 2763 } 2764 2765 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2766 int userId) { 2767 if (!sUserManager.exists(userId)) return null; 2768 PackageSetting ps = mSettings.mPackages.get(packageName); 2769 if (ps != null) { 2770 if (ps.pkg == null) { 2771 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2772 flags, userId); 2773 if (pInfo != null) { 2774 return pInfo.applicationInfo; 2775 } 2776 return null; 2777 } 2778 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2779 ps.readUserState(userId), userId); 2780 } 2781 return null; 2782 } 2783 2784 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2785 int userId) { 2786 if (!sUserManager.exists(userId)) return null; 2787 PackageSetting ps = mSettings.mPackages.get(packageName); 2788 if (ps != null) { 2789 PackageParser.Package pkg = ps.pkg; 2790 if (pkg == null) { 2791 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2792 return null; 2793 } 2794 // Only data remains, so we aren't worried about code paths 2795 pkg = new PackageParser.Package(packageName); 2796 pkg.applicationInfo.packageName = packageName; 2797 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2798 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2799 pkg.applicationInfo.dataDir = Environment 2800 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2801 .getAbsolutePath(); 2802 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2803 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2804 } 2805 return generatePackageInfo(pkg, flags, userId); 2806 } 2807 return null; 2808 } 2809 2810 @Override 2811 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2812 if (!sUserManager.exists(userId)) return null; 2813 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2814 // writer 2815 synchronized (mPackages) { 2816 PackageParser.Package p = mPackages.get(packageName); 2817 if (DEBUG_PACKAGE_INFO) Log.v( 2818 TAG, "getApplicationInfo " + packageName 2819 + ": " + p); 2820 if (p != null) { 2821 PackageSetting ps = mSettings.mPackages.get(packageName); 2822 if (ps == null) return null; 2823 // Note: isEnabledLP() does not apply here - always return info 2824 return PackageParser.generateApplicationInfo( 2825 p, flags, ps.readUserState(userId), userId); 2826 } 2827 if ("android".equals(packageName)||"system".equals(packageName)) { 2828 return mAndroidApplication; 2829 } 2830 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2831 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2832 } 2833 } 2834 return null; 2835 } 2836 2837 @Override 2838 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2839 final IPackageDataObserver observer) { 2840 mContext.enforceCallingOrSelfPermission( 2841 android.Manifest.permission.CLEAR_APP_CACHE, null); 2842 // Queue up an async operation since clearing cache may take a little while. 2843 mHandler.post(new Runnable() { 2844 public void run() { 2845 mHandler.removeCallbacks(this); 2846 int retCode = -1; 2847 synchronized (mInstallLock) { 2848 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2849 if (retCode < 0) { 2850 Slog.w(TAG, "Couldn't clear application caches"); 2851 } 2852 } 2853 if (observer != null) { 2854 try { 2855 observer.onRemoveCompleted(null, (retCode >= 0)); 2856 } catch (RemoteException e) { 2857 Slog.w(TAG, "RemoveException when invoking call back"); 2858 } 2859 } 2860 } 2861 }); 2862 } 2863 2864 @Override 2865 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2866 final IntentSender pi) { 2867 mContext.enforceCallingOrSelfPermission( 2868 android.Manifest.permission.CLEAR_APP_CACHE, null); 2869 // Queue up an async operation since clearing cache may take a little while. 2870 mHandler.post(new Runnable() { 2871 public void run() { 2872 mHandler.removeCallbacks(this); 2873 int retCode = -1; 2874 synchronized (mInstallLock) { 2875 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2876 if (retCode < 0) { 2877 Slog.w(TAG, "Couldn't clear application caches"); 2878 } 2879 } 2880 if(pi != null) { 2881 try { 2882 // Callback via pending intent 2883 int code = (retCode >= 0) ? 1 : 0; 2884 pi.sendIntent(null, code, null, 2885 null, null); 2886 } catch (SendIntentException e1) { 2887 Slog.i(TAG, "Failed to send pending intent"); 2888 } 2889 } 2890 } 2891 }); 2892 } 2893 2894 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2895 synchronized (mInstallLock) { 2896 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2897 throw new IOException("Failed to free enough space"); 2898 } 2899 } 2900 } 2901 2902 @Override 2903 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2904 if (!sUserManager.exists(userId)) return null; 2905 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2906 synchronized (mPackages) { 2907 PackageParser.Activity a = mActivities.mActivities.get(component); 2908 2909 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2910 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2911 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2912 if (ps == null) return null; 2913 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2914 userId); 2915 } 2916 if (mResolveComponentName.equals(component)) { 2917 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2918 new PackageUserState(), userId); 2919 } 2920 } 2921 return null; 2922 } 2923 2924 @Override 2925 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2926 String resolvedType) { 2927 synchronized (mPackages) { 2928 PackageParser.Activity a = mActivities.mActivities.get(component); 2929 if (a == null) { 2930 return false; 2931 } 2932 for (int i=0; i<a.intents.size(); i++) { 2933 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2934 intent.getData(), intent.getCategories(), TAG) >= 0) { 2935 return true; 2936 } 2937 } 2938 return false; 2939 } 2940 } 2941 2942 @Override 2943 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2944 if (!sUserManager.exists(userId)) return null; 2945 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2946 synchronized (mPackages) { 2947 PackageParser.Activity a = mReceivers.mActivities.get(component); 2948 if (DEBUG_PACKAGE_INFO) Log.v( 2949 TAG, "getReceiverInfo " + component + ": " + a); 2950 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2951 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2952 if (ps == null) return null; 2953 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2954 userId); 2955 } 2956 } 2957 return null; 2958 } 2959 2960 @Override 2961 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2962 if (!sUserManager.exists(userId)) return null; 2963 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2964 synchronized (mPackages) { 2965 PackageParser.Service s = mServices.mServices.get(component); 2966 if (DEBUG_PACKAGE_INFO) Log.v( 2967 TAG, "getServiceInfo " + component + ": " + s); 2968 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2969 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2970 if (ps == null) return null; 2971 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2972 userId); 2973 } 2974 } 2975 return null; 2976 } 2977 2978 @Override 2979 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2980 if (!sUserManager.exists(userId)) return null; 2981 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2982 synchronized (mPackages) { 2983 PackageParser.Provider p = mProviders.mProviders.get(component); 2984 if (DEBUG_PACKAGE_INFO) Log.v( 2985 TAG, "getProviderInfo " + component + ": " + p); 2986 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2987 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2988 if (ps == null) return null; 2989 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2990 userId); 2991 } 2992 } 2993 return null; 2994 } 2995 2996 @Override 2997 public String[] getSystemSharedLibraryNames() { 2998 Set<String> libSet; 2999 synchronized (mPackages) { 3000 libSet = mSharedLibraries.keySet(); 3001 int size = libSet.size(); 3002 if (size > 0) { 3003 String[] libs = new String[size]; 3004 libSet.toArray(libs); 3005 return libs; 3006 } 3007 } 3008 return null; 3009 } 3010 3011 /** 3012 * @hide 3013 */ 3014 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3015 synchronized (mPackages) { 3016 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3017 if (lib != null && lib.apk != null) { 3018 return mPackages.get(lib.apk); 3019 } 3020 } 3021 return null; 3022 } 3023 3024 @Override 3025 public FeatureInfo[] getSystemAvailableFeatures() { 3026 Collection<FeatureInfo> featSet; 3027 synchronized (mPackages) { 3028 featSet = mAvailableFeatures.values(); 3029 int size = featSet.size(); 3030 if (size > 0) { 3031 FeatureInfo[] features = new FeatureInfo[size+1]; 3032 featSet.toArray(features); 3033 FeatureInfo fi = new FeatureInfo(); 3034 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3035 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3036 features[size] = fi; 3037 return features; 3038 } 3039 } 3040 return null; 3041 } 3042 3043 @Override 3044 public boolean hasSystemFeature(String name) { 3045 synchronized (mPackages) { 3046 return mAvailableFeatures.containsKey(name); 3047 } 3048 } 3049 3050 private void checkValidCaller(int uid, int userId) { 3051 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3052 return; 3053 3054 throw new SecurityException("Caller uid=" + uid 3055 + " is not privileged to communicate with user=" + userId); 3056 } 3057 3058 @Override 3059 public int checkPermission(String permName, String pkgName, int userId) { 3060 if (!sUserManager.exists(userId)) { 3061 return PackageManager.PERMISSION_DENIED; 3062 } 3063 3064 synchronized (mPackages) { 3065 final PackageParser.Package p = mPackages.get(pkgName); 3066 if (p != null && p.mExtras != null) { 3067 final PackageSetting ps = (PackageSetting) p.mExtras; 3068 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3069 return PackageManager.PERMISSION_GRANTED; 3070 } 3071 } 3072 } 3073 3074 return PackageManager.PERMISSION_DENIED; 3075 } 3076 3077 @Override 3078 public int checkUidPermission(String permName, int uid) { 3079 final int userId = UserHandle.getUserId(uid); 3080 3081 if (!sUserManager.exists(userId)) { 3082 return PackageManager.PERMISSION_DENIED; 3083 } 3084 3085 synchronized (mPackages) { 3086 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3087 if (obj != null) { 3088 final SettingBase ps = (SettingBase) obj; 3089 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3090 return PackageManager.PERMISSION_GRANTED; 3091 } 3092 } else { 3093 ArraySet<String> perms = mSystemPermissions.get(uid); 3094 if (perms != null && perms.contains(permName)) { 3095 return PackageManager.PERMISSION_GRANTED; 3096 } 3097 } 3098 } 3099 3100 return PackageManager.PERMISSION_DENIED; 3101 } 3102 3103 /** 3104 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3105 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3106 * @param checkShell TODO(yamasani): 3107 * @param message the message to log on security exception 3108 */ 3109 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3110 boolean checkShell, String message) { 3111 if (userId < 0) { 3112 throw new IllegalArgumentException("Invalid userId " + userId); 3113 } 3114 if (checkShell) { 3115 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3116 } 3117 if (userId == UserHandle.getUserId(callingUid)) return; 3118 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3119 if (requireFullPermission) { 3120 mContext.enforceCallingOrSelfPermission( 3121 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3122 } else { 3123 try { 3124 mContext.enforceCallingOrSelfPermission( 3125 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3126 } catch (SecurityException se) { 3127 mContext.enforceCallingOrSelfPermission( 3128 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3129 } 3130 } 3131 } 3132 } 3133 3134 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3135 if (callingUid == Process.SHELL_UID) { 3136 if (userHandle >= 0 3137 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3138 throw new SecurityException("Shell does not have permission to access user " 3139 + userHandle); 3140 } else if (userHandle < 0) { 3141 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3142 + Debug.getCallers(3)); 3143 } 3144 } 3145 } 3146 3147 private BasePermission findPermissionTreeLP(String permName) { 3148 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3149 if (permName.startsWith(bp.name) && 3150 permName.length() > bp.name.length() && 3151 permName.charAt(bp.name.length()) == '.') { 3152 return bp; 3153 } 3154 } 3155 return null; 3156 } 3157 3158 private BasePermission checkPermissionTreeLP(String permName) { 3159 if (permName != null) { 3160 BasePermission bp = findPermissionTreeLP(permName); 3161 if (bp != null) { 3162 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3163 return bp; 3164 } 3165 throw new SecurityException("Calling uid " 3166 + Binder.getCallingUid() 3167 + " is not allowed to add to permission tree " 3168 + bp.name + " owned by uid " + bp.uid); 3169 } 3170 } 3171 throw new SecurityException("No permission tree found for " + permName); 3172 } 3173 3174 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3175 if (s1 == null) { 3176 return s2 == null; 3177 } 3178 if (s2 == null) { 3179 return false; 3180 } 3181 if (s1.getClass() != s2.getClass()) { 3182 return false; 3183 } 3184 return s1.equals(s2); 3185 } 3186 3187 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3188 if (pi1.icon != pi2.icon) return false; 3189 if (pi1.logo != pi2.logo) return false; 3190 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3191 if (!compareStrings(pi1.name, pi2.name)) return false; 3192 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3193 // We'll take care of setting this one. 3194 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3195 // These are not currently stored in settings. 3196 //if (!compareStrings(pi1.group, pi2.group)) return false; 3197 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3198 //if (pi1.labelRes != pi2.labelRes) return false; 3199 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3200 return true; 3201 } 3202 3203 int permissionInfoFootprint(PermissionInfo info) { 3204 int size = info.name.length(); 3205 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3206 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3207 return size; 3208 } 3209 3210 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3211 int size = 0; 3212 for (BasePermission perm : mSettings.mPermissions.values()) { 3213 if (perm.uid == tree.uid) { 3214 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3215 } 3216 } 3217 return size; 3218 } 3219 3220 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3221 // We calculate the max size of permissions defined by this uid and throw 3222 // if that plus the size of 'info' would exceed our stated maximum. 3223 if (tree.uid != Process.SYSTEM_UID) { 3224 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3225 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3226 throw new SecurityException("Permission tree size cap exceeded"); 3227 } 3228 } 3229 } 3230 3231 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3232 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3233 throw new SecurityException("Label must be specified in permission"); 3234 } 3235 BasePermission tree = checkPermissionTreeLP(info.name); 3236 BasePermission bp = mSettings.mPermissions.get(info.name); 3237 boolean added = bp == null; 3238 boolean changed = true; 3239 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3240 if (added) { 3241 enforcePermissionCapLocked(info, tree); 3242 bp = new BasePermission(info.name, tree.sourcePackage, 3243 BasePermission.TYPE_DYNAMIC); 3244 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3245 throw new SecurityException( 3246 "Not allowed to modify non-dynamic permission " 3247 + info.name); 3248 } else { 3249 if (bp.protectionLevel == fixedLevel 3250 && bp.perm.owner.equals(tree.perm.owner) 3251 && bp.uid == tree.uid 3252 && comparePermissionInfos(bp.perm.info, info)) { 3253 changed = false; 3254 } 3255 } 3256 bp.protectionLevel = fixedLevel; 3257 info = new PermissionInfo(info); 3258 info.protectionLevel = fixedLevel; 3259 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3260 bp.perm.info.packageName = tree.perm.info.packageName; 3261 bp.uid = tree.uid; 3262 if (added) { 3263 mSettings.mPermissions.put(info.name, bp); 3264 } 3265 if (changed) { 3266 if (!async) { 3267 mSettings.writeLPr(); 3268 } else { 3269 scheduleWriteSettingsLocked(); 3270 } 3271 } 3272 return added; 3273 } 3274 3275 @Override 3276 public boolean addPermission(PermissionInfo info) { 3277 synchronized (mPackages) { 3278 return addPermissionLocked(info, false); 3279 } 3280 } 3281 3282 @Override 3283 public boolean addPermissionAsync(PermissionInfo info) { 3284 synchronized (mPackages) { 3285 return addPermissionLocked(info, true); 3286 } 3287 } 3288 3289 @Override 3290 public void removePermission(String name) { 3291 synchronized (mPackages) { 3292 checkPermissionTreeLP(name); 3293 BasePermission bp = mSettings.mPermissions.get(name); 3294 if (bp != null) { 3295 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3296 throw new SecurityException( 3297 "Not allowed to modify non-dynamic permission " 3298 + name); 3299 } 3300 mSettings.mPermissions.remove(name); 3301 mSettings.writeLPr(); 3302 } 3303 } 3304 } 3305 3306 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3307 BasePermission bp) { 3308 int index = pkg.requestedPermissions.indexOf(bp.name); 3309 if (index == -1) { 3310 throw new SecurityException("Package " + pkg.packageName 3311 + " has not requested permission " + bp.name); 3312 } 3313 if (!bp.isRuntime()) { 3314 throw new SecurityException("Permission " + bp.name 3315 + " is not a changeable permission type"); 3316 } 3317 } 3318 3319 @Override 3320 public void grantRuntimePermission(String packageName, String name, final int userId) { 3321 if (!sUserManager.exists(userId)) { 3322 Log.e(TAG, "No such user:" + userId); 3323 return; 3324 } 3325 3326 mContext.enforceCallingOrSelfPermission( 3327 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3328 "grantRuntimePermission"); 3329 3330 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3331 "grantRuntimePermission"); 3332 3333 final int uid; 3334 final SettingBase sb; 3335 3336 synchronized (mPackages) { 3337 final PackageParser.Package pkg = mPackages.get(packageName); 3338 if (pkg == null) { 3339 throw new IllegalArgumentException("Unknown package: " + packageName); 3340 } 3341 3342 final BasePermission bp = mSettings.mPermissions.get(name); 3343 if (bp == null) { 3344 throw new IllegalArgumentException("Unknown permission: " + name); 3345 } 3346 3347 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3348 3349 uid = pkg.applicationInfo.uid; 3350 sb = (SettingBase) pkg.mExtras; 3351 if (sb == null) { 3352 throw new IllegalArgumentException("Unknown package: " + packageName); 3353 } 3354 3355 final PermissionsState permissionsState = sb.getPermissionsState(); 3356 3357 final int flags = permissionsState.getPermissionFlags(name, userId); 3358 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3359 throw new SecurityException("Cannot grant system fixed permission: " 3360 + name + " for package: " + packageName); 3361 } 3362 3363 final int result = permissionsState.grantRuntimePermission(bp, userId); 3364 switch (result) { 3365 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3366 return; 3367 } 3368 3369 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3370 mHandler.post(new Runnable() { 3371 @Override 3372 public void run() { 3373 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3374 } 3375 }); 3376 } break; 3377 } 3378 3379 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3380 3381 // Not critical if that is lost - app has to request again. 3382 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3383 } 3384 3385 if (READ_EXTERNAL_STORAGE.equals(name) 3386 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3387 final long token = Binder.clearCallingIdentity(); 3388 try { 3389 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3390 storage.remountUid(uid); 3391 } finally { 3392 Binder.restoreCallingIdentity(token); 3393 } 3394 } 3395 } 3396 3397 @Override 3398 public void revokeRuntimePermission(String packageName, String name, int userId) { 3399 if (!sUserManager.exists(userId)) { 3400 Log.e(TAG, "No such user:" + userId); 3401 return; 3402 } 3403 3404 mContext.enforceCallingOrSelfPermission( 3405 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3406 "revokeRuntimePermission"); 3407 3408 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3409 "revokeRuntimePermission"); 3410 3411 final SettingBase sb; 3412 3413 synchronized (mPackages) { 3414 final PackageParser.Package pkg = mPackages.get(packageName); 3415 if (pkg == null) { 3416 throw new IllegalArgumentException("Unknown package: " + packageName); 3417 } 3418 3419 final BasePermission bp = mSettings.mPermissions.get(name); 3420 if (bp == null) { 3421 throw new IllegalArgumentException("Unknown permission: " + name); 3422 } 3423 3424 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3425 3426 sb = (SettingBase) pkg.mExtras; 3427 if (sb == null) { 3428 throw new IllegalArgumentException("Unknown package: " + packageName); 3429 } 3430 3431 final PermissionsState permissionsState = sb.getPermissionsState(); 3432 3433 final int flags = permissionsState.getPermissionFlags(name, userId); 3434 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3435 throw new SecurityException("Cannot revoke system fixed permission: " 3436 + name + " for package: " + packageName); 3437 } 3438 3439 if (permissionsState.revokeRuntimePermission(bp, userId) == 3440 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3441 return; 3442 } 3443 3444 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3445 3446 // Critical, after this call app should never have the permission. 3447 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3448 } 3449 3450 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3451 } 3452 3453 @Override 3454 public void resetRuntimePermissions() { 3455 mContext.enforceCallingOrSelfPermission( 3456 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3457 "revokeRuntimePermission"); 3458 3459 int callingUid = Binder.getCallingUid(); 3460 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3461 mContext.enforceCallingOrSelfPermission( 3462 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3463 "resetRuntimePermissions"); 3464 } 3465 3466 final int[] userIds; 3467 3468 synchronized (mPackages) { 3469 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3470 final int userCount = UserManagerService.getInstance().getUserIds().length; 3471 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3472 } 3473 3474 for (int userId : userIds) { 3475 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3476 } 3477 } 3478 3479 @Override 3480 public int getPermissionFlags(String name, String packageName, int userId) { 3481 if (!sUserManager.exists(userId)) { 3482 return 0; 3483 } 3484 3485 mContext.enforceCallingOrSelfPermission( 3486 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3487 "getPermissionFlags"); 3488 3489 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3490 "getPermissionFlags"); 3491 3492 synchronized (mPackages) { 3493 final PackageParser.Package pkg = mPackages.get(packageName); 3494 if (pkg == null) { 3495 throw new IllegalArgumentException("Unknown package: " + packageName); 3496 } 3497 3498 final BasePermission bp = mSettings.mPermissions.get(name); 3499 if (bp == null) { 3500 throw new IllegalArgumentException("Unknown permission: " + name); 3501 } 3502 3503 SettingBase sb = (SettingBase) pkg.mExtras; 3504 if (sb == null) { 3505 throw new IllegalArgumentException("Unknown package: " + packageName); 3506 } 3507 3508 PermissionsState permissionsState = sb.getPermissionsState(); 3509 return permissionsState.getPermissionFlags(name, userId); 3510 } 3511 } 3512 3513 @Override 3514 public void updatePermissionFlags(String name, String packageName, int flagMask, 3515 int flagValues, int userId) { 3516 if (!sUserManager.exists(userId)) { 3517 return; 3518 } 3519 3520 mContext.enforceCallingOrSelfPermission( 3521 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3522 "updatePermissionFlags"); 3523 3524 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3525 "updatePermissionFlags"); 3526 3527 // Only the system can change system fixed flags. 3528 if (getCallingUid() != Process.SYSTEM_UID) { 3529 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3530 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3531 } 3532 3533 synchronized (mPackages) { 3534 final PackageParser.Package pkg = mPackages.get(packageName); 3535 if (pkg == null) { 3536 throw new IllegalArgumentException("Unknown package: " + packageName); 3537 } 3538 3539 final BasePermission bp = mSettings.mPermissions.get(name); 3540 if (bp == null) { 3541 throw new IllegalArgumentException("Unknown permission: " + name); 3542 } 3543 3544 SettingBase sb = (SettingBase) pkg.mExtras; 3545 if (sb == null) { 3546 throw new IllegalArgumentException("Unknown package: " + packageName); 3547 } 3548 3549 PermissionsState permissionsState = sb.getPermissionsState(); 3550 3551 // Only the package manager can change flags for system component permissions. 3552 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3553 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3554 return; 3555 } 3556 3557 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3558 3559 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3560 // Install and runtime permissions are stored in different places, 3561 // so figure out what permission changed and persist the change. 3562 if (permissionsState.getInstallPermissionState(name) != null) { 3563 scheduleWriteSettingsLocked(); 3564 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3565 || hadState) { 3566 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3567 } 3568 } 3569 } 3570 } 3571 3572 /** 3573 * Update the permission flags for all packages and runtime permissions of a user in order 3574 * to allow device or profile owner to remove POLICY_FIXED. 3575 */ 3576 @Override 3577 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3578 if (!sUserManager.exists(userId)) { 3579 return; 3580 } 3581 3582 mContext.enforceCallingOrSelfPermission( 3583 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3584 "updatePermissionFlagsForAllApps"); 3585 3586 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3587 "updatePermissionFlagsForAllApps"); 3588 3589 // Only the system can change system fixed flags. 3590 if (getCallingUid() != Process.SYSTEM_UID) { 3591 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3592 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3593 } 3594 3595 synchronized (mPackages) { 3596 boolean changed = false; 3597 final int packageCount = mPackages.size(); 3598 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3599 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3600 SettingBase sb = (SettingBase) pkg.mExtras; 3601 if (sb == null) { 3602 continue; 3603 } 3604 PermissionsState permissionsState = sb.getPermissionsState(); 3605 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3606 userId, flagMask, flagValues); 3607 } 3608 if (changed) { 3609 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3610 } 3611 } 3612 } 3613 3614 @Override 3615 public boolean shouldShowRequestPermissionRationale(String permissionName, 3616 String packageName, int userId) { 3617 if (UserHandle.getCallingUserId() != userId) { 3618 mContext.enforceCallingPermission( 3619 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3620 "canShowRequestPermissionRationale for user " + userId); 3621 } 3622 3623 final int uid = getPackageUid(packageName, userId); 3624 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3625 return false; 3626 } 3627 3628 if (checkPermission(permissionName, packageName, userId) 3629 == PackageManager.PERMISSION_GRANTED) { 3630 return false; 3631 } 3632 3633 final int flags; 3634 3635 final long identity = Binder.clearCallingIdentity(); 3636 try { 3637 flags = getPermissionFlags(permissionName, 3638 packageName, userId); 3639 } finally { 3640 Binder.restoreCallingIdentity(identity); 3641 } 3642 3643 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3644 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3645 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3646 3647 if ((flags & fixedFlags) != 0) { 3648 return false; 3649 } 3650 3651 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3652 } 3653 3654 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3655 BasePermission bp = mSettings.mPermissions.get(permission); 3656 if (bp == null) { 3657 throw new SecurityException("Missing " + permission + " permission"); 3658 } 3659 3660 SettingBase sb = (SettingBase) pkg.mExtras; 3661 PermissionsState permissionsState = sb.getPermissionsState(); 3662 3663 if (permissionsState.grantInstallPermission(bp) != 3664 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3665 scheduleWriteSettingsLocked(); 3666 } 3667 } 3668 3669 @Override 3670 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3671 mContext.enforceCallingOrSelfPermission( 3672 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3673 "addOnPermissionsChangeListener"); 3674 3675 synchronized (mPackages) { 3676 mOnPermissionChangeListeners.addListenerLocked(listener); 3677 } 3678 } 3679 3680 @Override 3681 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3682 synchronized (mPackages) { 3683 mOnPermissionChangeListeners.removeListenerLocked(listener); 3684 } 3685 } 3686 3687 @Override 3688 public boolean isProtectedBroadcast(String actionName) { 3689 synchronized (mPackages) { 3690 return mProtectedBroadcasts.contains(actionName); 3691 } 3692 } 3693 3694 @Override 3695 public int checkSignatures(String pkg1, String pkg2) { 3696 synchronized (mPackages) { 3697 final PackageParser.Package p1 = mPackages.get(pkg1); 3698 final PackageParser.Package p2 = mPackages.get(pkg2); 3699 if (p1 == null || p1.mExtras == null 3700 || p2 == null || p2.mExtras == null) { 3701 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3702 } 3703 return compareSignatures(p1.mSignatures, p2.mSignatures); 3704 } 3705 } 3706 3707 @Override 3708 public int checkUidSignatures(int uid1, int uid2) { 3709 // Map to base uids. 3710 uid1 = UserHandle.getAppId(uid1); 3711 uid2 = UserHandle.getAppId(uid2); 3712 // reader 3713 synchronized (mPackages) { 3714 Signature[] s1; 3715 Signature[] s2; 3716 Object obj = mSettings.getUserIdLPr(uid1); 3717 if (obj != null) { 3718 if (obj instanceof SharedUserSetting) { 3719 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3720 } else if (obj instanceof PackageSetting) { 3721 s1 = ((PackageSetting)obj).signatures.mSignatures; 3722 } else { 3723 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3724 } 3725 } else { 3726 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3727 } 3728 obj = mSettings.getUserIdLPr(uid2); 3729 if (obj != null) { 3730 if (obj instanceof SharedUserSetting) { 3731 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3732 } else if (obj instanceof PackageSetting) { 3733 s2 = ((PackageSetting)obj).signatures.mSignatures; 3734 } else { 3735 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3736 } 3737 } else { 3738 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3739 } 3740 return compareSignatures(s1, s2); 3741 } 3742 } 3743 3744 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3745 final long identity = Binder.clearCallingIdentity(); 3746 try { 3747 if (sb instanceof SharedUserSetting) { 3748 SharedUserSetting sus = (SharedUserSetting) sb; 3749 final int packageCount = sus.packages.size(); 3750 for (int i = 0; i < packageCount; i++) { 3751 PackageSetting susPs = sus.packages.valueAt(i); 3752 if (userId == UserHandle.USER_ALL) { 3753 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3754 } else { 3755 final int uid = UserHandle.getUid(userId, susPs.appId); 3756 killUid(uid, reason); 3757 } 3758 } 3759 } else if (sb instanceof PackageSetting) { 3760 PackageSetting ps = (PackageSetting) sb; 3761 if (userId == UserHandle.USER_ALL) { 3762 killApplication(ps.pkg.packageName, ps.appId, reason); 3763 } else { 3764 final int uid = UserHandle.getUid(userId, ps.appId); 3765 killUid(uid, reason); 3766 } 3767 } 3768 } finally { 3769 Binder.restoreCallingIdentity(identity); 3770 } 3771 } 3772 3773 private static void killUid(int uid, String reason) { 3774 IActivityManager am = ActivityManagerNative.getDefault(); 3775 if (am != null) { 3776 try { 3777 am.killUid(uid, reason); 3778 } catch (RemoteException e) { 3779 /* ignore - same process */ 3780 } 3781 } 3782 } 3783 3784 /** 3785 * Compares two sets of signatures. Returns: 3786 * <br /> 3787 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3788 * <br /> 3789 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3790 * <br /> 3791 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3792 * <br /> 3793 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3794 * <br /> 3795 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3796 */ 3797 static int compareSignatures(Signature[] s1, Signature[] s2) { 3798 if (s1 == null) { 3799 return s2 == null 3800 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3801 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3802 } 3803 3804 if (s2 == null) { 3805 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3806 } 3807 3808 if (s1.length != s2.length) { 3809 return PackageManager.SIGNATURE_NO_MATCH; 3810 } 3811 3812 // Since both signature sets are of size 1, we can compare without HashSets. 3813 if (s1.length == 1) { 3814 return s1[0].equals(s2[0]) ? 3815 PackageManager.SIGNATURE_MATCH : 3816 PackageManager.SIGNATURE_NO_MATCH; 3817 } 3818 3819 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3820 for (Signature sig : s1) { 3821 set1.add(sig); 3822 } 3823 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3824 for (Signature sig : s2) { 3825 set2.add(sig); 3826 } 3827 // Make sure s2 contains all signatures in s1. 3828 if (set1.equals(set2)) { 3829 return PackageManager.SIGNATURE_MATCH; 3830 } 3831 return PackageManager.SIGNATURE_NO_MATCH; 3832 } 3833 3834 /** 3835 * If the database version for this type of package (internal storage or 3836 * external storage) is less than the version where package signatures 3837 * were updated, return true. 3838 */ 3839 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3840 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3841 DatabaseVersion.SIGNATURE_END_ENTITY)) 3842 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3843 DatabaseVersion.SIGNATURE_END_ENTITY)); 3844 } 3845 3846 /** 3847 * Used for backward compatibility to make sure any packages with 3848 * certificate chains get upgraded to the new style. {@code existingSigs} 3849 * will be in the old format (since they were stored on disk from before the 3850 * system upgrade) and {@code scannedSigs} will be in the newer format. 3851 */ 3852 private int compareSignaturesCompat(PackageSignatures existingSigs, 3853 PackageParser.Package scannedPkg) { 3854 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3855 return PackageManager.SIGNATURE_NO_MATCH; 3856 } 3857 3858 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3859 for (Signature sig : existingSigs.mSignatures) { 3860 existingSet.add(sig); 3861 } 3862 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3863 for (Signature sig : scannedPkg.mSignatures) { 3864 try { 3865 Signature[] chainSignatures = sig.getChainSignatures(); 3866 for (Signature chainSig : chainSignatures) { 3867 scannedCompatSet.add(chainSig); 3868 } 3869 } catch (CertificateEncodingException e) { 3870 scannedCompatSet.add(sig); 3871 } 3872 } 3873 /* 3874 * Make sure the expanded scanned set contains all signatures in the 3875 * existing one. 3876 */ 3877 if (scannedCompatSet.equals(existingSet)) { 3878 // Migrate the old signatures to the new scheme. 3879 existingSigs.assignSignatures(scannedPkg.mSignatures); 3880 // The new KeySets will be re-added later in the scanning process. 3881 synchronized (mPackages) { 3882 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3883 } 3884 return PackageManager.SIGNATURE_MATCH; 3885 } 3886 return PackageManager.SIGNATURE_NO_MATCH; 3887 } 3888 3889 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3890 if (isExternal(scannedPkg)) { 3891 return mSettings.isExternalDatabaseVersionOlderThan( 3892 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3893 } else { 3894 return mSettings.isInternalDatabaseVersionOlderThan( 3895 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3896 } 3897 } 3898 3899 private int compareSignaturesRecover(PackageSignatures existingSigs, 3900 PackageParser.Package scannedPkg) { 3901 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3902 return PackageManager.SIGNATURE_NO_MATCH; 3903 } 3904 3905 String msg = null; 3906 try { 3907 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3908 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3909 + scannedPkg.packageName); 3910 return PackageManager.SIGNATURE_MATCH; 3911 } 3912 } catch (CertificateException e) { 3913 msg = e.getMessage(); 3914 } 3915 3916 logCriticalInfo(Log.INFO, 3917 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3918 return PackageManager.SIGNATURE_NO_MATCH; 3919 } 3920 3921 @Override 3922 public String[] getPackagesForUid(int uid) { 3923 uid = UserHandle.getAppId(uid); 3924 // reader 3925 synchronized (mPackages) { 3926 Object obj = mSettings.getUserIdLPr(uid); 3927 if (obj instanceof SharedUserSetting) { 3928 final SharedUserSetting sus = (SharedUserSetting) obj; 3929 final int N = sus.packages.size(); 3930 final String[] res = new String[N]; 3931 final Iterator<PackageSetting> it = sus.packages.iterator(); 3932 int i = 0; 3933 while (it.hasNext()) { 3934 res[i++] = it.next().name; 3935 } 3936 return res; 3937 } else if (obj instanceof PackageSetting) { 3938 final PackageSetting ps = (PackageSetting) obj; 3939 return new String[] { ps.name }; 3940 } 3941 } 3942 return null; 3943 } 3944 3945 @Override 3946 public String getNameForUid(int uid) { 3947 // reader 3948 synchronized (mPackages) { 3949 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3950 if (obj instanceof SharedUserSetting) { 3951 final SharedUserSetting sus = (SharedUserSetting) obj; 3952 return sus.name + ":" + sus.userId; 3953 } else if (obj instanceof PackageSetting) { 3954 final PackageSetting ps = (PackageSetting) obj; 3955 return ps.name; 3956 } 3957 } 3958 return null; 3959 } 3960 3961 @Override 3962 public int getUidForSharedUser(String sharedUserName) { 3963 if(sharedUserName == null) { 3964 return -1; 3965 } 3966 // reader 3967 synchronized (mPackages) { 3968 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3969 if (suid == null) { 3970 return -1; 3971 } 3972 return suid.userId; 3973 } 3974 } 3975 3976 @Override 3977 public int getFlagsForUid(int uid) { 3978 synchronized (mPackages) { 3979 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3980 if (obj instanceof SharedUserSetting) { 3981 final SharedUserSetting sus = (SharedUserSetting) obj; 3982 return sus.pkgFlags; 3983 } else if (obj instanceof PackageSetting) { 3984 final PackageSetting ps = (PackageSetting) obj; 3985 return ps.pkgFlags; 3986 } 3987 } 3988 return 0; 3989 } 3990 3991 @Override 3992 public int getPrivateFlagsForUid(int uid) { 3993 synchronized (mPackages) { 3994 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3995 if (obj instanceof SharedUserSetting) { 3996 final SharedUserSetting sus = (SharedUserSetting) obj; 3997 return sus.pkgPrivateFlags; 3998 } else if (obj instanceof PackageSetting) { 3999 final PackageSetting ps = (PackageSetting) obj; 4000 return ps.pkgPrivateFlags; 4001 } 4002 } 4003 return 0; 4004 } 4005 4006 @Override 4007 public boolean isUidPrivileged(int uid) { 4008 uid = UserHandle.getAppId(uid); 4009 // reader 4010 synchronized (mPackages) { 4011 Object obj = mSettings.getUserIdLPr(uid); 4012 if (obj instanceof SharedUserSetting) { 4013 final SharedUserSetting sus = (SharedUserSetting) obj; 4014 final Iterator<PackageSetting> it = sus.packages.iterator(); 4015 while (it.hasNext()) { 4016 if (it.next().isPrivileged()) { 4017 return true; 4018 } 4019 } 4020 } else if (obj instanceof PackageSetting) { 4021 final PackageSetting ps = (PackageSetting) obj; 4022 return ps.isPrivileged(); 4023 } 4024 } 4025 return false; 4026 } 4027 4028 @Override 4029 public String[] getAppOpPermissionPackages(String permissionName) { 4030 synchronized (mPackages) { 4031 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4032 if (pkgs == null) { 4033 return null; 4034 } 4035 return pkgs.toArray(new String[pkgs.size()]); 4036 } 4037 } 4038 4039 @Override 4040 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4041 int flags, int userId) { 4042 if (!sUserManager.exists(userId)) return null; 4043 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4044 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4045 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4046 } 4047 4048 @Override 4049 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4050 IntentFilter filter, int match, ComponentName activity) { 4051 final int userId = UserHandle.getCallingUserId(); 4052 if (DEBUG_PREFERRED) { 4053 Log.v(TAG, "setLastChosenActivity intent=" + intent 4054 + " resolvedType=" + resolvedType 4055 + " flags=" + flags 4056 + " filter=" + filter 4057 + " match=" + match 4058 + " activity=" + activity); 4059 filter.dump(new PrintStreamPrinter(System.out), " "); 4060 } 4061 intent.setComponent(null); 4062 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4063 // Find any earlier preferred or last chosen entries and nuke them 4064 findPreferredActivity(intent, resolvedType, 4065 flags, query, 0, false, true, false, userId); 4066 // Add the new activity as the last chosen for this filter 4067 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4068 "Setting last chosen"); 4069 } 4070 4071 @Override 4072 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4073 final int userId = UserHandle.getCallingUserId(); 4074 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4075 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4076 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4077 false, false, false, userId); 4078 } 4079 4080 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4081 int flags, List<ResolveInfo> query, int userId) { 4082 if (query != null) { 4083 final int N = query.size(); 4084 if (N == 1) { 4085 return query.get(0); 4086 } else if (N > 1) { 4087 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4088 // If there is more than one activity with the same priority, 4089 // then let the user decide between them. 4090 ResolveInfo r0 = query.get(0); 4091 ResolveInfo r1 = query.get(1); 4092 if (DEBUG_INTENT_MATCHING || debug) { 4093 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4094 + r1.activityInfo.name + "=" + r1.priority); 4095 } 4096 // If the first activity has a higher priority, or a different 4097 // default, then it is always desireable to pick it. 4098 if (r0.priority != r1.priority 4099 || r0.preferredOrder != r1.preferredOrder 4100 || r0.isDefault != r1.isDefault) { 4101 return query.get(0); 4102 } 4103 // If we have saved a preference for a preferred activity for 4104 // this Intent, use that. 4105 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4106 flags, query, r0.priority, true, false, debug, userId); 4107 if (ri != null) { 4108 return ri; 4109 } 4110 if (userId != 0) { 4111 ri = new ResolveInfo(mResolveInfo); 4112 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4113 ri.activityInfo.applicationInfo = new ApplicationInfo( 4114 ri.activityInfo.applicationInfo); 4115 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4116 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4117 return ri; 4118 } 4119 return mResolveInfo; 4120 } 4121 } 4122 return null; 4123 } 4124 4125 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4126 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4127 final int N = query.size(); 4128 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4129 .get(userId); 4130 // Get the list of persistent preferred activities that handle the intent 4131 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4132 List<PersistentPreferredActivity> pprefs = ppir != null 4133 ? ppir.queryIntent(intent, resolvedType, 4134 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4135 : null; 4136 if (pprefs != null && pprefs.size() > 0) { 4137 final int M = pprefs.size(); 4138 for (int i=0; i<M; i++) { 4139 final PersistentPreferredActivity ppa = pprefs.get(i); 4140 if (DEBUG_PREFERRED || debug) { 4141 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4142 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4143 + "\n component=" + ppa.mComponent); 4144 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4145 } 4146 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4147 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4148 if (DEBUG_PREFERRED || debug) { 4149 Slog.v(TAG, "Found persistent preferred activity:"); 4150 if (ai != null) { 4151 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4152 } else { 4153 Slog.v(TAG, " null"); 4154 } 4155 } 4156 if (ai == null) { 4157 // This previously registered persistent preferred activity 4158 // component is no longer known. Ignore it and do NOT remove it. 4159 continue; 4160 } 4161 for (int j=0; j<N; j++) { 4162 final ResolveInfo ri = query.get(j); 4163 if (!ri.activityInfo.applicationInfo.packageName 4164 .equals(ai.applicationInfo.packageName)) { 4165 continue; 4166 } 4167 if (!ri.activityInfo.name.equals(ai.name)) { 4168 continue; 4169 } 4170 // Found a persistent preference that can handle the intent. 4171 if (DEBUG_PREFERRED || debug) { 4172 Slog.v(TAG, "Returning persistent preferred activity: " + 4173 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4174 } 4175 return ri; 4176 } 4177 } 4178 } 4179 return null; 4180 } 4181 4182 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4183 List<ResolveInfo> query, int priority, boolean always, 4184 boolean removeMatches, boolean debug, int userId) { 4185 if (!sUserManager.exists(userId)) return null; 4186 // writer 4187 synchronized (mPackages) { 4188 if (intent.getSelector() != null) { 4189 intent = intent.getSelector(); 4190 } 4191 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4192 4193 // Try to find a matching persistent preferred activity. 4194 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4195 debug, userId); 4196 4197 // If a persistent preferred activity matched, use it. 4198 if (pri != null) { 4199 return pri; 4200 } 4201 4202 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4203 // Get the list of preferred activities that handle the intent 4204 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4205 List<PreferredActivity> prefs = pir != null 4206 ? pir.queryIntent(intent, resolvedType, 4207 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4208 : null; 4209 if (prefs != null && prefs.size() > 0) { 4210 boolean changed = false; 4211 try { 4212 // First figure out how good the original match set is. 4213 // We will only allow preferred activities that came 4214 // from the same match quality. 4215 int match = 0; 4216 4217 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4218 4219 final int N = query.size(); 4220 for (int j=0; j<N; j++) { 4221 final ResolveInfo ri = query.get(j); 4222 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4223 + ": 0x" + Integer.toHexString(match)); 4224 if (ri.match > match) { 4225 match = ri.match; 4226 } 4227 } 4228 4229 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4230 + Integer.toHexString(match)); 4231 4232 match &= IntentFilter.MATCH_CATEGORY_MASK; 4233 final int M = prefs.size(); 4234 for (int i=0; i<M; i++) { 4235 final PreferredActivity pa = prefs.get(i); 4236 if (DEBUG_PREFERRED || debug) { 4237 Slog.v(TAG, "Checking PreferredActivity ds=" 4238 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4239 + "\n component=" + pa.mPref.mComponent); 4240 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4241 } 4242 if (pa.mPref.mMatch != match) { 4243 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4244 + Integer.toHexString(pa.mPref.mMatch)); 4245 continue; 4246 } 4247 // If it's not an "always" type preferred activity and that's what we're 4248 // looking for, skip it. 4249 if (always && !pa.mPref.mAlways) { 4250 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4251 continue; 4252 } 4253 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4254 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4255 if (DEBUG_PREFERRED || debug) { 4256 Slog.v(TAG, "Found preferred activity:"); 4257 if (ai != null) { 4258 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4259 } else { 4260 Slog.v(TAG, " null"); 4261 } 4262 } 4263 if (ai == null) { 4264 // This previously registered preferred activity 4265 // component is no longer known. Most likely an update 4266 // to the app was installed and in the new version this 4267 // component no longer exists. Clean it up by removing 4268 // it from the preferred activities list, and skip it. 4269 Slog.w(TAG, "Removing dangling preferred activity: " 4270 + pa.mPref.mComponent); 4271 pir.removeFilter(pa); 4272 changed = true; 4273 continue; 4274 } 4275 for (int j=0; j<N; j++) { 4276 final ResolveInfo ri = query.get(j); 4277 if (!ri.activityInfo.applicationInfo.packageName 4278 .equals(ai.applicationInfo.packageName)) { 4279 continue; 4280 } 4281 if (!ri.activityInfo.name.equals(ai.name)) { 4282 continue; 4283 } 4284 4285 if (removeMatches) { 4286 pir.removeFilter(pa); 4287 changed = true; 4288 if (DEBUG_PREFERRED) { 4289 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4290 } 4291 break; 4292 } 4293 4294 // Okay we found a previously set preferred or last chosen app. 4295 // If the result set is different from when this 4296 // was created, we need to clear it and re-ask the 4297 // user their preference, if we're looking for an "always" type entry. 4298 if (always && !pa.mPref.sameSet(query)) { 4299 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4300 + intent + " type " + resolvedType); 4301 if (DEBUG_PREFERRED) { 4302 Slog.v(TAG, "Removing preferred activity since set changed " 4303 + pa.mPref.mComponent); 4304 } 4305 pir.removeFilter(pa); 4306 // Re-add the filter as a "last chosen" entry (!always) 4307 PreferredActivity lastChosen = new PreferredActivity( 4308 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4309 pir.addFilter(lastChosen); 4310 changed = true; 4311 return null; 4312 } 4313 4314 // Yay! Either the set matched or we're looking for the last chosen 4315 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4316 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4317 return ri; 4318 } 4319 } 4320 } finally { 4321 if (changed) { 4322 if (DEBUG_PREFERRED) { 4323 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4324 } 4325 scheduleWritePackageRestrictionsLocked(userId); 4326 } 4327 } 4328 } 4329 } 4330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4331 return null; 4332 } 4333 4334 /* 4335 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4336 */ 4337 @Override 4338 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4339 int targetUserId) { 4340 mContext.enforceCallingOrSelfPermission( 4341 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4342 List<CrossProfileIntentFilter> matches = 4343 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4344 if (matches != null) { 4345 int size = matches.size(); 4346 for (int i = 0; i < size; i++) { 4347 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4348 } 4349 } 4350 if (hasWebURI(intent)) { 4351 // cross-profile app linking works only towards the parent. 4352 final UserInfo parent = getProfileParent(sourceUserId); 4353 synchronized(mPackages) { 4354 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4355 parent.id) != null; 4356 } 4357 } 4358 return false; 4359 } 4360 4361 private UserInfo getProfileParent(int userId) { 4362 final long identity = Binder.clearCallingIdentity(); 4363 try { 4364 return sUserManager.getProfileParent(userId); 4365 } finally { 4366 Binder.restoreCallingIdentity(identity); 4367 } 4368 } 4369 4370 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4371 String resolvedType, int userId) { 4372 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4373 if (resolver != null) { 4374 return resolver.queryIntent(intent, resolvedType, false, userId); 4375 } 4376 return null; 4377 } 4378 4379 @Override 4380 public List<ResolveInfo> queryIntentActivities(Intent intent, 4381 String resolvedType, int flags, int userId) { 4382 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4383 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4384 ComponentName comp = intent.getComponent(); 4385 if (comp == null) { 4386 if (intent.getSelector() != null) { 4387 intent = intent.getSelector(); 4388 comp = intent.getComponent(); 4389 } 4390 } 4391 4392 if (comp != null) { 4393 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4394 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4395 if (ai != null) { 4396 final ResolveInfo ri = new ResolveInfo(); 4397 ri.activityInfo = ai; 4398 list.add(ri); 4399 } 4400 return list; 4401 } 4402 4403 // reader 4404 synchronized (mPackages) { 4405 final String pkgName = intent.getPackage(); 4406 if (pkgName == null) { 4407 List<CrossProfileIntentFilter> matchingFilters = 4408 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4409 // Check for results that need to skip the current profile. 4410 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4411 resolvedType, flags, userId); 4412 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4413 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4414 result.add(xpResolveInfo); 4415 return filterIfNotPrimaryUser(result, userId); 4416 } 4417 4418 // Check for results in the current profile. 4419 List<ResolveInfo> result = mActivities.queryIntent( 4420 intent, resolvedType, flags, userId); 4421 4422 // Check for cross profile results. 4423 xpResolveInfo = queryCrossProfileIntents( 4424 matchingFilters, intent, resolvedType, flags, userId); 4425 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4426 result.add(xpResolveInfo); 4427 Collections.sort(result, mResolvePrioritySorter); 4428 } 4429 result = filterIfNotPrimaryUser(result, userId); 4430 if (hasWebURI(intent)) { 4431 CrossProfileDomainInfo xpDomainInfo = null; 4432 final UserInfo parent = getProfileParent(userId); 4433 if (parent != null) { 4434 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4435 flags, userId, parent.id); 4436 } 4437 if (xpDomainInfo != null) { 4438 if (xpResolveInfo != null) { 4439 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4440 // in the result. 4441 result.remove(xpResolveInfo); 4442 } 4443 if (result.size() == 0) { 4444 result.add(xpDomainInfo.resolveInfo); 4445 return result; 4446 } 4447 } else if (result.size() <= 1) { 4448 return result; 4449 } 4450 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4451 xpDomainInfo); 4452 Collections.sort(result, mResolvePrioritySorter); 4453 } 4454 return result; 4455 } 4456 final PackageParser.Package pkg = mPackages.get(pkgName); 4457 if (pkg != null) { 4458 return filterIfNotPrimaryUser( 4459 mActivities.queryIntentForPackage( 4460 intent, resolvedType, flags, pkg.activities, userId), 4461 userId); 4462 } 4463 return new ArrayList<ResolveInfo>(); 4464 } 4465 } 4466 4467 private static class CrossProfileDomainInfo { 4468 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4469 ResolveInfo resolveInfo; 4470 /* Best domain verification status of the activities found in the other profile */ 4471 int bestDomainVerificationStatus; 4472 } 4473 4474 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4475 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4476 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4477 sourceUserId)) { 4478 return null; 4479 } 4480 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4481 resolvedType, flags, parentUserId); 4482 4483 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4484 return null; 4485 } 4486 CrossProfileDomainInfo result = null; 4487 int size = resultTargetUser.size(); 4488 for (int i = 0; i < size; i++) { 4489 ResolveInfo riTargetUser = resultTargetUser.get(i); 4490 // Intent filter verification is only for filters that specify a host. So don't return 4491 // those that handle all web uris. 4492 if (riTargetUser.handleAllWebDataURI) { 4493 continue; 4494 } 4495 String packageName = riTargetUser.activityInfo.packageName; 4496 PackageSetting ps = mSettings.mPackages.get(packageName); 4497 if (ps == null) { 4498 continue; 4499 } 4500 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4501 if (result == null) { 4502 result = new CrossProfileDomainInfo(); 4503 result.resolveInfo = 4504 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4505 result.bestDomainVerificationStatus = status; 4506 } else { 4507 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4508 result.bestDomainVerificationStatus); 4509 } 4510 } 4511 return result; 4512 } 4513 4514 /** 4515 * Verification statuses are ordered from the worse to the best, except for 4516 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4517 */ 4518 private int bestDomainVerificationStatus(int status1, int status2) { 4519 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4520 return status2; 4521 } 4522 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4523 return status1; 4524 } 4525 return (int) MathUtils.max(status1, status2); 4526 } 4527 4528 private boolean isUserEnabled(int userId) { 4529 long callingId = Binder.clearCallingIdentity(); 4530 try { 4531 UserInfo userInfo = sUserManager.getUserInfo(userId); 4532 return userInfo != null && userInfo.isEnabled(); 4533 } finally { 4534 Binder.restoreCallingIdentity(callingId); 4535 } 4536 } 4537 4538 /** 4539 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4540 * 4541 * @return filtered list 4542 */ 4543 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4544 if (userId == UserHandle.USER_OWNER) { 4545 return resolveInfos; 4546 } 4547 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4548 ResolveInfo info = resolveInfos.get(i); 4549 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4550 resolveInfos.remove(i); 4551 } 4552 } 4553 return resolveInfos; 4554 } 4555 4556 private static boolean hasWebURI(Intent intent) { 4557 if (intent.getData() == null) { 4558 return false; 4559 } 4560 final String scheme = intent.getScheme(); 4561 if (TextUtils.isEmpty(scheme)) { 4562 return false; 4563 } 4564 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4565 } 4566 4567 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4568 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4569 if (DEBUG_PREFERRED) { 4570 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4571 candidates.size()); 4572 } 4573 4574 final int userId = UserHandle.getCallingUserId(); 4575 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4576 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4577 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4578 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4579 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4580 4581 synchronized (mPackages) { 4582 final int count = candidates.size(); 4583 // First, try to use the domain preferred app. Partition the candidates into four lists: 4584 // one for the final results, one for the "do not use ever", one for "undefined status" 4585 // and finally one for "Browser App type". 4586 for (int n=0; n<count; n++) { 4587 ResolveInfo info = candidates.get(n); 4588 String packageName = info.activityInfo.packageName; 4589 PackageSetting ps = mSettings.mPackages.get(packageName); 4590 if (ps != null) { 4591 // Add to the special match all list (Browser use case) 4592 if (info.handleAllWebDataURI) { 4593 matchAllList.add(info); 4594 continue; 4595 } 4596 // Try to get the status from User settings first 4597 int status = getDomainVerificationStatusLPr(ps, userId); 4598 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4599 alwaysList.add(info); 4600 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4601 neverList.add(info); 4602 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4603 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4604 undefinedList.add(info); 4605 } 4606 } 4607 } 4608 // First try to add the "always" resolution for the current user if there is any 4609 if (alwaysList.size() > 0) { 4610 result.addAll(alwaysList); 4611 // if there is an "always" for the parent user, add it. 4612 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4613 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4614 result.add(xpDomainInfo.resolveInfo); 4615 } else { 4616 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4617 result.addAll(undefinedList); 4618 if (xpDomainInfo != null && ( 4619 xpDomainInfo.bestDomainVerificationStatus 4620 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4621 || xpDomainInfo.bestDomainVerificationStatus 4622 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4623 result.add(xpDomainInfo.resolveInfo); 4624 } 4625 // Also add Browsers (all of them or only the default one) 4626 if ((flags & MATCH_ALL) != 0) { 4627 result.addAll(matchAllList); 4628 } else { 4629 // Try to add the Default Browser if we can 4630 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4631 UserHandle.myUserId()); 4632 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4633 boolean defaultBrowserFound = false; 4634 final int browserCount = matchAllList.size(); 4635 for (int n=0; n<browserCount; n++) { 4636 ResolveInfo browser = matchAllList.get(n); 4637 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4638 result.add(browser); 4639 defaultBrowserFound = true; 4640 break; 4641 } 4642 } 4643 if (!defaultBrowserFound) { 4644 result.addAll(matchAllList); 4645 } 4646 } else { 4647 result.addAll(matchAllList); 4648 } 4649 } 4650 4651 // If there is nothing selected, add all candidates and remove the ones that the User 4652 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4653 if (result.size() == 0) { 4654 result.addAll(candidates); 4655 result.removeAll(neverList); 4656 } 4657 } 4658 } 4659 if (DEBUG_PREFERRED) { 4660 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4661 result.size()); 4662 } 4663 return result; 4664 } 4665 4666 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4667 int status = ps.getDomainVerificationStatusForUser(userId); 4668 // if none available, get the master status 4669 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4670 if (ps.getIntentFilterVerificationInfo() != null) { 4671 status = ps.getIntentFilterVerificationInfo().getStatus(); 4672 } 4673 } 4674 return status; 4675 } 4676 4677 private ResolveInfo querySkipCurrentProfileIntents( 4678 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4679 int flags, int sourceUserId) { 4680 if (matchingFilters != null) { 4681 int size = matchingFilters.size(); 4682 for (int i = 0; i < size; i ++) { 4683 CrossProfileIntentFilter filter = matchingFilters.get(i); 4684 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4685 // Checking if there are activities in the target user that can handle the 4686 // intent. 4687 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4688 flags, sourceUserId); 4689 if (resolveInfo != null) { 4690 return resolveInfo; 4691 } 4692 } 4693 } 4694 } 4695 return null; 4696 } 4697 4698 // Return matching ResolveInfo if any for skip current profile intent filters. 4699 private ResolveInfo queryCrossProfileIntents( 4700 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4701 int flags, int sourceUserId) { 4702 if (matchingFilters != null) { 4703 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4704 // match the same intent. For performance reasons, it is better not to 4705 // run queryIntent twice for the same userId 4706 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4707 int size = matchingFilters.size(); 4708 for (int i = 0; i < size; i++) { 4709 CrossProfileIntentFilter filter = matchingFilters.get(i); 4710 int targetUserId = filter.getTargetUserId(); 4711 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4712 && !alreadyTriedUserIds.get(targetUserId)) { 4713 // Checking if there are activities in the target user that can handle the 4714 // intent. 4715 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4716 flags, sourceUserId); 4717 if (resolveInfo != null) return resolveInfo; 4718 alreadyTriedUserIds.put(targetUserId, true); 4719 } 4720 } 4721 } 4722 return null; 4723 } 4724 4725 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4726 String resolvedType, int flags, int sourceUserId) { 4727 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4728 resolvedType, flags, filter.getTargetUserId()); 4729 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4730 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4731 } 4732 return null; 4733 } 4734 4735 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4736 int sourceUserId, int targetUserId) { 4737 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4738 String className; 4739 if (targetUserId == UserHandle.USER_OWNER) { 4740 className = FORWARD_INTENT_TO_USER_OWNER; 4741 } else { 4742 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4743 } 4744 ComponentName forwardingActivityComponentName = new ComponentName( 4745 mAndroidApplication.packageName, className); 4746 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4747 sourceUserId); 4748 if (targetUserId == UserHandle.USER_OWNER) { 4749 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4750 forwardingResolveInfo.noResourceId = true; 4751 } 4752 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4753 forwardingResolveInfo.priority = 0; 4754 forwardingResolveInfo.preferredOrder = 0; 4755 forwardingResolveInfo.match = 0; 4756 forwardingResolveInfo.isDefault = true; 4757 forwardingResolveInfo.filter = filter; 4758 forwardingResolveInfo.targetUserId = targetUserId; 4759 return forwardingResolveInfo; 4760 } 4761 4762 @Override 4763 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4764 Intent[] specifics, String[] specificTypes, Intent intent, 4765 String resolvedType, int flags, int userId) { 4766 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4767 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4768 false, "query intent activity options"); 4769 final String resultsAction = intent.getAction(); 4770 4771 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4772 | PackageManager.GET_RESOLVED_FILTER, userId); 4773 4774 if (DEBUG_INTENT_MATCHING) { 4775 Log.v(TAG, "Query " + intent + ": " + results); 4776 } 4777 4778 int specificsPos = 0; 4779 int N; 4780 4781 // todo: note that the algorithm used here is O(N^2). This 4782 // isn't a problem in our current environment, but if we start running 4783 // into situations where we have more than 5 or 10 matches then this 4784 // should probably be changed to something smarter... 4785 4786 // First we go through and resolve each of the specific items 4787 // that were supplied, taking care of removing any corresponding 4788 // duplicate items in the generic resolve list. 4789 if (specifics != null) { 4790 for (int i=0; i<specifics.length; i++) { 4791 final Intent sintent = specifics[i]; 4792 if (sintent == null) { 4793 continue; 4794 } 4795 4796 if (DEBUG_INTENT_MATCHING) { 4797 Log.v(TAG, "Specific #" + i + ": " + sintent); 4798 } 4799 4800 String action = sintent.getAction(); 4801 if (resultsAction != null && resultsAction.equals(action)) { 4802 // If this action was explicitly requested, then don't 4803 // remove things that have it. 4804 action = null; 4805 } 4806 4807 ResolveInfo ri = null; 4808 ActivityInfo ai = null; 4809 4810 ComponentName comp = sintent.getComponent(); 4811 if (comp == null) { 4812 ri = resolveIntent( 4813 sintent, 4814 specificTypes != null ? specificTypes[i] : null, 4815 flags, userId); 4816 if (ri == null) { 4817 continue; 4818 } 4819 if (ri == mResolveInfo) { 4820 // ACK! Must do something better with this. 4821 } 4822 ai = ri.activityInfo; 4823 comp = new ComponentName(ai.applicationInfo.packageName, 4824 ai.name); 4825 } else { 4826 ai = getActivityInfo(comp, flags, userId); 4827 if (ai == null) { 4828 continue; 4829 } 4830 } 4831 4832 // Look for any generic query activities that are duplicates 4833 // of this specific one, and remove them from the results. 4834 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4835 N = results.size(); 4836 int j; 4837 for (j=specificsPos; j<N; j++) { 4838 ResolveInfo sri = results.get(j); 4839 if ((sri.activityInfo.name.equals(comp.getClassName()) 4840 && sri.activityInfo.applicationInfo.packageName.equals( 4841 comp.getPackageName())) 4842 || (action != null && sri.filter.matchAction(action))) { 4843 results.remove(j); 4844 if (DEBUG_INTENT_MATCHING) Log.v( 4845 TAG, "Removing duplicate item from " + j 4846 + " due to specific " + specificsPos); 4847 if (ri == null) { 4848 ri = sri; 4849 } 4850 j--; 4851 N--; 4852 } 4853 } 4854 4855 // Add this specific item to its proper place. 4856 if (ri == null) { 4857 ri = new ResolveInfo(); 4858 ri.activityInfo = ai; 4859 } 4860 results.add(specificsPos, ri); 4861 ri.specificIndex = i; 4862 specificsPos++; 4863 } 4864 } 4865 4866 // Now we go through the remaining generic results and remove any 4867 // duplicate actions that are found here. 4868 N = results.size(); 4869 for (int i=specificsPos; i<N-1; i++) { 4870 final ResolveInfo rii = results.get(i); 4871 if (rii.filter == null) { 4872 continue; 4873 } 4874 4875 // Iterate over all of the actions of this result's intent 4876 // filter... typically this should be just one. 4877 final Iterator<String> it = rii.filter.actionsIterator(); 4878 if (it == null) { 4879 continue; 4880 } 4881 while (it.hasNext()) { 4882 final String action = it.next(); 4883 if (resultsAction != null && resultsAction.equals(action)) { 4884 // If this action was explicitly requested, then don't 4885 // remove things that have it. 4886 continue; 4887 } 4888 for (int j=i+1; j<N; j++) { 4889 final ResolveInfo rij = results.get(j); 4890 if (rij.filter != null && rij.filter.hasAction(action)) { 4891 results.remove(j); 4892 if (DEBUG_INTENT_MATCHING) Log.v( 4893 TAG, "Removing duplicate item from " + j 4894 + " due to action " + action + " at " + i); 4895 j--; 4896 N--; 4897 } 4898 } 4899 } 4900 4901 // If the caller didn't request filter information, drop it now 4902 // so we don't have to marshall/unmarshall it. 4903 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4904 rii.filter = null; 4905 } 4906 } 4907 4908 // Filter out the caller activity if so requested. 4909 if (caller != null) { 4910 N = results.size(); 4911 for (int i=0; i<N; i++) { 4912 ActivityInfo ainfo = results.get(i).activityInfo; 4913 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4914 && caller.getClassName().equals(ainfo.name)) { 4915 results.remove(i); 4916 break; 4917 } 4918 } 4919 } 4920 4921 // If the caller didn't request filter information, 4922 // drop them now so we don't have to 4923 // marshall/unmarshall it. 4924 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4925 N = results.size(); 4926 for (int i=0; i<N; i++) { 4927 results.get(i).filter = null; 4928 } 4929 } 4930 4931 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4932 return results; 4933 } 4934 4935 @Override 4936 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4937 int userId) { 4938 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4939 ComponentName comp = intent.getComponent(); 4940 if (comp == null) { 4941 if (intent.getSelector() != null) { 4942 intent = intent.getSelector(); 4943 comp = intent.getComponent(); 4944 } 4945 } 4946 if (comp != null) { 4947 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4948 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4949 if (ai != null) { 4950 ResolveInfo ri = new ResolveInfo(); 4951 ri.activityInfo = ai; 4952 list.add(ri); 4953 } 4954 return list; 4955 } 4956 4957 // reader 4958 synchronized (mPackages) { 4959 String pkgName = intent.getPackage(); 4960 if (pkgName == null) { 4961 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4962 } 4963 final PackageParser.Package pkg = mPackages.get(pkgName); 4964 if (pkg != null) { 4965 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4966 userId); 4967 } 4968 return null; 4969 } 4970 } 4971 4972 @Override 4973 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4974 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4975 if (!sUserManager.exists(userId)) return null; 4976 if (query != null) { 4977 if (query.size() >= 1) { 4978 // If there is more than one service with the same priority, 4979 // just arbitrarily pick the first one. 4980 return query.get(0); 4981 } 4982 } 4983 return null; 4984 } 4985 4986 @Override 4987 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4988 int userId) { 4989 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4990 ComponentName comp = intent.getComponent(); 4991 if (comp == null) { 4992 if (intent.getSelector() != null) { 4993 intent = intent.getSelector(); 4994 comp = intent.getComponent(); 4995 } 4996 } 4997 if (comp != null) { 4998 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4999 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5000 if (si != null) { 5001 final ResolveInfo ri = new ResolveInfo(); 5002 ri.serviceInfo = si; 5003 list.add(ri); 5004 } 5005 return list; 5006 } 5007 5008 // reader 5009 synchronized (mPackages) { 5010 String pkgName = intent.getPackage(); 5011 if (pkgName == null) { 5012 return mServices.queryIntent(intent, resolvedType, flags, userId); 5013 } 5014 final PackageParser.Package pkg = mPackages.get(pkgName); 5015 if (pkg != null) { 5016 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5017 userId); 5018 } 5019 return null; 5020 } 5021 } 5022 5023 @Override 5024 public List<ResolveInfo> queryIntentContentProviders( 5025 Intent intent, String resolvedType, int flags, int userId) { 5026 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5027 ComponentName comp = intent.getComponent(); 5028 if (comp == null) { 5029 if (intent.getSelector() != null) { 5030 intent = intent.getSelector(); 5031 comp = intent.getComponent(); 5032 } 5033 } 5034 if (comp != null) { 5035 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5036 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5037 if (pi != null) { 5038 final ResolveInfo ri = new ResolveInfo(); 5039 ri.providerInfo = pi; 5040 list.add(ri); 5041 } 5042 return list; 5043 } 5044 5045 // reader 5046 synchronized (mPackages) { 5047 String pkgName = intent.getPackage(); 5048 if (pkgName == null) { 5049 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5050 } 5051 final PackageParser.Package pkg = mPackages.get(pkgName); 5052 if (pkg != null) { 5053 return mProviders.queryIntentForPackage( 5054 intent, resolvedType, flags, pkg.providers, userId); 5055 } 5056 return null; 5057 } 5058 } 5059 5060 @Override 5061 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5062 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5063 5064 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5065 5066 // writer 5067 synchronized (mPackages) { 5068 ArrayList<PackageInfo> list; 5069 if (listUninstalled) { 5070 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5071 for (PackageSetting ps : mSettings.mPackages.values()) { 5072 PackageInfo pi; 5073 if (ps.pkg != null) { 5074 pi = generatePackageInfo(ps.pkg, flags, userId); 5075 } else { 5076 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5077 } 5078 if (pi != null) { 5079 list.add(pi); 5080 } 5081 } 5082 } else { 5083 list = new ArrayList<PackageInfo>(mPackages.size()); 5084 for (PackageParser.Package p : mPackages.values()) { 5085 PackageInfo pi = generatePackageInfo(p, flags, userId); 5086 if (pi != null) { 5087 list.add(pi); 5088 } 5089 } 5090 } 5091 5092 return new ParceledListSlice<PackageInfo>(list); 5093 } 5094 } 5095 5096 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5097 String[] permissions, boolean[] tmp, int flags, int userId) { 5098 int numMatch = 0; 5099 final PermissionsState permissionsState = ps.getPermissionsState(); 5100 for (int i=0; i<permissions.length; i++) { 5101 final String permission = permissions[i]; 5102 if (permissionsState.hasPermission(permission, userId)) { 5103 tmp[i] = true; 5104 numMatch++; 5105 } else { 5106 tmp[i] = false; 5107 } 5108 } 5109 if (numMatch == 0) { 5110 return; 5111 } 5112 PackageInfo pi; 5113 if (ps.pkg != null) { 5114 pi = generatePackageInfo(ps.pkg, flags, userId); 5115 } else { 5116 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5117 } 5118 // The above might return null in cases of uninstalled apps or install-state 5119 // skew across users/profiles. 5120 if (pi != null) { 5121 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5122 if (numMatch == permissions.length) { 5123 pi.requestedPermissions = permissions; 5124 } else { 5125 pi.requestedPermissions = new String[numMatch]; 5126 numMatch = 0; 5127 for (int i=0; i<permissions.length; i++) { 5128 if (tmp[i]) { 5129 pi.requestedPermissions[numMatch] = permissions[i]; 5130 numMatch++; 5131 } 5132 } 5133 } 5134 } 5135 list.add(pi); 5136 } 5137 } 5138 5139 @Override 5140 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5141 String[] permissions, int flags, int userId) { 5142 if (!sUserManager.exists(userId)) return null; 5143 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5144 5145 // writer 5146 synchronized (mPackages) { 5147 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5148 boolean[] tmpBools = new boolean[permissions.length]; 5149 if (listUninstalled) { 5150 for (PackageSetting ps : mSettings.mPackages.values()) { 5151 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5152 } 5153 } else { 5154 for (PackageParser.Package pkg : mPackages.values()) { 5155 PackageSetting ps = (PackageSetting)pkg.mExtras; 5156 if (ps != null) { 5157 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5158 userId); 5159 } 5160 } 5161 } 5162 5163 return new ParceledListSlice<PackageInfo>(list); 5164 } 5165 } 5166 5167 @Override 5168 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5169 if (!sUserManager.exists(userId)) return null; 5170 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5171 5172 // writer 5173 synchronized (mPackages) { 5174 ArrayList<ApplicationInfo> list; 5175 if (listUninstalled) { 5176 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5177 for (PackageSetting ps : mSettings.mPackages.values()) { 5178 ApplicationInfo ai; 5179 if (ps.pkg != null) { 5180 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5181 ps.readUserState(userId), userId); 5182 } else { 5183 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5184 } 5185 if (ai != null) { 5186 list.add(ai); 5187 } 5188 } 5189 } else { 5190 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5191 for (PackageParser.Package p : mPackages.values()) { 5192 if (p.mExtras != null) { 5193 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5194 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5195 if (ai != null) { 5196 list.add(ai); 5197 } 5198 } 5199 } 5200 } 5201 5202 return new ParceledListSlice<ApplicationInfo>(list); 5203 } 5204 } 5205 5206 public List<ApplicationInfo> getPersistentApplications(int flags) { 5207 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5208 5209 // reader 5210 synchronized (mPackages) { 5211 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5212 final int userId = UserHandle.getCallingUserId(); 5213 while (i.hasNext()) { 5214 final PackageParser.Package p = i.next(); 5215 if (p.applicationInfo != null 5216 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5217 && (!mSafeMode || isSystemApp(p))) { 5218 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5219 if (ps != null) { 5220 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5221 ps.readUserState(userId), userId); 5222 if (ai != null) { 5223 finalList.add(ai); 5224 } 5225 } 5226 } 5227 } 5228 } 5229 5230 return finalList; 5231 } 5232 5233 @Override 5234 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5235 if (!sUserManager.exists(userId)) return null; 5236 // reader 5237 synchronized (mPackages) { 5238 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5239 PackageSetting ps = provider != null 5240 ? mSettings.mPackages.get(provider.owner.packageName) 5241 : null; 5242 return ps != null 5243 && mSettings.isEnabledLPr(provider.info, flags, userId) 5244 && (!mSafeMode || (provider.info.applicationInfo.flags 5245 &ApplicationInfo.FLAG_SYSTEM) != 0) 5246 ? PackageParser.generateProviderInfo(provider, flags, 5247 ps.readUserState(userId), userId) 5248 : null; 5249 } 5250 } 5251 5252 /** 5253 * @deprecated 5254 */ 5255 @Deprecated 5256 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5257 // reader 5258 synchronized (mPackages) { 5259 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5260 .entrySet().iterator(); 5261 final int userId = UserHandle.getCallingUserId(); 5262 while (i.hasNext()) { 5263 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5264 PackageParser.Provider p = entry.getValue(); 5265 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5266 5267 if (ps != null && p.syncable 5268 && (!mSafeMode || (p.info.applicationInfo.flags 5269 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5270 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5271 ps.readUserState(userId), userId); 5272 if (info != null) { 5273 outNames.add(entry.getKey()); 5274 outInfo.add(info); 5275 } 5276 } 5277 } 5278 } 5279 } 5280 5281 @Override 5282 public List<ProviderInfo> queryContentProviders(String processName, 5283 int uid, int flags) { 5284 ArrayList<ProviderInfo> finalList = null; 5285 // reader 5286 synchronized (mPackages) { 5287 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5288 final int userId = processName != null ? 5289 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5290 while (i.hasNext()) { 5291 final PackageParser.Provider p = i.next(); 5292 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5293 if (ps != null && p.info.authority != null 5294 && (processName == null 5295 || (p.info.processName.equals(processName) 5296 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5297 && mSettings.isEnabledLPr(p.info, flags, userId) 5298 && (!mSafeMode 5299 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5300 if (finalList == null) { 5301 finalList = new ArrayList<ProviderInfo>(3); 5302 } 5303 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5304 ps.readUserState(userId), userId); 5305 if (info != null) { 5306 finalList.add(info); 5307 } 5308 } 5309 } 5310 } 5311 5312 if (finalList != null) { 5313 Collections.sort(finalList, mProviderInitOrderSorter); 5314 } 5315 5316 return finalList; 5317 } 5318 5319 @Override 5320 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5321 int flags) { 5322 // reader 5323 synchronized (mPackages) { 5324 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5325 return PackageParser.generateInstrumentationInfo(i, flags); 5326 } 5327 } 5328 5329 @Override 5330 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5331 int flags) { 5332 ArrayList<InstrumentationInfo> finalList = 5333 new ArrayList<InstrumentationInfo>(); 5334 5335 // reader 5336 synchronized (mPackages) { 5337 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5338 while (i.hasNext()) { 5339 final PackageParser.Instrumentation p = i.next(); 5340 if (targetPackage == null 5341 || targetPackage.equals(p.info.targetPackage)) { 5342 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5343 flags); 5344 if (ii != null) { 5345 finalList.add(ii); 5346 } 5347 } 5348 } 5349 } 5350 5351 return finalList; 5352 } 5353 5354 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5355 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5356 if (overlays == null) { 5357 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5358 return; 5359 } 5360 for (PackageParser.Package opkg : overlays.values()) { 5361 // Not much to do if idmap fails: we already logged the error 5362 // and we certainly don't want to abort installation of pkg simply 5363 // because an overlay didn't fit properly. For these reasons, 5364 // ignore the return value of createIdmapForPackagePairLI. 5365 createIdmapForPackagePairLI(pkg, opkg); 5366 } 5367 } 5368 5369 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5370 PackageParser.Package opkg) { 5371 if (!opkg.mTrustedOverlay) { 5372 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5373 opkg.baseCodePath + ": overlay not trusted"); 5374 return false; 5375 } 5376 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5377 if (overlaySet == null) { 5378 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5379 opkg.baseCodePath + " but target package has no known overlays"); 5380 return false; 5381 } 5382 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5383 // TODO: generate idmap for split APKs 5384 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5385 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5386 + opkg.baseCodePath); 5387 return false; 5388 } 5389 PackageParser.Package[] overlayArray = 5390 overlaySet.values().toArray(new PackageParser.Package[0]); 5391 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5392 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5393 return p1.mOverlayPriority - p2.mOverlayPriority; 5394 } 5395 }; 5396 Arrays.sort(overlayArray, cmp); 5397 5398 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5399 int i = 0; 5400 for (PackageParser.Package p : overlayArray) { 5401 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5402 } 5403 return true; 5404 } 5405 5406 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5407 final File[] files = dir.listFiles(); 5408 if (ArrayUtils.isEmpty(files)) { 5409 Log.d(TAG, "No files in app dir " + dir); 5410 return; 5411 } 5412 5413 if (DEBUG_PACKAGE_SCANNING) { 5414 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5415 + " flags=0x" + Integer.toHexString(parseFlags)); 5416 } 5417 5418 for (File file : files) { 5419 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5420 && !PackageInstallerService.isStageName(file.getName()); 5421 if (!isPackage) { 5422 // Ignore entries which are not packages 5423 continue; 5424 } 5425 try { 5426 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5427 scanFlags, currentTime, null); 5428 } catch (PackageManagerException e) { 5429 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5430 5431 // Delete invalid userdata apps 5432 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5433 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5434 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5435 if (file.isDirectory()) { 5436 mInstaller.rmPackageDir(file.getAbsolutePath()); 5437 } else { 5438 file.delete(); 5439 } 5440 } 5441 } 5442 } 5443 } 5444 5445 private static File getSettingsProblemFile() { 5446 File dataDir = Environment.getDataDirectory(); 5447 File systemDir = new File(dataDir, "system"); 5448 File fname = new File(systemDir, "uiderrors.txt"); 5449 return fname; 5450 } 5451 5452 static void reportSettingsProblem(int priority, String msg) { 5453 logCriticalInfo(priority, msg); 5454 } 5455 5456 static void logCriticalInfo(int priority, String msg) { 5457 Slog.println(priority, TAG, msg); 5458 EventLogTags.writePmCriticalInfo(msg); 5459 try { 5460 File fname = getSettingsProblemFile(); 5461 FileOutputStream out = new FileOutputStream(fname, true); 5462 PrintWriter pw = new FastPrintWriter(out); 5463 SimpleDateFormat formatter = new SimpleDateFormat(); 5464 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5465 pw.println(dateString + ": " + msg); 5466 pw.close(); 5467 FileUtils.setPermissions( 5468 fname.toString(), 5469 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5470 -1, -1); 5471 } catch (java.io.IOException e) { 5472 } 5473 } 5474 5475 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5476 PackageParser.Package pkg, File srcFile, int parseFlags) 5477 throws PackageManagerException { 5478 if (ps != null 5479 && ps.codePath.equals(srcFile) 5480 && ps.timeStamp == srcFile.lastModified() 5481 && !isCompatSignatureUpdateNeeded(pkg) 5482 && !isRecoverSignatureUpdateNeeded(pkg)) { 5483 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5484 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5485 ArraySet<PublicKey> signingKs; 5486 synchronized (mPackages) { 5487 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5488 } 5489 if (ps.signatures.mSignatures != null 5490 && ps.signatures.mSignatures.length != 0 5491 && signingKs != null) { 5492 // Optimization: reuse the existing cached certificates 5493 // if the package appears to be unchanged. 5494 pkg.mSignatures = ps.signatures.mSignatures; 5495 pkg.mSigningKeys = signingKs; 5496 return; 5497 } 5498 5499 Slog.w(TAG, "PackageSetting for " + ps.name 5500 + " is missing signatures. Collecting certs again to recover them."); 5501 } else { 5502 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5503 } 5504 5505 try { 5506 pp.collectCertificates(pkg, parseFlags); 5507 pp.collectManifestDigest(pkg); 5508 } catch (PackageParserException e) { 5509 throw PackageManagerException.from(e); 5510 } 5511 } 5512 5513 /* 5514 * Scan a package and return the newly parsed package. 5515 * Returns null in case of errors and the error code is stored in mLastScanError 5516 */ 5517 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5518 long currentTime, UserHandle user) throws PackageManagerException { 5519 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5520 parseFlags |= mDefParseFlags; 5521 PackageParser pp = new PackageParser(); 5522 pp.setSeparateProcesses(mSeparateProcesses); 5523 pp.setOnlyCoreApps(mOnlyCore); 5524 pp.setDisplayMetrics(mMetrics); 5525 5526 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5527 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5528 } 5529 5530 final PackageParser.Package pkg; 5531 try { 5532 pkg = pp.parsePackage(scanFile, parseFlags); 5533 } catch (PackageParserException e) { 5534 throw PackageManagerException.from(e); 5535 } 5536 5537 PackageSetting ps = null; 5538 PackageSetting updatedPkg; 5539 // reader 5540 synchronized (mPackages) { 5541 // Look to see if we already know about this package. 5542 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5543 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5544 // This package has been renamed to its original name. Let's 5545 // use that. 5546 ps = mSettings.peekPackageLPr(oldName); 5547 } 5548 // If there was no original package, see one for the real package name. 5549 if (ps == null) { 5550 ps = mSettings.peekPackageLPr(pkg.packageName); 5551 } 5552 // Check to see if this package could be hiding/updating a system 5553 // package. Must look for it either under the original or real 5554 // package name depending on our state. 5555 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5556 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5557 } 5558 boolean updatedPkgBetter = false; 5559 // First check if this is a system package that may involve an update 5560 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5561 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5562 // it needs to drop FLAG_PRIVILEGED. 5563 if (locationIsPrivileged(scanFile)) { 5564 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5565 } else { 5566 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5567 } 5568 5569 if (ps != null && !ps.codePath.equals(scanFile)) { 5570 // The path has changed from what was last scanned... check the 5571 // version of the new path against what we have stored to determine 5572 // what to do. 5573 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5574 if (pkg.mVersionCode <= ps.versionCode) { 5575 // The system package has been updated and the code path does not match 5576 // Ignore entry. Skip it. 5577 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5578 + " ignored: updated version " + ps.versionCode 5579 + " better than this " + pkg.mVersionCode); 5580 if (!updatedPkg.codePath.equals(scanFile)) { 5581 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5582 + ps.name + " changing from " + updatedPkg.codePathString 5583 + " to " + scanFile); 5584 updatedPkg.codePath = scanFile; 5585 updatedPkg.codePathString = scanFile.toString(); 5586 updatedPkg.resourcePath = scanFile; 5587 updatedPkg.resourcePathString = scanFile.toString(); 5588 } 5589 updatedPkg.pkg = pkg; 5590 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5591 } else { 5592 // The current app on the system partition is better than 5593 // what we have updated to on the data partition; switch 5594 // back to the system partition version. 5595 // At this point, its safely assumed that package installation for 5596 // apps in system partition will go through. If not there won't be a working 5597 // version of the app 5598 // writer 5599 synchronized (mPackages) { 5600 // Just remove the loaded entries from package lists. 5601 mPackages.remove(ps.name); 5602 } 5603 5604 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5605 + " reverting from " + ps.codePathString 5606 + ": new version " + pkg.mVersionCode 5607 + " better than installed " + ps.versionCode); 5608 5609 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5610 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5611 synchronized (mInstallLock) { 5612 args.cleanUpResourcesLI(); 5613 } 5614 synchronized (mPackages) { 5615 mSettings.enableSystemPackageLPw(ps.name); 5616 } 5617 updatedPkgBetter = true; 5618 } 5619 } 5620 } 5621 5622 if (updatedPkg != null) { 5623 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5624 // initially 5625 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5626 5627 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5628 // flag set initially 5629 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5630 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5631 } 5632 } 5633 5634 // Verify certificates against what was last scanned 5635 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5636 5637 /* 5638 * A new system app appeared, but we already had a non-system one of the 5639 * same name installed earlier. 5640 */ 5641 boolean shouldHideSystemApp = false; 5642 if (updatedPkg == null && ps != null 5643 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5644 /* 5645 * Check to make sure the signatures match first. If they don't, 5646 * wipe the installed application and its data. 5647 */ 5648 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5649 != PackageManager.SIGNATURE_MATCH) { 5650 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5651 + " signatures don't match existing userdata copy; removing"); 5652 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5653 ps = null; 5654 } else { 5655 /* 5656 * If the newly-added system app is an older version than the 5657 * already installed version, hide it. It will be scanned later 5658 * and re-added like an update. 5659 */ 5660 if (pkg.mVersionCode <= ps.versionCode) { 5661 shouldHideSystemApp = true; 5662 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5663 + " but new version " + pkg.mVersionCode + " better than installed " 5664 + ps.versionCode + "; hiding system"); 5665 } else { 5666 /* 5667 * The newly found system app is a newer version that the 5668 * one previously installed. Simply remove the 5669 * already-installed application and replace it with our own 5670 * while keeping the application data. 5671 */ 5672 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5673 + " reverting from " + ps.codePathString + ": new version " 5674 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5675 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5676 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5677 synchronized (mInstallLock) { 5678 args.cleanUpResourcesLI(); 5679 } 5680 } 5681 } 5682 } 5683 5684 // The apk is forward locked (not public) if its code and resources 5685 // are kept in different files. (except for app in either system or 5686 // vendor path). 5687 // TODO grab this value from PackageSettings 5688 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5689 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5690 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5691 } 5692 } 5693 5694 // TODO: extend to support forward-locked splits 5695 String resourcePath = null; 5696 String baseResourcePath = null; 5697 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5698 if (ps != null && ps.resourcePathString != null) { 5699 resourcePath = ps.resourcePathString; 5700 baseResourcePath = ps.resourcePathString; 5701 } else { 5702 // Should not happen at all. Just log an error. 5703 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5704 } 5705 } else { 5706 resourcePath = pkg.codePath; 5707 baseResourcePath = pkg.baseCodePath; 5708 } 5709 5710 // Set application objects path explicitly. 5711 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5712 pkg.applicationInfo.setCodePath(pkg.codePath); 5713 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5714 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5715 pkg.applicationInfo.setResourcePath(resourcePath); 5716 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5717 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5718 5719 // Note that we invoke the following method only if we are about to unpack an application 5720 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5721 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5722 5723 /* 5724 * If the system app should be overridden by a previously installed 5725 * data, hide the system app now and let the /data/app scan pick it up 5726 * again. 5727 */ 5728 if (shouldHideSystemApp) { 5729 synchronized (mPackages) { 5730 /* 5731 * We have to grant systems permissions before we hide, because 5732 * grantPermissions will assume the package update is trying to 5733 * expand its permissions. 5734 */ 5735 grantPermissionsLPw(pkg, true, pkg.packageName); 5736 mSettings.disableSystemPackageLPw(pkg.packageName); 5737 } 5738 } 5739 5740 return scannedPkg; 5741 } 5742 5743 private static String fixProcessName(String defProcessName, 5744 String processName, int uid) { 5745 if (processName == null) { 5746 return defProcessName; 5747 } 5748 return processName; 5749 } 5750 5751 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5752 throws PackageManagerException { 5753 if (pkgSetting.signatures.mSignatures != null) { 5754 // Already existing package. Make sure signatures match 5755 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5756 == PackageManager.SIGNATURE_MATCH; 5757 if (!match) { 5758 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5759 == PackageManager.SIGNATURE_MATCH; 5760 } 5761 if (!match) { 5762 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5763 == PackageManager.SIGNATURE_MATCH; 5764 } 5765 if (!match) { 5766 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5767 + pkg.packageName + " signatures do not match the " 5768 + "previously installed version; ignoring!"); 5769 } 5770 } 5771 5772 // Check for shared user signatures 5773 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5774 // Already existing package. Make sure signatures match 5775 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5776 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5777 if (!match) { 5778 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5779 == PackageManager.SIGNATURE_MATCH; 5780 } 5781 if (!match) { 5782 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5783 == PackageManager.SIGNATURE_MATCH; 5784 } 5785 if (!match) { 5786 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5787 "Package " + pkg.packageName 5788 + " has no signatures that match those in shared user " 5789 + pkgSetting.sharedUser.name + "; ignoring!"); 5790 } 5791 } 5792 } 5793 5794 /** 5795 * Enforces that only the system UID or root's UID can call a method exposed 5796 * via Binder. 5797 * 5798 * @param message used as message if SecurityException is thrown 5799 * @throws SecurityException if the caller is not system or root 5800 */ 5801 private static final void enforceSystemOrRoot(String message) { 5802 final int uid = Binder.getCallingUid(); 5803 if (uid != Process.SYSTEM_UID && uid != 0) { 5804 throw new SecurityException(message); 5805 } 5806 } 5807 5808 @Override 5809 public void performBootDexOpt() { 5810 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5811 5812 // Before everything else, see whether we need to fstrim. 5813 try { 5814 IMountService ms = PackageHelper.getMountService(); 5815 if (ms != null) { 5816 final boolean isUpgrade = isUpgrade(); 5817 boolean doTrim = isUpgrade; 5818 if (doTrim) { 5819 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5820 } else { 5821 final long interval = android.provider.Settings.Global.getLong( 5822 mContext.getContentResolver(), 5823 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5824 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5825 if (interval > 0) { 5826 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5827 if (timeSinceLast > interval) { 5828 doTrim = true; 5829 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5830 + "; running immediately"); 5831 } 5832 } 5833 } 5834 if (doTrim) { 5835 if (!isFirstBoot()) { 5836 try { 5837 ActivityManagerNative.getDefault().showBootMessage( 5838 mContext.getResources().getString( 5839 R.string.android_upgrading_fstrim), true); 5840 } catch (RemoteException e) { 5841 } 5842 } 5843 ms.runMaintenance(); 5844 } 5845 } else { 5846 Slog.e(TAG, "Mount service unavailable!"); 5847 } 5848 } catch (RemoteException e) { 5849 // Can't happen; MountService is local 5850 } 5851 5852 final ArraySet<PackageParser.Package> pkgs; 5853 synchronized (mPackages) { 5854 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5855 } 5856 5857 if (pkgs != null) { 5858 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5859 // in case the device runs out of space. 5860 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5861 // Give priority to core apps. 5862 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5863 PackageParser.Package pkg = it.next(); 5864 if (pkg.coreApp) { 5865 if (DEBUG_DEXOPT) { 5866 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5867 } 5868 sortedPkgs.add(pkg); 5869 it.remove(); 5870 } 5871 } 5872 // Give priority to system apps that listen for pre boot complete. 5873 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5874 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5875 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5876 PackageParser.Package pkg = it.next(); 5877 if (pkgNames.contains(pkg.packageName)) { 5878 if (DEBUG_DEXOPT) { 5879 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5880 } 5881 sortedPkgs.add(pkg); 5882 it.remove(); 5883 } 5884 } 5885 // Give priority to system apps. 5886 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5887 PackageParser.Package pkg = it.next(); 5888 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5889 if (DEBUG_DEXOPT) { 5890 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5891 } 5892 sortedPkgs.add(pkg); 5893 it.remove(); 5894 } 5895 } 5896 // Give priority to updated system apps. 5897 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5898 PackageParser.Package pkg = it.next(); 5899 if (pkg.isUpdatedSystemApp()) { 5900 if (DEBUG_DEXOPT) { 5901 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5902 } 5903 sortedPkgs.add(pkg); 5904 it.remove(); 5905 } 5906 } 5907 // Give priority to apps that listen for boot complete. 5908 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5909 pkgNames = getPackageNamesForIntent(intent); 5910 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5911 PackageParser.Package pkg = it.next(); 5912 if (pkgNames.contains(pkg.packageName)) { 5913 if (DEBUG_DEXOPT) { 5914 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5915 } 5916 sortedPkgs.add(pkg); 5917 it.remove(); 5918 } 5919 } 5920 // Filter out packages that aren't recently used. 5921 filterRecentlyUsedApps(pkgs); 5922 // Add all remaining apps. 5923 for (PackageParser.Package pkg : pkgs) { 5924 if (DEBUG_DEXOPT) { 5925 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5926 } 5927 sortedPkgs.add(pkg); 5928 } 5929 5930 // If we want to be lazy, filter everything that wasn't recently used. 5931 if (mLazyDexOpt) { 5932 filterRecentlyUsedApps(sortedPkgs); 5933 } 5934 5935 int i = 0; 5936 int total = sortedPkgs.size(); 5937 File dataDir = Environment.getDataDirectory(); 5938 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5939 if (lowThreshold == 0) { 5940 throw new IllegalStateException("Invalid low memory threshold"); 5941 } 5942 for (PackageParser.Package pkg : sortedPkgs) { 5943 long usableSpace = dataDir.getUsableSpace(); 5944 if (usableSpace < lowThreshold) { 5945 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5946 break; 5947 } 5948 performBootDexOpt(pkg, ++i, total); 5949 } 5950 } 5951 } 5952 5953 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5954 // Filter out packages that aren't recently used. 5955 // 5956 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5957 // should do a full dexopt. 5958 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5959 int total = pkgs.size(); 5960 int skipped = 0; 5961 long now = System.currentTimeMillis(); 5962 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5963 PackageParser.Package pkg = i.next(); 5964 long then = pkg.mLastPackageUsageTimeInMills; 5965 if (then + mDexOptLRUThresholdInMills < now) { 5966 if (DEBUG_DEXOPT) { 5967 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5968 ((then == 0) ? "never" : new Date(then))); 5969 } 5970 i.remove(); 5971 skipped++; 5972 } 5973 } 5974 if (DEBUG_DEXOPT) { 5975 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5976 } 5977 } 5978 } 5979 5980 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5981 List<ResolveInfo> ris = null; 5982 try { 5983 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5984 intent, null, 0, UserHandle.USER_OWNER); 5985 } catch (RemoteException e) { 5986 } 5987 ArraySet<String> pkgNames = new ArraySet<String>(); 5988 if (ris != null) { 5989 for (ResolveInfo ri : ris) { 5990 pkgNames.add(ri.activityInfo.packageName); 5991 } 5992 } 5993 return pkgNames; 5994 } 5995 5996 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5997 if (DEBUG_DEXOPT) { 5998 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5999 } 6000 if (!isFirstBoot()) { 6001 try { 6002 ActivityManagerNative.getDefault().showBootMessage( 6003 mContext.getResources().getString(R.string.android_upgrading_apk, 6004 curr, total), true); 6005 } catch (RemoteException e) { 6006 } 6007 } 6008 PackageParser.Package p = pkg; 6009 synchronized (mInstallLock) { 6010 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6011 false /* force dex */, false /* defer */, true /* include dependencies */); 6012 } 6013 } 6014 6015 @Override 6016 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6017 return performDexOpt(packageName, instructionSet, false); 6018 } 6019 6020 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6021 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6022 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6023 if (!dexopt && !updateUsage) { 6024 // We aren't going to dexopt or update usage, so bail early. 6025 return false; 6026 } 6027 PackageParser.Package p; 6028 final String targetInstructionSet; 6029 synchronized (mPackages) { 6030 p = mPackages.get(packageName); 6031 if (p == null) { 6032 return false; 6033 } 6034 if (updateUsage) { 6035 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6036 } 6037 mPackageUsage.write(false); 6038 if (!dexopt) { 6039 // We aren't going to dexopt, so bail early. 6040 return false; 6041 } 6042 6043 targetInstructionSet = instructionSet != null ? instructionSet : 6044 getPrimaryInstructionSet(p.applicationInfo); 6045 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6046 return false; 6047 } 6048 } 6049 6050 synchronized (mInstallLock) { 6051 final String[] instructionSets = new String[] { targetInstructionSet }; 6052 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6053 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6054 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6055 } 6056 } 6057 6058 public ArraySet<String> getPackagesThatNeedDexOpt() { 6059 ArraySet<String> pkgs = null; 6060 synchronized (mPackages) { 6061 for (PackageParser.Package p : mPackages.values()) { 6062 if (DEBUG_DEXOPT) { 6063 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6064 } 6065 if (!p.mDexOptPerformed.isEmpty()) { 6066 continue; 6067 } 6068 if (pkgs == null) { 6069 pkgs = new ArraySet<String>(); 6070 } 6071 pkgs.add(p.packageName); 6072 } 6073 } 6074 return pkgs; 6075 } 6076 6077 public void shutdown() { 6078 mPackageUsage.write(true); 6079 } 6080 6081 @Override 6082 public void forceDexOpt(String packageName) { 6083 enforceSystemOrRoot("forceDexOpt"); 6084 6085 PackageParser.Package pkg; 6086 synchronized (mPackages) { 6087 pkg = mPackages.get(packageName); 6088 if (pkg == null) { 6089 throw new IllegalArgumentException("Missing package: " + packageName); 6090 } 6091 } 6092 6093 synchronized (mInstallLock) { 6094 final String[] instructionSets = new String[] { 6095 getPrimaryInstructionSet(pkg.applicationInfo) }; 6096 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6097 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6098 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6099 throw new IllegalStateException("Failed to dexopt: " + res); 6100 } 6101 } 6102 } 6103 6104 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6105 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6106 Slog.w(TAG, "Unable to update from " + oldPkg.name 6107 + " to " + newPkg.packageName 6108 + ": old package not in system partition"); 6109 return false; 6110 } else if (mPackages.get(oldPkg.name) != null) { 6111 Slog.w(TAG, "Unable to update from " + oldPkg.name 6112 + " to " + newPkg.packageName 6113 + ": old package still exists"); 6114 return false; 6115 } 6116 return true; 6117 } 6118 6119 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6120 int[] users = sUserManager.getUserIds(); 6121 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6122 if (res < 0) { 6123 return res; 6124 } 6125 for (int user : users) { 6126 if (user != 0) { 6127 res = mInstaller.createUserData(volumeUuid, packageName, 6128 UserHandle.getUid(user, uid), user, seinfo); 6129 if (res < 0) { 6130 return res; 6131 } 6132 } 6133 } 6134 return res; 6135 } 6136 6137 private int removeDataDirsLI(String volumeUuid, String packageName) { 6138 int[] users = sUserManager.getUserIds(); 6139 int res = 0; 6140 for (int user : users) { 6141 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6142 if (resInner < 0) { 6143 res = resInner; 6144 } 6145 } 6146 6147 return res; 6148 } 6149 6150 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6151 int[] users = sUserManager.getUserIds(); 6152 int res = 0; 6153 for (int user : users) { 6154 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6155 if (resInner < 0) { 6156 res = resInner; 6157 } 6158 } 6159 return res; 6160 } 6161 6162 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6163 PackageParser.Package changingLib) { 6164 if (file.path != null) { 6165 usesLibraryFiles.add(file.path); 6166 return; 6167 } 6168 PackageParser.Package p = mPackages.get(file.apk); 6169 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6170 // If we are doing this while in the middle of updating a library apk, 6171 // then we need to make sure to use that new apk for determining the 6172 // dependencies here. (We haven't yet finished committing the new apk 6173 // to the package manager state.) 6174 if (p == null || p.packageName.equals(changingLib.packageName)) { 6175 p = changingLib; 6176 } 6177 } 6178 if (p != null) { 6179 usesLibraryFiles.addAll(p.getAllCodePaths()); 6180 } 6181 } 6182 6183 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6184 PackageParser.Package changingLib) throws PackageManagerException { 6185 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6186 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6187 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6188 for (int i=0; i<N; i++) { 6189 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6190 if (file == null) { 6191 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6192 "Package " + pkg.packageName + " requires unavailable shared library " 6193 + pkg.usesLibraries.get(i) + "; failing!"); 6194 } 6195 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6196 } 6197 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6198 for (int i=0; i<N; i++) { 6199 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6200 if (file == null) { 6201 Slog.w(TAG, "Package " + pkg.packageName 6202 + " desires unavailable shared library " 6203 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6204 } else { 6205 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6206 } 6207 } 6208 N = usesLibraryFiles.size(); 6209 if (N > 0) { 6210 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6211 } else { 6212 pkg.usesLibraryFiles = null; 6213 } 6214 } 6215 } 6216 6217 private static boolean hasString(List<String> list, List<String> which) { 6218 if (list == null) { 6219 return false; 6220 } 6221 for (int i=list.size()-1; i>=0; i--) { 6222 for (int j=which.size()-1; j>=0; j--) { 6223 if (which.get(j).equals(list.get(i))) { 6224 return true; 6225 } 6226 } 6227 } 6228 return false; 6229 } 6230 6231 private void updateAllSharedLibrariesLPw() { 6232 for (PackageParser.Package pkg : mPackages.values()) { 6233 try { 6234 updateSharedLibrariesLPw(pkg, null); 6235 } catch (PackageManagerException e) { 6236 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6237 } 6238 } 6239 } 6240 6241 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6242 PackageParser.Package changingPkg) { 6243 ArrayList<PackageParser.Package> res = null; 6244 for (PackageParser.Package pkg : mPackages.values()) { 6245 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6246 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6247 if (res == null) { 6248 res = new ArrayList<PackageParser.Package>(); 6249 } 6250 res.add(pkg); 6251 try { 6252 updateSharedLibrariesLPw(pkg, changingPkg); 6253 } catch (PackageManagerException e) { 6254 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6255 } 6256 } 6257 } 6258 return res; 6259 } 6260 6261 /** 6262 * Derive the value of the {@code cpuAbiOverride} based on the provided 6263 * value and an optional stored value from the package settings. 6264 */ 6265 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6266 String cpuAbiOverride = null; 6267 6268 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6269 cpuAbiOverride = null; 6270 } else if (abiOverride != null) { 6271 cpuAbiOverride = abiOverride; 6272 } else if (settings != null) { 6273 cpuAbiOverride = settings.cpuAbiOverrideString; 6274 } 6275 6276 return cpuAbiOverride; 6277 } 6278 6279 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6280 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6281 boolean success = false; 6282 try { 6283 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6284 currentTime, user); 6285 success = true; 6286 return res; 6287 } finally { 6288 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6289 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6290 } 6291 } 6292 } 6293 6294 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6295 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6296 final File scanFile = new File(pkg.codePath); 6297 if (pkg.applicationInfo.getCodePath() == null || 6298 pkg.applicationInfo.getResourcePath() == null) { 6299 // Bail out. The resource and code paths haven't been set. 6300 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6301 "Code and resource paths haven't been set correctly"); 6302 } 6303 6304 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6305 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6306 } else { 6307 // Only allow system apps to be flagged as core apps. 6308 pkg.coreApp = false; 6309 } 6310 6311 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6312 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6313 } 6314 6315 if (mCustomResolverComponentName != null && 6316 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6317 setUpCustomResolverActivity(pkg); 6318 } 6319 6320 if (pkg.packageName.equals("android")) { 6321 synchronized (mPackages) { 6322 if (mAndroidApplication != null) { 6323 Slog.w(TAG, "*************************************************"); 6324 Slog.w(TAG, "Core android package being redefined. Skipping."); 6325 Slog.w(TAG, " file=" + scanFile); 6326 Slog.w(TAG, "*************************************************"); 6327 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6328 "Core android package being redefined. Skipping."); 6329 } 6330 6331 // Set up information for our fall-back user intent resolution activity. 6332 mPlatformPackage = pkg; 6333 pkg.mVersionCode = mSdkVersion; 6334 mAndroidApplication = pkg.applicationInfo; 6335 6336 if (!mResolverReplaced) { 6337 mResolveActivity.applicationInfo = mAndroidApplication; 6338 mResolveActivity.name = ResolverActivity.class.getName(); 6339 mResolveActivity.packageName = mAndroidApplication.packageName; 6340 mResolveActivity.processName = "system:ui"; 6341 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6342 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6343 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6344 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6345 mResolveActivity.exported = true; 6346 mResolveActivity.enabled = true; 6347 mResolveInfo.activityInfo = mResolveActivity; 6348 mResolveInfo.priority = 0; 6349 mResolveInfo.preferredOrder = 0; 6350 mResolveInfo.match = 0; 6351 mResolveComponentName = new ComponentName( 6352 mAndroidApplication.packageName, mResolveActivity.name); 6353 } 6354 } 6355 } 6356 6357 if (DEBUG_PACKAGE_SCANNING) { 6358 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6359 Log.d(TAG, "Scanning package " + pkg.packageName); 6360 } 6361 6362 if (mPackages.containsKey(pkg.packageName) 6363 || mSharedLibraries.containsKey(pkg.packageName)) { 6364 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6365 "Application package " + pkg.packageName 6366 + " already installed. Skipping duplicate."); 6367 } 6368 6369 // If we're only installing presumed-existing packages, require that the 6370 // scanned APK is both already known and at the path previously established 6371 // for it. Previously unknown packages we pick up normally, but if we have an 6372 // a priori expectation about this package's install presence, enforce it. 6373 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6374 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6375 if (known != null) { 6376 if (DEBUG_PACKAGE_SCANNING) { 6377 Log.d(TAG, "Examining " + pkg.codePath 6378 + " and requiring known paths " + known.codePathString 6379 + " & " + known.resourcePathString); 6380 } 6381 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6382 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6383 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6384 "Application package " + pkg.packageName 6385 + " found at " + pkg.applicationInfo.getCodePath() 6386 + " but expected at " + known.codePathString + "; ignoring."); 6387 } 6388 } 6389 } 6390 6391 // Initialize package source and resource directories 6392 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6393 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6394 6395 SharedUserSetting suid = null; 6396 PackageSetting pkgSetting = null; 6397 6398 if (!isSystemApp(pkg)) { 6399 // Only system apps can use these features. 6400 pkg.mOriginalPackages = null; 6401 pkg.mRealPackage = null; 6402 pkg.mAdoptPermissions = null; 6403 } 6404 6405 // writer 6406 synchronized (mPackages) { 6407 if (pkg.mSharedUserId != null) { 6408 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6409 if (suid == null) { 6410 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6411 "Creating application package " + pkg.packageName 6412 + " for shared user failed"); 6413 } 6414 if (DEBUG_PACKAGE_SCANNING) { 6415 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6416 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6417 + "): packages=" + suid.packages); 6418 } 6419 } 6420 6421 // Check if we are renaming from an original package name. 6422 PackageSetting origPackage = null; 6423 String realName = null; 6424 if (pkg.mOriginalPackages != null) { 6425 // This package may need to be renamed to a previously 6426 // installed name. Let's check on that... 6427 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6428 if (pkg.mOriginalPackages.contains(renamed)) { 6429 // This package had originally been installed as the 6430 // original name, and we have already taken care of 6431 // transitioning to the new one. Just update the new 6432 // one to continue using the old name. 6433 realName = pkg.mRealPackage; 6434 if (!pkg.packageName.equals(renamed)) { 6435 // Callers into this function may have already taken 6436 // care of renaming the package; only do it here if 6437 // it is not already done. 6438 pkg.setPackageName(renamed); 6439 } 6440 6441 } else { 6442 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6443 if ((origPackage = mSettings.peekPackageLPr( 6444 pkg.mOriginalPackages.get(i))) != null) { 6445 // We do have the package already installed under its 6446 // original name... should we use it? 6447 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6448 // New package is not compatible with original. 6449 origPackage = null; 6450 continue; 6451 } else if (origPackage.sharedUser != null) { 6452 // Make sure uid is compatible between packages. 6453 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6454 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6455 + " to " + pkg.packageName + ": old uid " 6456 + origPackage.sharedUser.name 6457 + " differs from " + pkg.mSharedUserId); 6458 origPackage = null; 6459 continue; 6460 } 6461 } else { 6462 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6463 + pkg.packageName + " to old name " + origPackage.name); 6464 } 6465 break; 6466 } 6467 } 6468 } 6469 } 6470 6471 if (mTransferedPackages.contains(pkg.packageName)) { 6472 Slog.w(TAG, "Package " + pkg.packageName 6473 + " was transferred to another, but its .apk remains"); 6474 } 6475 6476 // Just create the setting, don't add it yet. For already existing packages 6477 // the PkgSetting exists already and doesn't have to be created. 6478 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6479 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6480 pkg.applicationInfo.primaryCpuAbi, 6481 pkg.applicationInfo.secondaryCpuAbi, 6482 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6483 user, false); 6484 if (pkgSetting == null) { 6485 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6486 "Creating application package " + pkg.packageName + " failed"); 6487 } 6488 6489 if (pkgSetting.origPackage != null) { 6490 // If we are first transitioning from an original package, 6491 // fix up the new package's name now. We need to do this after 6492 // looking up the package under its new name, so getPackageLP 6493 // can take care of fiddling things correctly. 6494 pkg.setPackageName(origPackage.name); 6495 6496 // File a report about this. 6497 String msg = "New package " + pkgSetting.realName 6498 + " renamed to replace old package " + pkgSetting.name; 6499 reportSettingsProblem(Log.WARN, msg); 6500 6501 // Make a note of it. 6502 mTransferedPackages.add(origPackage.name); 6503 6504 // No longer need to retain this. 6505 pkgSetting.origPackage = null; 6506 } 6507 6508 if (realName != null) { 6509 // Make a note of it. 6510 mTransferedPackages.add(pkg.packageName); 6511 } 6512 6513 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6514 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6515 } 6516 6517 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6518 // Check all shared libraries and map to their actual file path. 6519 // We only do this here for apps not on a system dir, because those 6520 // are the only ones that can fail an install due to this. We 6521 // will take care of the system apps by updating all of their 6522 // library paths after the scan is done. 6523 updateSharedLibrariesLPw(pkg, null); 6524 } 6525 6526 if (mFoundPolicyFile) { 6527 SELinuxMMAC.assignSeinfoValue(pkg); 6528 } 6529 6530 pkg.applicationInfo.uid = pkgSetting.appId; 6531 pkg.mExtras = pkgSetting; 6532 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6533 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6534 // We just determined the app is signed correctly, so bring 6535 // over the latest parsed certs. 6536 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6537 } else { 6538 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6539 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6540 "Package " + pkg.packageName + " upgrade keys do not match the " 6541 + "previously installed version"); 6542 } else { 6543 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6544 String msg = "System package " + pkg.packageName 6545 + " signature changed; retaining data."; 6546 reportSettingsProblem(Log.WARN, msg); 6547 } 6548 } 6549 } else { 6550 try { 6551 verifySignaturesLP(pkgSetting, pkg); 6552 // We just determined the app is signed correctly, so bring 6553 // over the latest parsed certs. 6554 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6555 } catch (PackageManagerException e) { 6556 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6557 throw e; 6558 } 6559 // The signature has changed, but this package is in the system 6560 // image... let's recover! 6561 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6562 // However... if this package is part of a shared user, but it 6563 // doesn't match the signature of the shared user, let's fail. 6564 // What this means is that you can't change the signatures 6565 // associated with an overall shared user, which doesn't seem all 6566 // that unreasonable. 6567 if (pkgSetting.sharedUser != null) { 6568 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6569 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6570 throw new PackageManagerException( 6571 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6572 "Signature mismatch for shared user : " 6573 + pkgSetting.sharedUser); 6574 } 6575 } 6576 // File a report about this. 6577 String msg = "System package " + pkg.packageName 6578 + " signature changed; retaining data."; 6579 reportSettingsProblem(Log.WARN, msg); 6580 } 6581 } 6582 // Verify that this new package doesn't have any content providers 6583 // that conflict with existing packages. Only do this if the 6584 // package isn't already installed, since we don't want to break 6585 // things that are installed. 6586 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6587 final int N = pkg.providers.size(); 6588 int i; 6589 for (i=0; i<N; i++) { 6590 PackageParser.Provider p = pkg.providers.get(i); 6591 if (p.info.authority != null) { 6592 String names[] = p.info.authority.split(";"); 6593 for (int j = 0; j < names.length; j++) { 6594 if (mProvidersByAuthority.containsKey(names[j])) { 6595 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6596 final String otherPackageName = 6597 ((other != null && other.getComponentName() != null) ? 6598 other.getComponentName().getPackageName() : "?"); 6599 throw new PackageManagerException( 6600 INSTALL_FAILED_CONFLICTING_PROVIDER, 6601 "Can't install because provider name " + names[j] 6602 + " (in package " + pkg.applicationInfo.packageName 6603 + ") is already used by " + otherPackageName); 6604 } 6605 } 6606 } 6607 } 6608 } 6609 6610 if (pkg.mAdoptPermissions != null) { 6611 // This package wants to adopt ownership of permissions from 6612 // another package. 6613 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6614 final String origName = pkg.mAdoptPermissions.get(i); 6615 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6616 if (orig != null) { 6617 if (verifyPackageUpdateLPr(orig, pkg)) { 6618 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6619 + pkg.packageName); 6620 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6621 } 6622 } 6623 } 6624 } 6625 } 6626 6627 final String pkgName = pkg.packageName; 6628 6629 final long scanFileTime = scanFile.lastModified(); 6630 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6631 pkg.applicationInfo.processName = fixProcessName( 6632 pkg.applicationInfo.packageName, 6633 pkg.applicationInfo.processName, 6634 pkg.applicationInfo.uid); 6635 6636 File dataPath; 6637 if (mPlatformPackage == pkg) { 6638 // The system package is special. 6639 dataPath = new File(Environment.getDataDirectory(), "system"); 6640 6641 pkg.applicationInfo.dataDir = dataPath.getPath(); 6642 6643 } else { 6644 // This is a normal package, need to make its data directory. 6645 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6646 UserHandle.USER_OWNER, pkg.packageName); 6647 6648 boolean uidError = false; 6649 if (dataPath.exists()) { 6650 int currentUid = 0; 6651 try { 6652 StructStat stat = Os.stat(dataPath.getPath()); 6653 currentUid = stat.st_uid; 6654 } catch (ErrnoException e) { 6655 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6656 } 6657 6658 // If we have mismatched owners for the data path, we have a problem. 6659 if (currentUid != pkg.applicationInfo.uid) { 6660 boolean recovered = false; 6661 if (currentUid == 0) { 6662 // The directory somehow became owned by root. Wow. 6663 // This is probably because the system was stopped while 6664 // installd was in the middle of messing with its libs 6665 // directory. Ask installd to fix that. 6666 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6667 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6668 if (ret >= 0) { 6669 recovered = true; 6670 String msg = "Package " + pkg.packageName 6671 + " unexpectedly changed to uid 0; recovered to " + 6672 + pkg.applicationInfo.uid; 6673 reportSettingsProblem(Log.WARN, msg); 6674 } 6675 } 6676 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6677 || (scanFlags&SCAN_BOOTING) != 0)) { 6678 // If this is a system app, we can at least delete its 6679 // current data so the application will still work. 6680 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6681 if (ret >= 0) { 6682 // TODO: Kill the processes first 6683 // Old data gone! 6684 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6685 ? "System package " : "Third party package "; 6686 String msg = prefix + pkg.packageName 6687 + " has changed from uid: " 6688 + currentUid + " to " 6689 + pkg.applicationInfo.uid + "; old data erased"; 6690 reportSettingsProblem(Log.WARN, msg); 6691 recovered = true; 6692 6693 // And now re-install the app. 6694 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6695 pkg.applicationInfo.seinfo); 6696 if (ret == -1) { 6697 // Ack should not happen! 6698 msg = prefix + pkg.packageName 6699 + " could not have data directory re-created after delete."; 6700 reportSettingsProblem(Log.WARN, msg); 6701 throw new PackageManagerException( 6702 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6703 } 6704 } 6705 if (!recovered) { 6706 mHasSystemUidErrors = true; 6707 } 6708 } else if (!recovered) { 6709 // If we allow this install to proceed, we will be broken. 6710 // Abort, abort! 6711 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6712 "scanPackageLI"); 6713 } 6714 if (!recovered) { 6715 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6716 + pkg.applicationInfo.uid + "/fs_" 6717 + currentUid; 6718 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6719 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6720 String msg = "Package " + pkg.packageName 6721 + " has mismatched uid: " 6722 + currentUid + " on disk, " 6723 + pkg.applicationInfo.uid + " in settings"; 6724 // writer 6725 synchronized (mPackages) { 6726 mSettings.mReadMessages.append(msg); 6727 mSettings.mReadMessages.append('\n'); 6728 uidError = true; 6729 if (!pkgSetting.uidError) { 6730 reportSettingsProblem(Log.ERROR, msg); 6731 } 6732 } 6733 } 6734 } 6735 pkg.applicationInfo.dataDir = dataPath.getPath(); 6736 if (mShouldRestoreconData) { 6737 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6738 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6739 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6740 } 6741 } else { 6742 if (DEBUG_PACKAGE_SCANNING) { 6743 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6744 Log.v(TAG, "Want this data dir: " + dataPath); 6745 } 6746 //invoke installer to do the actual installation 6747 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6748 pkg.applicationInfo.seinfo); 6749 if (ret < 0) { 6750 // Error from installer 6751 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6752 "Unable to create data dirs [errorCode=" + ret + "]"); 6753 } 6754 6755 if (dataPath.exists()) { 6756 pkg.applicationInfo.dataDir = dataPath.getPath(); 6757 } else { 6758 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6759 pkg.applicationInfo.dataDir = null; 6760 } 6761 } 6762 6763 pkgSetting.uidError = uidError; 6764 } 6765 6766 final String path = scanFile.getPath(); 6767 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6768 6769 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6770 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6771 6772 // Some system apps still use directory structure for native libraries 6773 // in which case we might end up not detecting abi solely based on apk 6774 // structure. Try to detect abi based on directory structure. 6775 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6776 pkg.applicationInfo.primaryCpuAbi == null) { 6777 setBundledAppAbisAndRoots(pkg, pkgSetting); 6778 setNativeLibraryPaths(pkg); 6779 } 6780 6781 } else { 6782 if ((scanFlags & SCAN_MOVE) != 0) { 6783 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6784 // but we already have this packages package info in the PackageSetting. We just 6785 // use that and derive the native library path based on the new codepath. 6786 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6787 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6788 } 6789 6790 // Set native library paths again. For moves, the path will be updated based on the 6791 // ABIs we've determined above. For non-moves, the path will be updated based on the 6792 // ABIs we determined during compilation, but the path will depend on the final 6793 // package path (after the rename away from the stage path). 6794 setNativeLibraryPaths(pkg); 6795 } 6796 6797 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6798 final int[] userIds = sUserManager.getUserIds(); 6799 synchronized (mInstallLock) { 6800 // Make sure all user data directories are ready to roll; we're okay 6801 // if they already exist 6802 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6803 for (int userId : userIds) { 6804 if (userId != 0) { 6805 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6806 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6807 pkg.applicationInfo.seinfo); 6808 } 6809 } 6810 } 6811 6812 // Create a native library symlink only if we have native libraries 6813 // and if the native libraries are 32 bit libraries. We do not provide 6814 // this symlink for 64 bit libraries. 6815 if (pkg.applicationInfo.primaryCpuAbi != null && 6816 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6817 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6818 for (int userId : userIds) { 6819 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6820 nativeLibPath, userId) < 0) { 6821 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6822 "Failed linking native library dir (user=" + userId + ")"); 6823 } 6824 } 6825 } 6826 } 6827 6828 // This is a special case for the "system" package, where the ABI is 6829 // dictated by the zygote configuration (and init.rc). We should keep track 6830 // of this ABI so that we can deal with "normal" applications that run under 6831 // the same UID correctly. 6832 if (mPlatformPackage == pkg) { 6833 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6834 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6835 } 6836 6837 // If there's a mismatch between the abi-override in the package setting 6838 // and the abiOverride specified for the install. Warn about this because we 6839 // would've already compiled the app without taking the package setting into 6840 // account. 6841 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6842 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6843 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6844 " for package: " + pkg.packageName); 6845 } 6846 } 6847 6848 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6849 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6850 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6851 6852 // Copy the derived override back to the parsed package, so that we can 6853 // update the package settings accordingly. 6854 pkg.cpuAbiOverride = cpuAbiOverride; 6855 6856 if (DEBUG_ABI_SELECTION) { 6857 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6858 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6859 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6860 } 6861 6862 // Push the derived path down into PackageSettings so we know what to 6863 // clean up at uninstall time. 6864 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6865 6866 if (DEBUG_ABI_SELECTION) { 6867 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6868 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6869 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6870 } 6871 6872 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6873 // We don't do this here during boot because we can do it all 6874 // at once after scanning all existing packages. 6875 // 6876 // We also do this *before* we perform dexopt on this package, so that 6877 // we can avoid redundant dexopts, and also to make sure we've got the 6878 // code and package path correct. 6879 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6880 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6881 } 6882 6883 if ((scanFlags & SCAN_NO_DEX) == 0) { 6884 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6885 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6886 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6887 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6888 } 6889 } 6890 if (mFactoryTest && pkg.requestedPermissions.contains( 6891 android.Manifest.permission.FACTORY_TEST)) { 6892 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6893 } 6894 6895 ArrayList<PackageParser.Package> clientLibPkgs = null; 6896 6897 // writer 6898 synchronized (mPackages) { 6899 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6900 // Only system apps can add new shared libraries. 6901 if (pkg.libraryNames != null) { 6902 for (int i=0; i<pkg.libraryNames.size(); i++) { 6903 String name = pkg.libraryNames.get(i); 6904 boolean allowed = false; 6905 if (pkg.isUpdatedSystemApp()) { 6906 // New library entries can only be added through the 6907 // system image. This is important to get rid of a lot 6908 // of nasty edge cases: for example if we allowed a non- 6909 // system update of the app to add a library, then uninstalling 6910 // the update would make the library go away, and assumptions 6911 // we made such as through app install filtering would now 6912 // have allowed apps on the device which aren't compatible 6913 // with it. Better to just have the restriction here, be 6914 // conservative, and create many fewer cases that can negatively 6915 // impact the user experience. 6916 final PackageSetting sysPs = mSettings 6917 .getDisabledSystemPkgLPr(pkg.packageName); 6918 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6919 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6920 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6921 allowed = true; 6922 allowed = true; 6923 break; 6924 } 6925 } 6926 } 6927 } else { 6928 allowed = true; 6929 } 6930 if (allowed) { 6931 if (!mSharedLibraries.containsKey(name)) { 6932 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6933 } else if (!name.equals(pkg.packageName)) { 6934 Slog.w(TAG, "Package " + pkg.packageName + " library " 6935 + name + " already exists; skipping"); 6936 } 6937 } else { 6938 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6939 + name + " that is not declared on system image; skipping"); 6940 } 6941 } 6942 if ((scanFlags&SCAN_BOOTING) == 0) { 6943 // If we are not booting, we need to update any applications 6944 // that are clients of our shared library. If we are booting, 6945 // this will all be done once the scan is complete. 6946 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6947 } 6948 } 6949 } 6950 } 6951 6952 // We also need to dexopt any apps that are dependent on this library. Note that 6953 // if these fail, we should abort the install since installing the library will 6954 // result in some apps being broken. 6955 if (clientLibPkgs != null) { 6956 if ((scanFlags & SCAN_NO_DEX) == 0) { 6957 for (int i = 0; i < clientLibPkgs.size(); i++) { 6958 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6959 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6960 null /* instruction sets */, forceDex, 6961 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6962 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6963 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6964 "scanPackageLI failed to dexopt clientLibPkgs"); 6965 } 6966 } 6967 } 6968 } 6969 6970 // Also need to kill any apps that are dependent on the library. 6971 if (clientLibPkgs != null) { 6972 for (int i=0; i<clientLibPkgs.size(); i++) { 6973 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6974 killApplication(clientPkg.applicationInfo.packageName, 6975 clientPkg.applicationInfo.uid, "update lib"); 6976 } 6977 } 6978 6979 // Make sure we're not adding any bogus keyset info 6980 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6981 ksms.assertScannedPackageValid(pkg); 6982 6983 // writer 6984 synchronized (mPackages) { 6985 // We don't expect installation to fail beyond this point 6986 6987 // Add the new setting to mSettings 6988 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6989 // Add the new setting to mPackages 6990 mPackages.put(pkg.applicationInfo.packageName, pkg); 6991 // Make sure we don't accidentally delete its data. 6992 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6993 while (iter.hasNext()) { 6994 PackageCleanItem item = iter.next(); 6995 if (pkgName.equals(item.packageName)) { 6996 iter.remove(); 6997 } 6998 } 6999 7000 // Take care of first install / last update times. 7001 if (currentTime != 0) { 7002 if (pkgSetting.firstInstallTime == 0) { 7003 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7004 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7005 pkgSetting.lastUpdateTime = currentTime; 7006 } 7007 } else if (pkgSetting.firstInstallTime == 0) { 7008 // We need *something*. Take time time stamp of the file. 7009 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7010 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7011 if (scanFileTime != pkgSetting.timeStamp) { 7012 // A package on the system image has changed; consider this 7013 // to be an update. 7014 pkgSetting.lastUpdateTime = scanFileTime; 7015 } 7016 } 7017 7018 // Add the package's KeySets to the global KeySetManagerService 7019 ksms.addScannedPackageLPw(pkg); 7020 7021 int N = pkg.providers.size(); 7022 StringBuilder r = null; 7023 int i; 7024 for (i=0; i<N; i++) { 7025 PackageParser.Provider p = pkg.providers.get(i); 7026 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7027 p.info.processName, pkg.applicationInfo.uid); 7028 mProviders.addProvider(p); 7029 p.syncable = p.info.isSyncable; 7030 if (p.info.authority != null) { 7031 String names[] = p.info.authority.split(";"); 7032 p.info.authority = null; 7033 for (int j = 0; j < names.length; j++) { 7034 if (j == 1 && p.syncable) { 7035 // We only want the first authority for a provider to possibly be 7036 // syncable, so if we already added this provider using a different 7037 // authority clear the syncable flag. We copy the provider before 7038 // changing it because the mProviders object contains a reference 7039 // to a provider that we don't want to change. 7040 // Only do this for the second authority since the resulting provider 7041 // object can be the same for all future authorities for this provider. 7042 p = new PackageParser.Provider(p); 7043 p.syncable = false; 7044 } 7045 if (!mProvidersByAuthority.containsKey(names[j])) { 7046 mProvidersByAuthority.put(names[j], p); 7047 if (p.info.authority == null) { 7048 p.info.authority = names[j]; 7049 } else { 7050 p.info.authority = p.info.authority + ";" + names[j]; 7051 } 7052 if (DEBUG_PACKAGE_SCANNING) { 7053 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7054 Log.d(TAG, "Registered content provider: " + names[j] 7055 + ", className = " + p.info.name + ", isSyncable = " 7056 + p.info.isSyncable); 7057 } 7058 } else { 7059 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7060 Slog.w(TAG, "Skipping provider name " + names[j] + 7061 " (in package " + pkg.applicationInfo.packageName + 7062 "): name already used by " 7063 + ((other != null && other.getComponentName() != null) 7064 ? other.getComponentName().getPackageName() : "?")); 7065 } 7066 } 7067 } 7068 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7069 if (r == null) { 7070 r = new StringBuilder(256); 7071 } else { 7072 r.append(' '); 7073 } 7074 r.append(p.info.name); 7075 } 7076 } 7077 if (r != null) { 7078 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7079 } 7080 7081 N = pkg.services.size(); 7082 r = null; 7083 for (i=0; i<N; i++) { 7084 PackageParser.Service s = pkg.services.get(i); 7085 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7086 s.info.processName, pkg.applicationInfo.uid); 7087 mServices.addService(s); 7088 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7089 if (r == null) { 7090 r = new StringBuilder(256); 7091 } else { 7092 r.append(' '); 7093 } 7094 r.append(s.info.name); 7095 } 7096 } 7097 if (r != null) { 7098 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7099 } 7100 7101 N = pkg.receivers.size(); 7102 r = null; 7103 for (i=0; i<N; i++) { 7104 PackageParser.Activity a = pkg.receivers.get(i); 7105 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7106 a.info.processName, pkg.applicationInfo.uid); 7107 mReceivers.addActivity(a, "receiver"); 7108 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7109 if (r == null) { 7110 r = new StringBuilder(256); 7111 } else { 7112 r.append(' '); 7113 } 7114 r.append(a.info.name); 7115 } 7116 } 7117 if (r != null) { 7118 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7119 } 7120 7121 N = pkg.activities.size(); 7122 r = null; 7123 for (i=0; i<N; i++) { 7124 PackageParser.Activity a = pkg.activities.get(i); 7125 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7126 a.info.processName, pkg.applicationInfo.uid); 7127 mActivities.addActivity(a, "activity"); 7128 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7129 if (r == null) { 7130 r = new StringBuilder(256); 7131 } else { 7132 r.append(' '); 7133 } 7134 r.append(a.info.name); 7135 } 7136 } 7137 if (r != null) { 7138 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7139 } 7140 7141 N = pkg.permissionGroups.size(); 7142 r = null; 7143 for (i=0; i<N; i++) { 7144 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7145 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7146 if (cur == null) { 7147 mPermissionGroups.put(pg.info.name, pg); 7148 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7149 if (r == null) { 7150 r = new StringBuilder(256); 7151 } else { 7152 r.append(' '); 7153 } 7154 r.append(pg.info.name); 7155 } 7156 } else { 7157 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7158 + pg.info.packageName + " ignored: original from " 7159 + cur.info.packageName); 7160 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7161 if (r == null) { 7162 r = new StringBuilder(256); 7163 } else { 7164 r.append(' '); 7165 } 7166 r.append("DUP:"); 7167 r.append(pg.info.name); 7168 } 7169 } 7170 } 7171 if (r != null) { 7172 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7173 } 7174 7175 N = pkg.permissions.size(); 7176 r = null; 7177 for (i=0; i<N; i++) { 7178 PackageParser.Permission p = pkg.permissions.get(i); 7179 7180 // Now that permission groups have a special meaning, we ignore permission 7181 // groups for legacy apps to prevent unexpected behavior. In particular, 7182 // permissions for one app being granted to someone just becuase they happen 7183 // to be in a group defined by another app (before this had no implications). 7184 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7185 p.group = mPermissionGroups.get(p.info.group); 7186 // Warn for a permission in an unknown group. 7187 if (p.info.group != null && p.group == null) { 7188 Slog.w(TAG, "Permission " + p.info.name + " from package " 7189 + p.info.packageName + " in an unknown group " + p.info.group); 7190 } 7191 } 7192 7193 ArrayMap<String, BasePermission> permissionMap = 7194 p.tree ? mSettings.mPermissionTrees 7195 : mSettings.mPermissions; 7196 BasePermission bp = permissionMap.get(p.info.name); 7197 7198 // Allow system apps to redefine non-system permissions 7199 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7200 final boolean currentOwnerIsSystem = (bp.perm != null 7201 && isSystemApp(bp.perm.owner)); 7202 if (isSystemApp(p.owner)) { 7203 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7204 // It's a built-in permission and no owner, take ownership now 7205 bp.packageSetting = pkgSetting; 7206 bp.perm = p; 7207 bp.uid = pkg.applicationInfo.uid; 7208 bp.sourcePackage = p.info.packageName; 7209 } else if (!currentOwnerIsSystem) { 7210 String msg = "New decl " + p.owner + " of permission " 7211 + p.info.name + " is system; overriding " + bp.sourcePackage; 7212 reportSettingsProblem(Log.WARN, msg); 7213 bp = null; 7214 } 7215 } 7216 } 7217 7218 if (bp == null) { 7219 bp = new BasePermission(p.info.name, p.info.packageName, 7220 BasePermission.TYPE_NORMAL); 7221 permissionMap.put(p.info.name, bp); 7222 } 7223 7224 if (bp.perm == null) { 7225 if (bp.sourcePackage == null 7226 || bp.sourcePackage.equals(p.info.packageName)) { 7227 BasePermission tree = findPermissionTreeLP(p.info.name); 7228 if (tree == null 7229 || tree.sourcePackage.equals(p.info.packageName)) { 7230 bp.packageSetting = pkgSetting; 7231 bp.perm = p; 7232 bp.uid = pkg.applicationInfo.uid; 7233 bp.sourcePackage = p.info.packageName; 7234 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7235 if (r == null) { 7236 r = new StringBuilder(256); 7237 } else { 7238 r.append(' '); 7239 } 7240 r.append(p.info.name); 7241 } 7242 } else { 7243 Slog.w(TAG, "Permission " + p.info.name + " from package " 7244 + p.info.packageName + " ignored: base tree " 7245 + tree.name + " is from package " 7246 + tree.sourcePackage); 7247 } 7248 } else { 7249 Slog.w(TAG, "Permission " + p.info.name + " from package " 7250 + p.info.packageName + " ignored: original from " 7251 + bp.sourcePackage); 7252 } 7253 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7254 if (r == null) { 7255 r = new StringBuilder(256); 7256 } else { 7257 r.append(' '); 7258 } 7259 r.append("DUP:"); 7260 r.append(p.info.name); 7261 } 7262 if (bp.perm == p) { 7263 bp.protectionLevel = p.info.protectionLevel; 7264 } 7265 } 7266 7267 if (r != null) { 7268 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7269 } 7270 7271 N = pkg.instrumentation.size(); 7272 r = null; 7273 for (i=0; i<N; i++) { 7274 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7275 a.info.packageName = pkg.applicationInfo.packageName; 7276 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7277 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7278 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7279 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7280 a.info.dataDir = pkg.applicationInfo.dataDir; 7281 7282 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7283 // need other information about the application, like the ABI and what not ? 7284 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7285 mInstrumentation.put(a.getComponentName(), a); 7286 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7287 if (r == null) { 7288 r = new StringBuilder(256); 7289 } else { 7290 r.append(' '); 7291 } 7292 r.append(a.info.name); 7293 } 7294 } 7295 if (r != null) { 7296 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7297 } 7298 7299 if (pkg.protectedBroadcasts != null) { 7300 N = pkg.protectedBroadcasts.size(); 7301 for (i=0; i<N; i++) { 7302 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7303 } 7304 } 7305 7306 pkgSetting.setTimeStamp(scanFileTime); 7307 7308 // Create idmap files for pairs of (packages, overlay packages). 7309 // Note: "android", ie framework-res.apk, is handled by native layers. 7310 if (pkg.mOverlayTarget != null) { 7311 // This is an overlay package. 7312 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7313 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7314 mOverlays.put(pkg.mOverlayTarget, 7315 new ArrayMap<String, PackageParser.Package>()); 7316 } 7317 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7318 map.put(pkg.packageName, pkg); 7319 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7320 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7321 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7322 "scanPackageLI failed to createIdmap"); 7323 } 7324 } 7325 } else if (mOverlays.containsKey(pkg.packageName) && 7326 !pkg.packageName.equals("android")) { 7327 // This is a regular package, with one or more known overlay packages. 7328 createIdmapsForPackageLI(pkg); 7329 } 7330 } 7331 7332 return pkg; 7333 } 7334 7335 /** 7336 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7337 * is derived purely on the basis of the contents of {@code scanFile} and 7338 * {@code cpuAbiOverride}. 7339 * 7340 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7341 */ 7342 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7343 String cpuAbiOverride, boolean extractLibs) 7344 throws PackageManagerException { 7345 // TODO: We can probably be smarter about this stuff. For installed apps, 7346 // we can calculate this information at install time once and for all. For 7347 // system apps, we can probably assume that this information doesn't change 7348 // after the first boot scan. As things stand, we do lots of unnecessary work. 7349 7350 // Give ourselves some initial paths; we'll come back for another 7351 // pass once we've determined ABI below. 7352 setNativeLibraryPaths(pkg); 7353 7354 // We would never need to extract libs for forward-locked and external packages, 7355 // since the container service will do it for us. We shouldn't attempt to 7356 // extract libs from system app when it was not updated. 7357 if (pkg.isForwardLocked() || isExternal(pkg) || 7358 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7359 extractLibs = false; 7360 } 7361 7362 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7363 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7364 7365 NativeLibraryHelper.Handle handle = null; 7366 try { 7367 handle = NativeLibraryHelper.Handle.create(pkg); 7368 // TODO(multiArch): This can be null for apps that didn't go through the 7369 // usual installation process. We can calculate it again, like we 7370 // do during install time. 7371 // 7372 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7373 // unnecessary. 7374 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7375 7376 // Null out the abis so that they can be recalculated. 7377 pkg.applicationInfo.primaryCpuAbi = null; 7378 pkg.applicationInfo.secondaryCpuAbi = null; 7379 if (isMultiArch(pkg.applicationInfo)) { 7380 // Warn if we've set an abiOverride for multi-lib packages.. 7381 // By definition, we need to copy both 32 and 64 bit libraries for 7382 // such packages. 7383 if (pkg.cpuAbiOverride != null 7384 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7385 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7386 } 7387 7388 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7389 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7390 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7391 if (extractLibs) { 7392 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7393 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7394 useIsaSpecificSubdirs); 7395 } else { 7396 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7397 } 7398 } 7399 7400 maybeThrowExceptionForMultiArchCopy( 7401 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7402 7403 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7404 if (extractLibs) { 7405 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7406 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7407 useIsaSpecificSubdirs); 7408 } else { 7409 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7410 } 7411 } 7412 7413 maybeThrowExceptionForMultiArchCopy( 7414 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7415 7416 if (abi64 >= 0) { 7417 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7418 } 7419 7420 if (abi32 >= 0) { 7421 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7422 if (abi64 >= 0) { 7423 pkg.applicationInfo.secondaryCpuAbi = abi; 7424 } else { 7425 pkg.applicationInfo.primaryCpuAbi = abi; 7426 } 7427 } 7428 } else { 7429 String[] abiList = (cpuAbiOverride != null) ? 7430 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7431 7432 // Enable gross and lame hacks for apps that are built with old 7433 // SDK tools. We must scan their APKs for renderscript bitcode and 7434 // not launch them if it's present. Don't bother checking on devices 7435 // that don't have 64 bit support. 7436 boolean needsRenderScriptOverride = false; 7437 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7438 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7439 abiList = Build.SUPPORTED_32_BIT_ABIS; 7440 needsRenderScriptOverride = true; 7441 } 7442 7443 final int copyRet; 7444 if (extractLibs) { 7445 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7446 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7447 } else { 7448 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7449 } 7450 7451 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7452 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7453 "Error unpackaging native libs for app, errorCode=" + copyRet); 7454 } 7455 7456 if (copyRet >= 0) { 7457 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7458 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7459 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7460 } else if (needsRenderScriptOverride) { 7461 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7462 } 7463 } 7464 } catch (IOException ioe) { 7465 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7466 } finally { 7467 IoUtils.closeQuietly(handle); 7468 } 7469 7470 // Now that we've calculated the ABIs and determined if it's an internal app, 7471 // we will go ahead and populate the nativeLibraryPath. 7472 setNativeLibraryPaths(pkg); 7473 } 7474 7475 /** 7476 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7477 * i.e, so that all packages can be run inside a single process if required. 7478 * 7479 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7480 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7481 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7482 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7483 * updating a package that belongs to a shared user. 7484 * 7485 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7486 * adds unnecessary complexity. 7487 */ 7488 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7489 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7490 String requiredInstructionSet = null; 7491 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7492 requiredInstructionSet = VMRuntime.getInstructionSet( 7493 scannedPackage.applicationInfo.primaryCpuAbi); 7494 } 7495 7496 PackageSetting requirer = null; 7497 for (PackageSetting ps : packagesForUser) { 7498 // If packagesForUser contains scannedPackage, we skip it. This will happen 7499 // when scannedPackage is an update of an existing package. Without this check, 7500 // we will never be able to change the ABI of any package belonging to a shared 7501 // user, even if it's compatible with other packages. 7502 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7503 if (ps.primaryCpuAbiString == null) { 7504 continue; 7505 } 7506 7507 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7508 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7509 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7510 // this but there's not much we can do. 7511 String errorMessage = "Instruction set mismatch, " 7512 + ((requirer == null) ? "[caller]" : requirer) 7513 + " requires " + requiredInstructionSet + " whereas " + ps 7514 + " requires " + instructionSet; 7515 Slog.w(TAG, errorMessage); 7516 } 7517 7518 if (requiredInstructionSet == null) { 7519 requiredInstructionSet = instructionSet; 7520 requirer = ps; 7521 } 7522 } 7523 } 7524 7525 if (requiredInstructionSet != null) { 7526 String adjustedAbi; 7527 if (requirer != null) { 7528 // requirer != null implies that either scannedPackage was null or that scannedPackage 7529 // did not require an ABI, in which case we have to adjust scannedPackage to match 7530 // the ABI of the set (which is the same as requirer's ABI) 7531 adjustedAbi = requirer.primaryCpuAbiString; 7532 if (scannedPackage != null) { 7533 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7534 } 7535 } else { 7536 // requirer == null implies that we're updating all ABIs in the set to 7537 // match scannedPackage. 7538 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7539 } 7540 7541 for (PackageSetting ps : packagesForUser) { 7542 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7543 if (ps.primaryCpuAbiString != null) { 7544 continue; 7545 } 7546 7547 ps.primaryCpuAbiString = adjustedAbi; 7548 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7549 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7550 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7551 7552 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7553 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7554 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7555 ps.primaryCpuAbiString = null; 7556 ps.pkg.applicationInfo.primaryCpuAbi = null; 7557 return; 7558 } else { 7559 mInstaller.rmdex(ps.codePathString, 7560 getDexCodeInstructionSet(getPreferredInstructionSet())); 7561 } 7562 } 7563 } 7564 } 7565 } 7566 } 7567 7568 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7569 synchronized (mPackages) { 7570 mResolverReplaced = true; 7571 // Set up information for custom user intent resolution activity. 7572 mResolveActivity.applicationInfo = pkg.applicationInfo; 7573 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7574 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7575 mResolveActivity.processName = pkg.applicationInfo.packageName; 7576 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7577 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7578 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7579 mResolveActivity.theme = 0; 7580 mResolveActivity.exported = true; 7581 mResolveActivity.enabled = true; 7582 mResolveInfo.activityInfo = mResolveActivity; 7583 mResolveInfo.priority = 0; 7584 mResolveInfo.preferredOrder = 0; 7585 mResolveInfo.match = 0; 7586 mResolveComponentName = mCustomResolverComponentName; 7587 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7588 mResolveComponentName); 7589 } 7590 } 7591 7592 private static String calculateBundledApkRoot(final String codePathString) { 7593 final File codePath = new File(codePathString); 7594 final File codeRoot; 7595 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7596 codeRoot = Environment.getRootDirectory(); 7597 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7598 codeRoot = Environment.getOemDirectory(); 7599 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7600 codeRoot = Environment.getVendorDirectory(); 7601 } else { 7602 // Unrecognized code path; take its top real segment as the apk root: 7603 // e.g. /something/app/blah.apk => /something 7604 try { 7605 File f = codePath.getCanonicalFile(); 7606 File parent = f.getParentFile(); // non-null because codePath is a file 7607 File tmp; 7608 while ((tmp = parent.getParentFile()) != null) { 7609 f = parent; 7610 parent = tmp; 7611 } 7612 codeRoot = f; 7613 Slog.w(TAG, "Unrecognized code path " 7614 + codePath + " - using " + codeRoot); 7615 } catch (IOException e) { 7616 // Can't canonicalize the code path -- shenanigans? 7617 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7618 return Environment.getRootDirectory().getPath(); 7619 } 7620 } 7621 return codeRoot.getPath(); 7622 } 7623 7624 /** 7625 * Derive and set the location of native libraries for the given package, 7626 * which varies depending on where and how the package was installed. 7627 */ 7628 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7629 final ApplicationInfo info = pkg.applicationInfo; 7630 final String codePath = pkg.codePath; 7631 final File codeFile = new File(codePath); 7632 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7633 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7634 7635 info.nativeLibraryRootDir = null; 7636 info.nativeLibraryRootRequiresIsa = false; 7637 info.nativeLibraryDir = null; 7638 info.secondaryNativeLibraryDir = null; 7639 7640 if (isApkFile(codeFile)) { 7641 // Monolithic install 7642 if (bundledApp) { 7643 // If "/system/lib64/apkname" exists, assume that is the per-package 7644 // native library directory to use; otherwise use "/system/lib/apkname". 7645 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7646 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7647 getPrimaryInstructionSet(info)); 7648 7649 // This is a bundled system app so choose the path based on the ABI. 7650 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7651 // is just the default path. 7652 final String apkName = deriveCodePathName(codePath); 7653 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7654 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7655 apkName).getAbsolutePath(); 7656 7657 if (info.secondaryCpuAbi != null) { 7658 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7659 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7660 secondaryLibDir, apkName).getAbsolutePath(); 7661 } 7662 } else if (asecApp) { 7663 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7664 .getAbsolutePath(); 7665 } else { 7666 final String apkName = deriveCodePathName(codePath); 7667 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7668 .getAbsolutePath(); 7669 } 7670 7671 info.nativeLibraryRootRequiresIsa = false; 7672 info.nativeLibraryDir = info.nativeLibraryRootDir; 7673 } else { 7674 // Cluster install 7675 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7676 info.nativeLibraryRootRequiresIsa = true; 7677 7678 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7679 getPrimaryInstructionSet(info)).getAbsolutePath(); 7680 7681 if (info.secondaryCpuAbi != null) { 7682 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7683 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7684 } 7685 } 7686 } 7687 7688 /** 7689 * Calculate the abis and roots for a bundled app. These can uniquely 7690 * be determined from the contents of the system partition, i.e whether 7691 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7692 * of this information, and instead assume that the system was built 7693 * sensibly. 7694 */ 7695 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7696 PackageSetting pkgSetting) { 7697 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7698 7699 // If "/system/lib64/apkname" exists, assume that is the per-package 7700 // native library directory to use; otherwise use "/system/lib/apkname". 7701 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7702 setBundledAppAbi(pkg, apkRoot, apkName); 7703 // pkgSetting might be null during rescan following uninstall of updates 7704 // to a bundled app, so accommodate that possibility. The settings in 7705 // that case will be established later from the parsed package. 7706 // 7707 // If the settings aren't null, sync them up with what we've just derived. 7708 // note that apkRoot isn't stored in the package settings. 7709 if (pkgSetting != null) { 7710 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7711 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7712 } 7713 } 7714 7715 /** 7716 * Deduces the ABI of a bundled app and sets the relevant fields on the 7717 * parsed pkg object. 7718 * 7719 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7720 * under which system libraries are installed. 7721 * @param apkName the name of the installed package. 7722 */ 7723 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7724 final File codeFile = new File(pkg.codePath); 7725 7726 final boolean has64BitLibs; 7727 final boolean has32BitLibs; 7728 if (isApkFile(codeFile)) { 7729 // Monolithic install 7730 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7731 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7732 } else { 7733 // Cluster install 7734 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7735 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7736 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7737 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7738 has64BitLibs = (new File(rootDir, isa)).exists(); 7739 } else { 7740 has64BitLibs = false; 7741 } 7742 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7743 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7744 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7745 has32BitLibs = (new File(rootDir, isa)).exists(); 7746 } else { 7747 has32BitLibs = false; 7748 } 7749 } 7750 7751 if (has64BitLibs && !has32BitLibs) { 7752 // The package has 64 bit libs, but not 32 bit libs. Its primary 7753 // ABI should be 64 bit. We can safely assume here that the bundled 7754 // native libraries correspond to the most preferred ABI in the list. 7755 7756 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7757 pkg.applicationInfo.secondaryCpuAbi = null; 7758 } else if (has32BitLibs && !has64BitLibs) { 7759 // The package has 32 bit libs but not 64 bit libs. Its primary 7760 // ABI should be 32 bit. 7761 7762 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7763 pkg.applicationInfo.secondaryCpuAbi = null; 7764 } else if (has32BitLibs && has64BitLibs) { 7765 // The application has both 64 and 32 bit bundled libraries. We check 7766 // here that the app declares multiArch support, and warn if it doesn't. 7767 // 7768 // We will be lenient here and record both ABIs. The primary will be the 7769 // ABI that's higher on the list, i.e, a device that's configured to prefer 7770 // 64 bit apps will see a 64 bit primary ABI, 7771 7772 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7773 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7774 } 7775 7776 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7777 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7778 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7779 } else { 7780 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7781 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7782 } 7783 } else { 7784 pkg.applicationInfo.primaryCpuAbi = null; 7785 pkg.applicationInfo.secondaryCpuAbi = null; 7786 } 7787 } 7788 7789 private void killApplication(String pkgName, int appId, String reason) { 7790 // Request the ActivityManager to kill the process(only for existing packages) 7791 // so that we do not end up in a confused state while the user is still using the older 7792 // version of the application while the new one gets installed. 7793 IActivityManager am = ActivityManagerNative.getDefault(); 7794 if (am != null) { 7795 try { 7796 am.killApplicationWithAppId(pkgName, appId, reason); 7797 } catch (RemoteException e) { 7798 } 7799 } 7800 } 7801 7802 void removePackageLI(PackageSetting ps, boolean chatty) { 7803 if (DEBUG_INSTALL) { 7804 if (chatty) 7805 Log.d(TAG, "Removing package " + ps.name); 7806 } 7807 7808 // writer 7809 synchronized (mPackages) { 7810 mPackages.remove(ps.name); 7811 final PackageParser.Package pkg = ps.pkg; 7812 if (pkg != null) { 7813 cleanPackageDataStructuresLILPw(pkg, chatty); 7814 } 7815 } 7816 } 7817 7818 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7819 if (DEBUG_INSTALL) { 7820 if (chatty) 7821 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7822 } 7823 7824 // writer 7825 synchronized (mPackages) { 7826 mPackages.remove(pkg.applicationInfo.packageName); 7827 cleanPackageDataStructuresLILPw(pkg, chatty); 7828 } 7829 } 7830 7831 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7832 int N = pkg.providers.size(); 7833 StringBuilder r = null; 7834 int i; 7835 for (i=0; i<N; i++) { 7836 PackageParser.Provider p = pkg.providers.get(i); 7837 mProviders.removeProvider(p); 7838 if (p.info.authority == null) { 7839 7840 /* There was another ContentProvider with this authority when 7841 * this app was installed so this authority is null, 7842 * Ignore it as we don't have to unregister the provider. 7843 */ 7844 continue; 7845 } 7846 String names[] = p.info.authority.split(";"); 7847 for (int j = 0; j < names.length; j++) { 7848 if (mProvidersByAuthority.get(names[j]) == p) { 7849 mProvidersByAuthority.remove(names[j]); 7850 if (DEBUG_REMOVE) { 7851 if (chatty) 7852 Log.d(TAG, "Unregistered content provider: " + names[j] 7853 + ", className = " + p.info.name + ", isSyncable = " 7854 + p.info.isSyncable); 7855 } 7856 } 7857 } 7858 if (DEBUG_REMOVE && chatty) { 7859 if (r == null) { 7860 r = new StringBuilder(256); 7861 } else { 7862 r.append(' '); 7863 } 7864 r.append(p.info.name); 7865 } 7866 } 7867 if (r != null) { 7868 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7869 } 7870 7871 N = pkg.services.size(); 7872 r = null; 7873 for (i=0; i<N; i++) { 7874 PackageParser.Service s = pkg.services.get(i); 7875 mServices.removeService(s); 7876 if (chatty) { 7877 if (r == null) { 7878 r = new StringBuilder(256); 7879 } else { 7880 r.append(' '); 7881 } 7882 r.append(s.info.name); 7883 } 7884 } 7885 if (r != null) { 7886 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7887 } 7888 7889 N = pkg.receivers.size(); 7890 r = null; 7891 for (i=0; i<N; i++) { 7892 PackageParser.Activity a = pkg.receivers.get(i); 7893 mReceivers.removeActivity(a, "receiver"); 7894 if (DEBUG_REMOVE && chatty) { 7895 if (r == null) { 7896 r = new StringBuilder(256); 7897 } else { 7898 r.append(' '); 7899 } 7900 r.append(a.info.name); 7901 } 7902 } 7903 if (r != null) { 7904 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7905 } 7906 7907 N = pkg.activities.size(); 7908 r = null; 7909 for (i=0; i<N; i++) { 7910 PackageParser.Activity a = pkg.activities.get(i); 7911 mActivities.removeActivity(a, "activity"); 7912 if (DEBUG_REMOVE && chatty) { 7913 if (r == null) { 7914 r = new StringBuilder(256); 7915 } else { 7916 r.append(' '); 7917 } 7918 r.append(a.info.name); 7919 } 7920 } 7921 if (r != null) { 7922 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7923 } 7924 7925 N = pkg.permissions.size(); 7926 r = null; 7927 for (i=0; i<N; i++) { 7928 PackageParser.Permission p = pkg.permissions.get(i); 7929 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7930 if (bp == null) { 7931 bp = mSettings.mPermissionTrees.get(p.info.name); 7932 } 7933 if (bp != null && bp.perm == p) { 7934 bp.perm = null; 7935 if (DEBUG_REMOVE && chatty) { 7936 if (r == null) { 7937 r = new StringBuilder(256); 7938 } else { 7939 r.append(' '); 7940 } 7941 r.append(p.info.name); 7942 } 7943 } 7944 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7945 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7946 if (appOpPerms != null) { 7947 appOpPerms.remove(pkg.packageName); 7948 } 7949 } 7950 } 7951 if (r != null) { 7952 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7953 } 7954 7955 N = pkg.requestedPermissions.size(); 7956 r = null; 7957 for (i=0; i<N; i++) { 7958 String perm = pkg.requestedPermissions.get(i); 7959 BasePermission bp = mSettings.mPermissions.get(perm); 7960 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7961 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7962 if (appOpPerms != null) { 7963 appOpPerms.remove(pkg.packageName); 7964 if (appOpPerms.isEmpty()) { 7965 mAppOpPermissionPackages.remove(perm); 7966 } 7967 } 7968 } 7969 } 7970 if (r != null) { 7971 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7972 } 7973 7974 N = pkg.instrumentation.size(); 7975 r = null; 7976 for (i=0; i<N; i++) { 7977 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7978 mInstrumentation.remove(a.getComponentName()); 7979 if (DEBUG_REMOVE && chatty) { 7980 if (r == null) { 7981 r = new StringBuilder(256); 7982 } else { 7983 r.append(' '); 7984 } 7985 r.append(a.info.name); 7986 } 7987 } 7988 if (r != null) { 7989 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7990 } 7991 7992 r = null; 7993 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7994 // Only system apps can hold shared libraries. 7995 if (pkg.libraryNames != null) { 7996 for (i=0; i<pkg.libraryNames.size(); i++) { 7997 String name = pkg.libraryNames.get(i); 7998 SharedLibraryEntry cur = mSharedLibraries.get(name); 7999 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8000 mSharedLibraries.remove(name); 8001 if (DEBUG_REMOVE && chatty) { 8002 if (r == null) { 8003 r = new StringBuilder(256); 8004 } else { 8005 r.append(' '); 8006 } 8007 r.append(name); 8008 } 8009 } 8010 } 8011 } 8012 } 8013 if (r != null) { 8014 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8015 } 8016 } 8017 8018 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8019 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8020 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8021 return true; 8022 } 8023 } 8024 return false; 8025 } 8026 8027 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8028 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8029 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8030 8031 private void updatePermissionsLPw(String changingPkg, 8032 PackageParser.Package pkgInfo, int flags) { 8033 // Make sure there are no dangling permission trees. 8034 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8035 while (it.hasNext()) { 8036 final BasePermission bp = it.next(); 8037 if (bp.packageSetting == null) { 8038 // We may not yet have parsed the package, so just see if 8039 // we still know about its settings. 8040 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8041 } 8042 if (bp.packageSetting == null) { 8043 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8044 + " from package " + bp.sourcePackage); 8045 it.remove(); 8046 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8047 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8048 Slog.i(TAG, "Removing old permission tree: " + bp.name 8049 + " from package " + bp.sourcePackage); 8050 flags |= UPDATE_PERMISSIONS_ALL; 8051 it.remove(); 8052 } 8053 } 8054 } 8055 8056 // Make sure all dynamic permissions have been assigned to a package, 8057 // and make sure there are no dangling permissions. 8058 it = mSettings.mPermissions.values().iterator(); 8059 while (it.hasNext()) { 8060 final BasePermission bp = it.next(); 8061 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8062 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8063 + bp.name + " pkg=" + bp.sourcePackage 8064 + " info=" + bp.pendingInfo); 8065 if (bp.packageSetting == null && bp.pendingInfo != null) { 8066 final BasePermission tree = findPermissionTreeLP(bp.name); 8067 if (tree != null && tree.perm != null) { 8068 bp.packageSetting = tree.packageSetting; 8069 bp.perm = new PackageParser.Permission(tree.perm.owner, 8070 new PermissionInfo(bp.pendingInfo)); 8071 bp.perm.info.packageName = tree.perm.info.packageName; 8072 bp.perm.info.name = bp.name; 8073 bp.uid = tree.uid; 8074 } 8075 } 8076 } 8077 if (bp.packageSetting == null) { 8078 // We may not yet have parsed the package, so just see if 8079 // we still know about its settings. 8080 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8081 } 8082 if (bp.packageSetting == null) { 8083 Slog.w(TAG, "Removing dangling permission: " + bp.name 8084 + " from package " + bp.sourcePackage); 8085 it.remove(); 8086 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8087 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8088 Slog.i(TAG, "Removing old permission: " + bp.name 8089 + " from package " + bp.sourcePackage); 8090 flags |= UPDATE_PERMISSIONS_ALL; 8091 it.remove(); 8092 } 8093 } 8094 } 8095 8096 // Now update the permissions for all packages, in particular 8097 // replace the granted permissions of the system packages. 8098 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8099 for (PackageParser.Package pkg : mPackages.values()) { 8100 if (pkg != pkgInfo) { 8101 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8102 changingPkg); 8103 } 8104 } 8105 } 8106 8107 if (pkgInfo != null) { 8108 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8109 } 8110 } 8111 8112 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8113 String packageOfInterest) { 8114 // IMPORTANT: There are two types of permissions: install and runtime. 8115 // Install time permissions are granted when the app is installed to 8116 // all device users and users added in the future. Runtime permissions 8117 // are granted at runtime explicitly to specific users. Normal and signature 8118 // protected permissions are install time permissions. Dangerous permissions 8119 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8120 // otherwise they are runtime permissions. This function does not manage 8121 // runtime permissions except for the case an app targeting Lollipop MR1 8122 // being upgraded to target a newer SDK, in which case dangerous permissions 8123 // are transformed from install time to runtime ones. 8124 8125 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8126 if (ps == null) { 8127 return; 8128 } 8129 8130 PermissionsState permissionsState = ps.getPermissionsState(); 8131 PermissionsState origPermissions = permissionsState; 8132 8133 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8134 8135 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8136 8137 boolean changedInstallPermission = false; 8138 8139 if (replace) { 8140 ps.installPermissionsFixed = false; 8141 if (!ps.isSharedUser()) { 8142 origPermissions = new PermissionsState(permissionsState); 8143 permissionsState.reset(); 8144 } 8145 } 8146 8147 permissionsState.setGlobalGids(mGlobalGids); 8148 8149 final int N = pkg.requestedPermissions.size(); 8150 for (int i=0; i<N; i++) { 8151 final String name = pkg.requestedPermissions.get(i); 8152 final BasePermission bp = mSettings.mPermissions.get(name); 8153 8154 if (DEBUG_INSTALL) { 8155 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8156 } 8157 8158 if (bp == null || bp.packageSetting == null) { 8159 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8160 Slog.w(TAG, "Unknown permission " + name 8161 + " in package " + pkg.packageName); 8162 } 8163 continue; 8164 } 8165 8166 final String perm = bp.name; 8167 boolean allowedSig = false; 8168 int grant = GRANT_DENIED; 8169 8170 // Keep track of app op permissions. 8171 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8172 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8173 if (pkgs == null) { 8174 pkgs = new ArraySet<>(); 8175 mAppOpPermissionPackages.put(bp.name, pkgs); 8176 } 8177 pkgs.add(pkg.packageName); 8178 } 8179 8180 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8181 switch (level) { 8182 case PermissionInfo.PROTECTION_NORMAL: { 8183 // For all apps normal permissions are install time ones. 8184 grant = GRANT_INSTALL; 8185 } break; 8186 8187 case PermissionInfo.PROTECTION_DANGEROUS: { 8188 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8189 // For legacy apps dangerous permissions are install time ones. 8190 grant = GRANT_INSTALL_LEGACY; 8191 } else if (origPermissions.hasInstallPermission(bp.name)) { 8192 // For legacy apps that became modern, install becomes runtime. 8193 grant = GRANT_UPGRADE; 8194 } else { 8195 // For modern apps keep runtime permissions unchanged. 8196 grant = GRANT_RUNTIME; 8197 } 8198 } break; 8199 8200 case PermissionInfo.PROTECTION_SIGNATURE: { 8201 // For all apps signature permissions are install time ones. 8202 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8203 if (allowedSig) { 8204 grant = GRANT_INSTALL; 8205 } 8206 } break; 8207 } 8208 8209 if (DEBUG_INSTALL) { 8210 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8211 } 8212 8213 if (grant != GRANT_DENIED) { 8214 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8215 // If this is an existing, non-system package, then 8216 // we can't add any new permissions to it. 8217 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8218 // Except... if this is a permission that was added 8219 // to the platform (note: need to only do this when 8220 // updating the platform). 8221 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8222 grant = GRANT_DENIED; 8223 } 8224 } 8225 } 8226 8227 switch (grant) { 8228 case GRANT_INSTALL: { 8229 // Revoke this as runtime permission to handle the case of 8230 // a runtime permission being downgraded to an install one. 8231 for (int userId : UserManagerService.getInstance().getUserIds()) { 8232 if (origPermissions.getRuntimePermissionState( 8233 bp.name, userId) != null) { 8234 // Revoke the runtime permission and clear the flags. 8235 origPermissions.revokeRuntimePermission(bp, userId); 8236 origPermissions.updatePermissionFlags(bp, userId, 8237 PackageManager.MASK_PERMISSION_FLAGS, 0); 8238 // If we revoked a permission permission, we have to write. 8239 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8240 changedRuntimePermissionUserIds, userId); 8241 } 8242 } 8243 // Grant an install permission. 8244 if (permissionsState.grantInstallPermission(bp) != 8245 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8246 changedInstallPermission = true; 8247 } 8248 } break; 8249 8250 case GRANT_INSTALL_LEGACY: { 8251 // Grant an install permission. 8252 if (permissionsState.grantInstallPermission(bp) != 8253 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8254 changedInstallPermission = true; 8255 } 8256 } break; 8257 8258 case GRANT_RUNTIME: { 8259 // Grant previously granted runtime permissions. 8260 for (int userId : UserManagerService.getInstance().getUserIds()) { 8261 PermissionState permissionState = origPermissions 8262 .getRuntimePermissionState(bp.name, userId); 8263 final int flags = permissionState != null 8264 ? permissionState.getFlags() : 0; 8265 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8266 if (permissionsState.grantRuntimePermission(bp, userId) == 8267 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8268 // If we cannot put the permission as it was, we have to write. 8269 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8270 changedRuntimePermissionUserIds, userId); 8271 } 8272 } 8273 // Propagate the permission flags. 8274 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8275 } 8276 } break; 8277 8278 case GRANT_UPGRADE: { 8279 // Grant runtime permissions for a previously held install permission. 8280 PermissionState permissionState = origPermissions 8281 .getInstallPermissionState(bp.name); 8282 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8283 8284 if (origPermissions.revokeInstallPermission(bp) 8285 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8286 // We will be transferring the permission flags, so clear them. 8287 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8288 PackageManager.MASK_PERMISSION_FLAGS, 0); 8289 changedInstallPermission = true; 8290 } 8291 8292 // If the permission is not to be promoted to runtime we ignore it and 8293 // also its other flags as they are not applicable to install permissions. 8294 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8295 for (int userId : currentUserIds) { 8296 if (permissionsState.grantRuntimePermission(bp, userId) != 8297 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8298 // Transfer the permission flags. 8299 permissionsState.updatePermissionFlags(bp, userId, 8300 flags, flags); 8301 // If we granted the permission, we have to write. 8302 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8303 changedRuntimePermissionUserIds, userId); 8304 } 8305 } 8306 } 8307 } break; 8308 8309 default: { 8310 if (packageOfInterest == null 8311 || packageOfInterest.equals(pkg.packageName)) { 8312 Slog.w(TAG, "Not granting permission " + perm 8313 + " to package " + pkg.packageName 8314 + " because it was previously installed without"); 8315 } 8316 } break; 8317 } 8318 } else { 8319 if (permissionsState.revokeInstallPermission(bp) != 8320 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8321 // Also drop the permission flags. 8322 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8323 PackageManager.MASK_PERMISSION_FLAGS, 0); 8324 changedInstallPermission = true; 8325 Slog.i(TAG, "Un-granting permission " + perm 8326 + " from package " + pkg.packageName 8327 + " (protectionLevel=" + bp.protectionLevel 8328 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8329 + ")"); 8330 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8331 // Don't print warning for app op permissions, since it is fine for them 8332 // not to be granted, there is a UI for the user to decide. 8333 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8334 Slog.w(TAG, "Not granting permission " + perm 8335 + " to package " + pkg.packageName 8336 + " (protectionLevel=" + bp.protectionLevel 8337 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8338 + ")"); 8339 } 8340 } 8341 } 8342 } 8343 8344 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8345 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8346 // This is the first that we have heard about this package, so the 8347 // permissions we have now selected are fixed until explicitly 8348 // changed. 8349 ps.installPermissionsFixed = true; 8350 } 8351 8352 // Persist the runtime permissions state for users with changes. 8353 for (int userId : changedRuntimePermissionUserIds) { 8354 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8355 } 8356 } 8357 8358 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8359 boolean allowed = false; 8360 final int NP = PackageParser.NEW_PERMISSIONS.length; 8361 for (int ip=0; ip<NP; ip++) { 8362 final PackageParser.NewPermissionInfo npi 8363 = PackageParser.NEW_PERMISSIONS[ip]; 8364 if (npi.name.equals(perm) 8365 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8366 allowed = true; 8367 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8368 + pkg.packageName); 8369 break; 8370 } 8371 } 8372 return allowed; 8373 } 8374 8375 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8376 BasePermission bp, PermissionsState origPermissions) { 8377 boolean allowed; 8378 allowed = (compareSignatures( 8379 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8380 == PackageManager.SIGNATURE_MATCH) 8381 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8382 == PackageManager.SIGNATURE_MATCH); 8383 if (!allowed && (bp.protectionLevel 8384 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8385 if (isSystemApp(pkg)) { 8386 // For updated system applications, a system permission 8387 // is granted only if it had been defined by the original application. 8388 if (pkg.isUpdatedSystemApp()) { 8389 final PackageSetting sysPs = mSettings 8390 .getDisabledSystemPkgLPr(pkg.packageName); 8391 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8392 // If the original was granted this permission, we take 8393 // that grant decision as read and propagate it to the 8394 // update. 8395 if (sysPs.isPrivileged()) { 8396 allowed = true; 8397 } 8398 } else { 8399 // The system apk may have been updated with an older 8400 // version of the one on the data partition, but which 8401 // granted a new system permission that it didn't have 8402 // before. In this case we do want to allow the app to 8403 // now get the new permission if the ancestral apk is 8404 // privileged to get it. 8405 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8406 for (int j=0; 8407 j<sysPs.pkg.requestedPermissions.size(); j++) { 8408 if (perm.equals( 8409 sysPs.pkg.requestedPermissions.get(j))) { 8410 allowed = true; 8411 break; 8412 } 8413 } 8414 } 8415 } 8416 } else { 8417 allowed = isPrivilegedApp(pkg); 8418 } 8419 } 8420 } 8421 if (!allowed && (bp.protectionLevel 8422 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8423 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8424 // If this was a previously normal/dangerous permission that got moved 8425 // to a system permission as part of the runtime permission redesign, then 8426 // we still want to blindly grant it to old apps. 8427 allowed = true; 8428 } 8429 if (!allowed && (bp.protectionLevel 8430 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8431 // For development permissions, a development permission 8432 // is granted only if it was already granted. 8433 allowed = origPermissions.hasInstallPermission(perm); 8434 } 8435 return allowed; 8436 } 8437 8438 final class ActivityIntentResolver 8439 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8440 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8441 boolean defaultOnly, int userId) { 8442 if (!sUserManager.exists(userId)) return null; 8443 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8444 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8445 } 8446 8447 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8448 int userId) { 8449 if (!sUserManager.exists(userId)) return null; 8450 mFlags = flags; 8451 return super.queryIntent(intent, resolvedType, 8452 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8453 } 8454 8455 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8456 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8457 if (!sUserManager.exists(userId)) return null; 8458 if (packageActivities == null) { 8459 return null; 8460 } 8461 mFlags = flags; 8462 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8463 final int N = packageActivities.size(); 8464 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8465 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8466 8467 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8468 for (int i = 0; i < N; ++i) { 8469 intentFilters = packageActivities.get(i).intents; 8470 if (intentFilters != null && intentFilters.size() > 0) { 8471 PackageParser.ActivityIntentInfo[] array = 8472 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8473 intentFilters.toArray(array); 8474 listCut.add(array); 8475 } 8476 } 8477 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8478 } 8479 8480 public final void addActivity(PackageParser.Activity a, String type) { 8481 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8482 mActivities.put(a.getComponentName(), a); 8483 if (DEBUG_SHOW_INFO) 8484 Log.v( 8485 TAG, " " + type + " " + 8486 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8487 if (DEBUG_SHOW_INFO) 8488 Log.v(TAG, " Class=" + a.info.name); 8489 final int NI = a.intents.size(); 8490 for (int j=0; j<NI; j++) { 8491 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8492 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8493 intent.setPriority(0); 8494 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8495 + a.className + " with priority > 0, forcing to 0"); 8496 } 8497 if (DEBUG_SHOW_INFO) { 8498 Log.v(TAG, " IntentFilter:"); 8499 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8500 } 8501 if (!intent.debugCheck()) { 8502 Log.w(TAG, "==> For Activity " + a.info.name); 8503 } 8504 addFilter(intent); 8505 } 8506 } 8507 8508 public final void removeActivity(PackageParser.Activity a, String type) { 8509 mActivities.remove(a.getComponentName()); 8510 if (DEBUG_SHOW_INFO) { 8511 Log.v(TAG, " " + type + " " 8512 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8513 : a.info.name) + ":"); 8514 Log.v(TAG, " Class=" + a.info.name); 8515 } 8516 final int NI = a.intents.size(); 8517 for (int j=0; j<NI; j++) { 8518 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8519 if (DEBUG_SHOW_INFO) { 8520 Log.v(TAG, " IntentFilter:"); 8521 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8522 } 8523 removeFilter(intent); 8524 } 8525 } 8526 8527 @Override 8528 protected boolean allowFilterResult( 8529 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8530 ActivityInfo filterAi = filter.activity.info; 8531 for (int i=dest.size()-1; i>=0; i--) { 8532 ActivityInfo destAi = dest.get(i).activityInfo; 8533 if (destAi.name == filterAi.name 8534 && destAi.packageName == filterAi.packageName) { 8535 return false; 8536 } 8537 } 8538 return true; 8539 } 8540 8541 @Override 8542 protected ActivityIntentInfo[] newArray(int size) { 8543 return new ActivityIntentInfo[size]; 8544 } 8545 8546 @Override 8547 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8548 if (!sUserManager.exists(userId)) return true; 8549 PackageParser.Package p = filter.activity.owner; 8550 if (p != null) { 8551 PackageSetting ps = (PackageSetting)p.mExtras; 8552 if (ps != null) { 8553 // System apps are never considered stopped for purposes of 8554 // filtering, because there may be no way for the user to 8555 // actually re-launch them. 8556 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8557 && ps.getStopped(userId); 8558 } 8559 } 8560 return false; 8561 } 8562 8563 @Override 8564 protected boolean isPackageForFilter(String packageName, 8565 PackageParser.ActivityIntentInfo info) { 8566 return packageName.equals(info.activity.owner.packageName); 8567 } 8568 8569 @Override 8570 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8571 int match, int userId) { 8572 if (!sUserManager.exists(userId)) return null; 8573 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8574 return null; 8575 } 8576 final PackageParser.Activity activity = info.activity; 8577 if (mSafeMode && (activity.info.applicationInfo.flags 8578 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8579 return null; 8580 } 8581 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8582 if (ps == null) { 8583 return null; 8584 } 8585 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8586 ps.readUserState(userId), userId); 8587 if (ai == null) { 8588 return null; 8589 } 8590 final ResolveInfo res = new ResolveInfo(); 8591 res.activityInfo = ai; 8592 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8593 res.filter = info; 8594 } 8595 if (info != null) { 8596 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8597 } 8598 res.priority = info.getPriority(); 8599 res.preferredOrder = activity.owner.mPreferredOrder; 8600 //System.out.println("Result: " + res.activityInfo.className + 8601 // " = " + res.priority); 8602 res.match = match; 8603 res.isDefault = info.hasDefault; 8604 res.labelRes = info.labelRes; 8605 res.nonLocalizedLabel = info.nonLocalizedLabel; 8606 if (userNeedsBadging(userId)) { 8607 res.noResourceId = true; 8608 } else { 8609 res.icon = info.icon; 8610 } 8611 res.iconResourceId = info.icon; 8612 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8613 return res; 8614 } 8615 8616 @Override 8617 protected void sortResults(List<ResolveInfo> results) { 8618 Collections.sort(results, mResolvePrioritySorter); 8619 } 8620 8621 @Override 8622 protected void dumpFilter(PrintWriter out, String prefix, 8623 PackageParser.ActivityIntentInfo filter) { 8624 out.print(prefix); out.print( 8625 Integer.toHexString(System.identityHashCode(filter.activity))); 8626 out.print(' '); 8627 filter.activity.printComponentShortName(out); 8628 out.print(" filter "); 8629 out.println(Integer.toHexString(System.identityHashCode(filter))); 8630 } 8631 8632 @Override 8633 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8634 return filter.activity; 8635 } 8636 8637 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8638 PackageParser.Activity activity = (PackageParser.Activity)label; 8639 out.print(prefix); out.print( 8640 Integer.toHexString(System.identityHashCode(activity))); 8641 out.print(' '); 8642 activity.printComponentShortName(out); 8643 if (count > 1) { 8644 out.print(" ("); out.print(count); out.print(" filters)"); 8645 } 8646 out.println(); 8647 } 8648 8649// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8650// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8651// final List<ResolveInfo> retList = Lists.newArrayList(); 8652// while (i.hasNext()) { 8653// final ResolveInfo resolveInfo = i.next(); 8654// if (isEnabledLP(resolveInfo.activityInfo)) { 8655// retList.add(resolveInfo); 8656// } 8657// } 8658// return retList; 8659// } 8660 8661 // Keys are String (activity class name), values are Activity. 8662 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8663 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8664 private int mFlags; 8665 } 8666 8667 private final class ServiceIntentResolver 8668 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8669 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8670 boolean defaultOnly, int userId) { 8671 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8672 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8673 } 8674 8675 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8676 int userId) { 8677 if (!sUserManager.exists(userId)) return null; 8678 mFlags = flags; 8679 return super.queryIntent(intent, resolvedType, 8680 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8681 } 8682 8683 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8684 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8685 if (!sUserManager.exists(userId)) return null; 8686 if (packageServices == null) { 8687 return null; 8688 } 8689 mFlags = flags; 8690 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8691 final int N = packageServices.size(); 8692 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8693 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8694 8695 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8696 for (int i = 0; i < N; ++i) { 8697 intentFilters = packageServices.get(i).intents; 8698 if (intentFilters != null && intentFilters.size() > 0) { 8699 PackageParser.ServiceIntentInfo[] array = 8700 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8701 intentFilters.toArray(array); 8702 listCut.add(array); 8703 } 8704 } 8705 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8706 } 8707 8708 public final void addService(PackageParser.Service s) { 8709 mServices.put(s.getComponentName(), s); 8710 if (DEBUG_SHOW_INFO) { 8711 Log.v(TAG, " " 8712 + (s.info.nonLocalizedLabel != null 8713 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8714 Log.v(TAG, " Class=" + s.info.name); 8715 } 8716 final int NI = s.intents.size(); 8717 int j; 8718 for (j=0; j<NI; j++) { 8719 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8720 if (DEBUG_SHOW_INFO) { 8721 Log.v(TAG, " IntentFilter:"); 8722 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8723 } 8724 if (!intent.debugCheck()) { 8725 Log.w(TAG, "==> For Service " + s.info.name); 8726 } 8727 addFilter(intent); 8728 } 8729 } 8730 8731 public final void removeService(PackageParser.Service s) { 8732 mServices.remove(s.getComponentName()); 8733 if (DEBUG_SHOW_INFO) { 8734 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8735 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8736 Log.v(TAG, " Class=" + s.info.name); 8737 } 8738 final int NI = s.intents.size(); 8739 int j; 8740 for (j=0; j<NI; j++) { 8741 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8742 if (DEBUG_SHOW_INFO) { 8743 Log.v(TAG, " IntentFilter:"); 8744 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8745 } 8746 removeFilter(intent); 8747 } 8748 } 8749 8750 @Override 8751 protected boolean allowFilterResult( 8752 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8753 ServiceInfo filterSi = filter.service.info; 8754 for (int i=dest.size()-1; i>=0; i--) { 8755 ServiceInfo destAi = dest.get(i).serviceInfo; 8756 if (destAi.name == filterSi.name 8757 && destAi.packageName == filterSi.packageName) { 8758 return false; 8759 } 8760 } 8761 return true; 8762 } 8763 8764 @Override 8765 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8766 return new PackageParser.ServiceIntentInfo[size]; 8767 } 8768 8769 @Override 8770 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8771 if (!sUserManager.exists(userId)) return true; 8772 PackageParser.Package p = filter.service.owner; 8773 if (p != null) { 8774 PackageSetting ps = (PackageSetting)p.mExtras; 8775 if (ps != null) { 8776 // System apps are never considered stopped for purposes of 8777 // filtering, because there may be no way for the user to 8778 // actually re-launch them. 8779 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8780 && ps.getStopped(userId); 8781 } 8782 } 8783 return false; 8784 } 8785 8786 @Override 8787 protected boolean isPackageForFilter(String packageName, 8788 PackageParser.ServiceIntentInfo info) { 8789 return packageName.equals(info.service.owner.packageName); 8790 } 8791 8792 @Override 8793 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8794 int match, int userId) { 8795 if (!sUserManager.exists(userId)) return null; 8796 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8797 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8798 return null; 8799 } 8800 final PackageParser.Service service = info.service; 8801 if (mSafeMode && (service.info.applicationInfo.flags 8802 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8803 return null; 8804 } 8805 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8806 if (ps == null) { 8807 return null; 8808 } 8809 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8810 ps.readUserState(userId), userId); 8811 if (si == null) { 8812 return null; 8813 } 8814 final ResolveInfo res = new ResolveInfo(); 8815 res.serviceInfo = si; 8816 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8817 res.filter = filter; 8818 } 8819 res.priority = info.getPriority(); 8820 res.preferredOrder = service.owner.mPreferredOrder; 8821 res.match = match; 8822 res.isDefault = info.hasDefault; 8823 res.labelRes = info.labelRes; 8824 res.nonLocalizedLabel = info.nonLocalizedLabel; 8825 res.icon = info.icon; 8826 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8827 return res; 8828 } 8829 8830 @Override 8831 protected void sortResults(List<ResolveInfo> results) { 8832 Collections.sort(results, mResolvePrioritySorter); 8833 } 8834 8835 @Override 8836 protected void dumpFilter(PrintWriter out, String prefix, 8837 PackageParser.ServiceIntentInfo filter) { 8838 out.print(prefix); out.print( 8839 Integer.toHexString(System.identityHashCode(filter.service))); 8840 out.print(' '); 8841 filter.service.printComponentShortName(out); 8842 out.print(" filter "); 8843 out.println(Integer.toHexString(System.identityHashCode(filter))); 8844 } 8845 8846 @Override 8847 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8848 return filter.service; 8849 } 8850 8851 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8852 PackageParser.Service service = (PackageParser.Service)label; 8853 out.print(prefix); out.print( 8854 Integer.toHexString(System.identityHashCode(service))); 8855 out.print(' '); 8856 service.printComponentShortName(out); 8857 if (count > 1) { 8858 out.print(" ("); out.print(count); out.print(" filters)"); 8859 } 8860 out.println(); 8861 } 8862 8863// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8864// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8865// final List<ResolveInfo> retList = Lists.newArrayList(); 8866// while (i.hasNext()) { 8867// final ResolveInfo resolveInfo = (ResolveInfo) i; 8868// if (isEnabledLP(resolveInfo.serviceInfo)) { 8869// retList.add(resolveInfo); 8870// } 8871// } 8872// return retList; 8873// } 8874 8875 // Keys are String (activity class name), values are Activity. 8876 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8877 = new ArrayMap<ComponentName, PackageParser.Service>(); 8878 private int mFlags; 8879 }; 8880 8881 private final class ProviderIntentResolver 8882 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8883 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8884 boolean defaultOnly, int userId) { 8885 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8886 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8887 } 8888 8889 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8890 int userId) { 8891 if (!sUserManager.exists(userId)) 8892 return null; 8893 mFlags = flags; 8894 return super.queryIntent(intent, resolvedType, 8895 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8896 } 8897 8898 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8899 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8900 if (!sUserManager.exists(userId)) 8901 return null; 8902 if (packageProviders == null) { 8903 return null; 8904 } 8905 mFlags = flags; 8906 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8907 final int N = packageProviders.size(); 8908 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8909 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8910 8911 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8912 for (int i = 0; i < N; ++i) { 8913 intentFilters = packageProviders.get(i).intents; 8914 if (intentFilters != null && intentFilters.size() > 0) { 8915 PackageParser.ProviderIntentInfo[] array = 8916 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8917 intentFilters.toArray(array); 8918 listCut.add(array); 8919 } 8920 } 8921 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8922 } 8923 8924 public final void addProvider(PackageParser.Provider p) { 8925 if (mProviders.containsKey(p.getComponentName())) { 8926 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8927 return; 8928 } 8929 8930 mProviders.put(p.getComponentName(), p); 8931 if (DEBUG_SHOW_INFO) { 8932 Log.v(TAG, " " 8933 + (p.info.nonLocalizedLabel != null 8934 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8935 Log.v(TAG, " Class=" + p.info.name); 8936 } 8937 final int NI = p.intents.size(); 8938 int j; 8939 for (j = 0; j < NI; j++) { 8940 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8941 if (DEBUG_SHOW_INFO) { 8942 Log.v(TAG, " IntentFilter:"); 8943 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8944 } 8945 if (!intent.debugCheck()) { 8946 Log.w(TAG, "==> For Provider " + p.info.name); 8947 } 8948 addFilter(intent); 8949 } 8950 } 8951 8952 public final void removeProvider(PackageParser.Provider p) { 8953 mProviders.remove(p.getComponentName()); 8954 if (DEBUG_SHOW_INFO) { 8955 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8956 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8957 Log.v(TAG, " Class=" + p.info.name); 8958 } 8959 final int NI = p.intents.size(); 8960 int j; 8961 for (j = 0; j < NI; j++) { 8962 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8963 if (DEBUG_SHOW_INFO) { 8964 Log.v(TAG, " IntentFilter:"); 8965 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8966 } 8967 removeFilter(intent); 8968 } 8969 } 8970 8971 @Override 8972 protected boolean allowFilterResult( 8973 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8974 ProviderInfo filterPi = filter.provider.info; 8975 for (int i = dest.size() - 1; i >= 0; i--) { 8976 ProviderInfo destPi = dest.get(i).providerInfo; 8977 if (destPi.name == filterPi.name 8978 && destPi.packageName == filterPi.packageName) { 8979 return false; 8980 } 8981 } 8982 return true; 8983 } 8984 8985 @Override 8986 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8987 return new PackageParser.ProviderIntentInfo[size]; 8988 } 8989 8990 @Override 8991 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8992 if (!sUserManager.exists(userId)) 8993 return true; 8994 PackageParser.Package p = filter.provider.owner; 8995 if (p != null) { 8996 PackageSetting ps = (PackageSetting) p.mExtras; 8997 if (ps != null) { 8998 // System apps are never considered stopped for purposes of 8999 // filtering, because there may be no way for the user to 9000 // actually re-launch them. 9001 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9002 && ps.getStopped(userId); 9003 } 9004 } 9005 return false; 9006 } 9007 9008 @Override 9009 protected boolean isPackageForFilter(String packageName, 9010 PackageParser.ProviderIntentInfo info) { 9011 return packageName.equals(info.provider.owner.packageName); 9012 } 9013 9014 @Override 9015 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9016 int match, int userId) { 9017 if (!sUserManager.exists(userId)) 9018 return null; 9019 final PackageParser.ProviderIntentInfo info = filter; 9020 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9021 return null; 9022 } 9023 final PackageParser.Provider provider = info.provider; 9024 if (mSafeMode && (provider.info.applicationInfo.flags 9025 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9026 return null; 9027 } 9028 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9029 if (ps == null) { 9030 return null; 9031 } 9032 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9033 ps.readUserState(userId), userId); 9034 if (pi == null) { 9035 return null; 9036 } 9037 final ResolveInfo res = new ResolveInfo(); 9038 res.providerInfo = pi; 9039 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9040 res.filter = filter; 9041 } 9042 res.priority = info.getPriority(); 9043 res.preferredOrder = provider.owner.mPreferredOrder; 9044 res.match = match; 9045 res.isDefault = info.hasDefault; 9046 res.labelRes = info.labelRes; 9047 res.nonLocalizedLabel = info.nonLocalizedLabel; 9048 res.icon = info.icon; 9049 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9050 return res; 9051 } 9052 9053 @Override 9054 protected void sortResults(List<ResolveInfo> results) { 9055 Collections.sort(results, mResolvePrioritySorter); 9056 } 9057 9058 @Override 9059 protected void dumpFilter(PrintWriter out, String prefix, 9060 PackageParser.ProviderIntentInfo filter) { 9061 out.print(prefix); 9062 out.print( 9063 Integer.toHexString(System.identityHashCode(filter.provider))); 9064 out.print(' '); 9065 filter.provider.printComponentShortName(out); 9066 out.print(" filter "); 9067 out.println(Integer.toHexString(System.identityHashCode(filter))); 9068 } 9069 9070 @Override 9071 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9072 return filter.provider; 9073 } 9074 9075 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9076 PackageParser.Provider provider = (PackageParser.Provider)label; 9077 out.print(prefix); out.print( 9078 Integer.toHexString(System.identityHashCode(provider))); 9079 out.print(' '); 9080 provider.printComponentShortName(out); 9081 if (count > 1) { 9082 out.print(" ("); out.print(count); out.print(" filters)"); 9083 } 9084 out.println(); 9085 } 9086 9087 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9088 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9089 private int mFlags; 9090 }; 9091 9092 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9093 new Comparator<ResolveInfo>() { 9094 public int compare(ResolveInfo r1, ResolveInfo r2) { 9095 int v1 = r1.priority; 9096 int v2 = r2.priority; 9097 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9098 if (v1 != v2) { 9099 return (v1 > v2) ? -1 : 1; 9100 } 9101 v1 = r1.preferredOrder; 9102 v2 = r2.preferredOrder; 9103 if (v1 != v2) { 9104 return (v1 > v2) ? -1 : 1; 9105 } 9106 if (r1.isDefault != r2.isDefault) { 9107 return r1.isDefault ? -1 : 1; 9108 } 9109 v1 = r1.match; 9110 v2 = r2.match; 9111 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9112 if (v1 != v2) { 9113 return (v1 > v2) ? -1 : 1; 9114 } 9115 if (r1.system != r2.system) { 9116 return r1.system ? -1 : 1; 9117 } 9118 return 0; 9119 } 9120 }; 9121 9122 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9123 new Comparator<ProviderInfo>() { 9124 public int compare(ProviderInfo p1, ProviderInfo p2) { 9125 final int v1 = p1.initOrder; 9126 final int v2 = p2.initOrder; 9127 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9128 } 9129 }; 9130 9131 final void sendPackageBroadcast(final String action, final String pkg, 9132 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9133 final int[] userIds) { 9134 mHandler.post(new Runnable() { 9135 @Override 9136 public void run() { 9137 try { 9138 final IActivityManager am = ActivityManagerNative.getDefault(); 9139 if (am == null) return; 9140 final int[] resolvedUserIds; 9141 if (userIds == null) { 9142 resolvedUserIds = am.getRunningUserIds(); 9143 } else { 9144 resolvedUserIds = userIds; 9145 } 9146 for (int id : resolvedUserIds) { 9147 final Intent intent = new Intent(action, 9148 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9149 if (extras != null) { 9150 intent.putExtras(extras); 9151 } 9152 if (targetPkg != null) { 9153 intent.setPackage(targetPkg); 9154 } 9155 // Modify the UID when posting to other users 9156 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9157 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9158 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9159 intent.putExtra(Intent.EXTRA_UID, uid); 9160 } 9161 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9162 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9163 if (DEBUG_BROADCASTS) { 9164 RuntimeException here = new RuntimeException("here"); 9165 here.fillInStackTrace(); 9166 Slog.d(TAG, "Sending to user " + id + ": " 9167 + intent.toShortString(false, true, false, false) 9168 + " " + intent.getExtras(), here); 9169 } 9170 am.broadcastIntent(null, intent, null, finishedReceiver, 9171 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9172 null, finishedReceiver != null, false, id); 9173 } 9174 } catch (RemoteException ex) { 9175 } 9176 } 9177 }); 9178 } 9179 9180 /** 9181 * Check if the external storage media is available. This is true if there 9182 * is a mounted external storage medium or if the external storage is 9183 * emulated. 9184 */ 9185 private boolean isExternalMediaAvailable() { 9186 return mMediaMounted || Environment.isExternalStorageEmulated(); 9187 } 9188 9189 @Override 9190 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9191 // writer 9192 synchronized (mPackages) { 9193 if (!isExternalMediaAvailable()) { 9194 // If the external storage is no longer mounted at this point, 9195 // the caller may not have been able to delete all of this 9196 // packages files and can not delete any more. Bail. 9197 return null; 9198 } 9199 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9200 if (lastPackage != null) { 9201 pkgs.remove(lastPackage); 9202 } 9203 if (pkgs.size() > 0) { 9204 return pkgs.get(0); 9205 } 9206 } 9207 return null; 9208 } 9209 9210 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9211 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9212 userId, andCode ? 1 : 0, packageName); 9213 if (mSystemReady) { 9214 msg.sendToTarget(); 9215 } else { 9216 if (mPostSystemReadyMessages == null) { 9217 mPostSystemReadyMessages = new ArrayList<>(); 9218 } 9219 mPostSystemReadyMessages.add(msg); 9220 } 9221 } 9222 9223 void startCleaningPackages() { 9224 // reader 9225 synchronized (mPackages) { 9226 if (!isExternalMediaAvailable()) { 9227 return; 9228 } 9229 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9230 return; 9231 } 9232 } 9233 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9234 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9235 IActivityManager am = ActivityManagerNative.getDefault(); 9236 if (am != null) { 9237 try { 9238 am.startService(null, intent, null, mContext.getOpPackageName(), 9239 UserHandle.USER_OWNER); 9240 } catch (RemoteException e) { 9241 } 9242 } 9243 } 9244 9245 @Override 9246 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9247 int installFlags, String installerPackageName, VerificationParams verificationParams, 9248 String packageAbiOverride) { 9249 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9250 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9251 } 9252 9253 @Override 9254 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9255 int installFlags, String installerPackageName, VerificationParams verificationParams, 9256 String packageAbiOverride, int userId) { 9257 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9258 9259 final int callingUid = Binder.getCallingUid(); 9260 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9261 9262 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9263 try { 9264 if (observer != null) { 9265 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9266 } 9267 } catch (RemoteException re) { 9268 } 9269 return; 9270 } 9271 9272 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9273 installFlags |= PackageManager.INSTALL_FROM_ADB; 9274 9275 } else { 9276 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9277 // about installerPackageName. 9278 9279 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9280 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9281 } 9282 9283 UserHandle user; 9284 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9285 user = UserHandle.ALL; 9286 } else { 9287 user = new UserHandle(userId); 9288 } 9289 9290 // Only system components can circumvent runtime permissions when installing. 9291 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9292 && mContext.checkCallingOrSelfPermission(Manifest.permission 9293 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9294 throw new SecurityException("You need the " 9295 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9296 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9297 } 9298 9299 verificationParams.setInstallerUid(callingUid); 9300 9301 final File originFile = new File(originPath); 9302 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9303 9304 final Message msg = mHandler.obtainMessage(INIT_COPY); 9305 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9306 null, verificationParams, user, packageAbiOverride); 9307 mHandler.sendMessage(msg); 9308 } 9309 9310 void installStage(String packageName, File stagedDir, String stagedCid, 9311 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9312 String installerPackageName, int installerUid, UserHandle user) { 9313 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9314 params.referrerUri, installerUid, null); 9315 verifParams.setInstallerUid(installerUid); 9316 9317 final OriginInfo origin; 9318 if (stagedDir != null) { 9319 origin = OriginInfo.fromStagedFile(stagedDir); 9320 } else { 9321 origin = OriginInfo.fromStagedContainer(stagedCid); 9322 } 9323 9324 final Message msg = mHandler.obtainMessage(INIT_COPY); 9325 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9326 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9327 mHandler.sendMessage(msg); 9328 } 9329 9330 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9331 Bundle extras = new Bundle(1); 9332 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9333 9334 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9335 packageName, extras, null, null, new int[] {userId}); 9336 try { 9337 IActivityManager am = ActivityManagerNative.getDefault(); 9338 final boolean isSystem = 9339 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9340 if (isSystem && am.isUserRunning(userId, false)) { 9341 // The just-installed/enabled app is bundled on the system, so presumed 9342 // to be able to run automatically without needing an explicit launch. 9343 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9344 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9345 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9346 .setPackage(packageName); 9347 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9348 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9349 } 9350 } catch (RemoteException e) { 9351 // shouldn't happen 9352 Slog.w(TAG, "Unable to bootstrap installed package", e); 9353 } 9354 } 9355 9356 @Override 9357 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9358 int userId) { 9359 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9360 PackageSetting pkgSetting; 9361 final int uid = Binder.getCallingUid(); 9362 enforceCrossUserPermission(uid, userId, true, true, 9363 "setApplicationHiddenSetting for user " + userId); 9364 9365 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9366 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9367 return false; 9368 } 9369 9370 long callingId = Binder.clearCallingIdentity(); 9371 try { 9372 boolean sendAdded = false; 9373 boolean sendRemoved = false; 9374 // writer 9375 synchronized (mPackages) { 9376 pkgSetting = mSettings.mPackages.get(packageName); 9377 if (pkgSetting == null) { 9378 return false; 9379 } 9380 if (pkgSetting.getHidden(userId) != hidden) { 9381 pkgSetting.setHidden(hidden, userId); 9382 mSettings.writePackageRestrictionsLPr(userId); 9383 if (hidden) { 9384 sendRemoved = true; 9385 } else { 9386 sendAdded = true; 9387 } 9388 } 9389 } 9390 if (sendAdded) { 9391 sendPackageAddedForUser(packageName, pkgSetting, userId); 9392 return true; 9393 } 9394 if (sendRemoved) { 9395 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9396 "hiding pkg"); 9397 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9398 } 9399 } finally { 9400 Binder.restoreCallingIdentity(callingId); 9401 } 9402 return false; 9403 } 9404 9405 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9406 int userId) { 9407 final PackageRemovedInfo info = new PackageRemovedInfo(); 9408 info.removedPackage = packageName; 9409 info.removedUsers = new int[] {userId}; 9410 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9411 info.sendBroadcast(false, false, false); 9412 } 9413 9414 /** 9415 * Returns true if application is not found or there was an error. Otherwise it returns 9416 * the hidden state of the package for the given user. 9417 */ 9418 @Override 9419 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9420 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9421 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9422 false, "getApplicationHidden for user " + userId); 9423 PackageSetting pkgSetting; 9424 long callingId = Binder.clearCallingIdentity(); 9425 try { 9426 // writer 9427 synchronized (mPackages) { 9428 pkgSetting = mSettings.mPackages.get(packageName); 9429 if (pkgSetting == null) { 9430 return true; 9431 } 9432 return pkgSetting.getHidden(userId); 9433 } 9434 } finally { 9435 Binder.restoreCallingIdentity(callingId); 9436 } 9437 } 9438 9439 /** 9440 * @hide 9441 */ 9442 @Override 9443 public int installExistingPackageAsUser(String packageName, int userId) { 9444 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9445 null); 9446 PackageSetting pkgSetting; 9447 final int uid = Binder.getCallingUid(); 9448 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9449 + userId); 9450 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9451 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9452 } 9453 9454 long callingId = Binder.clearCallingIdentity(); 9455 try { 9456 boolean sendAdded = false; 9457 9458 // writer 9459 synchronized (mPackages) { 9460 pkgSetting = mSettings.mPackages.get(packageName); 9461 if (pkgSetting == null) { 9462 return PackageManager.INSTALL_FAILED_INVALID_URI; 9463 } 9464 if (!pkgSetting.getInstalled(userId)) { 9465 pkgSetting.setInstalled(true, userId); 9466 pkgSetting.setHidden(false, userId); 9467 mSettings.writePackageRestrictionsLPr(userId); 9468 sendAdded = true; 9469 } 9470 } 9471 9472 if (sendAdded) { 9473 sendPackageAddedForUser(packageName, pkgSetting, userId); 9474 } 9475 } finally { 9476 Binder.restoreCallingIdentity(callingId); 9477 } 9478 9479 return PackageManager.INSTALL_SUCCEEDED; 9480 } 9481 9482 boolean isUserRestricted(int userId, String restrictionKey) { 9483 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9484 if (restrictions.getBoolean(restrictionKey, false)) { 9485 Log.w(TAG, "User is restricted: " + restrictionKey); 9486 return true; 9487 } 9488 return false; 9489 } 9490 9491 @Override 9492 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9493 mContext.enforceCallingOrSelfPermission( 9494 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9495 "Only package verification agents can verify applications"); 9496 9497 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9498 final PackageVerificationResponse response = new PackageVerificationResponse( 9499 verificationCode, Binder.getCallingUid()); 9500 msg.arg1 = id; 9501 msg.obj = response; 9502 mHandler.sendMessage(msg); 9503 } 9504 9505 @Override 9506 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9507 long millisecondsToDelay) { 9508 mContext.enforceCallingOrSelfPermission( 9509 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9510 "Only package verification agents can extend verification timeouts"); 9511 9512 final PackageVerificationState state = mPendingVerification.get(id); 9513 final PackageVerificationResponse response = new PackageVerificationResponse( 9514 verificationCodeAtTimeout, Binder.getCallingUid()); 9515 9516 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9517 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9518 } 9519 if (millisecondsToDelay < 0) { 9520 millisecondsToDelay = 0; 9521 } 9522 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9523 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9524 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9525 } 9526 9527 if ((state != null) && !state.timeoutExtended()) { 9528 state.extendTimeout(); 9529 9530 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9531 msg.arg1 = id; 9532 msg.obj = response; 9533 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9534 } 9535 } 9536 9537 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9538 int verificationCode, UserHandle user) { 9539 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9540 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9541 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9542 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9543 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9544 9545 mContext.sendBroadcastAsUser(intent, user, 9546 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9547 } 9548 9549 private ComponentName matchComponentForVerifier(String packageName, 9550 List<ResolveInfo> receivers) { 9551 ActivityInfo targetReceiver = null; 9552 9553 final int NR = receivers.size(); 9554 for (int i = 0; i < NR; i++) { 9555 final ResolveInfo info = receivers.get(i); 9556 if (info.activityInfo == null) { 9557 continue; 9558 } 9559 9560 if (packageName.equals(info.activityInfo.packageName)) { 9561 targetReceiver = info.activityInfo; 9562 break; 9563 } 9564 } 9565 9566 if (targetReceiver == null) { 9567 return null; 9568 } 9569 9570 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9571 } 9572 9573 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9574 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9575 if (pkgInfo.verifiers.length == 0) { 9576 return null; 9577 } 9578 9579 final int N = pkgInfo.verifiers.length; 9580 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9581 for (int i = 0; i < N; i++) { 9582 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9583 9584 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9585 receivers); 9586 if (comp == null) { 9587 continue; 9588 } 9589 9590 final int verifierUid = getUidForVerifier(verifierInfo); 9591 if (verifierUid == -1) { 9592 continue; 9593 } 9594 9595 if (DEBUG_VERIFY) { 9596 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9597 + " with the correct signature"); 9598 } 9599 sufficientVerifiers.add(comp); 9600 verificationState.addSufficientVerifier(verifierUid); 9601 } 9602 9603 return sufficientVerifiers; 9604 } 9605 9606 private int getUidForVerifier(VerifierInfo verifierInfo) { 9607 synchronized (mPackages) { 9608 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9609 if (pkg == null) { 9610 return -1; 9611 } else if (pkg.mSignatures.length != 1) { 9612 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9613 + " has more than one signature; ignoring"); 9614 return -1; 9615 } 9616 9617 /* 9618 * If the public key of the package's signature does not match 9619 * our expected public key, then this is a different package and 9620 * we should skip. 9621 */ 9622 9623 final byte[] expectedPublicKey; 9624 try { 9625 final Signature verifierSig = pkg.mSignatures[0]; 9626 final PublicKey publicKey = verifierSig.getPublicKey(); 9627 expectedPublicKey = publicKey.getEncoded(); 9628 } catch (CertificateException e) { 9629 return -1; 9630 } 9631 9632 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9633 9634 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9635 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9636 + " does not have the expected public key; ignoring"); 9637 return -1; 9638 } 9639 9640 return pkg.applicationInfo.uid; 9641 } 9642 } 9643 9644 @Override 9645 public void finishPackageInstall(int token) { 9646 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9647 9648 if (DEBUG_INSTALL) { 9649 Slog.v(TAG, "BM finishing package install for " + token); 9650 } 9651 9652 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9653 mHandler.sendMessage(msg); 9654 } 9655 9656 /** 9657 * Get the verification agent timeout. 9658 * 9659 * @return verification timeout in milliseconds 9660 */ 9661 private long getVerificationTimeout() { 9662 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9663 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9664 DEFAULT_VERIFICATION_TIMEOUT); 9665 } 9666 9667 /** 9668 * Get the default verification agent response code. 9669 * 9670 * @return default verification response code 9671 */ 9672 private int getDefaultVerificationResponse() { 9673 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9674 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9675 DEFAULT_VERIFICATION_RESPONSE); 9676 } 9677 9678 /** 9679 * Check whether or not package verification has been enabled. 9680 * 9681 * @return true if verification should be performed 9682 */ 9683 private boolean isVerificationEnabled(int userId, int installFlags) { 9684 if (!DEFAULT_VERIFY_ENABLE) { 9685 return false; 9686 } 9687 9688 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9689 9690 // Check if installing from ADB 9691 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9692 // Do not run verification in a test harness environment 9693 if (ActivityManager.isRunningInTestHarness()) { 9694 return false; 9695 } 9696 if (ensureVerifyAppsEnabled) { 9697 return true; 9698 } 9699 // Check if the developer does not want package verification for ADB installs 9700 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9701 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9702 return false; 9703 } 9704 } 9705 9706 if (ensureVerifyAppsEnabled) { 9707 return true; 9708 } 9709 9710 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9711 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9712 } 9713 9714 @Override 9715 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9716 throws RemoteException { 9717 mContext.enforceCallingOrSelfPermission( 9718 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9719 "Only intentfilter verification agents can verify applications"); 9720 9721 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9722 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9723 Binder.getCallingUid(), verificationCode, failedDomains); 9724 msg.arg1 = id; 9725 msg.obj = response; 9726 mHandler.sendMessage(msg); 9727 } 9728 9729 @Override 9730 public int getIntentVerificationStatus(String packageName, int userId) { 9731 synchronized (mPackages) { 9732 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9733 } 9734 } 9735 9736 @Override 9737 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9738 mContext.enforceCallingOrSelfPermission( 9739 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9740 9741 boolean result = false; 9742 synchronized (mPackages) { 9743 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9744 } 9745 if (result) { 9746 scheduleWritePackageRestrictionsLocked(userId); 9747 } 9748 return result; 9749 } 9750 9751 @Override 9752 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9753 synchronized (mPackages) { 9754 return mSettings.getIntentFilterVerificationsLPr(packageName); 9755 } 9756 } 9757 9758 @Override 9759 public List<IntentFilter> getAllIntentFilters(String packageName) { 9760 if (TextUtils.isEmpty(packageName)) { 9761 return Collections.<IntentFilter>emptyList(); 9762 } 9763 synchronized (mPackages) { 9764 PackageParser.Package pkg = mPackages.get(packageName); 9765 if (pkg == null || pkg.activities == null) { 9766 return Collections.<IntentFilter>emptyList(); 9767 } 9768 final int count = pkg.activities.size(); 9769 ArrayList<IntentFilter> result = new ArrayList<>(); 9770 for (int n=0; n<count; n++) { 9771 PackageParser.Activity activity = pkg.activities.get(n); 9772 if (activity.intents != null || activity.intents.size() > 0) { 9773 result.addAll(activity.intents); 9774 } 9775 } 9776 return result; 9777 } 9778 } 9779 9780 @Override 9781 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9782 mContext.enforceCallingOrSelfPermission( 9783 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9784 9785 synchronized (mPackages) { 9786 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9787 if (packageName != null) { 9788 result |= updateIntentVerificationStatus(packageName, 9789 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9790 UserHandle.myUserId()); 9791 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9792 packageName, userId); 9793 } 9794 return result; 9795 } 9796 } 9797 9798 @Override 9799 public String getDefaultBrowserPackageName(int userId) { 9800 synchronized (mPackages) { 9801 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9802 } 9803 } 9804 9805 /** 9806 * Get the "allow unknown sources" setting. 9807 * 9808 * @return the current "allow unknown sources" setting 9809 */ 9810 private int getUnknownSourcesSettings() { 9811 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9812 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9813 -1); 9814 } 9815 9816 @Override 9817 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9818 final int uid = Binder.getCallingUid(); 9819 // writer 9820 synchronized (mPackages) { 9821 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9822 if (targetPackageSetting == null) { 9823 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9824 } 9825 9826 PackageSetting installerPackageSetting; 9827 if (installerPackageName != null) { 9828 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9829 if (installerPackageSetting == null) { 9830 throw new IllegalArgumentException("Unknown installer package: " 9831 + installerPackageName); 9832 } 9833 } else { 9834 installerPackageSetting = null; 9835 } 9836 9837 Signature[] callerSignature; 9838 Object obj = mSettings.getUserIdLPr(uid); 9839 if (obj != null) { 9840 if (obj instanceof SharedUserSetting) { 9841 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9842 } else if (obj instanceof PackageSetting) { 9843 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9844 } else { 9845 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9846 } 9847 } else { 9848 throw new SecurityException("Unknown calling uid " + uid); 9849 } 9850 9851 // Verify: can't set installerPackageName to a package that is 9852 // not signed with the same cert as the caller. 9853 if (installerPackageSetting != null) { 9854 if (compareSignatures(callerSignature, 9855 installerPackageSetting.signatures.mSignatures) 9856 != PackageManager.SIGNATURE_MATCH) { 9857 throw new SecurityException( 9858 "Caller does not have same cert as new installer package " 9859 + installerPackageName); 9860 } 9861 } 9862 9863 // Verify: if target already has an installer package, it must 9864 // be signed with the same cert as the caller. 9865 if (targetPackageSetting.installerPackageName != null) { 9866 PackageSetting setting = mSettings.mPackages.get( 9867 targetPackageSetting.installerPackageName); 9868 // If the currently set package isn't valid, then it's always 9869 // okay to change it. 9870 if (setting != null) { 9871 if (compareSignatures(callerSignature, 9872 setting.signatures.mSignatures) 9873 != PackageManager.SIGNATURE_MATCH) { 9874 throw new SecurityException( 9875 "Caller does not have same cert as old installer package " 9876 + targetPackageSetting.installerPackageName); 9877 } 9878 } 9879 } 9880 9881 // Okay! 9882 targetPackageSetting.installerPackageName = installerPackageName; 9883 scheduleWriteSettingsLocked(); 9884 } 9885 } 9886 9887 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9888 // Queue up an async operation since the package installation may take a little while. 9889 mHandler.post(new Runnable() { 9890 public void run() { 9891 mHandler.removeCallbacks(this); 9892 // Result object to be returned 9893 PackageInstalledInfo res = new PackageInstalledInfo(); 9894 res.returnCode = currentStatus; 9895 res.uid = -1; 9896 res.pkg = null; 9897 res.removedInfo = new PackageRemovedInfo(); 9898 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9899 args.doPreInstall(res.returnCode); 9900 synchronized (mInstallLock) { 9901 installPackageLI(args, res); 9902 } 9903 args.doPostInstall(res.returnCode, res.uid); 9904 } 9905 9906 // A restore should be performed at this point if (a) the install 9907 // succeeded, (b) the operation is not an update, and (c) the new 9908 // package has not opted out of backup participation. 9909 final boolean update = res.removedInfo.removedPackage != null; 9910 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9911 boolean doRestore = !update 9912 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9913 9914 // Set up the post-install work request bookkeeping. This will be used 9915 // and cleaned up by the post-install event handling regardless of whether 9916 // there's a restore pass performed. Token values are >= 1. 9917 int token; 9918 if (mNextInstallToken < 0) mNextInstallToken = 1; 9919 token = mNextInstallToken++; 9920 9921 PostInstallData data = new PostInstallData(args, res); 9922 mRunningInstalls.put(token, data); 9923 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9924 9925 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9926 // Pass responsibility to the Backup Manager. It will perform a 9927 // restore if appropriate, then pass responsibility back to the 9928 // Package Manager to run the post-install observer callbacks 9929 // and broadcasts. 9930 IBackupManager bm = IBackupManager.Stub.asInterface( 9931 ServiceManager.getService(Context.BACKUP_SERVICE)); 9932 if (bm != null) { 9933 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9934 + " to BM for possible restore"); 9935 try { 9936 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9937 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9938 } else { 9939 doRestore = false; 9940 } 9941 } catch (RemoteException e) { 9942 // can't happen; the backup manager is local 9943 } catch (Exception e) { 9944 Slog.e(TAG, "Exception trying to enqueue restore", e); 9945 doRestore = false; 9946 } 9947 } else { 9948 Slog.e(TAG, "Backup Manager not found!"); 9949 doRestore = false; 9950 } 9951 } 9952 9953 if (!doRestore) { 9954 // No restore possible, or the Backup Manager was mysteriously not 9955 // available -- just fire the post-install work request directly. 9956 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9957 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9958 mHandler.sendMessage(msg); 9959 } 9960 } 9961 }); 9962 } 9963 9964 private abstract class HandlerParams { 9965 private static final int MAX_RETRIES = 4; 9966 9967 /** 9968 * Number of times startCopy() has been attempted and had a non-fatal 9969 * error. 9970 */ 9971 private int mRetries = 0; 9972 9973 /** User handle for the user requesting the information or installation. */ 9974 private final UserHandle mUser; 9975 9976 HandlerParams(UserHandle user) { 9977 mUser = user; 9978 } 9979 9980 UserHandle getUser() { 9981 return mUser; 9982 } 9983 9984 final boolean startCopy() { 9985 boolean res; 9986 try { 9987 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9988 9989 if (++mRetries > MAX_RETRIES) { 9990 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9991 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9992 handleServiceError(); 9993 return false; 9994 } else { 9995 handleStartCopy(); 9996 res = true; 9997 } 9998 } catch (RemoteException e) { 9999 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10000 mHandler.sendEmptyMessage(MCS_RECONNECT); 10001 res = false; 10002 } 10003 handleReturnCode(); 10004 return res; 10005 } 10006 10007 final void serviceError() { 10008 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10009 handleServiceError(); 10010 handleReturnCode(); 10011 } 10012 10013 abstract void handleStartCopy() throws RemoteException; 10014 abstract void handleServiceError(); 10015 abstract void handleReturnCode(); 10016 } 10017 10018 class MeasureParams extends HandlerParams { 10019 private final PackageStats mStats; 10020 private boolean mSuccess; 10021 10022 private final IPackageStatsObserver mObserver; 10023 10024 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10025 super(new UserHandle(stats.userHandle)); 10026 mObserver = observer; 10027 mStats = stats; 10028 } 10029 10030 @Override 10031 public String toString() { 10032 return "MeasureParams{" 10033 + Integer.toHexString(System.identityHashCode(this)) 10034 + " " + mStats.packageName + "}"; 10035 } 10036 10037 @Override 10038 void handleStartCopy() throws RemoteException { 10039 synchronized (mInstallLock) { 10040 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10041 } 10042 10043 if (mSuccess) { 10044 final boolean mounted; 10045 if (Environment.isExternalStorageEmulated()) { 10046 mounted = true; 10047 } else { 10048 final String status = Environment.getExternalStorageState(); 10049 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10050 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10051 } 10052 10053 if (mounted) { 10054 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10055 10056 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10057 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10058 10059 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10060 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10061 10062 // Always subtract cache size, since it's a subdirectory 10063 mStats.externalDataSize -= mStats.externalCacheSize; 10064 10065 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10066 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10067 10068 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10069 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10070 } 10071 } 10072 } 10073 10074 @Override 10075 void handleReturnCode() { 10076 if (mObserver != null) { 10077 try { 10078 mObserver.onGetStatsCompleted(mStats, mSuccess); 10079 } catch (RemoteException e) { 10080 Slog.i(TAG, "Observer no longer exists."); 10081 } 10082 } 10083 } 10084 10085 @Override 10086 void handleServiceError() { 10087 Slog.e(TAG, "Could not measure application " + mStats.packageName 10088 + " external storage"); 10089 } 10090 } 10091 10092 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10093 throws RemoteException { 10094 long result = 0; 10095 for (File path : paths) { 10096 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10097 } 10098 return result; 10099 } 10100 10101 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10102 for (File path : paths) { 10103 try { 10104 mcs.clearDirectory(path.getAbsolutePath()); 10105 } catch (RemoteException e) { 10106 } 10107 } 10108 } 10109 10110 static class OriginInfo { 10111 /** 10112 * Location where install is coming from, before it has been 10113 * copied/renamed into place. This could be a single monolithic APK 10114 * file, or a cluster directory. This location may be untrusted. 10115 */ 10116 final File file; 10117 final String cid; 10118 10119 /** 10120 * Flag indicating that {@link #file} or {@link #cid} has already been 10121 * staged, meaning downstream users don't need to defensively copy the 10122 * contents. 10123 */ 10124 final boolean staged; 10125 10126 /** 10127 * Flag indicating that {@link #file} or {@link #cid} is an already 10128 * installed app that is being moved. 10129 */ 10130 final boolean existing; 10131 10132 final String resolvedPath; 10133 final File resolvedFile; 10134 10135 static OriginInfo fromNothing() { 10136 return new OriginInfo(null, null, false, false); 10137 } 10138 10139 static OriginInfo fromUntrustedFile(File file) { 10140 return new OriginInfo(file, null, false, false); 10141 } 10142 10143 static OriginInfo fromExistingFile(File file) { 10144 return new OriginInfo(file, null, false, true); 10145 } 10146 10147 static OriginInfo fromStagedFile(File file) { 10148 return new OriginInfo(file, null, true, false); 10149 } 10150 10151 static OriginInfo fromStagedContainer(String cid) { 10152 return new OriginInfo(null, cid, true, false); 10153 } 10154 10155 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10156 this.file = file; 10157 this.cid = cid; 10158 this.staged = staged; 10159 this.existing = existing; 10160 10161 if (cid != null) { 10162 resolvedPath = PackageHelper.getSdDir(cid); 10163 resolvedFile = new File(resolvedPath); 10164 } else if (file != null) { 10165 resolvedPath = file.getAbsolutePath(); 10166 resolvedFile = file; 10167 } else { 10168 resolvedPath = null; 10169 resolvedFile = null; 10170 } 10171 } 10172 } 10173 10174 class MoveInfo { 10175 final int moveId; 10176 final String fromUuid; 10177 final String toUuid; 10178 final String packageName; 10179 final String dataAppName; 10180 final int appId; 10181 final String seinfo; 10182 10183 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10184 String dataAppName, int appId, String seinfo) { 10185 this.moveId = moveId; 10186 this.fromUuid = fromUuid; 10187 this.toUuid = toUuid; 10188 this.packageName = packageName; 10189 this.dataAppName = dataAppName; 10190 this.appId = appId; 10191 this.seinfo = seinfo; 10192 } 10193 } 10194 10195 class InstallParams extends HandlerParams { 10196 final OriginInfo origin; 10197 final MoveInfo move; 10198 final IPackageInstallObserver2 observer; 10199 int installFlags; 10200 final String installerPackageName; 10201 final String volumeUuid; 10202 final VerificationParams verificationParams; 10203 private InstallArgs mArgs; 10204 private int mRet; 10205 final String packageAbiOverride; 10206 10207 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10208 int installFlags, String installerPackageName, String volumeUuid, 10209 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10210 super(user); 10211 this.origin = origin; 10212 this.move = move; 10213 this.observer = observer; 10214 this.installFlags = installFlags; 10215 this.installerPackageName = installerPackageName; 10216 this.volumeUuid = volumeUuid; 10217 this.verificationParams = verificationParams; 10218 this.packageAbiOverride = packageAbiOverride; 10219 } 10220 10221 @Override 10222 public String toString() { 10223 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10224 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10225 } 10226 10227 public ManifestDigest getManifestDigest() { 10228 if (verificationParams == null) { 10229 return null; 10230 } 10231 return verificationParams.getManifestDigest(); 10232 } 10233 10234 private int installLocationPolicy(PackageInfoLite pkgLite) { 10235 String packageName = pkgLite.packageName; 10236 int installLocation = pkgLite.installLocation; 10237 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10238 // reader 10239 synchronized (mPackages) { 10240 PackageParser.Package pkg = mPackages.get(packageName); 10241 if (pkg != null) { 10242 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10243 // Check for downgrading. 10244 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10245 try { 10246 checkDowngrade(pkg, pkgLite); 10247 } catch (PackageManagerException e) { 10248 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10249 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10250 } 10251 } 10252 // Check for updated system application. 10253 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10254 if (onSd) { 10255 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10256 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10257 } 10258 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10259 } else { 10260 if (onSd) { 10261 // Install flag overrides everything. 10262 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10263 } 10264 // If current upgrade specifies particular preference 10265 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10266 // Application explicitly specified internal. 10267 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10268 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10269 // App explictly prefers external. Let policy decide 10270 } else { 10271 // Prefer previous location 10272 if (isExternal(pkg)) { 10273 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10274 } 10275 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10276 } 10277 } 10278 } else { 10279 // Invalid install. Return error code 10280 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10281 } 10282 } 10283 } 10284 // All the special cases have been taken care of. 10285 // Return result based on recommended install location. 10286 if (onSd) { 10287 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10288 } 10289 return pkgLite.recommendedInstallLocation; 10290 } 10291 10292 /* 10293 * Invoke remote method to get package information and install 10294 * location values. Override install location based on default 10295 * policy if needed and then create install arguments based 10296 * on the install location. 10297 */ 10298 public void handleStartCopy() throws RemoteException { 10299 int ret = PackageManager.INSTALL_SUCCEEDED; 10300 10301 // If we're already staged, we've firmly committed to an install location 10302 if (origin.staged) { 10303 if (origin.file != null) { 10304 installFlags |= PackageManager.INSTALL_INTERNAL; 10305 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10306 } else if (origin.cid != null) { 10307 installFlags |= PackageManager.INSTALL_EXTERNAL; 10308 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10309 } else { 10310 throw new IllegalStateException("Invalid stage location"); 10311 } 10312 } 10313 10314 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10315 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10316 10317 PackageInfoLite pkgLite = null; 10318 10319 if (onInt && onSd) { 10320 // Check if both bits are set. 10321 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10322 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10323 } else { 10324 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10325 packageAbiOverride); 10326 10327 /* 10328 * If we have too little free space, try to free cache 10329 * before giving up. 10330 */ 10331 if (!origin.staged && pkgLite.recommendedInstallLocation 10332 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10333 // TODO: focus freeing disk space on the target device 10334 final StorageManager storage = StorageManager.from(mContext); 10335 final long lowThreshold = storage.getStorageLowBytes( 10336 Environment.getDataDirectory()); 10337 10338 final long sizeBytes = mContainerService.calculateInstalledSize( 10339 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10340 10341 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10342 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10343 installFlags, packageAbiOverride); 10344 } 10345 10346 /* 10347 * The cache free must have deleted the file we 10348 * downloaded to install. 10349 * 10350 * TODO: fix the "freeCache" call to not delete 10351 * the file we care about. 10352 */ 10353 if (pkgLite.recommendedInstallLocation 10354 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10355 pkgLite.recommendedInstallLocation 10356 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10357 } 10358 } 10359 } 10360 10361 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10362 int loc = pkgLite.recommendedInstallLocation; 10363 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10364 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10365 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10366 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10367 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10368 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10369 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10370 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10371 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10372 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10373 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10374 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10375 } else { 10376 // Override with defaults if needed. 10377 loc = installLocationPolicy(pkgLite); 10378 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10379 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10380 } else if (!onSd && !onInt) { 10381 // Override install location with flags 10382 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10383 // Set the flag to install on external media. 10384 installFlags |= PackageManager.INSTALL_EXTERNAL; 10385 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10386 } else { 10387 // Make sure the flag for installing on external 10388 // media is unset 10389 installFlags |= PackageManager.INSTALL_INTERNAL; 10390 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10391 } 10392 } 10393 } 10394 } 10395 10396 final InstallArgs args = createInstallArgs(this); 10397 mArgs = args; 10398 10399 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10400 /* 10401 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10402 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10403 */ 10404 int userIdentifier = getUser().getIdentifier(); 10405 if (userIdentifier == UserHandle.USER_ALL 10406 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10407 userIdentifier = UserHandle.USER_OWNER; 10408 } 10409 10410 /* 10411 * Determine if we have any installed package verifiers. If we 10412 * do, then we'll defer to them to verify the packages. 10413 */ 10414 final int requiredUid = mRequiredVerifierPackage == null ? -1 10415 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10416 if (!origin.existing && requiredUid != -1 10417 && isVerificationEnabled(userIdentifier, installFlags)) { 10418 final Intent verification = new Intent( 10419 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10420 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10421 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10422 PACKAGE_MIME_TYPE); 10423 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10424 10425 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10426 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10427 0 /* TODO: Which userId? */); 10428 10429 if (DEBUG_VERIFY) { 10430 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10431 + verification.toString() + " with " + pkgLite.verifiers.length 10432 + " optional verifiers"); 10433 } 10434 10435 final int verificationId = mPendingVerificationToken++; 10436 10437 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10438 10439 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10440 installerPackageName); 10441 10442 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10443 installFlags); 10444 10445 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10446 pkgLite.packageName); 10447 10448 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10449 pkgLite.versionCode); 10450 10451 if (verificationParams != null) { 10452 if (verificationParams.getVerificationURI() != null) { 10453 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10454 verificationParams.getVerificationURI()); 10455 } 10456 if (verificationParams.getOriginatingURI() != null) { 10457 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10458 verificationParams.getOriginatingURI()); 10459 } 10460 if (verificationParams.getReferrer() != null) { 10461 verification.putExtra(Intent.EXTRA_REFERRER, 10462 verificationParams.getReferrer()); 10463 } 10464 if (verificationParams.getOriginatingUid() >= 0) { 10465 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10466 verificationParams.getOriginatingUid()); 10467 } 10468 if (verificationParams.getInstallerUid() >= 0) { 10469 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10470 verificationParams.getInstallerUid()); 10471 } 10472 } 10473 10474 final PackageVerificationState verificationState = new PackageVerificationState( 10475 requiredUid, args); 10476 10477 mPendingVerification.append(verificationId, verificationState); 10478 10479 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10480 receivers, verificationState); 10481 10482 /* 10483 * If any sufficient verifiers were listed in the package 10484 * manifest, attempt to ask them. 10485 */ 10486 if (sufficientVerifiers != null) { 10487 final int N = sufficientVerifiers.size(); 10488 if (N == 0) { 10489 Slog.i(TAG, "Additional verifiers required, but none installed."); 10490 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10491 } else { 10492 for (int i = 0; i < N; i++) { 10493 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10494 10495 final Intent sufficientIntent = new Intent(verification); 10496 sufficientIntent.setComponent(verifierComponent); 10497 10498 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10499 } 10500 } 10501 } 10502 10503 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10504 mRequiredVerifierPackage, receivers); 10505 if (ret == PackageManager.INSTALL_SUCCEEDED 10506 && mRequiredVerifierPackage != null) { 10507 /* 10508 * Send the intent to the required verification agent, 10509 * but only start the verification timeout after the 10510 * target BroadcastReceivers have run. 10511 */ 10512 verification.setComponent(requiredVerifierComponent); 10513 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10514 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10515 new BroadcastReceiver() { 10516 @Override 10517 public void onReceive(Context context, Intent intent) { 10518 final Message msg = mHandler 10519 .obtainMessage(CHECK_PENDING_VERIFICATION); 10520 msg.arg1 = verificationId; 10521 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10522 } 10523 }, null, 0, null, null); 10524 10525 /* 10526 * We don't want the copy to proceed until verification 10527 * succeeds, so null out this field. 10528 */ 10529 mArgs = null; 10530 } 10531 } else { 10532 /* 10533 * No package verification is enabled, so immediately start 10534 * the remote call to initiate copy using temporary file. 10535 */ 10536 ret = args.copyApk(mContainerService, true); 10537 } 10538 } 10539 10540 mRet = ret; 10541 } 10542 10543 @Override 10544 void handleReturnCode() { 10545 // If mArgs is null, then MCS couldn't be reached. When it 10546 // reconnects, it will try again to install. At that point, this 10547 // will succeed. 10548 if (mArgs != null) { 10549 processPendingInstall(mArgs, mRet); 10550 } 10551 } 10552 10553 @Override 10554 void handleServiceError() { 10555 mArgs = createInstallArgs(this); 10556 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10557 } 10558 10559 public boolean isForwardLocked() { 10560 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10561 } 10562 } 10563 10564 /** 10565 * Used during creation of InstallArgs 10566 * 10567 * @param installFlags package installation flags 10568 * @return true if should be installed on external storage 10569 */ 10570 private static boolean installOnExternalAsec(int installFlags) { 10571 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10572 return false; 10573 } 10574 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10575 return true; 10576 } 10577 return false; 10578 } 10579 10580 /** 10581 * Used during creation of InstallArgs 10582 * 10583 * @param installFlags package installation flags 10584 * @return true if should be installed as forward locked 10585 */ 10586 private static boolean installForwardLocked(int installFlags) { 10587 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10588 } 10589 10590 private InstallArgs createInstallArgs(InstallParams params) { 10591 if (params.move != null) { 10592 return new MoveInstallArgs(params); 10593 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10594 return new AsecInstallArgs(params); 10595 } else { 10596 return new FileInstallArgs(params); 10597 } 10598 } 10599 10600 /** 10601 * Create args that describe an existing installed package. Typically used 10602 * when cleaning up old installs, or used as a move source. 10603 */ 10604 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10605 String resourcePath, String[] instructionSets) { 10606 final boolean isInAsec; 10607 if (installOnExternalAsec(installFlags)) { 10608 /* Apps on SD card are always in ASEC containers. */ 10609 isInAsec = true; 10610 } else if (installForwardLocked(installFlags) 10611 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10612 /* 10613 * Forward-locked apps are only in ASEC containers if they're the 10614 * new style 10615 */ 10616 isInAsec = true; 10617 } else { 10618 isInAsec = false; 10619 } 10620 10621 if (isInAsec) { 10622 return new AsecInstallArgs(codePath, instructionSets, 10623 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10624 } else { 10625 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10626 } 10627 } 10628 10629 static abstract class InstallArgs { 10630 /** @see InstallParams#origin */ 10631 final OriginInfo origin; 10632 /** @see InstallParams#move */ 10633 final MoveInfo move; 10634 10635 final IPackageInstallObserver2 observer; 10636 // Always refers to PackageManager flags only 10637 final int installFlags; 10638 final String installerPackageName; 10639 final String volumeUuid; 10640 final ManifestDigest manifestDigest; 10641 final UserHandle user; 10642 final String abiOverride; 10643 10644 // The list of instruction sets supported by this app. This is currently 10645 // only used during the rmdex() phase to clean up resources. We can get rid of this 10646 // if we move dex files under the common app path. 10647 /* nullable */ String[] instructionSets; 10648 10649 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10650 int installFlags, String installerPackageName, String volumeUuid, 10651 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10652 String abiOverride) { 10653 this.origin = origin; 10654 this.move = move; 10655 this.installFlags = installFlags; 10656 this.observer = observer; 10657 this.installerPackageName = installerPackageName; 10658 this.volumeUuid = volumeUuid; 10659 this.manifestDigest = manifestDigest; 10660 this.user = user; 10661 this.instructionSets = instructionSets; 10662 this.abiOverride = abiOverride; 10663 } 10664 10665 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10666 abstract int doPreInstall(int status); 10667 10668 /** 10669 * Rename package into final resting place. All paths on the given 10670 * scanned package should be updated to reflect the rename. 10671 */ 10672 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10673 abstract int doPostInstall(int status, int uid); 10674 10675 /** @see PackageSettingBase#codePathString */ 10676 abstract String getCodePath(); 10677 /** @see PackageSettingBase#resourcePathString */ 10678 abstract String getResourcePath(); 10679 10680 // Need installer lock especially for dex file removal. 10681 abstract void cleanUpResourcesLI(); 10682 abstract boolean doPostDeleteLI(boolean delete); 10683 10684 /** 10685 * Called before the source arguments are copied. This is used mostly 10686 * for MoveParams when it needs to read the source file to put it in the 10687 * destination. 10688 */ 10689 int doPreCopy() { 10690 return PackageManager.INSTALL_SUCCEEDED; 10691 } 10692 10693 /** 10694 * Called after the source arguments are copied. This is used mostly for 10695 * MoveParams when it needs to read the source file to put it in the 10696 * destination. 10697 * 10698 * @return 10699 */ 10700 int doPostCopy(int uid) { 10701 return PackageManager.INSTALL_SUCCEEDED; 10702 } 10703 10704 protected boolean isFwdLocked() { 10705 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10706 } 10707 10708 protected boolean isExternalAsec() { 10709 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10710 } 10711 10712 UserHandle getUser() { 10713 return user; 10714 } 10715 } 10716 10717 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10718 if (!allCodePaths.isEmpty()) { 10719 if (instructionSets == null) { 10720 throw new IllegalStateException("instructionSet == null"); 10721 } 10722 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10723 for (String codePath : allCodePaths) { 10724 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10725 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10726 if (retCode < 0) { 10727 Slog.w(TAG, "Couldn't remove dex file for package: " 10728 + " at location " + codePath + ", retcode=" + retCode); 10729 // we don't consider this to be a failure of the core package deletion 10730 } 10731 } 10732 } 10733 } 10734 } 10735 10736 /** 10737 * Logic to handle installation of non-ASEC applications, including copying 10738 * and renaming logic. 10739 */ 10740 class FileInstallArgs extends InstallArgs { 10741 private File codeFile; 10742 private File resourceFile; 10743 10744 // Example topology: 10745 // /data/app/com.example/base.apk 10746 // /data/app/com.example/split_foo.apk 10747 // /data/app/com.example/lib/arm/libfoo.so 10748 // /data/app/com.example/lib/arm64/libfoo.so 10749 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10750 10751 /** New install */ 10752 FileInstallArgs(InstallParams params) { 10753 super(params.origin, params.move, params.observer, params.installFlags, 10754 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10755 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10756 if (isFwdLocked()) { 10757 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10758 } 10759 } 10760 10761 /** Existing install */ 10762 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10763 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10764 null); 10765 this.codeFile = (codePath != null) ? new File(codePath) : null; 10766 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10767 } 10768 10769 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10770 if (origin.staged) { 10771 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10772 codeFile = origin.file; 10773 resourceFile = origin.file; 10774 return PackageManager.INSTALL_SUCCEEDED; 10775 } 10776 10777 try { 10778 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10779 codeFile = tempDir; 10780 resourceFile = tempDir; 10781 } catch (IOException e) { 10782 Slog.w(TAG, "Failed to create copy file: " + e); 10783 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10784 } 10785 10786 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10787 @Override 10788 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10789 if (!FileUtils.isValidExtFilename(name)) { 10790 throw new IllegalArgumentException("Invalid filename: " + name); 10791 } 10792 try { 10793 final File file = new File(codeFile, name); 10794 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10795 O_RDWR | O_CREAT, 0644); 10796 Os.chmod(file.getAbsolutePath(), 0644); 10797 return new ParcelFileDescriptor(fd); 10798 } catch (ErrnoException e) { 10799 throw new RemoteException("Failed to open: " + e.getMessage()); 10800 } 10801 } 10802 }; 10803 10804 int ret = PackageManager.INSTALL_SUCCEEDED; 10805 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10806 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10807 Slog.e(TAG, "Failed to copy package"); 10808 return ret; 10809 } 10810 10811 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10812 NativeLibraryHelper.Handle handle = null; 10813 try { 10814 handle = NativeLibraryHelper.Handle.create(codeFile); 10815 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10816 abiOverride); 10817 } catch (IOException e) { 10818 Slog.e(TAG, "Copying native libraries failed", e); 10819 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10820 } finally { 10821 IoUtils.closeQuietly(handle); 10822 } 10823 10824 return ret; 10825 } 10826 10827 int doPreInstall(int status) { 10828 if (status != PackageManager.INSTALL_SUCCEEDED) { 10829 cleanUp(); 10830 } 10831 return status; 10832 } 10833 10834 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10835 if (status != PackageManager.INSTALL_SUCCEEDED) { 10836 cleanUp(); 10837 return false; 10838 } 10839 10840 final File targetDir = codeFile.getParentFile(); 10841 final File beforeCodeFile = codeFile; 10842 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10843 10844 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10845 try { 10846 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10847 } catch (ErrnoException e) { 10848 Slog.w(TAG, "Failed to rename", e); 10849 return false; 10850 } 10851 10852 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10853 Slog.w(TAG, "Failed to restorecon"); 10854 return false; 10855 } 10856 10857 // Reflect the rename internally 10858 codeFile = afterCodeFile; 10859 resourceFile = afterCodeFile; 10860 10861 // Reflect the rename in scanned details 10862 pkg.codePath = afterCodeFile.getAbsolutePath(); 10863 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10864 pkg.baseCodePath); 10865 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10866 pkg.splitCodePaths); 10867 10868 // Reflect the rename in app info 10869 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10870 pkg.applicationInfo.setCodePath(pkg.codePath); 10871 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10872 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10873 pkg.applicationInfo.setResourcePath(pkg.codePath); 10874 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10875 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10876 10877 return true; 10878 } 10879 10880 int doPostInstall(int status, int uid) { 10881 if (status != PackageManager.INSTALL_SUCCEEDED) { 10882 cleanUp(); 10883 } 10884 return status; 10885 } 10886 10887 @Override 10888 String getCodePath() { 10889 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10890 } 10891 10892 @Override 10893 String getResourcePath() { 10894 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10895 } 10896 10897 private boolean cleanUp() { 10898 if (codeFile == null || !codeFile.exists()) { 10899 return false; 10900 } 10901 10902 if (codeFile.isDirectory()) { 10903 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10904 } else { 10905 codeFile.delete(); 10906 } 10907 10908 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10909 resourceFile.delete(); 10910 } 10911 10912 return true; 10913 } 10914 10915 void cleanUpResourcesLI() { 10916 // Try enumerating all code paths before deleting 10917 List<String> allCodePaths = Collections.EMPTY_LIST; 10918 if (codeFile != null && codeFile.exists()) { 10919 try { 10920 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10921 allCodePaths = pkg.getAllCodePaths(); 10922 } catch (PackageParserException e) { 10923 // Ignored; we tried our best 10924 } 10925 } 10926 10927 cleanUp(); 10928 removeDexFiles(allCodePaths, instructionSets); 10929 } 10930 10931 boolean doPostDeleteLI(boolean delete) { 10932 // XXX err, shouldn't we respect the delete flag? 10933 cleanUpResourcesLI(); 10934 return true; 10935 } 10936 } 10937 10938 private boolean isAsecExternal(String cid) { 10939 final String asecPath = PackageHelper.getSdFilesystem(cid); 10940 return !asecPath.startsWith(mAsecInternalPath); 10941 } 10942 10943 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10944 PackageManagerException { 10945 if (copyRet < 0) { 10946 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10947 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10948 throw new PackageManagerException(copyRet, message); 10949 } 10950 } 10951 } 10952 10953 /** 10954 * Extract the MountService "container ID" from the full code path of an 10955 * .apk. 10956 */ 10957 static String cidFromCodePath(String fullCodePath) { 10958 int eidx = fullCodePath.lastIndexOf("/"); 10959 String subStr1 = fullCodePath.substring(0, eidx); 10960 int sidx = subStr1.lastIndexOf("/"); 10961 return subStr1.substring(sidx+1, eidx); 10962 } 10963 10964 /** 10965 * Logic to handle installation of ASEC applications, including copying and 10966 * renaming logic. 10967 */ 10968 class AsecInstallArgs extends InstallArgs { 10969 static final String RES_FILE_NAME = "pkg.apk"; 10970 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10971 10972 String cid; 10973 String packagePath; 10974 String resourcePath; 10975 10976 /** New install */ 10977 AsecInstallArgs(InstallParams params) { 10978 super(params.origin, params.move, params.observer, params.installFlags, 10979 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10980 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10981 } 10982 10983 /** Existing install */ 10984 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10985 boolean isExternal, boolean isForwardLocked) { 10986 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10987 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10988 instructionSets, null); 10989 // Hackily pretend we're still looking at a full code path 10990 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10991 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10992 } 10993 10994 // Extract cid from fullCodePath 10995 int eidx = fullCodePath.lastIndexOf("/"); 10996 String subStr1 = fullCodePath.substring(0, eidx); 10997 int sidx = subStr1.lastIndexOf("/"); 10998 cid = subStr1.substring(sidx+1, eidx); 10999 setMountPath(subStr1); 11000 } 11001 11002 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11003 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11004 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11005 instructionSets, null); 11006 this.cid = cid; 11007 setMountPath(PackageHelper.getSdDir(cid)); 11008 } 11009 11010 void createCopyFile() { 11011 cid = mInstallerService.allocateExternalStageCidLegacy(); 11012 } 11013 11014 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11015 if (origin.staged) { 11016 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11017 cid = origin.cid; 11018 setMountPath(PackageHelper.getSdDir(cid)); 11019 return PackageManager.INSTALL_SUCCEEDED; 11020 } 11021 11022 if (temp) { 11023 createCopyFile(); 11024 } else { 11025 /* 11026 * Pre-emptively destroy the container since it's destroyed if 11027 * copying fails due to it existing anyway. 11028 */ 11029 PackageHelper.destroySdDir(cid); 11030 } 11031 11032 final String newMountPath = imcs.copyPackageToContainer( 11033 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11034 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11035 11036 if (newMountPath != null) { 11037 setMountPath(newMountPath); 11038 return PackageManager.INSTALL_SUCCEEDED; 11039 } else { 11040 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11041 } 11042 } 11043 11044 @Override 11045 String getCodePath() { 11046 return packagePath; 11047 } 11048 11049 @Override 11050 String getResourcePath() { 11051 return resourcePath; 11052 } 11053 11054 int doPreInstall(int status) { 11055 if (status != PackageManager.INSTALL_SUCCEEDED) { 11056 // Destroy container 11057 PackageHelper.destroySdDir(cid); 11058 } else { 11059 boolean mounted = PackageHelper.isContainerMounted(cid); 11060 if (!mounted) { 11061 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11062 Process.SYSTEM_UID); 11063 if (newMountPath != null) { 11064 setMountPath(newMountPath); 11065 } else { 11066 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11067 } 11068 } 11069 } 11070 return status; 11071 } 11072 11073 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11074 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11075 String newMountPath = null; 11076 if (PackageHelper.isContainerMounted(cid)) { 11077 // Unmount the container 11078 if (!PackageHelper.unMountSdDir(cid)) { 11079 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11080 return false; 11081 } 11082 } 11083 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11084 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11085 " which might be stale. Will try to clean up."); 11086 // Clean up the stale container and proceed to recreate. 11087 if (!PackageHelper.destroySdDir(newCacheId)) { 11088 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11089 return false; 11090 } 11091 // Successfully cleaned up stale container. Try to rename again. 11092 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11093 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11094 + " inspite of cleaning it up."); 11095 return false; 11096 } 11097 } 11098 if (!PackageHelper.isContainerMounted(newCacheId)) { 11099 Slog.w(TAG, "Mounting container " + newCacheId); 11100 newMountPath = PackageHelper.mountSdDir(newCacheId, 11101 getEncryptKey(), Process.SYSTEM_UID); 11102 } else { 11103 newMountPath = PackageHelper.getSdDir(newCacheId); 11104 } 11105 if (newMountPath == null) { 11106 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11107 return false; 11108 } 11109 Log.i(TAG, "Succesfully renamed " + cid + 11110 " to " + newCacheId + 11111 " at new path: " + newMountPath); 11112 cid = newCacheId; 11113 11114 final File beforeCodeFile = new File(packagePath); 11115 setMountPath(newMountPath); 11116 final File afterCodeFile = new File(packagePath); 11117 11118 // Reflect the rename in scanned details 11119 pkg.codePath = afterCodeFile.getAbsolutePath(); 11120 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11121 pkg.baseCodePath); 11122 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11123 pkg.splitCodePaths); 11124 11125 // Reflect the rename in app info 11126 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11127 pkg.applicationInfo.setCodePath(pkg.codePath); 11128 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11129 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11130 pkg.applicationInfo.setResourcePath(pkg.codePath); 11131 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11132 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11133 11134 return true; 11135 } 11136 11137 private void setMountPath(String mountPath) { 11138 final File mountFile = new File(mountPath); 11139 11140 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11141 if (monolithicFile.exists()) { 11142 packagePath = monolithicFile.getAbsolutePath(); 11143 if (isFwdLocked()) { 11144 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11145 } else { 11146 resourcePath = packagePath; 11147 } 11148 } else { 11149 packagePath = mountFile.getAbsolutePath(); 11150 resourcePath = packagePath; 11151 } 11152 } 11153 11154 int doPostInstall(int status, int uid) { 11155 if (status != PackageManager.INSTALL_SUCCEEDED) { 11156 cleanUp(); 11157 } else { 11158 final int groupOwner; 11159 final String protectedFile; 11160 if (isFwdLocked()) { 11161 groupOwner = UserHandle.getSharedAppGid(uid); 11162 protectedFile = RES_FILE_NAME; 11163 } else { 11164 groupOwner = -1; 11165 protectedFile = null; 11166 } 11167 11168 if (uid < Process.FIRST_APPLICATION_UID 11169 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11170 Slog.e(TAG, "Failed to finalize " + cid); 11171 PackageHelper.destroySdDir(cid); 11172 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11173 } 11174 11175 boolean mounted = PackageHelper.isContainerMounted(cid); 11176 if (!mounted) { 11177 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11178 } 11179 } 11180 return status; 11181 } 11182 11183 private void cleanUp() { 11184 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11185 11186 // Destroy secure container 11187 PackageHelper.destroySdDir(cid); 11188 } 11189 11190 private List<String> getAllCodePaths() { 11191 final File codeFile = new File(getCodePath()); 11192 if (codeFile != null && codeFile.exists()) { 11193 try { 11194 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11195 return pkg.getAllCodePaths(); 11196 } catch (PackageParserException e) { 11197 // Ignored; we tried our best 11198 } 11199 } 11200 return Collections.EMPTY_LIST; 11201 } 11202 11203 void cleanUpResourcesLI() { 11204 // Enumerate all code paths before deleting 11205 cleanUpResourcesLI(getAllCodePaths()); 11206 } 11207 11208 private void cleanUpResourcesLI(List<String> allCodePaths) { 11209 cleanUp(); 11210 removeDexFiles(allCodePaths, instructionSets); 11211 } 11212 11213 String getPackageName() { 11214 return getAsecPackageName(cid); 11215 } 11216 11217 boolean doPostDeleteLI(boolean delete) { 11218 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11219 final List<String> allCodePaths = getAllCodePaths(); 11220 boolean mounted = PackageHelper.isContainerMounted(cid); 11221 if (mounted) { 11222 // Unmount first 11223 if (PackageHelper.unMountSdDir(cid)) { 11224 mounted = false; 11225 } 11226 } 11227 if (!mounted && delete) { 11228 cleanUpResourcesLI(allCodePaths); 11229 } 11230 return !mounted; 11231 } 11232 11233 @Override 11234 int doPreCopy() { 11235 if (isFwdLocked()) { 11236 if (!PackageHelper.fixSdPermissions(cid, 11237 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11238 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11239 } 11240 } 11241 11242 return PackageManager.INSTALL_SUCCEEDED; 11243 } 11244 11245 @Override 11246 int doPostCopy(int uid) { 11247 if (isFwdLocked()) { 11248 if (uid < Process.FIRST_APPLICATION_UID 11249 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11250 RES_FILE_NAME)) { 11251 Slog.e(TAG, "Failed to finalize " + cid); 11252 PackageHelper.destroySdDir(cid); 11253 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11254 } 11255 } 11256 11257 return PackageManager.INSTALL_SUCCEEDED; 11258 } 11259 } 11260 11261 /** 11262 * Logic to handle movement of existing installed applications. 11263 */ 11264 class MoveInstallArgs extends InstallArgs { 11265 private File codeFile; 11266 private File resourceFile; 11267 11268 /** New install */ 11269 MoveInstallArgs(InstallParams params) { 11270 super(params.origin, params.move, params.observer, params.installFlags, 11271 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11272 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11273 } 11274 11275 int copyApk(IMediaContainerService imcs, boolean temp) { 11276 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11277 + move.fromUuid + " to " + move.toUuid); 11278 synchronized (mInstaller) { 11279 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11280 move.dataAppName, move.appId, move.seinfo) != 0) { 11281 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11282 } 11283 } 11284 11285 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11286 resourceFile = codeFile; 11287 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11288 11289 return PackageManager.INSTALL_SUCCEEDED; 11290 } 11291 11292 int doPreInstall(int status) { 11293 if (status != PackageManager.INSTALL_SUCCEEDED) { 11294 cleanUp(move.toUuid); 11295 } 11296 return status; 11297 } 11298 11299 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11300 if (status != PackageManager.INSTALL_SUCCEEDED) { 11301 cleanUp(move.toUuid); 11302 return false; 11303 } 11304 11305 // Reflect the move in app info 11306 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11307 pkg.applicationInfo.setCodePath(pkg.codePath); 11308 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11309 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11310 pkg.applicationInfo.setResourcePath(pkg.codePath); 11311 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11312 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11313 11314 return true; 11315 } 11316 11317 int doPostInstall(int status, int uid) { 11318 if (status == PackageManager.INSTALL_SUCCEEDED) { 11319 cleanUp(move.fromUuid); 11320 } else { 11321 cleanUp(move.toUuid); 11322 } 11323 return status; 11324 } 11325 11326 @Override 11327 String getCodePath() { 11328 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11329 } 11330 11331 @Override 11332 String getResourcePath() { 11333 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11334 } 11335 11336 private boolean cleanUp(String volumeUuid) { 11337 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11338 move.dataAppName); 11339 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11340 synchronized (mInstallLock) { 11341 // Clean up both app data and code 11342 removeDataDirsLI(volumeUuid, move.packageName); 11343 if (codeFile.isDirectory()) { 11344 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11345 } else { 11346 codeFile.delete(); 11347 } 11348 } 11349 return true; 11350 } 11351 11352 void cleanUpResourcesLI() { 11353 throw new UnsupportedOperationException(); 11354 } 11355 11356 boolean doPostDeleteLI(boolean delete) { 11357 throw new UnsupportedOperationException(); 11358 } 11359 } 11360 11361 static String getAsecPackageName(String packageCid) { 11362 int idx = packageCid.lastIndexOf("-"); 11363 if (idx == -1) { 11364 return packageCid; 11365 } 11366 return packageCid.substring(0, idx); 11367 } 11368 11369 // Utility method used to create code paths based on package name and available index. 11370 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11371 String idxStr = ""; 11372 int idx = 1; 11373 // Fall back to default value of idx=1 if prefix is not 11374 // part of oldCodePath 11375 if (oldCodePath != null) { 11376 String subStr = oldCodePath; 11377 // Drop the suffix right away 11378 if (suffix != null && subStr.endsWith(suffix)) { 11379 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11380 } 11381 // If oldCodePath already contains prefix find out the 11382 // ending index to either increment or decrement. 11383 int sidx = subStr.lastIndexOf(prefix); 11384 if (sidx != -1) { 11385 subStr = subStr.substring(sidx + prefix.length()); 11386 if (subStr != null) { 11387 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11388 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11389 } 11390 try { 11391 idx = Integer.parseInt(subStr); 11392 if (idx <= 1) { 11393 idx++; 11394 } else { 11395 idx--; 11396 } 11397 } catch(NumberFormatException e) { 11398 } 11399 } 11400 } 11401 } 11402 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11403 return prefix + idxStr; 11404 } 11405 11406 private File getNextCodePath(File targetDir, String packageName) { 11407 int suffix = 1; 11408 File result; 11409 do { 11410 result = new File(targetDir, packageName + "-" + suffix); 11411 suffix++; 11412 } while (result.exists()); 11413 return result; 11414 } 11415 11416 // Utility method that returns the relative package path with respect 11417 // to the installation directory. Like say for /data/data/com.test-1.apk 11418 // string com.test-1 is returned. 11419 static String deriveCodePathName(String codePath) { 11420 if (codePath == null) { 11421 return null; 11422 } 11423 final File codeFile = new File(codePath); 11424 final String name = codeFile.getName(); 11425 if (codeFile.isDirectory()) { 11426 return name; 11427 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11428 final int lastDot = name.lastIndexOf('.'); 11429 return name.substring(0, lastDot); 11430 } else { 11431 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11432 return null; 11433 } 11434 } 11435 11436 class PackageInstalledInfo { 11437 String name; 11438 int uid; 11439 // The set of users that originally had this package installed. 11440 int[] origUsers; 11441 // The set of users that now have this package installed. 11442 int[] newUsers; 11443 PackageParser.Package pkg; 11444 int returnCode; 11445 String returnMsg; 11446 PackageRemovedInfo removedInfo; 11447 11448 public void setError(int code, String msg) { 11449 returnCode = code; 11450 returnMsg = msg; 11451 Slog.w(TAG, msg); 11452 } 11453 11454 public void setError(String msg, PackageParserException e) { 11455 returnCode = e.error; 11456 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11457 Slog.w(TAG, msg, e); 11458 } 11459 11460 public void setError(String msg, PackageManagerException e) { 11461 returnCode = e.error; 11462 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11463 Slog.w(TAG, msg, e); 11464 } 11465 11466 // In some error cases we want to convey more info back to the observer 11467 String origPackage; 11468 String origPermission; 11469 } 11470 11471 /* 11472 * Install a non-existing package. 11473 */ 11474 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11475 UserHandle user, String installerPackageName, String volumeUuid, 11476 PackageInstalledInfo res) { 11477 // Remember this for later, in case we need to rollback this install 11478 String pkgName = pkg.packageName; 11479 11480 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11481 final boolean dataDirExists = Environment 11482 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11483 synchronized(mPackages) { 11484 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11485 // A package with the same name is already installed, though 11486 // it has been renamed to an older name. The package we 11487 // are trying to install should be installed as an update to 11488 // the existing one, but that has not been requested, so bail. 11489 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11490 + " without first uninstalling package running as " 11491 + mSettings.mRenamedPackages.get(pkgName)); 11492 return; 11493 } 11494 if (mPackages.containsKey(pkgName)) { 11495 // Don't allow installation over an existing package with the same name. 11496 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11497 + " without first uninstalling."); 11498 return; 11499 } 11500 } 11501 11502 try { 11503 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11504 System.currentTimeMillis(), user); 11505 11506 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11507 // delete the partially installed application. the data directory will have to be 11508 // restored if it was already existing 11509 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11510 // remove package from internal structures. Note that we want deletePackageX to 11511 // delete the package data and cache directories that it created in 11512 // scanPackageLocked, unless those directories existed before we even tried to 11513 // install. 11514 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11515 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11516 res.removedInfo, true); 11517 } 11518 11519 } catch (PackageManagerException e) { 11520 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11521 } 11522 } 11523 11524 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11525 // Can't rotate keys during boot or if sharedUser. 11526 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11527 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11528 return false; 11529 } 11530 // app is using upgradeKeySets; make sure all are valid 11531 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11532 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11533 for (int i = 0; i < upgradeKeySets.length; i++) { 11534 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11535 Slog.wtf(TAG, "Package " 11536 + (oldPs.name != null ? oldPs.name : "<null>") 11537 + " contains upgrade-key-set reference to unknown key-set: " 11538 + upgradeKeySets[i] 11539 + " reverting to signatures check."); 11540 return false; 11541 } 11542 } 11543 return true; 11544 } 11545 11546 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11547 // Upgrade keysets are being used. Determine if new package has a superset of the 11548 // required keys. 11549 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11550 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11551 for (int i = 0; i < upgradeKeySets.length; i++) { 11552 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11553 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11554 return true; 11555 } 11556 } 11557 return false; 11558 } 11559 11560 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11561 UserHandle user, String installerPackageName, String volumeUuid, 11562 PackageInstalledInfo res) { 11563 final PackageParser.Package oldPackage; 11564 final String pkgName = pkg.packageName; 11565 final int[] allUsers; 11566 final boolean[] perUserInstalled; 11567 final boolean weFroze; 11568 11569 // First find the old package info and check signatures 11570 synchronized(mPackages) { 11571 oldPackage = mPackages.get(pkgName); 11572 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11573 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11574 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11575 if(!checkUpgradeKeySetLP(ps, pkg)) { 11576 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11577 "New package not signed by keys specified by upgrade-keysets: " 11578 + pkgName); 11579 return; 11580 } 11581 } else { 11582 // default to original signature matching 11583 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11584 != PackageManager.SIGNATURE_MATCH) { 11585 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11586 "New package has a different signature: " + pkgName); 11587 return; 11588 } 11589 } 11590 11591 // In case of rollback, remember per-user/profile install state 11592 allUsers = sUserManager.getUserIds(); 11593 perUserInstalled = new boolean[allUsers.length]; 11594 for (int i = 0; i < allUsers.length; i++) { 11595 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11596 } 11597 11598 // Mark the app as frozen to prevent launching during the upgrade 11599 // process, and then kill all running instances 11600 if (!ps.frozen) { 11601 ps.frozen = true; 11602 weFroze = true; 11603 } else { 11604 weFroze = false; 11605 } 11606 } 11607 11608 // Now that we're guarded by frozen state, kill app during upgrade 11609 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11610 11611 try { 11612 boolean sysPkg = (isSystemApp(oldPackage)); 11613 if (sysPkg) { 11614 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11615 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11616 } else { 11617 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11618 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11619 } 11620 } finally { 11621 // Regardless of success or failure of upgrade steps above, always 11622 // unfreeze the package if we froze it 11623 if (weFroze) { 11624 unfreezePackage(pkgName); 11625 } 11626 } 11627 } 11628 11629 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11630 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11631 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11632 String volumeUuid, PackageInstalledInfo res) { 11633 String pkgName = deletedPackage.packageName; 11634 boolean deletedPkg = true; 11635 boolean updatedSettings = false; 11636 11637 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11638 + deletedPackage); 11639 long origUpdateTime; 11640 if (pkg.mExtras != null) { 11641 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11642 } else { 11643 origUpdateTime = 0; 11644 } 11645 11646 // First delete the existing package while retaining the data directory 11647 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11648 res.removedInfo, true)) { 11649 // If the existing package wasn't successfully deleted 11650 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11651 deletedPkg = false; 11652 } else { 11653 // Successfully deleted the old package; proceed with replace. 11654 11655 // If deleted package lived in a container, give users a chance to 11656 // relinquish resources before killing. 11657 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11658 if (DEBUG_INSTALL) { 11659 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11660 } 11661 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11662 final ArrayList<String> pkgList = new ArrayList<String>(1); 11663 pkgList.add(deletedPackage.applicationInfo.packageName); 11664 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11665 } 11666 11667 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11668 try { 11669 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11670 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11671 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11672 perUserInstalled, res, user); 11673 updatedSettings = true; 11674 } catch (PackageManagerException e) { 11675 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11676 } 11677 } 11678 11679 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11680 // remove package from internal structures. Note that we want deletePackageX to 11681 // delete the package data and cache directories that it created in 11682 // scanPackageLocked, unless those directories existed before we even tried to 11683 // install. 11684 if(updatedSettings) { 11685 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11686 deletePackageLI( 11687 pkgName, null, true, allUsers, perUserInstalled, 11688 PackageManager.DELETE_KEEP_DATA, 11689 res.removedInfo, true); 11690 } 11691 // Since we failed to install the new package we need to restore the old 11692 // package that we deleted. 11693 if (deletedPkg) { 11694 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11695 File restoreFile = new File(deletedPackage.codePath); 11696 // Parse old package 11697 boolean oldExternal = isExternal(deletedPackage); 11698 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11699 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11700 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11701 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11702 try { 11703 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11704 } catch (PackageManagerException e) { 11705 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11706 + e.getMessage()); 11707 return; 11708 } 11709 // Restore of old package succeeded. Update permissions. 11710 // writer 11711 synchronized (mPackages) { 11712 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11713 UPDATE_PERMISSIONS_ALL); 11714 // can downgrade to reader 11715 mSettings.writeLPr(); 11716 } 11717 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11718 } 11719 } 11720 } 11721 11722 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11723 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11724 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11725 String volumeUuid, PackageInstalledInfo res) { 11726 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11727 + ", old=" + deletedPackage); 11728 boolean disabledSystem = false; 11729 boolean updatedSettings = false; 11730 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11731 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11732 != 0) { 11733 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11734 } 11735 String packageName = deletedPackage.packageName; 11736 if (packageName == null) { 11737 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11738 "Attempt to delete null packageName."); 11739 return; 11740 } 11741 PackageParser.Package oldPkg; 11742 PackageSetting oldPkgSetting; 11743 // reader 11744 synchronized (mPackages) { 11745 oldPkg = mPackages.get(packageName); 11746 oldPkgSetting = mSettings.mPackages.get(packageName); 11747 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11748 (oldPkgSetting == null)) { 11749 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11750 "Couldn't find package:" + packageName + " information"); 11751 return; 11752 } 11753 } 11754 11755 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11756 res.removedInfo.removedPackage = packageName; 11757 // Remove existing system package 11758 removePackageLI(oldPkgSetting, true); 11759 // writer 11760 synchronized (mPackages) { 11761 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11762 if (!disabledSystem && deletedPackage != null) { 11763 // We didn't need to disable the .apk as a current system package, 11764 // which means we are replacing another update that is already 11765 // installed. We need to make sure to delete the older one's .apk. 11766 res.removedInfo.args = createInstallArgsForExisting(0, 11767 deletedPackage.applicationInfo.getCodePath(), 11768 deletedPackage.applicationInfo.getResourcePath(), 11769 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11770 } else { 11771 res.removedInfo.args = null; 11772 } 11773 } 11774 11775 // Successfully disabled the old package. Now proceed with re-installation 11776 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11777 11778 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11779 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11780 11781 PackageParser.Package newPackage = null; 11782 try { 11783 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11784 if (newPackage.mExtras != null) { 11785 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11786 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11787 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11788 11789 // is the update attempting to change shared user? that isn't going to work... 11790 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11791 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11792 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11793 + " to " + newPkgSetting.sharedUser); 11794 updatedSettings = true; 11795 } 11796 } 11797 11798 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11799 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11800 perUserInstalled, res, user); 11801 updatedSettings = true; 11802 } 11803 11804 } catch (PackageManagerException e) { 11805 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11806 } 11807 11808 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11809 // Re installation failed. Restore old information 11810 // Remove new pkg information 11811 if (newPackage != null) { 11812 removeInstalledPackageLI(newPackage, true); 11813 } 11814 // Add back the old system package 11815 try { 11816 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11817 } catch (PackageManagerException e) { 11818 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11819 } 11820 // Restore the old system information in Settings 11821 synchronized (mPackages) { 11822 if (disabledSystem) { 11823 mSettings.enableSystemPackageLPw(packageName); 11824 } 11825 if (updatedSettings) { 11826 mSettings.setInstallerPackageName(packageName, 11827 oldPkgSetting.installerPackageName); 11828 } 11829 mSettings.writeLPr(); 11830 } 11831 } 11832 } 11833 11834 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11835 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11836 UserHandle user) { 11837 String pkgName = newPackage.packageName; 11838 synchronized (mPackages) { 11839 //write settings. the installStatus will be incomplete at this stage. 11840 //note that the new package setting would have already been 11841 //added to mPackages. It hasn't been persisted yet. 11842 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11843 mSettings.writeLPr(); 11844 } 11845 11846 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11847 11848 synchronized (mPackages) { 11849 updatePermissionsLPw(newPackage.packageName, newPackage, 11850 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11851 ? UPDATE_PERMISSIONS_ALL : 0)); 11852 // For system-bundled packages, we assume that installing an upgraded version 11853 // of the package implies that the user actually wants to run that new code, 11854 // so we enable the package. 11855 PackageSetting ps = mSettings.mPackages.get(pkgName); 11856 if (ps != null) { 11857 if (isSystemApp(newPackage)) { 11858 // NB: implicit assumption that system package upgrades apply to all users 11859 if (DEBUG_INSTALL) { 11860 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11861 } 11862 if (res.origUsers != null) { 11863 for (int userHandle : res.origUsers) { 11864 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11865 userHandle, installerPackageName); 11866 } 11867 } 11868 // Also convey the prior install/uninstall state 11869 if (allUsers != null && perUserInstalled != null) { 11870 for (int i = 0; i < allUsers.length; i++) { 11871 if (DEBUG_INSTALL) { 11872 Slog.d(TAG, " user " + allUsers[i] 11873 + " => " + perUserInstalled[i]); 11874 } 11875 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11876 } 11877 // these install state changes will be persisted in the 11878 // upcoming call to mSettings.writeLPr(). 11879 } 11880 } 11881 // It's implied that when a user requests installation, they want the app to be 11882 // installed and enabled. 11883 int userId = user.getIdentifier(); 11884 if (userId != UserHandle.USER_ALL) { 11885 ps.setInstalled(true, userId); 11886 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11887 } 11888 } 11889 res.name = pkgName; 11890 res.uid = newPackage.applicationInfo.uid; 11891 res.pkg = newPackage; 11892 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11893 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11894 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11895 //to update install status 11896 mSettings.writeLPr(); 11897 } 11898 } 11899 11900 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11901 final int installFlags = args.installFlags; 11902 final String installerPackageName = args.installerPackageName; 11903 final String volumeUuid = args.volumeUuid; 11904 final File tmpPackageFile = new File(args.getCodePath()); 11905 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11906 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11907 || (args.volumeUuid != null)); 11908 boolean replace = false; 11909 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11910 if (args.move != null) { 11911 // moving a complete application; perfom an initial scan on the new install location 11912 scanFlags |= SCAN_INITIAL; 11913 } 11914 // Result object to be returned 11915 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11916 11917 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11918 // Retrieve PackageSettings and parse package 11919 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11920 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11921 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11922 PackageParser pp = new PackageParser(); 11923 pp.setSeparateProcesses(mSeparateProcesses); 11924 pp.setDisplayMetrics(mMetrics); 11925 11926 final PackageParser.Package pkg; 11927 try { 11928 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11929 } catch (PackageParserException e) { 11930 res.setError("Failed parse during installPackageLI", e); 11931 return; 11932 } 11933 11934 // Mark that we have an install time CPU ABI override. 11935 pkg.cpuAbiOverride = args.abiOverride; 11936 11937 String pkgName = res.name = pkg.packageName; 11938 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11939 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11940 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11941 return; 11942 } 11943 } 11944 11945 try { 11946 pp.collectCertificates(pkg, parseFlags); 11947 pp.collectManifestDigest(pkg); 11948 } catch (PackageParserException e) { 11949 res.setError("Failed collect during installPackageLI", e); 11950 return; 11951 } 11952 11953 /* If the installer passed in a manifest digest, compare it now. */ 11954 if (args.manifestDigest != null) { 11955 if (DEBUG_INSTALL) { 11956 final String parsedManifest = pkg.manifestDigest == null ? "null" 11957 : pkg.manifestDigest.toString(); 11958 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11959 + parsedManifest); 11960 } 11961 11962 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11963 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11964 return; 11965 } 11966 } else if (DEBUG_INSTALL) { 11967 final String parsedManifest = pkg.manifestDigest == null 11968 ? "null" : pkg.manifestDigest.toString(); 11969 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11970 } 11971 11972 // Get rid of all references to package scan path via parser. 11973 pp = null; 11974 String oldCodePath = null; 11975 boolean systemApp = false; 11976 synchronized (mPackages) { 11977 // Check if installing already existing package 11978 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11979 String oldName = mSettings.mRenamedPackages.get(pkgName); 11980 if (pkg.mOriginalPackages != null 11981 && pkg.mOriginalPackages.contains(oldName) 11982 && mPackages.containsKey(oldName)) { 11983 // This package is derived from an original package, 11984 // and this device has been updating from that original 11985 // name. We must continue using the original name, so 11986 // rename the new package here. 11987 pkg.setPackageName(oldName); 11988 pkgName = pkg.packageName; 11989 replace = true; 11990 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11991 + oldName + " pkgName=" + pkgName); 11992 } else if (mPackages.containsKey(pkgName)) { 11993 // This package, under its official name, already exists 11994 // on the device; we should replace it. 11995 replace = true; 11996 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11997 } 11998 11999 // Prevent apps opting out from runtime permissions 12000 if (replace) { 12001 PackageParser.Package oldPackage = mPackages.get(pkgName); 12002 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12003 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12004 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12005 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12006 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12007 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12008 + " doesn't support runtime permissions but the old" 12009 + " target SDK " + oldTargetSdk + " does."); 12010 return; 12011 } 12012 } 12013 } 12014 12015 PackageSetting ps = mSettings.mPackages.get(pkgName); 12016 if (ps != null) { 12017 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12018 12019 // Quick sanity check that we're signed correctly if updating; 12020 // we'll check this again later when scanning, but we want to 12021 // bail early here before tripping over redefined permissions. 12022 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12023 if (!checkUpgradeKeySetLP(ps, pkg)) { 12024 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12025 + pkg.packageName + " upgrade keys do not match the " 12026 + "previously installed version"); 12027 return; 12028 } 12029 } else { 12030 try { 12031 verifySignaturesLP(ps, pkg); 12032 } catch (PackageManagerException e) { 12033 res.setError(e.error, e.getMessage()); 12034 return; 12035 } 12036 } 12037 12038 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12039 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12040 systemApp = (ps.pkg.applicationInfo.flags & 12041 ApplicationInfo.FLAG_SYSTEM) != 0; 12042 } 12043 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12044 } 12045 12046 // Check whether the newly-scanned package wants to define an already-defined perm 12047 int N = pkg.permissions.size(); 12048 for (int i = N-1; i >= 0; i--) { 12049 PackageParser.Permission perm = pkg.permissions.get(i); 12050 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12051 if (bp != null) { 12052 // If the defining package is signed with our cert, it's okay. This 12053 // also includes the "updating the same package" case, of course. 12054 // "updating same package" could also involve key-rotation. 12055 final boolean sigsOk; 12056 if (bp.sourcePackage.equals(pkg.packageName) 12057 && (bp.packageSetting instanceof PackageSetting) 12058 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12059 scanFlags))) { 12060 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12061 } else { 12062 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12063 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12064 } 12065 if (!sigsOk) { 12066 // If the owning package is the system itself, we log but allow 12067 // install to proceed; we fail the install on all other permission 12068 // redefinitions. 12069 if (!bp.sourcePackage.equals("android")) { 12070 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12071 + pkg.packageName + " attempting to redeclare permission " 12072 + perm.info.name + " already owned by " + bp.sourcePackage); 12073 res.origPermission = perm.info.name; 12074 res.origPackage = bp.sourcePackage; 12075 return; 12076 } else { 12077 Slog.w(TAG, "Package " + pkg.packageName 12078 + " attempting to redeclare system permission " 12079 + perm.info.name + "; ignoring new declaration"); 12080 pkg.permissions.remove(i); 12081 } 12082 } 12083 } 12084 } 12085 12086 } 12087 12088 if (systemApp && onExternal) { 12089 // Disable updates to system apps on sdcard 12090 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12091 "Cannot install updates to system apps on sdcard"); 12092 return; 12093 } 12094 12095 if (args.move != null) { 12096 // We did an in-place move, so dex is ready to roll 12097 scanFlags |= SCAN_NO_DEX; 12098 scanFlags |= SCAN_MOVE; 12099 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12100 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12101 scanFlags |= SCAN_NO_DEX; 12102 12103 try { 12104 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12105 true /* extract libs */); 12106 } catch (PackageManagerException pme) { 12107 Slog.e(TAG, "Error deriving application ABI", pme); 12108 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12109 return; 12110 } 12111 12112 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12113 int result = mPackageDexOptimizer 12114 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12115 false /* defer */, false /* inclDependencies */); 12116 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12117 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12118 return; 12119 } 12120 } 12121 12122 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12123 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12124 return; 12125 } 12126 12127 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12128 12129 if (replace) { 12130 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12131 installerPackageName, volumeUuid, res); 12132 } else { 12133 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12134 args.user, installerPackageName, volumeUuid, res); 12135 } 12136 synchronized (mPackages) { 12137 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12138 if (ps != null) { 12139 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12140 } 12141 } 12142 } 12143 12144 private void startIntentFilterVerifications(int userId, boolean replacing, 12145 PackageParser.Package pkg) { 12146 if (mIntentFilterVerifierComponent == null) { 12147 Slog.w(TAG, "No IntentFilter verification will not be done as " 12148 + "there is no IntentFilterVerifier available!"); 12149 return; 12150 } 12151 12152 final int verifierUid = getPackageUid( 12153 mIntentFilterVerifierComponent.getPackageName(), 12154 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12155 12156 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12157 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12158 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12159 mHandler.sendMessage(msg); 12160 } 12161 12162 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12163 PackageParser.Package pkg) { 12164 int size = pkg.activities.size(); 12165 if (size == 0) { 12166 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12167 "No activity, so no need to verify any IntentFilter!"); 12168 return; 12169 } 12170 12171 final boolean hasDomainURLs = hasDomainURLs(pkg); 12172 if (!hasDomainURLs) { 12173 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12174 "No domain URLs, so no need to verify any IntentFilter!"); 12175 return; 12176 } 12177 12178 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12179 + " if any IntentFilter from the " + size 12180 + " Activities needs verification ..."); 12181 12182 int count = 0; 12183 final String packageName = pkg.packageName; 12184 12185 synchronized (mPackages) { 12186 // If this is a new install and we see that we've already run verification for this 12187 // package, we have nothing to do: it means the state was restored from backup. 12188 if (!replacing) { 12189 IntentFilterVerificationInfo ivi = 12190 mSettings.getIntentFilterVerificationLPr(packageName); 12191 if (ivi != null) { 12192 if (DEBUG_DOMAIN_VERIFICATION) { 12193 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12194 + ivi.getStatusString()); 12195 } 12196 return; 12197 } 12198 } 12199 12200 // If any filters need to be verified, then all need to be. 12201 boolean needToVerify = false; 12202 for (PackageParser.Activity a : pkg.activities) { 12203 for (ActivityIntentInfo filter : a.intents) { 12204 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12205 if (DEBUG_DOMAIN_VERIFICATION) { 12206 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12207 } 12208 needToVerify = true; 12209 break; 12210 } 12211 } 12212 } 12213 12214 if (needToVerify) { 12215 final int verificationId = mIntentFilterVerificationToken++; 12216 for (PackageParser.Activity a : pkg.activities) { 12217 for (ActivityIntentInfo filter : a.intents) { 12218 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12219 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12220 "Verification needed for IntentFilter:" + filter.toString()); 12221 mIntentFilterVerifier.addOneIntentFilterVerification( 12222 verifierUid, userId, verificationId, filter, packageName); 12223 count++; 12224 } 12225 } 12226 } 12227 } 12228 } 12229 12230 if (count > 0) { 12231 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12232 + " IntentFilter verification" + (count > 1 ? "s" : "") 12233 + " for userId:" + userId); 12234 mIntentFilterVerifier.startVerifications(userId); 12235 } else { 12236 if (DEBUG_DOMAIN_VERIFICATION) { 12237 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12238 } 12239 } 12240 } 12241 12242 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12243 final ComponentName cn = filter.activity.getComponentName(); 12244 final String packageName = cn.getPackageName(); 12245 12246 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12247 packageName); 12248 if (ivi == null) { 12249 return true; 12250 } 12251 int status = ivi.getStatus(); 12252 switch (status) { 12253 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12254 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12255 return true; 12256 12257 default: 12258 // Nothing to do 12259 return false; 12260 } 12261 } 12262 12263 private static boolean isMultiArch(PackageSetting ps) { 12264 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12265 } 12266 12267 private static boolean isMultiArch(ApplicationInfo info) { 12268 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12269 } 12270 12271 private static boolean isExternal(PackageParser.Package pkg) { 12272 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12273 } 12274 12275 private static boolean isExternal(PackageSetting ps) { 12276 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12277 } 12278 12279 private static boolean isExternal(ApplicationInfo info) { 12280 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12281 } 12282 12283 private static boolean isSystemApp(PackageParser.Package pkg) { 12284 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12285 } 12286 12287 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12288 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12289 } 12290 12291 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12292 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12293 } 12294 12295 private static boolean isSystemApp(PackageSetting ps) { 12296 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12297 } 12298 12299 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12300 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12301 } 12302 12303 private int packageFlagsToInstallFlags(PackageSetting ps) { 12304 int installFlags = 0; 12305 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12306 // This existing package was an external ASEC install when we have 12307 // the external flag without a UUID 12308 installFlags |= PackageManager.INSTALL_EXTERNAL; 12309 } 12310 if (ps.isForwardLocked()) { 12311 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12312 } 12313 return installFlags; 12314 } 12315 12316 private void deleteTempPackageFiles() { 12317 final FilenameFilter filter = new FilenameFilter() { 12318 public boolean accept(File dir, String name) { 12319 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12320 } 12321 }; 12322 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12323 file.delete(); 12324 } 12325 } 12326 12327 @Override 12328 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12329 int flags) { 12330 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12331 flags); 12332 } 12333 12334 @Override 12335 public void deletePackage(final String packageName, 12336 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12337 mContext.enforceCallingOrSelfPermission( 12338 android.Manifest.permission.DELETE_PACKAGES, null); 12339 Preconditions.checkNotNull(packageName); 12340 Preconditions.checkNotNull(observer); 12341 final int uid = Binder.getCallingUid(); 12342 if (UserHandle.getUserId(uid) != userId) { 12343 mContext.enforceCallingPermission( 12344 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12345 "deletePackage for user " + userId); 12346 } 12347 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12348 try { 12349 observer.onPackageDeleted(packageName, 12350 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12351 } catch (RemoteException re) { 12352 } 12353 return; 12354 } 12355 12356 boolean uninstallBlocked = false; 12357 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12358 int[] users = sUserManager.getUserIds(); 12359 for (int i = 0; i < users.length; ++i) { 12360 if (getBlockUninstallForUser(packageName, users[i])) { 12361 uninstallBlocked = true; 12362 break; 12363 } 12364 } 12365 } else { 12366 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12367 } 12368 if (uninstallBlocked) { 12369 try { 12370 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12371 null); 12372 } catch (RemoteException re) { 12373 } 12374 return; 12375 } 12376 12377 if (DEBUG_REMOVE) { 12378 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12379 } 12380 // Queue up an async operation since the package deletion may take a little while. 12381 mHandler.post(new Runnable() { 12382 public void run() { 12383 mHandler.removeCallbacks(this); 12384 final int returnCode = deletePackageX(packageName, userId, flags); 12385 if (observer != null) { 12386 try { 12387 observer.onPackageDeleted(packageName, returnCode, null); 12388 } catch (RemoteException e) { 12389 Log.i(TAG, "Observer no longer exists."); 12390 } //end catch 12391 } //end if 12392 } //end run 12393 }); 12394 } 12395 12396 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12397 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12398 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12399 try { 12400 if (dpm != null) { 12401 if (dpm.isDeviceOwner(packageName)) { 12402 return true; 12403 } 12404 int[] users; 12405 if (userId == UserHandle.USER_ALL) { 12406 users = sUserManager.getUserIds(); 12407 } else { 12408 users = new int[]{userId}; 12409 } 12410 for (int i = 0; i < users.length; ++i) { 12411 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12412 return true; 12413 } 12414 } 12415 } 12416 } catch (RemoteException e) { 12417 } 12418 return false; 12419 } 12420 12421 /** 12422 * This method is an internal method that could be get invoked either 12423 * to delete an installed package or to clean up a failed installation. 12424 * After deleting an installed package, a broadcast is sent to notify any 12425 * listeners that the package has been installed. For cleaning up a failed 12426 * installation, the broadcast is not necessary since the package's 12427 * installation wouldn't have sent the initial broadcast either 12428 * The key steps in deleting a package are 12429 * deleting the package information in internal structures like mPackages, 12430 * deleting the packages base directories through installd 12431 * updating mSettings to reflect current status 12432 * persisting settings for later use 12433 * sending a broadcast if necessary 12434 */ 12435 private int deletePackageX(String packageName, int userId, int flags) { 12436 final PackageRemovedInfo info = new PackageRemovedInfo(); 12437 final boolean res; 12438 12439 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12440 ? UserHandle.ALL : new UserHandle(userId); 12441 12442 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12443 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12444 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12445 } 12446 12447 boolean removedForAllUsers = false; 12448 boolean systemUpdate = false; 12449 12450 // for the uninstall-updates case and restricted profiles, remember the per- 12451 // userhandle installed state 12452 int[] allUsers; 12453 boolean[] perUserInstalled; 12454 synchronized (mPackages) { 12455 PackageSetting ps = mSettings.mPackages.get(packageName); 12456 allUsers = sUserManager.getUserIds(); 12457 perUserInstalled = new boolean[allUsers.length]; 12458 for (int i = 0; i < allUsers.length; i++) { 12459 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12460 } 12461 } 12462 12463 synchronized (mInstallLock) { 12464 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12465 res = deletePackageLI(packageName, removeForUser, 12466 true, allUsers, perUserInstalled, 12467 flags | REMOVE_CHATTY, info, true); 12468 systemUpdate = info.isRemovedPackageSystemUpdate; 12469 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12470 removedForAllUsers = true; 12471 } 12472 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12473 + " removedForAllUsers=" + removedForAllUsers); 12474 } 12475 12476 if (res) { 12477 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12478 12479 // If the removed package was a system update, the old system package 12480 // was re-enabled; we need to broadcast this information 12481 if (systemUpdate) { 12482 Bundle extras = new Bundle(1); 12483 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12484 ? info.removedAppId : info.uid); 12485 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12486 12487 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12488 extras, null, null, null); 12489 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12490 extras, null, null, null); 12491 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12492 null, packageName, null, null); 12493 } 12494 } 12495 // Force a gc here. 12496 Runtime.getRuntime().gc(); 12497 // Delete the resources here after sending the broadcast to let 12498 // other processes clean up before deleting resources. 12499 if (info.args != null) { 12500 synchronized (mInstallLock) { 12501 info.args.doPostDeleteLI(true); 12502 } 12503 } 12504 12505 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12506 } 12507 12508 class PackageRemovedInfo { 12509 String removedPackage; 12510 int uid = -1; 12511 int removedAppId = -1; 12512 int[] removedUsers = null; 12513 boolean isRemovedPackageSystemUpdate = false; 12514 // Clean up resources deleted packages. 12515 InstallArgs args = null; 12516 12517 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12518 Bundle extras = new Bundle(1); 12519 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12520 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12521 if (replacing) { 12522 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12523 } 12524 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12525 if (removedPackage != null) { 12526 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12527 extras, null, null, removedUsers); 12528 if (fullRemove && !replacing) { 12529 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12530 extras, null, null, removedUsers); 12531 } 12532 } 12533 if (removedAppId >= 0) { 12534 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12535 removedUsers); 12536 } 12537 } 12538 } 12539 12540 /* 12541 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12542 * flag is not set, the data directory is removed as well. 12543 * make sure this flag is set for partially installed apps. If not its meaningless to 12544 * delete a partially installed application. 12545 */ 12546 private void removePackageDataLI(PackageSetting ps, 12547 int[] allUserHandles, boolean[] perUserInstalled, 12548 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12549 String packageName = ps.name; 12550 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12551 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12552 // Retrieve object to delete permissions for shared user later on 12553 final PackageSetting deletedPs; 12554 // reader 12555 synchronized (mPackages) { 12556 deletedPs = mSettings.mPackages.get(packageName); 12557 if (outInfo != null) { 12558 outInfo.removedPackage = packageName; 12559 outInfo.removedUsers = deletedPs != null 12560 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12561 : null; 12562 } 12563 } 12564 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12565 removeDataDirsLI(ps.volumeUuid, packageName); 12566 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12567 } 12568 // writer 12569 synchronized (mPackages) { 12570 if (deletedPs != null) { 12571 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12572 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12573 clearDefaultBrowserIfNeeded(packageName); 12574 if (outInfo != null) { 12575 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12576 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12577 } 12578 updatePermissionsLPw(deletedPs.name, null, 0); 12579 if (deletedPs.sharedUser != null) { 12580 // Remove permissions associated with package. Since runtime 12581 // permissions are per user we have to kill the removed package 12582 // or packages running under the shared user of the removed 12583 // package if revoking the permissions requested only by the removed 12584 // package is successful and this causes a change in gids. 12585 for (int userId : UserManagerService.getInstance().getUserIds()) { 12586 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12587 userId); 12588 if (userIdToKill == UserHandle.USER_ALL 12589 || userIdToKill >= UserHandle.USER_OWNER) { 12590 // If gids changed for this user, kill all affected packages. 12591 mHandler.post(new Runnable() { 12592 @Override 12593 public void run() { 12594 // This has to happen with no lock held. 12595 killSettingPackagesForUser(deletedPs, userIdToKill, 12596 KILL_APP_REASON_GIDS_CHANGED); 12597 } 12598 }); 12599 break; 12600 } 12601 } 12602 } 12603 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12604 } 12605 // make sure to preserve per-user disabled state if this removal was just 12606 // a downgrade of a system app to the factory package 12607 if (allUserHandles != null && perUserInstalled != null) { 12608 if (DEBUG_REMOVE) { 12609 Slog.d(TAG, "Propagating install state across downgrade"); 12610 } 12611 for (int i = 0; i < allUserHandles.length; i++) { 12612 if (DEBUG_REMOVE) { 12613 Slog.d(TAG, " user " + allUserHandles[i] 12614 + " => " + perUserInstalled[i]); 12615 } 12616 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12617 } 12618 } 12619 } 12620 // can downgrade to reader 12621 if (writeSettings) { 12622 // Save settings now 12623 mSettings.writeLPr(); 12624 } 12625 } 12626 if (outInfo != null) { 12627 // A user ID was deleted here. Go through all users and remove it 12628 // from KeyStore. 12629 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12630 } 12631 } 12632 12633 static boolean locationIsPrivileged(File path) { 12634 try { 12635 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12636 .getCanonicalPath(); 12637 return path.getCanonicalPath().startsWith(privilegedAppDir); 12638 } catch (IOException e) { 12639 Slog.e(TAG, "Unable to access code path " + path); 12640 } 12641 return false; 12642 } 12643 12644 /* 12645 * Tries to delete system package. 12646 */ 12647 private boolean deleteSystemPackageLI(PackageSetting newPs, 12648 int[] allUserHandles, boolean[] perUserInstalled, 12649 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12650 final boolean applyUserRestrictions 12651 = (allUserHandles != null) && (perUserInstalled != null); 12652 PackageSetting disabledPs = null; 12653 // Confirm if the system package has been updated 12654 // An updated system app can be deleted. This will also have to restore 12655 // the system pkg from system partition 12656 // reader 12657 synchronized (mPackages) { 12658 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12659 } 12660 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12661 + " disabledPs=" + disabledPs); 12662 if (disabledPs == null) { 12663 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12664 return false; 12665 } else if (DEBUG_REMOVE) { 12666 Slog.d(TAG, "Deleting system pkg from data partition"); 12667 } 12668 if (DEBUG_REMOVE) { 12669 if (applyUserRestrictions) { 12670 Slog.d(TAG, "Remembering install states:"); 12671 for (int i = 0; i < allUserHandles.length; i++) { 12672 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12673 } 12674 } 12675 } 12676 // Delete the updated package 12677 outInfo.isRemovedPackageSystemUpdate = true; 12678 if (disabledPs.versionCode < newPs.versionCode) { 12679 // Delete data for downgrades 12680 flags &= ~PackageManager.DELETE_KEEP_DATA; 12681 } else { 12682 // Preserve data by setting flag 12683 flags |= PackageManager.DELETE_KEEP_DATA; 12684 } 12685 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12686 allUserHandles, perUserInstalled, outInfo, writeSettings); 12687 if (!ret) { 12688 return false; 12689 } 12690 // writer 12691 synchronized (mPackages) { 12692 // Reinstate the old system package 12693 mSettings.enableSystemPackageLPw(newPs.name); 12694 // Remove any native libraries from the upgraded package. 12695 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12696 } 12697 // Install the system package 12698 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12699 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12700 if (locationIsPrivileged(disabledPs.codePath)) { 12701 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12702 } 12703 12704 final PackageParser.Package newPkg; 12705 try { 12706 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12707 } catch (PackageManagerException e) { 12708 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12709 return false; 12710 } 12711 12712 // writer 12713 synchronized (mPackages) { 12714 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12715 updatePermissionsLPw(newPkg.packageName, newPkg, 12716 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12717 if (applyUserRestrictions) { 12718 if (DEBUG_REMOVE) { 12719 Slog.d(TAG, "Propagating install state across reinstall"); 12720 } 12721 for (int i = 0; i < allUserHandles.length; i++) { 12722 if (DEBUG_REMOVE) { 12723 Slog.d(TAG, " user " + allUserHandles[i] 12724 + " => " + perUserInstalled[i]); 12725 } 12726 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12727 } 12728 // Regardless of writeSettings we need to ensure that this restriction 12729 // state propagation is persisted 12730 mSettings.writeAllUsersPackageRestrictionsLPr(); 12731 } 12732 // can downgrade to reader here 12733 if (writeSettings) { 12734 mSettings.writeLPr(); 12735 } 12736 } 12737 return true; 12738 } 12739 12740 private boolean deleteInstalledPackageLI(PackageSetting ps, 12741 boolean deleteCodeAndResources, int flags, 12742 int[] allUserHandles, boolean[] perUserInstalled, 12743 PackageRemovedInfo outInfo, boolean writeSettings) { 12744 if (outInfo != null) { 12745 outInfo.uid = ps.appId; 12746 } 12747 12748 // Delete package data from internal structures and also remove data if flag is set 12749 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12750 12751 // Delete application code and resources 12752 if (deleteCodeAndResources && (outInfo != null)) { 12753 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12754 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12755 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12756 } 12757 return true; 12758 } 12759 12760 @Override 12761 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12762 int userId) { 12763 mContext.enforceCallingOrSelfPermission( 12764 android.Manifest.permission.DELETE_PACKAGES, null); 12765 synchronized (mPackages) { 12766 PackageSetting ps = mSettings.mPackages.get(packageName); 12767 if (ps == null) { 12768 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12769 return false; 12770 } 12771 if (!ps.getInstalled(userId)) { 12772 // Can't block uninstall for an app that is not installed or enabled. 12773 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12774 return false; 12775 } 12776 ps.setBlockUninstall(blockUninstall, userId); 12777 mSettings.writePackageRestrictionsLPr(userId); 12778 } 12779 return true; 12780 } 12781 12782 @Override 12783 public boolean getBlockUninstallForUser(String packageName, int userId) { 12784 synchronized (mPackages) { 12785 PackageSetting ps = mSettings.mPackages.get(packageName); 12786 if (ps == null) { 12787 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12788 return false; 12789 } 12790 return ps.getBlockUninstall(userId); 12791 } 12792 } 12793 12794 /* 12795 * This method handles package deletion in general 12796 */ 12797 private boolean deletePackageLI(String packageName, UserHandle user, 12798 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12799 int flags, PackageRemovedInfo outInfo, 12800 boolean writeSettings) { 12801 if (packageName == null) { 12802 Slog.w(TAG, "Attempt to delete null packageName."); 12803 return false; 12804 } 12805 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12806 PackageSetting ps; 12807 boolean dataOnly = false; 12808 int removeUser = -1; 12809 int appId = -1; 12810 synchronized (mPackages) { 12811 ps = mSettings.mPackages.get(packageName); 12812 if (ps == null) { 12813 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12814 return false; 12815 } 12816 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12817 && user.getIdentifier() != UserHandle.USER_ALL) { 12818 // The caller is asking that the package only be deleted for a single 12819 // user. To do this, we just mark its uninstalled state and delete 12820 // its data. If this is a system app, we only allow this to happen if 12821 // they have set the special DELETE_SYSTEM_APP which requests different 12822 // semantics than normal for uninstalling system apps. 12823 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12824 ps.setUserState(user.getIdentifier(), 12825 COMPONENT_ENABLED_STATE_DEFAULT, 12826 false, //installed 12827 true, //stopped 12828 true, //notLaunched 12829 false, //hidden 12830 null, null, null, 12831 false, // blockUninstall 12832 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12833 if (!isSystemApp(ps)) { 12834 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12835 // Other user still have this package installed, so all 12836 // we need to do is clear this user's data and save that 12837 // it is uninstalled. 12838 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12839 removeUser = user.getIdentifier(); 12840 appId = ps.appId; 12841 scheduleWritePackageRestrictionsLocked(removeUser); 12842 } else { 12843 // We need to set it back to 'installed' so the uninstall 12844 // broadcasts will be sent correctly. 12845 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12846 ps.setInstalled(true, user.getIdentifier()); 12847 } 12848 } else { 12849 // This is a system app, so we assume that the 12850 // other users still have this package installed, so all 12851 // we need to do is clear this user's data and save that 12852 // it is uninstalled. 12853 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12854 removeUser = user.getIdentifier(); 12855 appId = ps.appId; 12856 scheduleWritePackageRestrictionsLocked(removeUser); 12857 } 12858 } 12859 } 12860 12861 if (removeUser >= 0) { 12862 // From above, we determined that we are deleting this only 12863 // for a single user. Continue the work here. 12864 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12865 if (outInfo != null) { 12866 outInfo.removedPackage = packageName; 12867 outInfo.removedAppId = appId; 12868 outInfo.removedUsers = new int[] {removeUser}; 12869 } 12870 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12871 removeKeystoreDataIfNeeded(removeUser, appId); 12872 schedulePackageCleaning(packageName, removeUser, false); 12873 synchronized (mPackages) { 12874 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12875 scheduleWritePackageRestrictionsLocked(removeUser); 12876 } 12877 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12878 removeUser); 12879 } 12880 return true; 12881 } 12882 12883 if (dataOnly) { 12884 // Delete application data first 12885 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12886 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12887 return true; 12888 } 12889 12890 boolean ret = false; 12891 if (isSystemApp(ps)) { 12892 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12893 // When an updated system application is deleted we delete the existing resources as well and 12894 // fall back to existing code in system partition 12895 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12896 flags, outInfo, writeSettings); 12897 } else { 12898 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12899 // Kill application pre-emptively especially for apps on sd. 12900 killApplication(packageName, ps.appId, "uninstall pkg"); 12901 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12902 allUserHandles, perUserInstalled, 12903 outInfo, writeSettings); 12904 } 12905 12906 return ret; 12907 } 12908 12909 private final class ClearStorageConnection implements ServiceConnection { 12910 IMediaContainerService mContainerService; 12911 12912 @Override 12913 public void onServiceConnected(ComponentName name, IBinder service) { 12914 synchronized (this) { 12915 mContainerService = IMediaContainerService.Stub.asInterface(service); 12916 notifyAll(); 12917 } 12918 } 12919 12920 @Override 12921 public void onServiceDisconnected(ComponentName name) { 12922 } 12923 } 12924 12925 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12926 final boolean mounted; 12927 if (Environment.isExternalStorageEmulated()) { 12928 mounted = true; 12929 } else { 12930 final String status = Environment.getExternalStorageState(); 12931 12932 mounted = status.equals(Environment.MEDIA_MOUNTED) 12933 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12934 } 12935 12936 if (!mounted) { 12937 return; 12938 } 12939 12940 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12941 int[] users; 12942 if (userId == UserHandle.USER_ALL) { 12943 users = sUserManager.getUserIds(); 12944 } else { 12945 users = new int[] { userId }; 12946 } 12947 final ClearStorageConnection conn = new ClearStorageConnection(); 12948 if (mContext.bindServiceAsUser( 12949 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12950 try { 12951 for (int curUser : users) { 12952 long timeout = SystemClock.uptimeMillis() + 5000; 12953 synchronized (conn) { 12954 long now = SystemClock.uptimeMillis(); 12955 while (conn.mContainerService == null && now < timeout) { 12956 try { 12957 conn.wait(timeout - now); 12958 } catch (InterruptedException e) { 12959 } 12960 } 12961 } 12962 if (conn.mContainerService == null) { 12963 return; 12964 } 12965 12966 final UserEnvironment userEnv = new UserEnvironment(curUser); 12967 clearDirectory(conn.mContainerService, 12968 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12969 if (allData) { 12970 clearDirectory(conn.mContainerService, 12971 userEnv.buildExternalStorageAppDataDirs(packageName)); 12972 clearDirectory(conn.mContainerService, 12973 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12974 } 12975 } 12976 } finally { 12977 mContext.unbindService(conn); 12978 } 12979 } 12980 } 12981 12982 @Override 12983 public void clearApplicationUserData(final String packageName, 12984 final IPackageDataObserver observer, final int userId) { 12985 mContext.enforceCallingOrSelfPermission( 12986 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12987 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12988 // Queue up an async operation since the package deletion may take a little while. 12989 mHandler.post(new Runnable() { 12990 public void run() { 12991 mHandler.removeCallbacks(this); 12992 final boolean succeeded; 12993 synchronized (mInstallLock) { 12994 succeeded = clearApplicationUserDataLI(packageName, userId); 12995 } 12996 clearExternalStorageDataSync(packageName, userId, true); 12997 if (succeeded) { 12998 // invoke DeviceStorageMonitor's update method to clear any notifications 12999 DeviceStorageMonitorInternal 13000 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13001 if (dsm != null) { 13002 dsm.checkMemory(); 13003 } 13004 } 13005 if(observer != null) { 13006 try { 13007 observer.onRemoveCompleted(packageName, succeeded); 13008 } catch (RemoteException e) { 13009 Log.i(TAG, "Observer no longer exists."); 13010 } 13011 } //end if observer 13012 } //end run 13013 }); 13014 } 13015 13016 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13017 if (packageName == null) { 13018 Slog.w(TAG, "Attempt to delete null packageName."); 13019 return false; 13020 } 13021 13022 // Try finding details about the requested package 13023 PackageParser.Package pkg; 13024 synchronized (mPackages) { 13025 pkg = mPackages.get(packageName); 13026 if (pkg == null) { 13027 final PackageSetting ps = mSettings.mPackages.get(packageName); 13028 if (ps != null) { 13029 pkg = ps.pkg; 13030 } 13031 } 13032 13033 if (pkg == null) { 13034 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13035 return false; 13036 } 13037 13038 PackageSetting ps = (PackageSetting) pkg.mExtras; 13039 PermissionsState permissionsState = ps.getPermissionsState(); 13040 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 13041 } 13042 13043 // Always delete data directories for package, even if we found no other 13044 // record of app. This helps users recover from UID mismatches without 13045 // resorting to a full data wipe. 13046 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13047 if (retCode < 0) { 13048 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13049 return false; 13050 } 13051 13052 final int appId = pkg.applicationInfo.uid; 13053 removeKeystoreDataIfNeeded(userId, appId); 13054 13055 // Create a native library symlink only if we have native libraries 13056 // and if the native libraries are 32 bit libraries. We do not provide 13057 // this symlink for 64 bit libraries. 13058 if (pkg.applicationInfo.primaryCpuAbi != null && 13059 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13060 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13061 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13062 nativeLibPath, userId) < 0) { 13063 Slog.w(TAG, "Failed linking native library dir"); 13064 return false; 13065 } 13066 } 13067 13068 return true; 13069 } 13070 13071 13072 /** 13073 * Revokes granted runtime permissions and clears resettable flags 13074 * which are flags that can be set by a user interaction. 13075 * 13076 * @param permissionsState The permission state to reset. 13077 * @param userId The device user for which to do a reset. 13078 */ 13079 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 13080 PermissionsState permissionsState, int userId) { 13081 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 13082 | PackageManager.FLAG_PERMISSION_USER_FIXED 13083 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13084 13085 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 13086 } 13087 13088 /** 13089 * Revokes granted runtime permissions and clears all flags. 13090 * 13091 * @param permissionsState The permission state to reset. 13092 * @param userId The device user for which to do a reset. 13093 */ 13094 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 13095 PermissionsState permissionsState, int userId) { 13096 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 13097 PackageManager.MASK_PERMISSION_FLAGS); 13098 } 13099 13100 /** 13101 * Revokes granted runtime permissions and clears certain flags. 13102 * 13103 * @param permissionsState The permission state to reset. 13104 * @param userId The device user for which to do a reset. 13105 * @param flags The flags that is going to be reset. 13106 */ 13107 private void revokeRuntimePermissionsAndClearFlagsLocked( 13108 PermissionsState permissionsState, final int userId, int flags) { 13109 boolean needsWrite = false; 13110 13111 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 13112 BasePermission bp = mSettings.mPermissions.get(state.getName()); 13113 if (bp != null) { 13114 permissionsState.revokeRuntimePermission(bp, userId); 13115 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 13116 needsWrite = true; 13117 } 13118 } 13119 13120 // Ensure default permissions are never cleared. 13121 mHandler.post(new Runnable() { 13122 @Override 13123 public void run() { 13124 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13125 } 13126 }); 13127 13128 if (needsWrite) { 13129 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13130 } 13131 } 13132 13133 /** 13134 * Remove entries from the keystore daemon. Will only remove it if the 13135 * {@code appId} is valid. 13136 */ 13137 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13138 if (appId < 0) { 13139 return; 13140 } 13141 13142 final KeyStore keyStore = KeyStore.getInstance(); 13143 if (keyStore != null) { 13144 if (userId == UserHandle.USER_ALL) { 13145 for (final int individual : sUserManager.getUserIds()) { 13146 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13147 } 13148 } else { 13149 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13150 } 13151 } else { 13152 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13153 } 13154 } 13155 13156 @Override 13157 public void deleteApplicationCacheFiles(final String packageName, 13158 final IPackageDataObserver observer) { 13159 mContext.enforceCallingOrSelfPermission( 13160 android.Manifest.permission.DELETE_CACHE_FILES, null); 13161 // Queue up an async operation since the package deletion may take a little while. 13162 final int userId = UserHandle.getCallingUserId(); 13163 mHandler.post(new Runnable() { 13164 public void run() { 13165 mHandler.removeCallbacks(this); 13166 final boolean succeded; 13167 synchronized (mInstallLock) { 13168 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13169 } 13170 clearExternalStorageDataSync(packageName, userId, false); 13171 if (observer != null) { 13172 try { 13173 observer.onRemoveCompleted(packageName, succeded); 13174 } catch (RemoteException e) { 13175 Log.i(TAG, "Observer no longer exists."); 13176 } 13177 } //end if observer 13178 } //end run 13179 }); 13180 } 13181 13182 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13183 if (packageName == null) { 13184 Slog.w(TAG, "Attempt to delete null packageName."); 13185 return false; 13186 } 13187 PackageParser.Package p; 13188 synchronized (mPackages) { 13189 p = mPackages.get(packageName); 13190 } 13191 if (p == null) { 13192 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13193 return false; 13194 } 13195 final ApplicationInfo applicationInfo = p.applicationInfo; 13196 if (applicationInfo == null) { 13197 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13198 return false; 13199 } 13200 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13201 if (retCode < 0) { 13202 Slog.w(TAG, "Couldn't remove cache files for package: " 13203 + packageName + " u" + userId); 13204 return false; 13205 } 13206 return true; 13207 } 13208 13209 @Override 13210 public void getPackageSizeInfo(final String packageName, int userHandle, 13211 final IPackageStatsObserver observer) { 13212 mContext.enforceCallingOrSelfPermission( 13213 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13214 if (packageName == null) { 13215 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13216 } 13217 13218 PackageStats stats = new PackageStats(packageName, userHandle); 13219 13220 /* 13221 * Queue up an async operation since the package measurement may take a 13222 * little while. 13223 */ 13224 Message msg = mHandler.obtainMessage(INIT_COPY); 13225 msg.obj = new MeasureParams(stats, observer); 13226 mHandler.sendMessage(msg); 13227 } 13228 13229 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13230 PackageStats pStats) { 13231 if (packageName == null) { 13232 Slog.w(TAG, "Attempt to get size of null packageName."); 13233 return false; 13234 } 13235 PackageParser.Package p; 13236 boolean dataOnly = false; 13237 String libDirRoot = null; 13238 String asecPath = null; 13239 PackageSetting ps = null; 13240 synchronized (mPackages) { 13241 p = mPackages.get(packageName); 13242 ps = mSettings.mPackages.get(packageName); 13243 if(p == null) { 13244 dataOnly = true; 13245 if((ps == null) || (ps.pkg == null)) { 13246 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13247 return false; 13248 } 13249 p = ps.pkg; 13250 } 13251 if (ps != null) { 13252 libDirRoot = ps.legacyNativeLibraryPathString; 13253 } 13254 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13255 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13256 if (secureContainerId != null) { 13257 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13258 } 13259 } 13260 } 13261 String publicSrcDir = null; 13262 if(!dataOnly) { 13263 final ApplicationInfo applicationInfo = p.applicationInfo; 13264 if (applicationInfo == null) { 13265 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13266 return false; 13267 } 13268 if (p.isForwardLocked()) { 13269 publicSrcDir = applicationInfo.getBaseResourcePath(); 13270 } 13271 } 13272 // TODO: extend to measure size of split APKs 13273 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13274 // not just the first level. 13275 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13276 // just the primary. 13277 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13278 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13279 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13280 if (res < 0) { 13281 return false; 13282 } 13283 13284 // Fix-up for forward-locked applications in ASEC containers. 13285 if (!isExternal(p)) { 13286 pStats.codeSize += pStats.externalCodeSize; 13287 pStats.externalCodeSize = 0L; 13288 } 13289 13290 return true; 13291 } 13292 13293 13294 @Override 13295 public void addPackageToPreferred(String packageName) { 13296 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13297 } 13298 13299 @Override 13300 public void removePackageFromPreferred(String packageName) { 13301 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13302 } 13303 13304 @Override 13305 public List<PackageInfo> getPreferredPackages(int flags) { 13306 return new ArrayList<PackageInfo>(); 13307 } 13308 13309 private int getUidTargetSdkVersionLockedLPr(int uid) { 13310 Object obj = mSettings.getUserIdLPr(uid); 13311 if (obj instanceof SharedUserSetting) { 13312 final SharedUserSetting sus = (SharedUserSetting) obj; 13313 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13314 final Iterator<PackageSetting> it = sus.packages.iterator(); 13315 while (it.hasNext()) { 13316 final PackageSetting ps = it.next(); 13317 if (ps.pkg != null) { 13318 int v = ps.pkg.applicationInfo.targetSdkVersion; 13319 if (v < vers) vers = v; 13320 } 13321 } 13322 return vers; 13323 } else if (obj instanceof PackageSetting) { 13324 final PackageSetting ps = (PackageSetting) obj; 13325 if (ps.pkg != null) { 13326 return ps.pkg.applicationInfo.targetSdkVersion; 13327 } 13328 } 13329 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13330 } 13331 13332 @Override 13333 public void addPreferredActivity(IntentFilter filter, int match, 13334 ComponentName[] set, ComponentName activity, int userId) { 13335 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13336 "Adding preferred"); 13337 } 13338 13339 private void addPreferredActivityInternal(IntentFilter filter, int match, 13340 ComponentName[] set, ComponentName activity, boolean always, int userId, 13341 String opname) { 13342 // writer 13343 int callingUid = Binder.getCallingUid(); 13344 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13345 if (filter.countActions() == 0) { 13346 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13347 return; 13348 } 13349 synchronized (mPackages) { 13350 if (mContext.checkCallingOrSelfPermission( 13351 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13352 != PackageManager.PERMISSION_GRANTED) { 13353 if (getUidTargetSdkVersionLockedLPr(callingUid) 13354 < Build.VERSION_CODES.FROYO) { 13355 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13356 + callingUid); 13357 return; 13358 } 13359 mContext.enforceCallingOrSelfPermission( 13360 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13361 } 13362 13363 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13364 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13365 + userId + ":"); 13366 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13367 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13368 scheduleWritePackageRestrictionsLocked(userId); 13369 } 13370 } 13371 13372 @Override 13373 public void replacePreferredActivity(IntentFilter filter, int match, 13374 ComponentName[] set, ComponentName activity, int userId) { 13375 if (filter.countActions() != 1) { 13376 throw new IllegalArgumentException( 13377 "replacePreferredActivity expects filter to have only 1 action."); 13378 } 13379 if (filter.countDataAuthorities() != 0 13380 || filter.countDataPaths() != 0 13381 || filter.countDataSchemes() > 1 13382 || filter.countDataTypes() != 0) { 13383 throw new IllegalArgumentException( 13384 "replacePreferredActivity expects filter to have no data authorities, " + 13385 "paths, or types; and at most one scheme."); 13386 } 13387 13388 final int callingUid = Binder.getCallingUid(); 13389 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13390 synchronized (mPackages) { 13391 if (mContext.checkCallingOrSelfPermission( 13392 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13393 != PackageManager.PERMISSION_GRANTED) { 13394 if (getUidTargetSdkVersionLockedLPr(callingUid) 13395 < Build.VERSION_CODES.FROYO) { 13396 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13397 + Binder.getCallingUid()); 13398 return; 13399 } 13400 mContext.enforceCallingOrSelfPermission( 13401 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13402 } 13403 13404 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13405 if (pir != null) { 13406 // Get all of the existing entries that exactly match this filter. 13407 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13408 if (existing != null && existing.size() == 1) { 13409 PreferredActivity cur = existing.get(0); 13410 if (DEBUG_PREFERRED) { 13411 Slog.i(TAG, "Checking replace of preferred:"); 13412 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13413 if (!cur.mPref.mAlways) { 13414 Slog.i(TAG, " -- CUR; not mAlways!"); 13415 } else { 13416 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13417 Slog.i(TAG, " -- CUR: mSet=" 13418 + Arrays.toString(cur.mPref.mSetComponents)); 13419 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13420 Slog.i(TAG, " -- NEW: mMatch=" 13421 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13422 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13423 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13424 } 13425 } 13426 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13427 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13428 && cur.mPref.sameSet(set)) { 13429 // Setting the preferred activity to what it happens to be already 13430 if (DEBUG_PREFERRED) { 13431 Slog.i(TAG, "Replacing with same preferred activity " 13432 + cur.mPref.mShortComponent + " for user " 13433 + userId + ":"); 13434 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13435 } 13436 return; 13437 } 13438 } 13439 13440 if (existing != null) { 13441 if (DEBUG_PREFERRED) { 13442 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13443 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13444 } 13445 for (int i = 0; i < existing.size(); i++) { 13446 PreferredActivity pa = existing.get(i); 13447 if (DEBUG_PREFERRED) { 13448 Slog.i(TAG, "Removing existing preferred activity " 13449 + pa.mPref.mComponent + ":"); 13450 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13451 } 13452 pir.removeFilter(pa); 13453 } 13454 } 13455 } 13456 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13457 "Replacing preferred"); 13458 } 13459 } 13460 13461 @Override 13462 public void clearPackagePreferredActivities(String packageName) { 13463 final int uid = Binder.getCallingUid(); 13464 // writer 13465 synchronized (mPackages) { 13466 PackageParser.Package pkg = mPackages.get(packageName); 13467 if (pkg == null || pkg.applicationInfo.uid != uid) { 13468 if (mContext.checkCallingOrSelfPermission( 13469 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13470 != PackageManager.PERMISSION_GRANTED) { 13471 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13472 < Build.VERSION_CODES.FROYO) { 13473 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13474 + Binder.getCallingUid()); 13475 return; 13476 } 13477 mContext.enforceCallingOrSelfPermission( 13478 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13479 } 13480 } 13481 13482 int user = UserHandle.getCallingUserId(); 13483 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13484 scheduleWritePackageRestrictionsLocked(user); 13485 } 13486 } 13487 } 13488 13489 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13490 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13491 ArrayList<PreferredActivity> removed = null; 13492 boolean changed = false; 13493 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13494 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13495 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13496 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13497 continue; 13498 } 13499 Iterator<PreferredActivity> it = pir.filterIterator(); 13500 while (it.hasNext()) { 13501 PreferredActivity pa = it.next(); 13502 // Mark entry for removal only if it matches the package name 13503 // and the entry is of type "always". 13504 if (packageName == null || 13505 (pa.mPref.mComponent.getPackageName().equals(packageName) 13506 && pa.mPref.mAlways)) { 13507 if (removed == null) { 13508 removed = new ArrayList<PreferredActivity>(); 13509 } 13510 removed.add(pa); 13511 } 13512 } 13513 if (removed != null) { 13514 for (int j=0; j<removed.size(); j++) { 13515 PreferredActivity pa = removed.get(j); 13516 pir.removeFilter(pa); 13517 } 13518 changed = true; 13519 } 13520 } 13521 return changed; 13522 } 13523 13524 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13525 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13526 if (userId == UserHandle.USER_ALL) { 13527 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13528 sUserManager.getUserIds())) { 13529 for (int oneUserId : sUserManager.getUserIds()) { 13530 scheduleWritePackageRestrictionsLocked(oneUserId); 13531 } 13532 } 13533 } else { 13534 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13535 scheduleWritePackageRestrictionsLocked(userId); 13536 } 13537 } 13538 } 13539 13540 13541 void clearDefaultBrowserIfNeeded(String packageName) { 13542 for (int oneUserId : sUserManager.getUserIds()) { 13543 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13544 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13545 if (packageName.equals(defaultBrowserPackageName)) { 13546 setDefaultBrowserPackageName(null, oneUserId); 13547 } 13548 } 13549 } 13550 13551 @Override 13552 public void resetPreferredActivities(int userId) { 13553 mContext.enforceCallingOrSelfPermission( 13554 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13555 // writer 13556 synchronized (mPackages) { 13557 clearPackagePreferredActivitiesLPw(null, userId); 13558 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13559 applyFactoryDefaultBrowserLPw(userId); 13560 13561 scheduleWritePackageRestrictionsLocked(userId); 13562 } 13563 } 13564 13565 @Override 13566 public int getPreferredActivities(List<IntentFilter> outFilters, 13567 List<ComponentName> outActivities, String packageName) { 13568 13569 int num = 0; 13570 final int userId = UserHandle.getCallingUserId(); 13571 // reader 13572 synchronized (mPackages) { 13573 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13574 if (pir != null) { 13575 final Iterator<PreferredActivity> it = pir.filterIterator(); 13576 while (it.hasNext()) { 13577 final PreferredActivity pa = it.next(); 13578 if (packageName == null 13579 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13580 && pa.mPref.mAlways)) { 13581 if (outFilters != null) { 13582 outFilters.add(new IntentFilter(pa)); 13583 } 13584 if (outActivities != null) { 13585 outActivities.add(pa.mPref.mComponent); 13586 } 13587 } 13588 } 13589 } 13590 } 13591 13592 return num; 13593 } 13594 13595 @Override 13596 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13597 int userId) { 13598 int callingUid = Binder.getCallingUid(); 13599 if (callingUid != Process.SYSTEM_UID) { 13600 throw new SecurityException( 13601 "addPersistentPreferredActivity can only be run by the system"); 13602 } 13603 if (filter.countActions() == 0) { 13604 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13605 return; 13606 } 13607 synchronized (mPackages) { 13608 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13609 " :"); 13610 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13611 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13612 new PersistentPreferredActivity(filter, activity)); 13613 scheduleWritePackageRestrictionsLocked(userId); 13614 } 13615 } 13616 13617 @Override 13618 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13619 int callingUid = Binder.getCallingUid(); 13620 if (callingUid != Process.SYSTEM_UID) { 13621 throw new SecurityException( 13622 "clearPackagePersistentPreferredActivities can only be run by the system"); 13623 } 13624 ArrayList<PersistentPreferredActivity> removed = null; 13625 boolean changed = false; 13626 synchronized (mPackages) { 13627 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13628 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13629 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13630 .valueAt(i); 13631 if (userId != thisUserId) { 13632 continue; 13633 } 13634 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13635 while (it.hasNext()) { 13636 PersistentPreferredActivity ppa = it.next(); 13637 // Mark entry for removal only if it matches the package name. 13638 if (ppa.mComponent.getPackageName().equals(packageName)) { 13639 if (removed == null) { 13640 removed = new ArrayList<PersistentPreferredActivity>(); 13641 } 13642 removed.add(ppa); 13643 } 13644 } 13645 if (removed != null) { 13646 for (int j=0; j<removed.size(); j++) { 13647 PersistentPreferredActivity ppa = removed.get(j); 13648 ppir.removeFilter(ppa); 13649 } 13650 changed = true; 13651 } 13652 } 13653 13654 if (changed) { 13655 scheduleWritePackageRestrictionsLocked(userId); 13656 } 13657 } 13658 } 13659 13660 /** 13661 * Common machinery for picking apart a restored XML blob and passing 13662 * it to a caller-supplied functor to be applied to the running system. 13663 */ 13664 private void restoreFromXml(XmlPullParser parser, int userId, 13665 String expectedStartTag, BlobXmlRestorer functor) 13666 throws IOException, XmlPullParserException { 13667 int type; 13668 while ((type = parser.next()) != XmlPullParser.START_TAG 13669 && type != XmlPullParser.END_DOCUMENT) { 13670 } 13671 if (type != XmlPullParser.START_TAG) { 13672 // oops didn't find a start tag?! 13673 if (DEBUG_BACKUP) { 13674 Slog.e(TAG, "Didn't find start tag during restore"); 13675 } 13676 return; 13677 } 13678 13679 // this is supposed to be TAG_PREFERRED_BACKUP 13680 if (!expectedStartTag.equals(parser.getName())) { 13681 if (DEBUG_BACKUP) { 13682 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13683 } 13684 return; 13685 } 13686 13687 // skip interfering stuff, then we're aligned with the backing implementation 13688 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13689 functor.apply(parser, userId); 13690 } 13691 13692 private interface BlobXmlRestorer { 13693 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13694 } 13695 13696 /** 13697 * Non-Binder method, support for the backup/restore mechanism: write the 13698 * full set of preferred activities in its canonical XML format. Returns the 13699 * XML output as a byte array, or null if there is none. 13700 */ 13701 @Override 13702 public byte[] getPreferredActivityBackup(int userId) { 13703 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13704 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13705 } 13706 13707 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13708 try { 13709 final XmlSerializer serializer = new FastXmlSerializer(); 13710 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13711 serializer.startDocument(null, true); 13712 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13713 13714 synchronized (mPackages) { 13715 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13716 } 13717 13718 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13719 serializer.endDocument(); 13720 serializer.flush(); 13721 } catch (Exception e) { 13722 if (DEBUG_BACKUP) { 13723 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13724 } 13725 return null; 13726 } 13727 13728 return dataStream.toByteArray(); 13729 } 13730 13731 @Override 13732 public void restorePreferredActivities(byte[] backup, int userId) { 13733 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13734 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13735 } 13736 13737 try { 13738 final XmlPullParser parser = Xml.newPullParser(); 13739 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13740 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13741 new BlobXmlRestorer() { 13742 @Override 13743 public void apply(XmlPullParser parser, int userId) 13744 throws XmlPullParserException, IOException { 13745 synchronized (mPackages) { 13746 mSettings.readPreferredActivitiesLPw(parser, userId); 13747 } 13748 } 13749 } ); 13750 } catch (Exception e) { 13751 if (DEBUG_BACKUP) { 13752 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13753 } 13754 } 13755 } 13756 13757 /** 13758 * Non-Binder method, support for the backup/restore mechanism: write the 13759 * default browser (etc) settings in its canonical XML format. Returns the default 13760 * browser XML representation as a byte array, or null if there is none. 13761 */ 13762 @Override 13763 public byte[] getDefaultAppsBackup(int userId) { 13764 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13765 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13766 } 13767 13768 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13769 try { 13770 final XmlSerializer serializer = new FastXmlSerializer(); 13771 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13772 serializer.startDocument(null, true); 13773 serializer.startTag(null, TAG_DEFAULT_APPS); 13774 13775 synchronized (mPackages) { 13776 mSettings.writeDefaultAppsLPr(serializer, userId); 13777 } 13778 13779 serializer.endTag(null, TAG_DEFAULT_APPS); 13780 serializer.endDocument(); 13781 serializer.flush(); 13782 } catch (Exception e) { 13783 if (DEBUG_BACKUP) { 13784 Slog.e(TAG, "Unable to write default apps for backup", e); 13785 } 13786 return null; 13787 } 13788 13789 return dataStream.toByteArray(); 13790 } 13791 13792 @Override 13793 public void restoreDefaultApps(byte[] backup, int userId) { 13794 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13795 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13796 } 13797 13798 try { 13799 final XmlPullParser parser = Xml.newPullParser(); 13800 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13801 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13802 new BlobXmlRestorer() { 13803 @Override 13804 public void apply(XmlPullParser parser, int userId) 13805 throws XmlPullParserException, IOException { 13806 synchronized (mPackages) { 13807 mSettings.readDefaultAppsLPw(parser, userId); 13808 } 13809 } 13810 } ); 13811 } catch (Exception e) { 13812 if (DEBUG_BACKUP) { 13813 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13814 } 13815 } 13816 } 13817 13818 @Override 13819 public byte[] getIntentFilterVerificationBackup(int userId) { 13820 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13821 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13822 } 13823 13824 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13825 try { 13826 final XmlSerializer serializer = new FastXmlSerializer(); 13827 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13828 serializer.startDocument(null, true); 13829 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13830 13831 synchronized (mPackages) { 13832 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13833 } 13834 13835 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13836 serializer.endDocument(); 13837 serializer.flush(); 13838 } catch (Exception e) { 13839 if (DEBUG_BACKUP) { 13840 Slog.e(TAG, "Unable to write default apps for backup", e); 13841 } 13842 return null; 13843 } 13844 13845 return dataStream.toByteArray(); 13846 } 13847 13848 @Override 13849 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13850 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13851 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13852 } 13853 13854 try { 13855 final XmlPullParser parser = Xml.newPullParser(); 13856 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13857 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13858 new BlobXmlRestorer() { 13859 @Override 13860 public void apply(XmlPullParser parser, int userId) 13861 throws XmlPullParserException, IOException { 13862 synchronized (mPackages) { 13863 mSettings.readAllDomainVerificationsLPr(parser, userId); 13864 mSettings.writeLPr(); 13865 } 13866 } 13867 } ); 13868 } catch (Exception e) { 13869 if (DEBUG_BACKUP) { 13870 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13871 } 13872 } 13873 } 13874 13875 @Override 13876 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13877 int sourceUserId, int targetUserId, int flags) { 13878 mContext.enforceCallingOrSelfPermission( 13879 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13880 int callingUid = Binder.getCallingUid(); 13881 enforceOwnerRights(ownerPackage, callingUid); 13882 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13883 if (intentFilter.countActions() == 0) { 13884 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13885 return; 13886 } 13887 synchronized (mPackages) { 13888 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13889 ownerPackage, targetUserId, flags); 13890 CrossProfileIntentResolver resolver = 13891 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13892 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13893 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13894 if (existing != null) { 13895 int size = existing.size(); 13896 for (int i = 0; i < size; i++) { 13897 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13898 return; 13899 } 13900 } 13901 } 13902 resolver.addFilter(newFilter); 13903 scheduleWritePackageRestrictionsLocked(sourceUserId); 13904 } 13905 } 13906 13907 @Override 13908 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13909 mContext.enforceCallingOrSelfPermission( 13910 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13911 int callingUid = Binder.getCallingUid(); 13912 enforceOwnerRights(ownerPackage, callingUid); 13913 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13914 synchronized (mPackages) { 13915 CrossProfileIntentResolver resolver = 13916 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13917 ArraySet<CrossProfileIntentFilter> set = 13918 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13919 for (CrossProfileIntentFilter filter : set) { 13920 if (filter.getOwnerPackage().equals(ownerPackage)) { 13921 resolver.removeFilter(filter); 13922 } 13923 } 13924 scheduleWritePackageRestrictionsLocked(sourceUserId); 13925 } 13926 } 13927 13928 // Enforcing that callingUid is owning pkg on userId 13929 private void enforceOwnerRights(String pkg, int callingUid) { 13930 // The system owns everything. 13931 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13932 return; 13933 } 13934 int callingUserId = UserHandle.getUserId(callingUid); 13935 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13936 if (pi == null) { 13937 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13938 + callingUserId); 13939 } 13940 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13941 throw new SecurityException("Calling uid " + callingUid 13942 + " does not own package " + pkg); 13943 } 13944 } 13945 13946 @Override 13947 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13948 Intent intent = new Intent(Intent.ACTION_MAIN); 13949 intent.addCategory(Intent.CATEGORY_HOME); 13950 13951 final int callingUserId = UserHandle.getCallingUserId(); 13952 List<ResolveInfo> list = queryIntentActivities(intent, null, 13953 PackageManager.GET_META_DATA, callingUserId); 13954 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13955 true, false, false, callingUserId); 13956 13957 allHomeCandidates.clear(); 13958 if (list != null) { 13959 for (ResolveInfo ri : list) { 13960 allHomeCandidates.add(ri); 13961 } 13962 } 13963 return (preferred == null || preferred.activityInfo == null) 13964 ? null 13965 : new ComponentName(preferred.activityInfo.packageName, 13966 preferred.activityInfo.name); 13967 } 13968 13969 @Override 13970 public void setApplicationEnabledSetting(String appPackageName, 13971 int newState, int flags, int userId, String callingPackage) { 13972 if (!sUserManager.exists(userId)) return; 13973 if (callingPackage == null) { 13974 callingPackage = Integer.toString(Binder.getCallingUid()); 13975 } 13976 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13977 } 13978 13979 @Override 13980 public void setComponentEnabledSetting(ComponentName componentName, 13981 int newState, int flags, int userId) { 13982 if (!sUserManager.exists(userId)) return; 13983 setEnabledSetting(componentName.getPackageName(), 13984 componentName.getClassName(), newState, flags, userId, null); 13985 } 13986 13987 private void setEnabledSetting(final String packageName, String className, int newState, 13988 final int flags, int userId, String callingPackage) { 13989 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13990 || newState == COMPONENT_ENABLED_STATE_ENABLED 13991 || newState == COMPONENT_ENABLED_STATE_DISABLED 13992 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13993 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13994 throw new IllegalArgumentException("Invalid new component state: " 13995 + newState); 13996 } 13997 PackageSetting pkgSetting; 13998 final int uid = Binder.getCallingUid(); 13999 final int permission = mContext.checkCallingOrSelfPermission( 14000 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14001 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14002 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14003 boolean sendNow = false; 14004 boolean isApp = (className == null); 14005 String componentName = isApp ? packageName : className; 14006 int packageUid = -1; 14007 ArrayList<String> components; 14008 14009 // writer 14010 synchronized (mPackages) { 14011 pkgSetting = mSettings.mPackages.get(packageName); 14012 if (pkgSetting == null) { 14013 if (className == null) { 14014 throw new IllegalArgumentException( 14015 "Unknown package: " + packageName); 14016 } 14017 throw new IllegalArgumentException( 14018 "Unknown component: " + packageName 14019 + "/" + className); 14020 } 14021 // Allow root and verify that userId is not being specified by a different user 14022 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14023 throw new SecurityException( 14024 "Permission Denial: attempt to change component state from pid=" 14025 + Binder.getCallingPid() 14026 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14027 } 14028 if (className == null) { 14029 // We're dealing with an application/package level state change 14030 if (pkgSetting.getEnabled(userId) == newState) { 14031 // Nothing to do 14032 return; 14033 } 14034 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14035 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14036 // Don't care about who enables an app. 14037 callingPackage = null; 14038 } 14039 pkgSetting.setEnabled(newState, userId, callingPackage); 14040 // pkgSetting.pkg.mSetEnabled = newState; 14041 } else { 14042 // We're dealing with a component level state change 14043 // First, verify that this is a valid class name. 14044 PackageParser.Package pkg = pkgSetting.pkg; 14045 if (pkg == null || !pkg.hasComponentClassName(className)) { 14046 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14047 throw new IllegalArgumentException("Component class " + className 14048 + " does not exist in " + packageName); 14049 } else { 14050 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14051 + className + " does not exist in " + packageName); 14052 } 14053 } 14054 switch (newState) { 14055 case COMPONENT_ENABLED_STATE_ENABLED: 14056 if (!pkgSetting.enableComponentLPw(className, userId)) { 14057 return; 14058 } 14059 break; 14060 case COMPONENT_ENABLED_STATE_DISABLED: 14061 if (!pkgSetting.disableComponentLPw(className, userId)) { 14062 return; 14063 } 14064 break; 14065 case COMPONENT_ENABLED_STATE_DEFAULT: 14066 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14067 return; 14068 } 14069 break; 14070 default: 14071 Slog.e(TAG, "Invalid new component state: " + newState); 14072 return; 14073 } 14074 } 14075 scheduleWritePackageRestrictionsLocked(userId); 14076 components = mPendingBroadcasts.get(userId, packageName); 14077 final boolean newPackage = components == null; 14078 if (newPackage) { 14079 components = new ArrayList<String>(); 14080 } 14081 if (!components.contains(componentName)) { 14082 components.add(componentName); 14083 } 14084 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14085 sendNow = true; 14086 // Purge entry from pending broadcast list if another one exists already 14087 // since we are sending one right away. 14088 mPendingBroadcasts.remove(userId, packageName); 14089 } else { 14090 if (newPackage) { 14091 mPendingBroadcasts.put(userId, packageName, components); 14092 } 14093 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14094 // Schedule a message 14095 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14096 } 14097 } 14098 } 14099 14100 long callingId = Binder.clearCallingIdentity(); 14101 try { 14102 if (sendNow) { 14103 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14104 sendPackageChangedBroadcast(packageName, 14105 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14106 } 14107 } finally { 14108 Binder.restoreCallingIdentity(callingId); 14109 } 14110 } 14111 14112 private void sendPackageChangedBroadcast(String packageName, 14113 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14114 if (DEBUG_INSTALL) 14115 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14116 + componentNames); 14117 Bundle extras = new Bundle(4); 14118 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14119 String nameList[] = new String[componentNames.size()]; 14120 componentNames.toArray(nameList); 14121 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14122 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14123 extras.putInt(Intent.EXTRA_UID, packageUid); 14124 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14125 new int[] {UserHandle.getUserId(packageUid)}); 14126 } 14127 14128 @Override 14129 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14130 if (!sUserManager.exists(userId)) return; 14131 final int uid = Binder.getCallingUid(); 14132 final int permission = mContext.checkCallingOrSelfPermission( 14133 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14134 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14135 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14136 // writer 14137 synchronized (mPackages) { 14138 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14139 allowedByPermission, uid, userId)) { 14140 scheduleWritePackageRestrictionsLocked(userId); 14141 } 14142 } 14143 } 14144 14145 @Override 14146 public String getInstallerPackageName(String packageName) { 14147 // reader 14148 synchronized (mPackages) { 14149 return mSettings.getInstallerPackageNameLPr(packageName); 14150 } 14151 } 14152 14153 @Override 14154 public int getApplicationEnabledSetting(String packageName, int userId) { 14155 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14156 int uid = Binder.getCallingUid(); 14157 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14158 // reader 14159 synchronized (mPackages) { 14160 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14161 } 14162 } 14163 14164 @Override 14165 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14166 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14167 int uid = Binder.getCallingUid(); 14168 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14169 // reader 14170 synchronized (mPackages) { 14171 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14172 } 14173 } 14174 14175 @Override 14176 public void enterSafeMode() { 14177 enforceSystemOrRoot("Only the system can request entering safe mode"); 14178 14179 if (!mSystemReady) { 14180 mSafeMode = true; 14181 } 14182 } 14183 14184 @Override 14185 public void systemReady() { 14186 mSystemReady = true; 14187 14188 // Read the compatibilty setting when the system is ready. 14189 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14190 mContext.getContentResolver(), 14191 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14192 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14193 if (DEBUG_SETTINGS) { 14194 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14195 } 14196 14197 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14198 14199 synchronized (mPackages) { 14200 // Verify that all of the preferred activity components actually 14201 // exist. It is possible for applications to be updated and at 14202 // that point remove a previously declared activity component that 14203 // had been set as a preferred activity. We try to clean this up 14204 // the next time we encounter that preferred activity, but it is 14205 // possible for the user flow to never be able to return to that 14206 // situation so here we do a sanity check to make sure we haven't 14207 // left any junk around. 14208 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14209 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14210 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14211 removed.clear(); 14212 for (PreferredActivity pa : pir.filterSet()) { 14213 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14214 removed.add(pa); 14215 } 14216 } 14217 if (removed.size() > 0) { 14218 for (int r=0; r<removed.size(); r++) { 14219 PreferredActivity pa = removed.get(r); 14220 Slog.w(TAG, "Removing dangling preferred activity: " 14221 + pa.mPref.mComponent); 14222 pir.removeFilter(pa); 14223 } 14224 mSettings.writePackageRestrictionsLPr( 14225 mSettings.mPreferredActivities.keyAt(i)); 14226 } 14227 } 14228 14229 for (int userId : UserManagerService.getInstance().getUserIds()) { 14230 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14231 grantPermissionsUserIds = ArrayUtils.appendInt( 14232 grantPermissionsUserIds, userId); 14233 } 14234 } 14235 } 14236 sUserManager.systemReady(); 14237 14238 // If we upgraded grant all default permissions before kicking off. 14239 for (int userId : grantPermissionsUserIds) { 14240 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14241 } 14242 14243 // Kick off any messages waiting for system ready 14244 if (mPostSystemReadyMessages != null) { 14245 for (Message msg : mPostSystemReadyMessages) { 14246 msg.sendToTarget(); 14247 } 14248 mPostSystemReadyMessages = null; 14249 } 14250 14251 // Watch for external volumes that come and go over time 14252 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14253 storage.registerListener(mStorageListener); 14254 14255 mInstallerService.systemReady(); 14256 mPackageDexOptimizer.systemReady(); 14257 } 14258 14259 @Override 14260 public boolean isSafeMode() { 14261 return mSafeMode; 14262 } 14263 14264 @Override 14265 public boolean hasSystemUidErrors() { 14266 return mHasSystemUidErrors; 14267 } 14268 14269 static String arrayToString(int[] array) { 14270 StringBuffer buf = new StringBuffer(128); 14271 buf.append('['); 14272 if (array != null) { 14273 for (int i=0; i<array.length; i++) { 14274 if (i > 0) buf.append(", "); 14275 buf.append(array[i]); 14276 } 14277 } 14278 buf.append(']'); 14279 return buf.toString(); 14280 } 14281 14282 static class DumpState { 14283 public static final int DUMP_LIBS = 1 << 0; 14284 public static final int DUMP_FEATURES = 1 << 1; 14285 public static final int DUMP_RESOLVERS = 1 << 2; 14286 public static final int DUMP_PERMISSIONS = 1 << 3; 14287 public static final int DUMP_PACKAGES = 1 << 4; 14288 public static final int DUMP_SHARED_USERS = 1 << 5; 14289 public static final int DUMP_MESSAGES = 1 << 6; 14290 public static final int DUMP_PROVIDERS = 1 << 7; 14291 public static final int DUMP_VERIFIERS = 1 << 8; 14292 public static final int DUMP_PREFERRED = 1 << 9; 14293 public static final int DUMP_PREFERRED_XML = 1 << 10; 14294 public static final int DUMP_KEYSETS = 1 << 11; 14295 public static final int DUMP_VERSION = 1 << 12; 14296 public static final int DUMP_INSTALLS = 1 << 13; 14297 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14298 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14299 14300 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14301 14302 private int mTypes; 14303 14304 private int mOptions; 14305 14306 private boolean mTitlePrinted; 14307 14308 private SharedUserSetting mSharedUser; 14309 14310 public boolean isDumping(int type) { 14311 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14312 return true; 14313 } 14314 14315 return (mTypes & type) != 0; 14316 } 14317 14318 public void setDump(int type) { 14319 mTypes |= type; 14320 } 14321 14322 public boolean isOptionEnabled(int option) { 14323 return (mOptions & option) != 0; 14324 } 14325 14326 public void setOptionEnabled(int option) { 14327 mOptions |= option; 14328 } 14329 14330 public boolean onTitlePrinted() { 14331 final boolean printed = mTitlePrinted; 14332 mTitlePrinted = true; 14333 return printed; 14334 } 14335 14336 public boolean getTitlePrinted() { 14337 return mTitlePrinted; 14338 } 14339 14340 public void setTitlePrinted(boolean enabled) { 14341 mTitlePrinted = enabled; 14342 } 14343 14344 public SharedUserSetting getSharedUser() { 14345 return mSharedUser; 14346 } 14347 14348 public void setSharedUser(SharedUserSetting user) { 14349 mSharedUser = user; 14350 } 14351 } 14352 14353 @Override 14354 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14355 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14356 != PackageManager.PERMISSION_GRANTED) { 14357 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14358 + Binder.getCallingPid() 14359 + ", uid=" + Binder.getCallingUid() 14360 + " without permission " 14361 + android.Manifest.permission.DUMP); 14362 return; 14363 } 14364 14365 DumpState dumpState = new DumpState(); 14366 boolean fullPreferred = false; 14367 boolean checkin = false; 14368 14369 String packageName = null; 14370 ArraySet<String> permissionNames = null; 14371 14372 int opti = 0; 14373 while (opti < args.length) { 14374 String opt = args[opti]; 14375 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14376 break; 14377 } 14378 opti++; 14379 14380 if ("-a".equals(opt)) { 14381 // Right now we only know how to print all. 14382 } else if ("-h".equals(opt)) { 14383 pw.println("Package manager dump options:"); 14384 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14385 pw.println(" --checkin: dump for a checkin"); 14386 pw.println(" -f: print details of intent filters"); 14387 pw.println(" -h: print this help"); 14388 pw.println(" cmd may be one of:"); 14389 pw.println(" l[ibraries]: list known shared libraries"); 14390 pw.println(" f[ibraries]: list device features"); 14391 pw.println(" k[eysets]: print known keysets"); 14392 pw.println(" r[esolvers]: dump intent resolvers"); 14393 pw.println(" perm[issions]: dump permissions"); 14394 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14395 pw.println(" pref[erred]: print preferred package settings"); 14396 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14397 pw.println(" prov[iders]: dump content providers"); 14398 pw.println(" p[ackages]: dump installed packages"); 14399 pw.println(" s[hared-users]: dump shared user IDs"); 14400 pw.println(" m[essages]: print collected runtime messages"); 14401 pw.println(" v[erifiers]: print package verifier info"); 14402 pw.println(" version: print database version info"); 14403 pw.println(" write: write current settings now"); 14404 pw.println(" <package.name>: info about given package"); 14405 pw.println(" installs: details about install sessions"); 14406 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14407 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14408 return; 14409 } else if ("--checkin".equals(opt)) { 14410 checkin = true; 14411 } else if ("-f".equals(opt)) { 14412 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14413 } else { 14414 pw.println("Unknown argument: " + opt + "; use -h for help"); 14415 } 14416 } 14417 14418 // Is the caller requesting to dump a particular piece of data? 14419 if (opti < args.length) { 14420 String cmd = args[opti]; 14421 opti++; 14422 // Is this a package name? 14423 if ("android".equals(cmd) || cmd.contains(".")) { 14424 packageName = cmd; 14425 // When dumping a single package, we always dump all of its 14426 // filter information since the amount of data will be reasonable. 14427 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14428 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14429 dumpState.setDump(DumpState.DUMP_LIBS); 14430 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14431 dumpState.setDump(DumpState.DUMP_FEATURES); 14432 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14433 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14434 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14435 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14436 } else if ("permission".equals(cmd)) { 14437 if (opti >= args.length) { 14438 pw.println("Error: permission requires permission name"); 14439 return; 14440 } 14441 permissionNames = new ArraySet<>(); 14442 while (opti < args.length) { 14443 permissionNames.add(args[opti]); 14444 opti++; 14445 } 14446 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14447 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14448 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14449 dumpState.setDump(DumpState.DUMP_PREFERRED); 14450 } else if ("preferred-xml".equals(cmd)) { 14451 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14452 if (opti < args.length && "--full".equals(args[opti])) { 14453 fullPreferred = true; 14454 opti++; 14455 } 14456 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14457 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14458 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14459 dumpState.setDump(DumpState.DUMP_PACKAGES); 14460 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14461 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14462 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14463 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14464 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14465 dumpState.setDump(DumpState.DUMP_MESSAGES); 14466 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14467 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14468 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14469 || "intent-filter-verifiers".equals(cmd)) { 14470 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14471 } else if ("version".equals(cmd)) { 14472 dumpState.setDump(DumpState.DUMP_VERSION); 14473 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14474 dumpState.setDump(DumpState.DUMP_KEYSETS); 14475 } else if ("installs".equals(cmd)) { 14476 dumpState.setDump(DumpState.DUMP_INSTALLS); 14477 } else if ("write".equals(cmd)) { 14478 synchronized (mPackages) { 14479 mSettings.writeLPr(); 14480 pw.println("Settings written."); 14481 return; 14482 } 14483 } 14484 } 14485 14486 if (checkin) { 14487 pw.println("vers,1"); 14488 } 14489 14490 // reader 14491 synchronized (mPackages) { 14492 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14493 if (!checkin) { 14494 if (dumpState.onTitlePrinted()) 14495 pw.println(); 14496 pw.println("Database versions:"); 14497 pw.print(" SDK Version:"); 14498 pw.print(" internal="); 14499 pw.print(mSettings.mInternalSdkPlatform); 14500 pw.print(" external="); 14501 pw.println(mSettings.mExternalSdkPlatform); 14502 pw.print(" DB Version:"); 14503 pw.print(" internal="); 14504 pw.print(mSettings.mInternalDatabaseVersion); 14505 pw.print(" external="); 14506 pw.println(mSettings.mExternalDatabaseVersion); 14507 } 14508 } 14509 14510 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14511 if (!checkin) { 14512 if (dumpState.onTitlePrinted()) 14513 pw.println(); 14514 pw.println("Verifiers:"); 14515 pw.print(" Required: "); 14516 pw.print(mRequiredVerifierPackage); 14517 pw.print(" (uid="); 14518 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14519 pw.println(")"); 14520 } else if (mRequiredVerifierPackage != null) { 14521 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14522 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14523 } 14524 } 14525 14526 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14527 packageName == null) { 14528 if (mIntentFilterVerifierComponent != null) { 14529 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14530 if (!checkin) { 14531 if (dumpState.onTitlePrinted()) 14532 pw.println(); 14533 pw.println("Intent Filter Verifier:"); 14534 pw.print(" Using: "); 14535 pw.print(verifierPackageName); 14536 pw.print(" (uid="); 14537 pw.print(getPackageUid(verifierPackageName, 0)); 14538 pw.println(")"); 14539 } else if (verifierPackageName != null) { 14540 pw.print("ifv,"); pw.print(verifierPackageName); 14541 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14542 } 14543 } else { 14544 pw.println(); 14545 pw.println("No Intent Filter Verifier available!"); 14546 } 14547 } 14548 14549 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14550 boolean printedHeader = false; 14551 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14552 while (it.hasNext()) { 14553 String name = it.next(); 14554 SharedLibraryEntry ent = mSharedLibraries.get(name); 14555 if (!checkin) { 14556 if (!printedHeader) { 14557 if (dumpState.onTitlePrinted()) 14558 pw.println(); 14559 pw.println("Libraries:"); 14560 printedHeader = true; 14561 } 14562 pw.print(" "); 14563 } else { 14564 pw.print("lib,"); 14565 } 14566 pw.print(name); 14567 if (!checkin) { 14568 pw.print(" -> "); 14569 } 14570 if (ent.path != null) { 14571 if (!checkin) { 14572 pw.print("(jar) "); 14573 pw.print(ent.path); 14574 } else { 14575 pw.print(",jar,"); 14576 pw.print(ent.path); 14577 } 14578 } else { 14579 if (!checkin) { 14580 pw.print("(apk) "); 14581 pw.print(ent.apk); 14582 } else { 14583 pw.print(",apk,"); 14584 pw.print(ent.apk); 14585 } 14586 } 14587 pw.println(); 14588 } 14589 } 14590 14591 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14592 if (dumpState.onTitlePrinted()) 14593 pw.println(); 14594 if (!checkin) { 14595 pw.println("Features:"); 14596 } 14597 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14598 while (it.hasNext()) { 14599 String name = it.next(); 14600 if (!checkin) { 14601 pw.print(" "); 14602 } else { 14603 pw.print("feat,"); 14604 } 14605 pw.println(name); 14606 } 14607 } 14608 14609 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14610 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14611 : "Activity Resolver Table:", " ", packageName, 14612 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14613 dumpState.setTitlePrinted(true); 14614 } 14615 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14616 : "Receiver Resolver Table:", " ", packageName, 14617 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14618 dumpState.setTitlePrinted(true); 14619 } 14620 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14621 : "Service Resolver Table:", " ", packageName, 14622 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14623 dumpState.setTitlePrinted(true); 14624 } 14625 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14626 : "Provider Resolver Table:", " ", packageName, 14627 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14628 dumpState.setTitlePrinted(true); 14629 } 14630 } 14631 14632 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14633 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14634 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14635 int user = mSettings.mPreferredActivities.keyAt(i); 14636 if (pir.dump(pw, 14637 dumpState.getTitlePrinted() 14638 ? "\nPreferred Activities User " + user + ":" 14639 : "Preferred Activities User " + user + ":", " ", 14640 packageName, true, false)) { 14641 dumpState.setTitlePrinted(true); 14642 } 14643 } 14644 } 14645 14646 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14647 pw.flush(); 14648 FileOutputStream fout = new FileOutputStream(fd); 14649 BufferedOutputStream str = new BufferedOutputStream(fout); 14650 XmlSerializer serializer = new FastXmlSerializer(); 14651 try { 14652 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14653 serializer.startDocument(null, true); 14654 serializer.setFeature( 14655 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14656 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14657 serializer.endDocument(); 14658 serializer.flush(); 14659 } catch (IllegalArgumentException e) { 14660 pw.println("Failed writing: " + e); 14661 } catch (IllegalStateException e) { 14662 pw.println("Failed writing: " + e); 14663 } catch (IOException e) { 14664 pw.println("Failed writing: " + e); 14665 } 14666 } 14667 14668 if (!checkin 14669 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14670 && packageName == null) { 14671 pw.println(); 14672 int count = mSettings.mPackages.size(); 14673 if (count == 0) { 14674 pw.println("No domain preferred apps!"); 14675 pw.println(); 14676 } else { 14677 final String prefix = " "; 14678 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14679 if (allPackageSettings.size() == 0) { 14680 pw.println("No domain preferred apps!"); 14681 pw.println(); 14682 } else { 14683 pw.println("Domain preferred apps status:"); 14684 pw.println(); 14685 count = 0; 14686 for (PackageSetting ps : allPackageSettings) { 14687 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14688 if (ivi == null || ivi.getPackageName() == null) continue; 14689 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14690 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14691 pw.println(prefix + "Status: " + ivi.getStatusString()); 14692 pw.println(); 14693 count++; 14694 } 14695 if (count == 0) { 14696 pw.println(prefix + "No domain preferred app status!"); 14697 pw.println(); 14698 } 14699 for (int userId : sUserManager.getUserIds()) { 14700 pw.println("Domain preferred apps for User " + userId + ":"); 14701 pw.println(); 14702 count = 0; 14703 for (PackageSetting ps : allPackageSettings) { 14704 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14705 if (ivi == null || ivi.getPackageName() == null) { 14706 continue; 14707 } 14708 final int status = ps.getDomainVerificationStatusForUser(userId); 14709 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14710 continue; 14711 } 14712 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14713 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14714 String statusStr = IntentFilterVerificationInfo. 14715 getStatusStringFromValue(status); 14716 pw.println(prefix + "Status: " + statusStr); 14717 pw.println(); 14718 count++; 14719 } 14720 if (count == 0) { 14721 pw.println(prefix + "No domain preferred apps!"); 14722 pw.println(); 14723 } 14724 } 14725 } 14726 } 14727 } 14728 14729 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14730 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14731 if (packageName == null && permissionNames == null) { 14732 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14733 if (iperm == 0) { 14734 if (dumpState.onTitlePrinted()) 14735 pw.println(); 14736 pw.println("AppOp Permissions:"); 14737 } 14738 pw.print(" AppOp Permission "); 14739 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14740 pw.println(":"); 14741 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14742 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14743 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14744 } 14745 } 14746 } 14747 } 14748 14749 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14750 boolean printedSomething = false; 14751 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14752 if (packageName != null && !packageName.equals(p.info.packageName)) { 14753 continue; 14754 } 14755 if (!printedSomething) { 14756 if (dumpState.onTitlePrinted()) 14757 pw.println(); 14758 pw.println("Registered ContentProviders:"); 14759 printedSomething = true; 14760 } 14761 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14762 pw.print(" "); pw.println(p.toString()); 14763 } 14764 printedSomething = false; 14765 for (Map.Entry<String, PackageParser.Provider> entry : 14766 mProvidersByAuthority.entrySet()) { 14767 PackageParser.Provider p = entry.getValue(); 14768 if (packageName != null && !packageName.equals(p.info.packageName)) { 14769 continue; 14770 } 14771 if (!printedSomething) { 14772 if (dumpState.onTitlePrinted()) 14773 pw.println(); 14774 pw.println("ContentProvider Authorities:"); 14775 printedSomething = true; 14776 } 14777 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14778 pw.print(" "); pw.println(p.toString()); 14779 if (p.info != null && p.info.applicationInfo != null) { 14780 final String appInfo = p.info.applicationInfo.toString(); 14781 pw.print(" applicationInfo="); pw.println(appInfo); 14782 } 14783 } 14784 } 14785 14786 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14787 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14788 } 14789 14790 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14791 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14792 } 14793 14794 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14795 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14796 } 14797 14798 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14799 // XXX should handle packageName != null by dumping only install data that 14800 // the given package is involved with. 14801 if (dumpState.onTitlePrinted()) pw.println(); 14802 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14803 } 14804 14805 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14806 if (dumpState.onTitlePrinted()) pw.println(); 14807 mSettings.dumpReadMessagesLPr(pw, dumpState); 14808 14809 pw.println(); 14810 pw.println("Package warning messages:"); 14811 BufferedReader in = null; 14812 String line = null; 14813 try { 14814 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14815 while ((line = in.readLine()) != null) { 14816 if (line.contains("ignored: updated version")) continue; 14817 pw.println(line); 14818 } 14819 } catch (IOException ignored) { 14820 } finally { 14821 IoUtils.closeQuietly(in); 14822 } 14823 } 14824 14825 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14826 BufferedReader in = null; 14827 String line = null; 14828 try { 14829 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14830 while ((line = in.readLine()) != null) { 14831 if (line.contains("ignored: updated version")) continue; 14832 pw.print("msg,"); 14833 pw.println(line); 14834 } 14835 } catch (IOException ignored) { 14836 } finally { 14837 IoUtils.closeQuietly(in); 14838 } 14839 } 14840 } 14841 } 14842 14843 // ------- apps on sdcard specific code ------- 14844 static final boolean DEBUG_SD_INSTALL = false; 14845 14846 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14847 14848 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14849 14850 private boolean mMediaMounted = false; 14851 14852 static String getEncryptKey() { 14853 try { 14854 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14855 SD_ENCRYPTION_KEYSTORE_NAME); 14856 if (sdEncKey == null) { 14857 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14858 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14859 if (sdEncKey == null) { 14860 Slog.e(TAG, "Failed to create encryption keys"); 14861 return null; 14862 } 14863 } 14864 return sdEncKey; 14865 } catch (NoSuchAlgorithmException nsae) { 14866 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14867 return null; 14868 } catch (IOException ioe) { 14869 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14870 return null; 14871 } 14872 } 14873 14874 /* 14875 * Update media status on PackageManager. 14876 */ 14877 @Override 14878 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14879 int callingUid = Binder.getCallingUid(); 14880 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14881 throw new SecurityException("Media status can only be updated by the system"); 14882 } 14883 // reader; this apparently protects mMediaMounted, but should probably 14884 // be a different lock in that case. 14885 synchronized (mPackages) { 14886 Log.i(TAG, "Updating external media status from " 14887 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14888 + (mediaStatus ? "mounted" : "unmounted")); 14889 if (DEBUG_SD_INSTALL) 14890 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14891 + ", mMediaMounted=" + mMediaMounted); 14892 if (mediaStatus == mMediaMounted) { 14893 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14894 : 0, -1); 14895 mHandler.sendMessage(msg); 14896 return; 14897 } 14898 mMediaMounted = mediaStatus; 14899 } 14900 // Queue up an async operation since the package installation may take a 14901 // little while. 14902 mHandler.post(new Runnable() { 14903 public void run() { 14904 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14905 } 14906 }); 14907 } 14908 14909 /** 14910 * Called by MountService when the initial ASECs to scan are available. 14911 * Should block until all the ASEC containers are finished being scanned. 14912 */ 14913 public void scanAvailableAsecs() { 14914 updateExternalMediaStatusInner(true, false, false); 14915 if (mShouldRestoreconData) { 14916 SELinuxMMAC.setRestoreconDone(); 14917 mShouldRestoreconData = false; 14918 } 14919 } 14920 14921 /* 14922 * Collect information of applications on external media, map them against 14923 * existing containers and update information based on current mount status. 14924 * Please note that we always have to report status if reportStatus has been 14925 * set to true especially when unloading packages. 14926 */ 14927 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14928 boolean externalStorage) { 14929 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14930 int[] uidArr = EmptyArray.INT; 14931 14932 final String[] list = PackageHelper.getSecureContainerList(); 14933 if (ArrayUtils.isEmpty(list)) { 14934 Log.i(TAG, "No secure containers found"); 14935 } else { 14936 // Process list of secure containers and categorize them 14937 // as active or stale based on their package internal state. 14938 14939 // reader 14940 synchronized (mPackages) { 14941 for (String cid : list) { 14942 // Leave stages untouched for now; installer service owns them 14943 if (PackageInstallerService.isStageName(cid)) continue; 14944 14945 if (DEBUG_SD_INSTALL) 14946 Log.i(TAG, "Processing container " + cid); 14947 String pkgName = getAsecPackageName(cid); 14948 if (pkgName == null) { 14949 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14950 continue; 14951 } 14952 if (DEBUG_SD_INSTALL) 14953 Log.i(TAG, "Looking for pkg : " + pkgName); 14954 14955 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14956 if (ps == null) { 14957 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14958 continue; 14959 } 14960 14961 /* 14962 * Skip packages that are not external if we're unmounting 14963 * external storage. 14964 */ 14965 if (externalStorage && !isMounted && !isExternal(ps)) { 14966 continue; 14967 } 14968 14969 final AsecInstallArgs args = new AsecInstallArgs(cid, 14970 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14971 // The package status is changed only if the code path 14972 // matches between settings and the container id. 14973 if (ps.codePathString != null 14974 && ps.codePathString.startsWith(args.getCodePath())) { 14975 if (DEBUG_SD_INSTALL) { 14976 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14977 + " at code path: " + ps.codePathString); 14978 } 14979 14980 // We do have a valid package installed on sdcard 14981 processCids.put(args, ps.codePathString); 14982 final int uid = ps.appId; 14983 if (uid != -1) { 14984 uidArr = ArrayUtils.appendInt(uidArr, uid); 14985 } 14986 } else { 14987 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14988 + ps.codePathString); 14989 } 14990 } 14991 } 14992 14993 Arrays.sort(uidArr); 14994 } 14995 14996 // Process packages with valid entries. 14997 if (isMounted) { 14998 if (DEBUG_SD_INSTALL) 14999 Log.i(TAG, "Loading packages"); 15000 loadMediaPackages(processCids, uidArr); 15001 startCleaningPackages(); 15002 mInstallerService.onSecureContainersAvailable(); 15003 } else { 15004 if (DEBUG_SD_INSTALL) 15005 Log.i(TAG, "Unloading packages"); 15006 unloadMediaPackages(processCids, uidArr, reportStatus); 15007 } 15008 } 15009 15010 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15011 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15012 final int size = infos.size(); 15013 final String[] packageNames = new String[size]; 15014 final int[] packageUids = new int[size]; 15015 for (int i = 0; i < size; i++) { 15016 final ApplicationInfo info = infos.get(i); 15017 packageNames[i] = info.packageName; 15018 packageUids[i] = info.uid; 15019 } 15020 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15021 finishedReceiver); 15022 } 15023 15024 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15025 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15026 sendResourcesChangedBroadcast(mediaStatus, replacing, 15027 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15028 } 15029 15030 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15031 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15032 int size = pkgList.length; 15033 if (size > 0) { 15034 // Send broadcasts here 15035 Bundle extras = new Bundle(); 15036 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15037 if (uidArr != null) { 15038 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15039 } 15040 if (replacing) { 15041 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15042 } 15043 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15044 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15045 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15046 } 15047 } 15048 15049 /* 15050 * Look at potentially valid container ids from processCids If package 15051 * information doesn't match the one on record or package scanning fails, 15052 * the cid is added to list of removeCids. We currently don't delete stale 15053 * containers. 15054 */ 15055 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15056 ArrayList<String> pkgList = new ArrayList<String>(); 15057 Set<AsecInstallArgs> keys = processCids.keySet(); 15058 15059 for (AsecInstallArgs args : keys) { 15060 String codePath = processCids.get(args); 15061 if (DEBUG_SD_INSTALL) 15062 Log.i(TAG, "Loading container : " + args.cid); 15063 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15064 try { 15065 // Make sure there are no container errors first. 15066 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15067 Slog.e(TAG, "Failed to mount cid : " + args.cid 15068 + " when installing from sdcard"); 15069 continue; 15070 } 15071 // Check code path here. 15072 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15073 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15074 + " does not match one in settings " + codePath); 15075 continue; 15076 } 15077 // Parse package 15078 int parseFlags = mDefParseFlags; 15079 if (args.isExternalAsec()) { 15080 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15081 } 15082 if (args.isFwdLocked()) { 15083 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15084 } 15085 15086 synchronized (mInstallLock) { 15087 PackageParser.Package pkg = null; 15088 try { 15089 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15090 } catch (PackageManagerException e) { 15091 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15092 } 15093 // Scan the package 15094 if (pkg != null) { 15095 /* 15096 * TODO why is the lock being held? doPostInstall is 15097 * called in other places without the lock. This needs 15098 * to be straightened out. 15099 */ 15100 // writer 15101 synchronized (mPackages) { 15102 retCode = PackageManager.INSTALL_SUCCEEDED; 15103 pkgList.add(pkg.packageName); 15104 // Post process args 15105 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15106 pkg.applicationInfo.uid); 15107 } 15108 } else { 15109 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15110 } 15111 } 15112 15113 } finally { 15114 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15115 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15116 } 15117 } 15118 } 15119 // writer 15120 synchronized (mPackages) { 15121 // If the platform SDK has changed since the last time we booted, 15122 // we need to re-grant app permission to catch any new ones that 15123 // appear. This is really a hack, and means that apps can in some 15124 // cases get permissions that the user didn't initially explicitly 15125 // allow... it would be nice to have some better way to handle 15126 // this situation. 15127 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15128 if (regrantPermissions) 15129 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15130 + mSdkVersion + "; regranting permissions for external storage"); 15131 mSettings.mExternalSdkPlatform = mSdkVersion; 15132 15133 // Make sure group IDs have been assigned, and any permission 15134 // changes in other apps are accounted for 15135 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15136 | (regrantPermissions 15137 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15138 : 0)); 15139 15140 mSettings.updateExternalDatabaseVersion(); 15141 15142 // can downgrade to reader 15143 // Persist settings 15144 mSettings.writeLPr(); 15145 } 15146 // Send a broadcast to let everyone know we are done processing 15147 if (pkgList.size() > 0) { 15148 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15149 } 15150 } 15151 15152 /* 15153 * Utility method to unload a list of specified containers 15154 */ 15155 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15156 // Just unmount all valid containers. 15157 for (AsecInstallArgs arg : cidArgs) { 15158 synchronized (mInstallLock) { 15159 arg.doPostDeleteLI(false); 15160 } 15161 } 15162 } 15163 15164 /* 15165 * Unload packages mounted on external media. This involves deleting package 15166 * data from internal structures, sending broadcasts about diabled packages, 15167 * gc'ing to free up references, unmounting all secure containers 15168 * corresponding to packages on external media, and posting a 15169 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15170 * that we always have to post this message if status has been requested no 15171 * matter what. 15172 */ 15173 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15174 final boolean reportStatus) { 15175 if (DEBUG_SD_INSTALL) 15176 Log.i(TAG, "unloading media packages"); 15177 ArrayList<String> pkgList = new ArrayList<String>(); 15178 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15179 final Set<AsecInstallArgs> keys = processCids.keySet(); 15180 for (AsecInstallArgs args : keys) { 15181 String pkgName = args.getPackageName(); 15182 if (DEBUG_SD_INSTALL) 15183 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15184 // Delete package internally 15185 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15186 synchronized (mInstallLock) { 15187 boolean res = deletePackageLI(pkgName, null, false, null, null, 15188 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15189 if (res) { 15190 pkgList.add(pkgName); 15191 } else { 15192 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15193 failedList.add(args); 15194 } 15195 } 15196 } 15197 15198 // reader 15199 synchronized (mPackages) { 15200 // We didn't update the settings after removing each package; 15201 // write them now for all packages. 15202 mSettings.writeLPr(); 15203 } 15204 15205 // We have to absolutely send UPDATED_MEDIA_STATUS only 15206 // after confirming that all the receivers processed the ordered 15207 // broadcast when packages get disabled, force a gc to clean things up. 15208 // and unload all the containers. 15209 if (pkgList.size() > 0) { 15210 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15211 new IIntentReceiver.Stub() { 15212 public void performReceive(Intent intent, int resultCode, String data, 15213 Bundle extras, boolean ordered, boolean sticky, 15214 int sendingUser) throws RemoteException { 15215 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15216 reportStatus ? 1 : 0, 1, keys); 15217 mHandler.sendMessage(msg); 15218 } 15219 }); 15220 } else { 15221 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15222 keys); 15223 mHandler.sendMessage(msg); 15224 } 15225 } 15226 15227 private void loadPrivatePackages(VolumeInfo vol) { 15228 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15229 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15230 synchronized (mInstallLock) { 15231 synchronized (mPackages) { 15232 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15233 for (PackageSetting ps : packages) { 15234 final PackageParser.Package pkg; 15235 try { 15236 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15237 loaded.add(pkg.applicationInfo); 15238 } catch (PackageManagerException e) { 15239 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15240 } 15241 } 15242 15243 // TODO: regrant any permissions that changed based since original install 15244 15245 mSettings.writeLPr(); 15246 } 15247 } 15248 15249 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15250 sendResourcesChangedBroadcast(true, false, loaded, null); 15251 } 15252 15253 private void unloadPrivatePackages(VolumeInfo vol) { 15254 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15255 synchronized (mInstallLock) { 15256 synchronized (mPackages) { 15257 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15258 for (PackageSetting ps : packages) { 15259 if (ps.pkg == null) continue; 15260 15261 final ApplicationInfo info = ps.pkg.applicationInfo; 15262 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15263 if (deletePackageLI(ps.name, null, false, null, null, 15264 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15265 unloaded.add(info); 15266 } else { 15267 Slog.w(TAG, "Failed to unload " + ps.codePath); 15268 } 15269 } 15270 15271 mSettings.writeLPr(); 15272 } 15273 } 15274 15275 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15276 sendResourcesChangedBroadcast(false, false, unloaded, null); 15277 } 15278 15279 /** 15280 * Examine all users present on given mounted volume, and destroy data 15281 * belonging to users that are no longer valid, or whose user ID has been 15282 * recycled. 15283 */ 15284 private void reconcileUsers(String volumeUuid) { 15285 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15286 if (ArrayUtils.isEmpty(files)) { 15287 Slog.d(TAG, "No users found on " + volumeUuid); 15288 return; 15289 } 15290 15291 for (File file : files) { 15292 if (!file.isDirectory()) continue; 15293 15294 final int userId; 15295 final UserInfo info; 15296 try { 15297 userId = Integer.parseInt(file.getName()); 15298 info = sUserManager.getUserInfo(userId); 15299 } catch (NumberFormatException e) { 15300 Slog.w(TAG, "Invalid user directory " + file); 15301 continue; 15302 } 15303 15304 boolean destroyUser = false; 15305 if (info == null) { 15306 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15307 + " because no matching user was found"); 15308 destroyUser = true; 15309 } else { 15310 try { 15311 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15312 } catch (IOException e) { 15313 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15314 + " because we failed to enforce serial number: " + e); 15315 destroyUser = true; 15316 } 15317 } 15318 15319 if (destroyUser) { 15320 synchronized (mInstallLock) { 15321 mInstaller.removeUserDataDirs(volumeUuid, userId); 15322 } 15323 } 15324 } 15325 15326 final UserManager um = mContext.getSystemService(UserManager.class); 15327 for (UserInfo user : um.getUsers()) { 15328 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15329 if (userDir.exists()) continue; 15330 15331 try { 15332 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15333 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15334 } catch (IOException e) { 15335 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15336 } 15337 } 15338 } 15339 15340 /** 15341 * Examine all apps present on given mounted volume, and destroy apps that 15342 * aren't expected, either due to uninstallation or reinstallation on 15343 * another volume. 15344 */ 15345 private void reconcileApps(String volumeUuid) { 15346 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15347 if (ArrayUtils.isEmpty(files)) { 15348 Slog.d(TAG, "No apps found on " + volumeUuid); 15349 return; 15350 } 15351 15352 for (File file : files) { 15353 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15354 && !PackageInstallerService.isStageName(file.getName()); 15355 if (!isPackage) { 15356 // Ignore entries which are not packages 15357 continue; 15358 } 15359 15360 boolean destroyApp = false; 15361 String packageName = null; 15362 try { 15363 final PackageLite pkg = PackageParser.parsePackageLite(file, 15364 PackageParser.PARSE_MUST_BE_APK); 15365 packageName = pkg.packageName; 15366 15367 synchronized (mPackages) { 15368 final PackageSetting ps = mSettings.mPackages.get(packageName); 15369 if (ps == null) { 15370 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15371 + volumeUuid + " because we found no install record"); 15372 destroyApp = true; 15373 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15374 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15375 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15376 destroyApp = true; 15377 } 15378 } 15379 15380 } catch (PackageParserException e) { 15381 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15382 destroyApp = true; 15383 } 15384 15385 if (destroyApp) { 15386 synchronized (mInstallLock) { 15387 if (packageName != null) { 15388 removeDataDirsLI(volumeUuid, packageName); 15389 } 15390 if (file.isDirectory()) { 15391 mInstaller.rmPackageDir(file.getAbsolutePath()); 15392 } else { 15393 file.delete(); 15394 } 15395 } 15396 } 15397 } 15398 } 15399 15400 private void unfreezePackage(String packageName) { 15401 synchronized (mPackages) { 15402 final PackageSetting ps = mSettings.mPackages.get(packageName); 15403 if (ps != null) { 15404 ps.frozen = false; 15405 } 15406 } 15407 } 15408 15409 @Override 15410 public int movePackage(final String packageName, final String volumeUuid) { 15411 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15412 15413 final int moveId = mNextMoveId.getAndIncrement(); 15414 try { 15415 movePackageInternal(packageName, volumeUuid, moveId); 15416 } catch (PackageManagerException e) { 15417 Slog.w(TAG, "Failed to move " + packageName, e); 15418 mMoveCallbacks.notifyStatusChanged(moveId, 15419 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15420 } 15421 return moveId; 15422 } 15423 15424 private void movePackageInternal(final String packageName, final String volumeUuid, 15425 final int moveId) throws PackageManagerException { 15426 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15427 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15428 final PackageManager pm = mContext.getPackageManager(); 15429 15430 final boolean currentAsec; 15431 final String currentVolumeUuid; 15432 final File codeFile; 15433 final String installerPackageName; 15434 final String packageAbiOverride; 15435 final int appId; 15436 final String seinfo; 15437 final String label; 15438 15439 // reader 15440 synchronized (mPackages) { 15441 final PackageParser.Package pkg = mPackages.get(packageName); 15442 final PackageSetting ps = mSettings.mPackages.get(packageName); 15443 if (pkg == null || ps == null) { 15444 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15445 } 15446 15447 if (pkg.applicationInfo.isSystemApp()) { 15448 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15449 "Cannot move system application"); 15450 } 15451 15452 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15453 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15454 "Package already moved to " + volumeUuid); 15455 } 15456 15457 final File probe = new File(pkg.codePath); 15458 final File probeOat = new File(probe, "oat"); 15459 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15460 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15461 "Move only supported for modern cluster style installs"); 15462 } 15463 15464 if (ps.frozen) { 15465 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15466 "Failed to move already frozen package"); 15467 } 15468 ps.frozen = true; 15469 15470 currentAsec = pkg.applicationInfo.isForwardLocked() 15471 || pkg.applicationInfo.isExternalAsec(); 15472 currentVolumeUuid = ps.volumeUuid; 15473 codeFile = new File(pkg.codePath); 15474 installerPackageName = ps.installerPackageName; 15475 packageAbiOverride = ps.cpuAbiOverrideString; 15476 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15477 seinfo = pkg.applicationInfo.seinfo; 15478 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15479 } 15480 15481 // Now that we're guarded by frozen state, kill app during move 15482 killApplication(packageName, appId, "move pkg"); 15483 15484 final Bundle extras = new Bundle(); 15485 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15486 extras.putString(Intent.EXTRA_TITLE, label); 15487 mMoveCallbacks.notifyCreated(moveId, extras); 15488 15489 int installFlags; 15490 final boolean moveCompleteApp; 15491 final File measurePath; 15492 15493 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15494 installFlags = INSTALL_INTERNAL; 15495 moveCompleteApp = !currentAsec; 15496 measurePath = Environment.getDataAppDirectory(volumeUuid); 15497 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15498 installFlags = INSTALL_EXTERNAL; 15499 moveCompleteApp = false; 15500 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15501 } else { 15502 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15503 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15504 || !volume.isMountedWritable()) { 15505 unfreezePackage(packageName); 15506 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15507 "Move location not mounted private volume"); 15508 } 15509 15510 Preconditions.checkState(!currentAsec); 15511 15512 installFlags = INSTALL_INTERNAL; 15513 moveCompleteApp = true; 15514 measurePath = Environment.getDataAppDirectory(volumeUuid); 15515 } 15516 15517 final PackageStats stats = new PackageStats(null, -1); 15518 synchronized (mInstaller) { 15519 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15520 unfreezePackage(packageName); 15521 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15522 "Failed to measure package size"); 15523 } 15524 } 15525 15526 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15527 + stats.dataSize); 15528 15529 final long startFreeBytes = measurePath.getFreeSpace(); 15530 final long sizeBytes; 15531 if (moveCompleteApp) { 15532 sizeBytes = stats.codeSize + stats.dataSize; 15533 } else { 15534 sizeBytes = stats.codeSize; 15535 } 15536 15537 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15538 unfreezePackage(packageName); 15539 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15540 "Not enough free space to move"); 15541 } 15542 15543 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15544 15545 final CountDownLatch installedLatch = new CountDownLatch(1); 15546 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15547 @Override 15548 public void onUserActionRequired(Intent intent) throws RemoteException { 15549 throw new IllegalStateException(); 15550 } 15551 15552 @Override 15553 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15554 Bundle extras) throws RemoteException { 15555 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15556 + PackageManager.installStatusToString(returnCode, msg)); 15557 15558 installedLatch.countDown(); 15559 15560 // Regardless of success or failure of the move operation, 15561 // always unfreeze the package 15562 unfreezePackage(packageName); 15563 15564 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15565 switch (status) { 15566 case PackageInstaller.STATUS_SUCCESS: 15567 mMoveCallbacks.notifyStatusChanged(moveId, 15568 PackageManager.MOVE_SUCCEEDED); 15569 break; 15570 case PackageInstaller.STATUS_FAILURE_STORAGE: 15571 mMoveCallbacks.notifyStatusChanged(moveId, 15572 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15573 break; 15574 default: 15575 mMoveCallbacks.notifyStatusChanged(moveId, 15576 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15577 break; 15578 } 15579 } 15580 }; 15581 15582 final MoveInfo move; 15583 if (moveCompleteApp) { 15584 // Kick off a thread to report progress estimates 15585 new Thread() { 15586 @Override 15587 public void run() { 15588 while (true) { 15589 try { 15590 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15591 break; 15592 } 15593 } catch (InterruptedException ignored) { 15594 } 15595 15596 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15597 final int progress = 10 + (int) MathUtils.constrain( 15598 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15599 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15600 } 15601 } 15602 }.start(); 15603 15604 final String dataAppName = codeFile.getName(); 15605 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15606 dataAppName, appId, seinfo); 15607 } else { 15608 move = null; 15609 } 15610 15611 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15612 15613 final Message msg = mHandler.obtainMessage(INIT_COPY); 15614 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15615 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15616 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15617 mHandler.sendMessage(msg); 15618 } 15619 15620 @Override 15621 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15622 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15623 15624 final int realMoveId = mNextMoveId.getAndIncrement(); 15625 final Bundle extras = new Bundle(); 15626 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15627 mMoveCallbacks.notifyCreated(realMoveId, extras); 15628 15629 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15630 @Override 15631 public void onCreated(int moveId, Bundle extras) { 15632 // Ignored 15633 } 15634 15635 @Override 15636 public void onStatusChanged(int moveId, int status, long estMillis) { 15637 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15638 } 15639 }; 15640 15641 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15642 storage.setPrimaryStorageUuid(volumeUuid, callback); 15643 return realMoveId; 15644 } 15645 15646 @Override 15647 public int getMoveStatus(int moveId) { 15648 mContext.enforceCallingOrSelfPermission( 15649 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15650 return mMoveCallbacks.mLastStatus.get(moveId); 15651 } 15652 15653 @Override 15654 public void registerMoveCallback(IPackageMoveObserver callback) { 15655 mContext.enforceCallingOrSelfPermission( 15656 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15657 mMoveCallbacks.register(callback); 15658 } 15659 15660 @Override 15661 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15662 mContext.enforceCallingOrSelfPermission( 15663 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15664 mMoveCallbacks.unregister(callback); 15665 } 15666 15667 @Override 15668 public boolean setInstallLocation(int loc) { 15669 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15670 null); 15671 if (getInstallLocation() == loc) { 15672 return true; 15673 } 15674 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15675 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15676 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15677 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15678 return true; 15679 } 15680 return false; 15681 } 15682 15683 @Override 15684 public int getInstallLocation() { 15685 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15686 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15687 PackageHelper.APP_INSTALL_AUTO); 15688 } 15689 15690 /** Called by UserManagerService */ 15691 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15692 mDirtyUsers.remove(userHandle); 15693 mSettings.removeUserLPw(userHandle); 15694 mPendingBroadcasts.remove(userHandle); 15695 if (mInstaller != null) { 15696 // Technically, we shouldn't be doing this with the package lock 15697 // held. However, this is very rare, and there is already so much 15698 // other disk I/O going on, that we'll let it slide for now. 15699 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15700 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15701 final String volumeUuid = vol.getFsUuid(); 15702 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15703 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15704 } 15705 } 15706 mUserNeedsBadging.delete(userHandle); 15707 removeUnusedPackagesLILPw(userManager, userHandle); 15708 } 15709 15710 /** 15711 * We're removing userHandle and would like to remove any downloaded packages 15712 * that are no longer in use by any other user. 15713 * @param userHandle the user being removed 15714 */ 15715 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15716 final boolean DEBUG_CLEAN_APKS = false; 15717 int [] users = userManager.getUserIdsLPr(); 15718 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15719 while (psit.hasNext()) { 15720 PackageSetting ps = psit.next(); 15721 if (ps.pkg == null) { 15722 continue; 15723 } 15724 final String packageName = ps.pkg.packageName; 15725 // Skip over if system app 15726 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15727 continue; 15728 } 15729 if (DEBUG_CLEAN_APKS) { 15730 Slog.i(TAG, "Checking package " + packageName); 15731 } 15732 boolean keep = false; 15733 for (int i = 0; i < users.length; i++) { 15734 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15735 keep = true; 15736 if (DEBUG_CLEAN_APKS) { 15737 Slog.i(TAG, " Keeping package " + packageName + " for user " 15738 + users[i]); 15739 } 15740 break; 15741 } 15742 } 15743 if (!keep) { 15744 if (DEBUG_CLEAN_APKS) { 15745 Slog.i(TAG, " Removing package " + packageName); 15746 } 15747 mHandler.post(new Runnable() { 15748 public void run() { 15749 deletePackageX(packageName, userHandle, 0); 15750 } //end run 15751 }); 15752 } 15753 } 15754 } 15755 15756 /** Called by UserManagerService */ 15757 void createNewUserLILPw(int userHandle) { 15758 if (mInstaller != null) { 15759 mInstaller.createUserConfig(userHandle); 15760 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15761 applyFactoryDefaultBrowserLPw(userHandle); 15762 } 15763 } 15764 15765 void newUserCreatedLILPw(final int userHandle) { 15766 // We cannot grant the default permissions with a lock held as 15767 // we query providers from other components for default handlers 15768 // such as enabled IMEs, etc. 15769 mHandler.post(new Runnable() { 15770 @Override 15771 public void run() { 15772 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15773 } 15774 }); 15775 } 15776 15777 @Override 15778 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15779 mContext.enforceCallingOrSelfPermission( 15780 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15781 "Only package verification agents can read the verifier device identity"); 15782 15783 synchronized (mPackages) { 15784 return mSettings.getVerifierDeviceIdentityLPw(); 15785 } 15786 } 15787 15788 @Override 15789 public void setPermissionEnforced(String permission, boolean enforced) { 15790 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15791 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15792 synchronized (mPackages) { 15793 if (mSettings.mReadExternalStorageEnforced == null 15794 || mSettings.mReadExternalStorageEnforced != enforced) { 15795 mSettings.mReadExternalStorageEnforced = enforced; 15796 mSettings.writeLPr(); 15797 } 15798 } 15799 // kill any non-foreground processes so we restart them and 15800 // grant/revoke the GID. 15801 final IActivityManager am = ActivityManagerNative.getDefault(); 15802 if (am != null) { 15803 final long token = Binder.clearCallingIdentity(); 15804 try { 15805 am.killProcessesBelowForeground("setPermissionEnforcement"); 15806 } catch (RemoteException e) { 15807 } finally { 15808 Binder.restoreCallingIdentity(token); 15809 } 15810 } 15811 } else { 15812 throw new IllegalArgumentException("No selective enforcement for " + permission); 15813 } 15814 } 15815 15816 @Override 15817 @Deprecated 15818 public boolean isPermissionEnforced(String permission) { 15819 return true; 15820 } 15821 15822 @Override 15823 public boolean isStorageLow() { 15824 final long token = Binder.clearCallingIdentity(); 15825 try { 15826 final DeviceStorageMonitorInternal 15827 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15828 if (dsm != null) { 15829 return dsm.isMemoryLow(); 15830 } else { 15831 return false; 15832 } 15833 } finally { 15834 Binder.restoreCallingIdentity(token); 15835 } 15836 } 15837 15838 @Override 15839 public IPackageInstaller getPackageInstaller() { 15840 return mInstallerService; 15841 } 15842 15843 private boolean userNeedsBadging(int userId) { 15844 int index = mUserNeedsBadging.indexOfKey(userId); 15845 if (index < 0) { 15846 final UserInfo userInfo; 15847 final long token = Binder.clearCallingIdentity(); 15848 try { 15849 userInfo = sUserManager.getUserInfo(userId); 15850 } finally { 15851 Binder.restoreCallingIdentity(token); 15852 } 15853 final boolean b; 15854 if (userInfo != null && userInfo.isManagedProfile()) { 15855 b = true; 15856 } else { 15857 b = false; 15858 } 15859 mUserNeedsBadging.put(userId, b); 15860 return b; 15861 } 15862 return mUserNeedsBadging.valueAt(index); 15863 } 15864 15865 @Override 15866 public KeySet getKeySetByAlias(String packageName, String alias) { 15867 if (packageName == null || alias == null) { 15868 return null; 15869 } 15870 synchronized(mPackages) { 15871 final PackageParser.Package pkg = mPackages.get(packageName); 15872 if (pkg == null) { 15873 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15874 throw new IllegalArgumentException("Unknown package: " + packageName); 15875 } 15876 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15877 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15878 } 15879 } 15880 15881 @Override 15882 public KeySet getSigningKeySet(String packageName) { 15883 if (packageName == null) { 15884 return null; 15885 } 15886 synchronized(mPackages) { 15887 final PackageParser.Package pkg = mPackages.get(packageName); 15888 if (pkg == null) { 15889 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15890 throw new IllegalArgumentException("Unknown package: " + packageName); 15891 } 15892 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15893 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15894 throw new SecurityException("May not access signing KeySet of other apps."); 15895 } 15896 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15897 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15898 } 15899 } 15900 15901 @Override 15902 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15903 if (packageName == null || ks == null) { 15904 return false; 15905 } 15906 synchronized(mPackages) { 15907 final PackageParser.Package pkg = mPackages.get(packageName); 15908 if (pkg == null) { 15909 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15910 throw new IllegalArgumentException("Unknown package: " + packageName); 15911 } 15912 IBinder ksh = ks.getToken(); 15913 if (ksh instanceof KeySetHandle) { 15914 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15915 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15916 } 15917 return false; 15918 } 15919 } 15920 15921 @Override 15922 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15923 if (packageName == null || ks == null) { 15924 return false; 15925 } 15926 synchronized(mPackages) { 15927 final PackageParser.Package pkg = mPackages.get(packageName); 15928 if (pkg == null) { 15929 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15930 throw new IllegalArgumentException("Unknown package: " + packageName); 15931 } 15932 IBinder ksh = ks.getToken(); 15933 if (ksh instanceof KeySetHandle) { 15934 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15935 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15936 } 15937 return false; 15938 } 15939 } 15940 15941 public void getUsageStatsIfNoPackageUsageInfo() { 15942 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15943 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15944 if (usm == null) { 15945 throw new IllegalStateException("UsageStatsManager must be initialized"); 15946 } 15947 long now = System.currentTimeMillis(); 15948 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15949 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15950 String packageName = entry.getKey(); 15951 PackageParser.Package pkg = mPackages.get(packageName); 15952 if (pkg == null) { 15953 continue; 15954 } 15955 UsageStats usage = entry.getValue(); 15956 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15957 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15958 } 15959 } 15960 } 15961 15962 /** 15963 * Check and throw if the given before/after packages would be considered a 15964 * downgrade. 15965 */ 15966 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15967 throws PackageManagerException { 15968 if (after.versionCode < before.mVersionCode) { 15969 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15970 "Update version code " + after.versionCode + " is older than current " 15971 + before.mVersionCode); 15972 } else if (after.versionCode == before.mVersionCode) { 15973 if (after.baseRevisionCode < before.baseRevisionCode) { 15974 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15975 "Update base revision code " + after.baseRevisionCode 15976 + " is older than current " + before.baseRevisionCode); 15977 } 15978 15979 if (!ArrayUtils.isEmpty(after.splitNames)) { 15980 for (int i = 0; i < after.splitNames.length; i++) { 15981 final String splitName = after.splitNames[i]; 15982 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15983 if (j != -1) { 15984 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15985 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15986 "Update split " + splitName + " revision code " 15987 + after.splitRevisionCodes[i] + " is older than current " 15988 + before.splitRevisionCodes[j]); 15989 } 15990 } 15991 } 15992 } 15993 } 15994 } 15995 15996 private static class MoveCallbacks extends Handler { 15997 private static final int MSG_CREATED = 1; 15998 private static final int MSG_STATUS_CHANGED = 2; 15999 16000 private final RemoteCallbackList<IPackageMoveObserver> 16001 mCallbacks = new RemoteCallbackList<>(); 16002 16003 private final SparseIntArray mLastStatus = new SparseIntArray(); 16004 16005 public MoveCallbacks(Looper looper) { 16006 super(looper); 16007 } 16008 16009 public void register(IPackageMoveObserver callback) { 16010 mCallbacks.register(callback); 16011 } 16012 16013 public void unregister(IPackageMoveObserver callback) { 16014 mCallbacks.unregister(callback); 16015 } 16016 16017 @Override 16018 public void handleMessage(Message msg) { 16019 final SomeArgs args = (SomeArgs) msg.obj; 16020 final int n = mCallbacks.beginBroadcast(); 16021 for (int i = 0; i < n; i++) { 16022 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16023 try { 16024 invokeCallback(callback, msg.what, args); 16025 } catch (RemoteException ignored) { 16026 } 16027 } 16028 mCallbacks.finishBroadcast(); 16029 args.recycle(); 16030 } 16031 16032 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16033 throws RemoteException { 16034 switch (what) { 16035 case MSG_CREATED: { 16036 callback.onCreated(args.argi1, (Bundle) args.arg2); 16037 break; 16038 } 16039 case MSG_STATUS_CHANGED: { 16040 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16041 break; 16042 } 16043 } 16044 } 16045 16046 private void notifyCreated(int moveId, Bundle extras) { 16047 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16048 16049 final SomeArgs args = SomeArgs.obtain(); 16050 args.argi1 = moveId; 16051 args.arg2 = extras; 16052 obtainMessage(MSG_CREATED, args).sendToTarget(); 16053 } 16054 16055 private void notifyStatusChanged(int moveId, int status) { 16056 notifyStatusChanged(moveId, status, -1); 16057 } 16058 16059 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16060 Slog.v(TAG, "Move " + moveId + " status " + status); 16061 16062 final SomeArgs args = SomeArgs.obtain(); 16063 args.argi1 = moveId; 16064 args.argi2 = status; 16065 args.arg3 = estMillis; 16066 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16067 16068 synchronized (mLastStatus) { 16069 mLastStatus.put(moveId, status); 16070 } 16071 } 16072 } 16073 16074 private final class OnPermissionChangeListeners extends Handler { 16075 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16076 16077 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16078 new RemoteCallbackList<>(); 16079 16080 public OnPermissionChangeListeners(Looper looper) { 16081 super(looper); 16082 } 16083 16084 @Override 16085 public void handleMessage(Message msg) { 16086 switch (msg.what) { 16087 case MSG_ON_PERMISSIONS_CHANGED: { 16088 final int uid = msg.arg1; 16089 handleOnPermissionsChanged(uid); 16090 } break; 16091 } 16092 } 16093 16094 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16095 mPermissionListeners.register(listener); 16096 16097 } 16098 16099 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16100 mPermissionListeners.unregister(listener); 16101 } 16102 16103 public void onPermissionsChanged(int uid) { 16104 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16105 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16106 } 16107 } 16108 16109 private void handleOnPermissionsChanged(int uid) { 16110 final int count = mPermissionListeners.beginBroadcast(); 16111 try { 16112 for (int i = 0; i < count; i++) { 16113 IOnPermissionsChangeListener callback = mPermissionListeners 16114 .getBroadcastItem(i); 16115 try { 16116 callback.onPermissionsChanged(uid); 16117 } catch (RemoteException e) { 16118 Log.e(TAG, "Permission listener is dead", e); 16119 } 16120 } 16121 } finally { 16122 mPermissionListeners.finishBroadcast(); 16123 } 16124 } 16125 } 16126 16127 private class PackageManagerInternalImpl extends PackageManagerInternal { 16128 @Override 16129 public void setLocationPackagesProvider(PackagesProvider provider) { 16130 synchronized (mPackages) { 16131 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16132 } 16133 } 16134 16135 @Override 16136 public void setImePackagesProvider(PackagesProvider provider) { 16137 synchronized (mPackages) { 16138 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16139 } 16140 } 16141 16142 @Override 16143 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16144 synchronized (mPackages) { 16145 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16146 } 16147 } 16148 16149 @Override 16150 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16151 synchronized (mPackages) { 16152 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16153 } 16154 } 16155 16156 @Override 16157 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16158 synchronized (mPackages) { 16159 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16160 } 16161 } 16162 16163 @Override 16164 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16165 synchronized (mPackages) { 16166 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16167 } 16168 } 16169 16170 @Override 16171 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16172 synchronized (mPackages) { 16173 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16174 packageName, userId); 16175 } 16176 } 16177 16178 @Override 16179 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16180 synchronized (mPackages) { 16181 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16182 packageName, userId); 16183 } 16184 } 16185 } 16186 16187 @Override 16188 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16189 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16190 synchronized (mPackages) { 16191 final long identity = Binder.clearCallingIdentity(); 16192 try { 16193 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16194 packageNames, userId); 16195 } finally { 16196 Binder.restoreCallingIdentity(identity); 16197 } 16198 } 16199 } 16200 16201 private static void enforceSystemOrPhoneCaller(String tag) { 16202 int callingUid = Binder.getCallingUid(); 16203 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16204 throw new SecurityException( 16205 "Cannot call " + tag + " from UID " + callingUid); 16206 } 16207 } 16208} 16209