PackageManagerService.java revision 3bb8c854189591fcee16d2a6854fae862b02d1e8
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 28import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 29import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 46import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 47import static android.content.pm.PackageManager.INSTALL_INTERNAL; 48import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 53import static android.content.pm.PackageManager.MATCH_ALL; 54import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 55import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 56import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 57import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 58import static android.content.pm.PackageManager.PERMISSION_GRANTED; 59import static android.content.pm.PackageParser.isApkFile; 60import static android.os.Process.PACKAGE_INFO_GID; 61import static android.os.Process.SYSTEM_UID; 62import static android.system.OsConstants.O_CREAT; 63import static android.system.OsConstants.O_RDWR; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 66import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 67import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 68import static com.android.internal.util.ArrayUtils.appendInt; 69import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 72import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 73import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 74 75import android.Manifest; 76import android.app.ActivityManager; 77import android.app.ActivityManagerNative; 78import android.app.AppGlobals; 79import android.app.IActivityManager; 80import android.app.admin.IDevicePolicyManager; 81import android.app.backup.IBackupManager; 82import android.app.usage.UsageStats; 83import android.app.usage.UsageStatsManager; 84import android.content.BroadcastReceiver; 85import android.content.ComponentName; 86import android.content.Context; 87import android.content.IIntentReceiver; 88import android.content.Intent; 89import android.content.IntentFilter; 90import android.content.IntentSender; 91import android.content.IntentSender.SendIntentException; 92import android.content.ServiceConnection; 93import android.content.pm.ActivityInfo; 94import android.content.pm.ApplicationInfo; 95import android.content.pm.FeatureInfo; 96import android.content.pm.IOnPermissionsChangeListener; 97import android.content.pm.IPackageDataObserver; 98import android.content.pm.IPackageDeleteObserver; 99import android.content.pm.IPackageDeleteObserver2; 100import android.content.pm.IPackageInstallObserver2; 101import android.content.pm.IPackageInstaller; 102import android.content.pm.IPackageManager; 103import android.content.pm.IPackageMoveObserver; 104import android.content.pm.IPackageStatsObserver; 105import android.content.pm.InstrumentationInfo; 106import android.content.pm.IntentFilterVerificationInfo; 107import android.content.pm.KeySet; 108import android.content.pm.ManifestDigest; 109import android.content.pm.PackageCleanItem; 110import android.content.pm.PackageInfo; 111import android.content.pm.PackageInfoLite; 112import android.content.pm.PackageInstaller; 113import android.content.pm.PackageManager; 114import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 115import android.content.pm.PackageManagerInternal; 116import android.content.pm.PackageParser; 117import android.content.pm.PackageParser.ActivityIntentInfo; 118import android.content.pm.PackageParser.PackageLite; 119import android.content.pm.PackageParser.PackageParserException; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Debug; 140import android.os.Environment; 141import android.os.Environment.UserEnvironment; 142import android.os.FileUtils; 143import android.os.Handler; 144import android.os.IBinder; 145import android.os.Looper; 146import android.os.Message; 147import android.os.Parcel; 148import android.os.ParcelFileDescriptor; 149import android.os.Process; 150import android.os.RemoteCallbackList; 151import android.os.RemoteException; 152import android.os.SELinux; 153import android.os.ServiceManager; 154import android.os.SystemClock; 155import android.os.SystemProperties; 156import android.os.UserHandle; 157import android.os.UserManager; 158import android.os.storage.IMountService; 159import android.os.storage.StorageEventListener; 160import android.os.storage.StorageManager; 161import android.os.storage.VolumeInfo; 162import android.os.storage.VolumeRecord; 163import android.security.KeyStore; 164import android.security.SystemKeyStore; 165import android.system.ErrnoException; 166import android.system.Os; 167import android.system.StructStat; 168import android.text.TextUtils; 169import android.text.format.DateUtils; 170import android.util.ArrayMap; 171import android.util.ArraySet; 172import android.util.AtomicFile; 173import android.util.DisplayMetrics; 174import android.util.EventLog; 175import android.util.ExceptionUtils; 176import android.util.Log; 177import android.util.LogPrinter; 178import android.util.MathUtils; 179import android.util.PrintStreamPrinter; 180import android.util.Slog; 181import android.util.SparseArray; 182import android.util.SparseBooleanArray; 183import android.util.SparseIntArray; 184import android.util.Xml; 185import android.view.Display; 186 187import dalvik.system.DexFile; 188import dalvik.system.VMRuntime; 189 190import libcore.io.IoUtils; 191import libcore.util.EmptyArray; 192 193import com.android.internal.R; 194import com.android.internal.annotations.GuardedBy; 195import com.android.internal.app.IMediaContainerService; 196import com.android.internal.app.ResolverActivity; 197import com.android.internal.content.NativeLibraryHelper; 198import com.android.internal.content.PackageHelper; 199import com.android.internal.os.IParcelFileDescriptorFactory; 200import com.android.internal.os.SomeArgs; 201import com.android.internal.os.Zygote; 202import com.android.internal.util.ArrayUtils; 203import com.android.internal.util.FastPrintWriter; 204import com.android.internal.util.FastXmlSerializer; 205import com.android.internal.util.IndentingPrintWriter; 206import com.android.internal.util.Preconditions; 207import com.android.server.EventLogTags; 208import com.android.server.FgThread; 209import com.android.server.IntentResolver; 210import com.android.server.LocalServices; 211import com.android.server.ServiceThread; 212import com.android.server.SystemConfig; 213import com.android.server.Watchdog; 214import com.android.server.pm.PermissionsState.PermissionState; 215import com.android.server.pm.Settings.DatabaseVersion; 216import com.android.server.storage.DeviceStorageMonitorInternal; 217 218import org.xmlpull.v1.XmlPullParser; 219import org.xmlpull.v1.XmlPullParserException; 220import org.xmlpull.v1.XmlSerializer; 221 222import java.io.BufferedInputStream; 223import java.io.BufferedOutputStream; 224import java.io.BufferedReader; 225import java.io.ByteArrayInputStream; 226import java.io.ByteArrayOutputStream; 227import java.io.File; 228import java.io.FileDescriptor; 229import java.io.FileNotFoundException; 230import java.io.FileOutputStream; 231import java.io.FileReader; 232import java.io.FilenameFilter; 233import java.io.IOException; 234import java.io.InputStream; 235import java.io.PrintWriter; 236import java.nio.charset.StandardCharsets; 237import java.security.NoSuchAlgorithmException; 238import java.security.PublicKey; 239import java.security.cert.CertificateEncodingException; 240import java.security.cert.CertificateException; 241import java.text.SimpleDateFormat; 242import java.util.ArrayList; 243import java.util.Arrays; 244import java.util.Collection; 245import java.util.Collections; 246import java.util.Comparator; 247import java.util.Date; 248import java.util.Iterator; 249import java.util.List; 250import java.util.Map; 251import java.util.Objects; 252import java.util.Set; 253import java.util.concurrent.CountDownLatch; 254import java.util.concurrent.TimeUnit; 255import java.util.concurrent.atomic.AtomicBoolean; 256import java.util.concurrent.atomic.AtomicInteger; 257import java.util.concurrent.atomic.AtomicLong; 258 259/** 260 * Keep track of all those .apks everywhere. 261 * 262 * This is very central to the platform's security; please run the unit 263 * tests whenever making modifications here: 264 * 265runtest -c android.content.pm.PackageManagerTests frameworks-core 266 * 267 * {@hide} 268 */ 269public class PackageManagerService extends IPackageManager.Stub { 270 static final String TAG = "PackageManager"; 271 static final boolean DEBUG_SETTINGS = false; 272 static final boolean DEBUG_PREFERRED = false; 273 static final boolean DEBUG_UPGRADE = false; 274 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 275 private static final boolean DEBUG_BACKUP = true; 276 private static final boolean DEBUG_INSTALL = false; 277 private static final boolean DEBUG_REMOVE = false; 278 private static final boolean DEBUG_BROADCASTS = false; 279 private static final boolean DEBUG_SHOW_INFO = false; 280 private static final boolean DEBUG_PACKAGE_INFO = false; 281 private static final boolean DEBUG_INTENT_MATCHING = false; 282 private static final boolean DEBUG_PACKAGE_SCANNING = false; 283 private static final boolean DEBUG_VERIFY = false; 284 private static final boolean DEBUG_DEXOPT = false; 285 private static final boolean DEBUG_ABI_SELECTION = false; 286 287 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 288 289 private static final int RADIO_UID = Process.PHONE_UID; 290 private static final int LOG_UID = Process.LOG_UID; 291 private static final int NFC_UID = Process.NFC_UID; 292 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 293 private static final int SHELL_UID = Process.SHELL_UID; 294 295 // Cap the size of permission trees that 3rd party apps can define 296 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 297 298 // Suffix used during package installation when copying/moving 299 // package apks to install directory. 300 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 301 302 static final int SCAN_NO_DEX = 1<<1; 303 static final int SCAN_FORCE_DEX = 1<<2; 304 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 305 static final int SCAN_NEW_INSTALL = 1<<4; 306 static final int SCAN_NO_PATHS = 1<<5; 307 static final int SCAN_UPDATE_TIME = 1<<6; 308 static final int SCAN_DEFER_DEX = 1<<7; 309 static final int SCAN_BOOTING = 1<<8; 310 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 311 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 312 static final int SCAN_REQUIRE_KNOWN = 1<<12; 313 static final int SCAN_MOVE = 1<<13; 314 static final int SCAN_INITIAL = 1<<14; 315 316 static final int REMOVE_CHATTY = 1<<16; 317 318 private static final int[] EMPTY_INT_ARRAY = new int[0]; 319 320 /** 321 * Timeout (in milliseconds) after which the watchdog should declare that 322 * our handler thread is wedged. The usual default for such things is one 323 * minute but we sometimes do very lengthy I/O operations on this thread, 324 * such as installing multi-gigabyte applications, so ours needs to be longer. 325 */ 326 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 327 328 /** 329 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 330 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 331 * settings entry if available, otherwise we use the hardcoded default. If it's been 332 * more than this long since the last fstrim, we force one during the boot sequence. 333 * 334 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 335 * one gets run at the next available charging+idle time. This final mandatory 336 * no-fstrim check kicks in only of the other scheduling criteria is never met. 337 */ 338 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 339 340 /** 341 * Whether verification is enabled by default. 342 */ 343 private static final boolean DEFAULT_VERIFY_ENABLE = true; 344 345 /** 346 * The default maximum time to wait for the verification agent to return in 347 * milliseconds. 348 */ 349 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 350 351 /** 352 * The default response for package verification timeout. 353 * 354 * This can be either PackageManager.VERIFICATION_ALLOW or 355 * PackageManager.VERIFICATION_REJECT. 356 */ 357 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 358 359 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 360 361 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 362 DEFAULT_CONTAINER_PACKAGE, 363 "com.android.defcontainer.DefaultContainerService"); 364 365 private static final String KILL_APP_REASON_GIDS_CHANGED = 366 "permission grant or revoke changed gids"; 367 368 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 369 "permissions revoked"; 370 371 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 372 373 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 374 375 /** Permission grant: not grant the permission. */ 376 private static final int GRANT_DENIED = 1; 377 378 /** Permission grant: grant the permission as an install permission. */ 379 private static final int GRANT_INSTALL = 2; 380 381 /** Permission grant: grant the permission as an install permission for a legacy app. */ 382 private static final int GRANT_INSTALL_LEGACY = 3; 383 384 /** Permission grant: grant the permission as a runtime one. */ 385 private static final int GRANT_RUNTIME = 4; 386 387 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 388 private static final int GRANT_UPGRADE = 5; 389 390 /** Canonical intent used to identify what counts as a "web browser" app */ 391 private static final Intent sBrowserIntent; 392 static { 393 sBrowserIntent = new Intent(); 394 sBrowserIntent.setAction(Intent.ACTION_VIEW); 395 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 396 sBrowserIntent.setData(Uri.parse("http:")); 397 } 398 399 final ServiceThread mHandlerThread; 400 401 final PackageHandler mHandler; 402 403 /** 404 * Messages for {@link #mHandler} that need to wait for system ready before 405 * being dispatched. 406 */ 407 private ArrayList<Message> mPostSystemReadyMessages; 408 409 final int mSdkVersion = Build.VERSION.SDK_INT; 410 411 final Context mContext; 412 final boolean mFactoryTest; 413 final boolean mOnlyCore; 414 final boolean mLazyDexOpt; 415 final long mDexOptLRUThresholdInMills; 416 final DisplayMetrics mMetrics; 417 final int mDefParseFlags; 418 final String[] mSeparateProcesses; 419 final boolean mIsUpgrade; 420 421 // This is where all application persistent data goes. 422 final File mAppDataDir; 423 424 // This is where all application persistent data goes for secondary users. 425 final File mUserAppDataDir; 426 427 /** The location for ASEC container files on internal storage. */ 428 final String mAsecInternalPath; 429 430 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 431 // LOCK HELD. Can be called with mInstallLock held. 432 @GuardedBy("mInstallLock") 433 final Installer mInstaller; 434 435 /** Directory where installed third-party apps stored */ 436 final File mAppInstallDir; 437 438 /** 439 * Directory to which applications installed internally have their 440 * 32 bit native libraries copied. 441 */ 442 private File mAppLib32InstallDir; 443 444 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 445 // apps. 446 final File mDrmAppPrivateInstallDir; 447 448 // ---------------------------------------------------------------- 449 450 // Lock for state used when installing and doing other long running 451 // operations. Methods that must be called with this lock held have 452 // the suffix "LI". 453 final Object mInstallLock = new Object(); 454 455 // ---------------------------------------------------------------- 456 457 // Keys are String (package name), values are Package. This also serves 458 // as the lock for the global state. Methods that must be called with 459 // this lock held have the prefix "LP". 460 @GuardedBy("mPackages") 461 final ArrayMap<String, PackageParser.Package> mPackages = 462 new ArrayMap<String, PackageParser.Package>(); 463 464 // Tracks available target package names -> overlay package paths. 465 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 466 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 467 468 final Settings mSettings; 469 boolean mRestoredSettings; 470 471 // System configuration read by SystemConfig. 472 final int[] mGlobalGids; 473 final SparseArray<ArraySet<String>> mSystemPermissions; 474 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 475 476 // If mac_permissions.xml was found for seinfo labeling. 477 boolean mFoundPolicyFile; 478 479 // If a recursive restorecon of /data/data/<pkg> is needed. 480 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 481 482 public static final class SharedLibraryEntry { 483 public final String path; 484 public final String apk; 485 486 SharedLibraryEntry(String _path, String _apk) { 487 path = _path; 488 apk = _apk; 489 } 490 } 491 492 // Currently known shared libraries. 493 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 494 new ArrayMap<String, SharedLibraryEntry>(); 495 496 // All available activities, for your resolving pleasure. 497 final ActivityIntentResolver mActivities = 498 new ActivityIntentResolver(); 499 500 // All available receivers, for your resolving pleasure. 501 final ActivityIntentResolver mReceivers = 502 new ActivityIntentResolver(); 503 504 // All available services, for your resolving pleasure. 505 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 506 507 // All available providers, for your resolving pleasure. 508 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 509 510 // Mapping from provider base names (first directory in content URI codePath) 511 // to the provider information. 512 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 513 new ArrayMap<String, PackageParser.Provider>(); 514 515 // Mapping from instrumentation class names to info about them. 516 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 517 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 518 519 // Mapping from permission names to info about them. 520 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 521 new ArrayMap<String, PackageParser.PermissionGroup>(); 522 523 // Packages whose data we have transfered into another package, thus 524 // should no longer exist. 525 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 526 527 // Broadcast actions that are only available to the system. 528 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 529 530 /** List of packages waiting for verification. */ 531 final SparseArray<PackageVerificationState> mPendingVerification 532 = new SparseArray<PackageVerificationState>(); 533 534 /** Set of packages associated with each app op permission. */ 535 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 536 537 final PackageInstallerService mInstallerService; 538 539 private final PackageDexOptimizer mPackageDexOptimizer; 540 541 private AtomicInteger mNextMoveId = new AtomicInteger(); 542 private final MoveCallbacks mMoveCallbacks; 543 544 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 545 546 // Cache of users who need badging. 547 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 548 549 /** Token for keys in mPendingVerification. */ 550 private int mPendingVerificationToken = 0; 551 552 volatile boolean mSystemReady; 553 volatile boolean mSafeMode; 554 volatile boolean mHasSystemUidErrors; 555 556 ApplicationInfo mAndroidApplication; 557 final ActivityInfo mResolveActivity = new ActivityInfo(); 558 final ResolveInfo mResolveInfo = new ResolveInfo(); 559 ComponentName mResolveComponentName; 560 PackageParser.Package mPlatformPackage; 561 ComponentName mCustomResolverComponentName; 562 563 boolean mResolverReplaced = false; 564 565 private final ComponentName mIntentFilterVerifierComponent; 566 private int mIntentFilterVerificationToken = 0; 567 568 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 569 = new SparseArray<IntentFilterVerificationState>(); 570 571 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 572 new DefaultPermissionGrantPolicy(this); 573 574 private static class IFVerificationParams { 575 PackageParser.Package pkg; 576 boolean replacing; 577 int userId; 578 int verifierUid; 579 580 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 581 int _userId, int _verifierUid) { 582 pkg = _pkg; 583 replacing = _replacing; 584 userId = _userId; 585 replacing = _replacing; 586 verifierUid = _verifierUid; 587 } 588 } 589 590 private interface IntentFilterVerifier<T extends IntentFilter> { 591 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 592 T filter, String packageName); 593 void startVerifications(int userId); 594 void receiveVerificationResponse(int verificationId); 595 } 596 597 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 598 private Context mContext; 599 private ComponentName mIntentFilterVerifierComponent; 600 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 601 602 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 603 mContext = context; 604 mIntentFilterVerifierComponent = verifierComponent; 605 } 606 607 private String getDefaultScheme() { 608 return IntentFilter.SCHEME_HTTPS; 609 } 610 611 @Override 612 public void startVerifications(int userId) { 613 // Launch verifications requests 614 int count = mCurrentIntentFilterVerifications.size(); 615 for (int n=0; n<count; n++) { 616 int verificationId = mCurrentIntentFilterVerifications.get(n); 617 final IntentFilterVerificationState ivs = 618 mIntentFilterVerificationStates.get(verificationId); 619 620 String packageName = ivs.getPackageName(); 621 622 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 623 final int filterCount = filters.size(); 624 ArraySet<String> domainsSet = new ArraySet<>(); 625 for (int m=0; m<filterCount; m++) { 626 PackageParser.ActivityIntentInfo filter = filters.get(m); 627 domainsSet.addAll(filter.getHostsList()); 628 } 629 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 630 synchronized (mPackages) { 631 if (mSettings.createIntentFilterVerificationIfNeededLPw( 632 packageName, domainsList) != null) { 633 scheduleWriteSettingsLocked(); 634 } 635 } 636 sendVerificationRequest(userId, verificationId, ivs); 637 } 638 mCurrentIntentFilterVerifications.clear(); 639 } 640 641 private void sendVerificationRequest(int userId, int verificationId, 642 IntentFilterVerificationState ivs) { 643 644 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 645 verificationIntent.putExtra( 646 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 647 verificationId); 648 verificationIntent.putExtra( 649 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 650 getDefaultScheme()); 651 verificationIntent.putExtra( 652 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 653 ivs.getHostsString()); 654 verificationIntent.putExtra( 655 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 656 ivs.getPackageName()); 657 verificationIntent.setComponent(mIntentFilterVerifierComponent); 658 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 659 660 UserHandle user = new UserHandle(userId); 661 mContext.sendBroadcastAsUser(verificationIntent, user); 662 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 663 "Sending IntentFilter verification broadcast"); 664 } 665 666 public void receiveVerificationResponse(int verificationId) { 667 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 668 669 final boolean verified = ivs.isVerified(); 670 671 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 672 final int count = filters.size(); 673 if (DEBUG_DOMAIN_VERIFICATION) { 674 Slog.i(TAG, "Received verification response " + verificationId 675 + " for " + count + " filters, verified=" + verified); 676 } 677 for (int n=0; n<count; n++) { 678 PackageParser.ActivityIntentInfo filter = filters.get(n); 679 filter.setVerified(verified); 680 681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 682 + " verified with result:" + verified + " and hosts:" 683 + ivs.getHostsString()); 684 } 685 686 mIntentFilterVerificationStates.remove(verificationId); 687 688 final String packageName = ivs.getPackageName(); 689 IntentFilterVerificationInfo ivi = null; 690 691 synchronized (mPackages) { 692 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 693 } 694 if (ivi == null) { 695 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 696 + verificationId + " packageName:" + packageName); 697 return; 698 } 699 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 700 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 701 702 synchronized (mPackages) { 703 if (verified) { 704 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 705 } else { 706 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 707 } 708 scheduleWriteSettingsLocked(); 709 710 final int userId = ivs.getUserId(); 711 if (userId != UserHandle.USER_ALL) { 712 final int userStatus = 713 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 714 715 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 716 boolean needUpdate = false; 717 718 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 719 // already been set by the User thru the Disambiguation dialog 720 switch (userStatus) { 721 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 722 if (verified) { 723 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 724 } else { 725 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 726 } 727 needUpdate = true; 728 break; 729 730 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 731 if (verified) { 732 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 733 needUpdate = true; 734 } 735 break; 736 737 default: 738 // Nothing to do 739 } 740 741 if (needUpdate) { 742 mSettings.updateIntentFilterVerificationStatusLPw( 743 packageName, updatedStatus, userId); 744 scheduleWritePackageRestrictionsLocked(userId); 745 } 746 } 747 } 748 } 749 750 @Override 751 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 752 ActivityIntentInfo filter, String packageName) { 753 if (!hasValidDomains(filter)) { 754 return false; 755 } 756 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 757 if (ivs == null) { 758 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 759 packageName); 760 } 761 if (DEBUG_DOMAIN_VERIFICATION) { 762 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 763 } 764 ivs.addFilter(filter); 765 return true; 766 } 767 768 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 769 int userId, int verificationId, String packageName) { 770 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 771 verifierUid, userId, packageName); 772 ivs.setPendingState(); 773 synchronized (mPackages) { 774 mIntentFilterVerificationStates.append(verificationId, ivs); 775 mCurrentIntentFilterVerifications.add(verificationId); 776 } 777 return ivs; 778 } 779 } 780 781 private static boolean hasValidDomains(ActivityIntentInfo filter) { 782 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 783 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 784 if (!hasHTTPorHTTPS) { 785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 786 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 787 return false; 788 } 789 return true; 790 } 791 792 private IntentFilterVerifier mIntentFilterVerifier; 793 794 // Set of pending broadcasts for aggregating enable/disable of components. 795 static class PendingPackageBroadcasts { 796 // for each user id, a map of <package name -> components within that package> 797 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 798 799 public PendingPackageBroadcasts() { 800 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 801 } 802 803 public ArrayList<String> get(int userId, String packageName) { 804 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 805 return packages.get(packageName); 806 } 807 808 public void put(int userId, String packageName, ArrayList<String> components) { 809 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 810 packages.put(packageName, components); 811 } 812 813 public void remove(int userId, String packageName) { 814 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 815 if (packages != null) { 816 packages.remove(packageName); 817 } 818 } 819 820 public void remove(int userId) { 821 mUidMap.remove(userId); 822 } 823 824 public int userIdCount() { 825 return mUidMap.size(); 826 } 827 828 public int userIdAt(int n) { 829 return mUidMap.keyAt(n); 830 } 831 832 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 833 return mUidMap.get(userId); 834 } 835 836 public int size() { 837 // total number of pending broadcast entries across all userIds 838 int num = 0; 839 for (int i = 0; i< mUidMap.size(); i++) { 840 num += mUidMap.valueAt(i).size(); 841 } 842 return num; 843 } 844 845 public void clear() { 846 mUidMap.clear(); 847 } 848 849 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 850 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 851 if (map == null) { 852 map = new ArrayMap<String, ArrayList<String>>(); 853 mUidMap.put(userId, map); 854 } 855 return map; 856 } 857 } 858 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 859 860 // Service Connection to remote media container service to copy 861 // package uri's from external media onto secure containers 862 // or internal storage. 863 private IMediaContainerService mContainerService = null; 864 865 static final int SEND_PENDING_BROADCAST = 1; 866 static final int MCS_BOUND = 3; 867 static final int END_COPY = 4; 868 static final int INIT_COPY = 5; 869 static final int MCS_UNBIND = 6; 870 static final int START_CLEANING_PACKAGE = 7; 871 static final int FIND_INSTALL_LOC = 8; 872 static final int POST_INSTALL = 9; 873 static final int MCS_RECONNECT = 10; 874 static final int MCS_GIVE_UP = 11; 875 static final int UPDATED_MEDIA_STATUS = 12; 876 static final int WRITE_SETTINGS = 13; 877 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 878 static final int PACKAGE_VERIFIED = 15; 879 static final int CHECK_PENDING_VERIFICATION = 16; 880 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 881 static final int INTENT_FILTER_VERIFIED = 18; 882 883 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 884 885 // Delay time in millisecs 886 static final int BROADCAST_DELAY = 10 * 1000; 887 888 static UserManagerService sUserManager; 889 890 // Stores a list of users whose package restrictions file needs to be updated 891 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 892 893 final private DefaultContainerConnection mDefContainerConn = 894 new DefaultContainerConnection(); 895 class DefaultContainerConnection implements ServiceConnection { 896 public void onServiceConnected(ComponentName name, IBinder service) { 897 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 898 IMediaContainerService imcs = 899 IMediaContainerService.Stub.asInterface(service); 900 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 901 } 902 903 public void onServiceDisconnected(ComponentName name) { 904 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 905 } 906 } 907 908 // Recordkeeping of restore-after-install operations that are currently in flight 909 // between the Package Manager and the Backup Manager 910 class PostInstallData { 911 public InstallArgs args; 912 public PackageInstalledInfo res; 913 914 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 915 args = _a; 916 res = _r; 917 } 918 } 919 920 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 921 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 922 923 // XML tags for backup/restore of various bits of state 924 private static final String TAG_PREFERRED_BACKUP = "pa"; 925 private static final String TAG_DEFAULT_APPS = "da"; 926 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 927 928 private final String mRequiredVerifierPackage; 929 930 private final PackageUsage mPackageUsage = new PackageUsage(); 931 932 private class PackageUsage { 933 private static final int WRITE_INTERVAL 934 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 935 936 private final Object mFileLock = new Object(); 937 private final AtomicLong mLastWritten = new AtomicLong(0); 938 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 939 940 private boolean mIsHistoricalPackageUsageAvailable = true; 941 942 boolean isHistoricalPackageUsageAvailable() { 943 return mIsHistoricalPackageUsageAvailable; 944 } 945 946 void write(boolean force) { 947 if (force) { 948 writeInternal(); 949 return; 950 } 951 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 952 && !DEBUG_DEXOPT) { 953 return; 954 } 955 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 956 new Thread("PackageUsage_DiskWriter") { 957 @Override 958 public void run() { 959 try { 960 writeInternal(); 961 } finally { 962 mBackgroundWriteRunning.set(false); 963 } 964 } 965 }.start(); 966 } 967 } 968 969 private void writeInternal() { 970 synchronized (mPackages) { 971 synchronized (mFileLock) { 972 AtomicFile file = getFile(); 973 FileOutputStream f = null; 974 try { 975 f = file.startWrite(); 976 BufferedOutputStream out = new BufferedOutputStream(f); 977 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 978 StringBuilder sb = new StringBuilder(); 979 for (PackageParser.Package pkg : mPackages.values()) { 980 if (pkg.mLastPackageUsageTimeInMills == 0) { 981 continue; 982 } 983 sb.setLength(0); 984 sb.append(pkg.packageName); 985 sb.append(' '); 986 sb.append((long)pkg.mLastPackageUsageTimeInMills); 987 sb.append('\n'); 988 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 989 } 990 out.flush(); 991 file.finishWrite(f); 992 } catch (IOException e) { 993 if (f != null) { 994 file.failWrite(f); 995 } 996 Log.e(TAG, "Failed to write package usage times", e); 997 } 998 } 999 } 1000 mLastWritten.set(SystemClock.elapsedRealtime()); 1001 } 1002 1003 void readLP() { 1004 synchronized (mFileLock) { 1005 AtomicFile file = getFile(); 1006 BufferedInputStream in = null; 1007 try { 1008 in = new BufferedInputStream(file.openRead()); 1009 StringBuffer sb = new StringBuffer(); 1010 while (true) { 1011 String packageName = readToken(in, sb, ' '); 1012 if (packageName == null) { 1013 break; 1014 } 1015 String timeInMillisString = readToken(in, sb, '\n'); 1016 if (timeInMillisString == null) { 1017 throw new IOException("Failed to find last usage time for package " 1018 + packageName); 1019 } 1020 PackageParser.Package pkg = mPackages.get(packageName); 1021 if (pkg == null) { 1022 continue; 1023 } 1024 long timeInMillis; 1025 try { 1026 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1027 } catch (NumberFormatException e) { 1028 throw new IOException("Failed to parse " + timeInMillisString 1029 + " as a long.", e); 1030 } 1031 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1032 } 1033 } catch (FileNotFoundException expected) { 1034 mIsHistoricalPackageUsageAvailable = false; 1035 } catch (IOException e) { 1036 Log.w(TAG, "Failed to read package usage times", e); 1037 } finally { 1038 IoUtils.closeQuietly(in); 1039 } 1040 } 1041 mLastWritten.set(SystemClock.elapsedRealtime()); 1042 } 1043 1044 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1045 throws IOException { 1046 sb.setLength(0); 1047 while (true) { 1048 int ch = in.read(); 1049 if (ch == -1) { 1050 if (sb.length() == 0) { 1051 return null; 1052 } 1053 throw new IOException("Unexpected EOF"); 1054 } 1055 if (ch == endOfToken) { 1056 return sb.toString(); 1057 } 1058 sb.append((char)ch); 1059 } 1060 } 1061 1062 private AtomicFile getFile() { 1063 File dataDir = Environment.getDataDirectory(); 1064 File systemDir = new File(dataDir, "system"); 1065 File fname = new File(systemDir, "package-usage.list"); 1066 return new AtomicFile(fname); 1067 } 1068 } 1069 1070 class PackageHandler extends Handler { 1071 private boolean mBound = false; 1072 final ArrayList<HandlerParams> mPendingInstalls = 1073 new ArrayList<HandlerParams>(); 1074 1075 private boolean connectToService() { 1076 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1077 " DefaultContainerService"); 1078 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1079 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1080 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1081 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1082 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1083 mBound = true; 1084 return true; 1085 } 1086 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1087 return false; 1088 } 1089 1090 private void disconnectService() { 1091 mContainerService = null; 1092 mBound = false; 1093 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1094 mContext.unbindService(mDefContainerConn); 1095 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1096 } 1097 1098 PackageHandler(Looper looper) { 1099 super(looper); 1100 } 1101 1102 public void handleMessage(Message msg) { 1103 try { 1104 doHandleMessage(msg); 1105 } finally { 1106 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1107 } 1108 } 1109 1110 void doHandleMessage(Message msg) { 1111 switch (msg.what) { 1112 case INIT_COPY: { 1113 HandlerParams params = (HandlerParams) msg.obj; 1114 int idx = mPendingInstalls.size(); 1115 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1116 // If a bind was already initiated we dont really 1117 // need to do anything. The pending install 1118 // will be processed later on. 1119 if (!mBound) { 1120 // If this is the only one pending we might 1121 // have to bind to the service again. 1122 if (!connectToService()) { 1123 Slog.e(TAG, "Failed to bind to media container service"); 1124 params.serviceError(); 1125 return; 1126 } else { 1127 // Once we bind to the service, the first 1128 // pending request will be processed. 1129 mPendingInstalls.add(idx, params); 1130 } 1131 } else { 1132 mPendingInstalls.add(idx, params); 1133 // Already bound to the service. Just make 1134 // sure we trigger off processing the first request. 1135 if (idx == 0) { 1136 mHandler.sendEmptyMessage(MCS_BOUND); 1137 } 1138 } 1139 break; 1140 } 1141 case MCS_BOUND: { 1142 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1143 if (msg.obj != null) { 1144 mContainerService = (IMediaContainerService) msg.obj; 1145 } 1146 if (mContainerService == null) { 1147 if (!mBound) { 1148 // Something seriously wrong since we are not bound and we are not 1149 // waiting for connection. Bail out. 1150 Slog.e(TAG, "Cannot bind to media container service"); 1151 for (HandlerParams params : mPendingInstalls) { 1152 // Indicate service bind error 1153 params.serviceError(); 1154 } 1155 mPendingInstalls.clear(); 1156 } else { 1157 Slog.w(TAG, "Waiting to connect to media container service"); 1158 } 1159 } else if (mPendingInstalls.size() > 0) { 1160 HandlerParams params = mPendingInstalls.get(0); 1161 if (params != null) { 1162 if (params.startCopy()) { 1163 // We are done... look for more work or to 1164 // go idle. 1165 if (DEBUG_SD_INSTALL) Log.i(TAG, 1166 "Checking for more work or unbind..."); 1167 // Delete pending install 1168 if (mPendingInstalls.size() > 0) { 1169 mPendingInstalls.remove(0); 1170 } 1171 if (mPendingInstalls.size() == 0) { 1172 if (mBound) { 1173 if (DEBUG_SD_INSTALL) Log.i(TAG, 1174 "Posting delayed MCS_UNBIND"); 1175 removeMessages(MCS_UNBIND); 1176 Message ubmsg = obtainMessage(MCS_UNBIND); 1177 // Unbind after a little delay, to avoid 1178 // continual thrashing. 1179 sendMessageDelayed(ubmsg, 10000); 1180 } 1181 } else { 1182 // There are more pending requests in queue. 1183 // Just post MCS_BOUND message to trigger processing 1184 // of next pending install. 1185 if (DEBUG_SD_INSTALL) Log.i(TAG, 1186 "Posting MCS_BOUND for next work"); 1187 mHandler.sendEmptyMessage(MCS_BOUND); 1188 } 1189 } 1190 } 1191 } else { 1192 // Should never happen ideally. 1193 Slog.w(TAG, "Empty queue"); 1194 } 1195 break; 1196 } 1197 case MCS_RECONNECT: { 1198 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1199 if (mPendingInstalls.size() > 0) { 1200 if (mBound) { 1201 disconnectService(); 1202 } 1203 if (!connectToService()) { 1204 Slog.e(TAG, "Failed to bind to media container service"); 1205 for (HandlerParams params : mPendingInstalls) { 1206 // Indicate service bind error 1207 params.serviceError(); 1208 } 1209 mPendingInstalls.clear(); 1210 } 1211 } 1212 break; 1213 } 1214 case MCS_UNBIND: { 1215 // If there is no actual work left, then time to unbind. 1216 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1217 1218 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1219 if (mBound) { 1220 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1221 1222 disconnectService(); 1223 } 1224 } else if (mPendingInstalls.size() > 0) { 1225 // There are more pending requests in queue. 1226 // Just post MCS_BOUND message to trigger processing 1227 // of next pending install. 1228 mHandler.sendEmptyMessage(MCS_BOUND); 1229 } 1230 1231 break; 1232 } 1233 case MCS_GIVE_UP: { 1234 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1235 mPendingInstalls.remove(0); 1236 break; 1237 } 1238 case SEND_PENDING_BROADCAST: { 1239 String packages[]; 1240 ArrayList<String> components[]; 1241 int size = 0; 1242 int uids[]; 1243 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1244 synchronized (mPackages) { 1245 if (mPendingBroadcasts == null) { 1246 return; 1247 } 1248 size = mPendingBroadcasts.size(); 1249 if (size <= 0) { 1250 // Nothing to be done. Just return 1251 return; 1252 } 1253 packages = new String[size]; 1254 components = new ArrayList[size]; 1255 uids = new int[size]; 1256 int i = 0; // filling out the above arrays 1257 1258 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1259 int packageUserId = mPendingBroadcasts.userIdAt(n); 1260 Iterator<Map.Entry<String, ArrayList<String>>> it 1261 = mPendingBroadcasts.packagesForUserId(packageUserId) 1262 .entrySet().iterator(); 1263 while (it.hasNext() && i < size) { 1264 Map.Entry<String, ArrayList<String>> ent = it.next(); 1265 packages[i] = ent.getKey(); 1266 components[i] = ent.getValue(); 1267 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1268 uids[i] = (ps != null) 1269 ? UserHandle.getUid(packageUserId, ps.appId) 1270 : -1; 1271 i++; 1272 } 1273 } 1274 size = i; 1275 mPendingBroadcasts.clear(); 1276 } 1277 // Send broadcasts 1278 for (int i = 0; i < size; i++) { 1279 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1280 } 1281 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1282 break; 1283 } 1284 case START_CLEANING_PACKAGE: { 1285 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1286 final String packageName = (String)msg.obj; 1287 final int userId = msg.arg1; 1288 final boolean andCode = msg.arg2 != 0; 1289 synchronized (mPackages) { 1290 if (userId == UserHandle.USER_ALL) { 1291 int[] users = sUserManager.getUserIds(); 1292 for (int user : users) { 1293 mSettings.addPackageToCleanLPw( 1294 new PackageCleanItem(user, packageName, andCode)); 1295 } 1296 } else { 1297 mSettings.addPackageToCleanLPw( 1298 new PackageCleanItem(userId, packageName, andCode)); 1299 } 1300 } 1301 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1302 startCleaningPackages(); 1303 } break; 1304 case POST_INSTALL: { 1305 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1306 PostInstallData data = mRunningInstalls.get(msg.arg1); 1307 mRunningInstalls.delete(msg.arg1); 1308 boolean deleteOld = false; 1309 1310 if (data != null) { 1311 InstallArgs args = data.args; 1312 PackageInstalledInfo res = data.res; 1313 1314 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1315 final String packageName = res.pkg.applicationInfo.packageName; 1316 res.removedInfo.sendBroadcast(false, true, false); 1317 Bundle extras = new Bundle(1); 1318 extras.putInt(Intent.EXTRA_UID, res.uid); 1319 1320 // Now that we successfully installed the package, grant runtime 1321 // permissions if requested before broadcasting the install. 1322 if ((args.installFlags 1323 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1324 grantRequestedRuntimePermissions(res.pkg, 1325 args.user.getIdentifier()); 1326 } 1327 1328 // Determine the set of users who are adding this 1329 // package for the first time vs. those who are seeing 1330 // an update. 1331 int[] firstUsers; 1332 int[] updateUsers = new int[0]; 1333 if (res.origUsers == null || res.origUsers.length == 0) { 1334 firstUsers = res.newUsers; 1335 } else { 1336 firstUsers = new int[0]; 1337 for (int i=0; i<res.newUsers.length; i++) { 1338 int user = res.newUsers[i]; 1339 boolean isNew = true; 1340 for (int j=0; j<res.origUsers.length; j++) { 1341 if (res.origUsers[j] == user) { 1342 isNew = false; 1343 break; 1344 } 1345 } 1346 if (isNew) { 1347 int[] newFirst = new int[firstUsers.length+1]; 1348 System.arraycopy(firstUsers, 0, newFirst, 0, 1349 firstUsers.length); 1350 newFirst[firstUsers.length] = user; 1351 firstUsers = newFirst; 1352 } else { 1353 int[] newUpdate = new int[updateUsers.length+1]; 1354 System.arraycopy(updateUsers, 0, newUpdate, 0, 1355 updateUsers.length); 1356 newUpdate[updateUsers.length] = user; 1357 updateUsers = newUpdate; 1358 } 1359 } 1360 } 1361 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1362 packageName, extras, null, null, firstUsers); 1363 final boolean update = res.removedInfo.removedPackage != null; 1364 if (update) { 1365 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1366 } 1367 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1368 packageName, extras, null, null, updateUsers); 1369 if (update) { 1370 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1371 packageName, extras, null, null, updateUsers); 1372 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1373 null, null, packageName, null, updateUsers); 1374 1375 // treat asec-hosted packages like removable media on upgrade 1376 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1377 if (DEBUG_INSTALL) { 1378 Slog.i(TAG, "upgrading pkg " + res.pkg 1379 + " is ASEC-hosted -> AVAILABLE"); 1380 } 1381 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1382 ArrayList<String> pkgList = new ArrayList<String>(1); 1383 pkgList.add(packageName); 1384 sendResourcesChangedBroadcast(true, true, 1385 pkgList,uidArray, null); 1386 } 1387 } 1388 if (res.removedInfo.args != null) { 1389 // Remove the replaced package's older resources safely now 1390 deleteOld = true; 1391 } 1392 1393 // If this app is a browser and it's newly-installed for some 1394 // users, clear any default-browser state in those users 1395 if (firstUsers.length > 0) { 1396 // the app's nature doesn't depend on the user, so we can just 1397 // check its browser nature in any user and generalize. 1398 if (packageIsBrowser(packageName, firstUsers[0])) { 1399 synchronized (mPackages) { 1400 for (int userId : firstUsers) { 1401 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1402 } 1403 } 1404 } 1405 } 1406 // Log current value of "unknown sources" setting 1407 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1408 getUnknownSourcesSettings()); 1409 } 1410 // Force a gc to clear up things 1411 Runtime.getRuntime().gc(); 1412 // We delete after a gc for applications on sdcard. 1413 if (deleteOld) { 1414 synchronized (mInstallLock) { 1415 res.removedInfo.args.doPostDeleteLI(true); 1416 } 1417 } 1418 if (args.observer != null) { 1419 try { 1420 Bundle extras = extrasForInstallResult(res); 1421 args.observer.onPackageInstalled(res.name, res.returnCode, 1422 res.returnMsg, extras); 1423 } catch (RemoteException e) { 1424 Slog.i(TAG, "Observer no longer exists."); 1425 } 1426 } 1427 } else { 1428 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1429 } 1430 } break; 1431 case UPDATED_MEDIA_STATUS: { 1432 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1433 boolean reportStatus = msg.arg1 == 1; 1434 boolean doGc = msg.arg2 == 1; 1435 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1436 if (doGc) { 1437 // Force a gc to clear up stale containers. 1438 Runtime.getRuntime().gc(); 1439 } 1440 if (msg.obj != null) { 1441 @SuppressWarnings("unchecked") 1442 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1443 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1444 // Unload containers 1445 unloadAllContainers(args); 1446 } 1447 if (reportStatus) { 1448 try { 1449 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1450 PackageHelper.getMountService().finishMediaUpdate(); 1451 } catch (RemoteException e) { 1452 Log.e(TAG, "MountService not running?"); 1453 } 1454 } 1455 } break; 1456 case WRITE_SETTINGS: { 1457 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1458 synchronized (mPackages) { 1459 removeMessages(WRITE_SETTINGS); 1460 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1461 mSettings.writeLPr(); 1462 mDirtyUsers.clear(); 1463 } 1464 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1465 } break; 1466 case WRITE_PACKAGE_RESTRICTIONS: { 1467 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1468 synchronized (mPackages) { 1469 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1470 for (int userId : mDirtyUsers) { 1471 mSettings.writePackageRestrictionsLPr(userId); 1472 } 1473 mDirtyUsers.clear(); 1474 } 1475 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1476 } break; 1477 case CHECK_PENDING_VERIFICATION: { 1478 final int verificationId = msg.arg1; 1479 final PackageVerificationState state = mPendingVerification.get(verificationId); 1480 1481 if ((state != null) && !state.timeoutExtended()) { 1482 final InstallArgs args = state.getInstallArgs(); 1483 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1484 1485 Slog.i(TAG, "Verification timed out for " + originUri); 1486 mPendingVerification.remove(verificationId); 1487 1488 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1489 1490 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1491 Slog.i(TAG, "Continuing with installation of " + originUri); 1492 state.setVerifierResponse(Binder.getCallingUid(), 1493 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1494 broadcastPackageVerified(verificationId, originUri, 1495 PackageManager.VERIFICATION_ALLOW, 1496 state.getInstallArgs().getUser()); 1497 try { 1498 ret = args.copyApk(mContainerService, true); 1499 } catch (RemoteException e) { 1500 Slog.e(TAG, "Could not contact the ContainerService"); 1501 } 1502 } else { 1503 broadcastPackageVerified(verificationId, originUri, 1504 PackageManager.VERIFICATION_REJECT, 1505 state.getInstallArgs().getUser()); 1506 } 1507 1508 processPendingInstall(args, ret); 1509 mHandler.sendEmptyMessage(MCS_UNBIND); 1510 } 1511 break; 1512 } 1513 case PACKAGE_VERIFIED: { 1514 final int verificationId = msg.arg1; 1515 1516 final PackageVerificationState state = mPendingVerification.get(verificationId); 1517 if (state == null) { 1518 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1519 break; 1520 } 1521 1522 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1523 1524 state.setVerifierResponse(response.callerUid, response.code); 1525 1526 if (state.isVerificationComplete()) { 1527 mPendingVerification.remove(verificationId); 1528 1529 final InstallArgs args = state.getInstallArgs(); 1530 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1531 1532 int ret; 1533 if (state.isInstallAllowed()) { 1534 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1535 broadcastPackageVerified(verificationId, originUri, 1536 response.code, state.getInstallArgs().getUser()); 1537 try { 1538 ret = args.copyApk(mContainerService, true); 1539 } catch (RemoteException e) { 1540 Slog.e(TAG, "Could not contact the ContainerService"); 1541 } 1542 } else { 1543 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1544 } 1545 1546 processPendingInstall(args, ret); 1547 1548 mHandler.sendEmptyMessage(MCS_UNBIND); 1549 } 1550 1551 break; 1552 } 1553 case START_INTENT_FILTER_VERIFICATIONS: { 1554 IFVerificationParams params = (IFVerificationParams) msg.obj; 1555 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1556 params.replacing, params.pkg); 1557 break; 1558 } 1559 case INTENT_FILTER_VERIFIED: { 1560 final int verificationId = msg.arg1; 1561 1562 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1563 verificationId); 1564 if (state == null) { 1565 Slog.w(TAG, "Invalid IntentFilter verification token " 1566 + verificationId + " received"); 1567 break; 1568 } 1569 1570 final int userId = state.getUserId(); 1571 1572 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1573 "Processing IntentFilter verification with token:" 1574 + verificationId + " and userId:" + userId); 1575 1576 final IntentFilterVerificationResponse response = 1577 (IntentFilterVerificationResponse) msg.obj; 1578 1579 state.setVerifierResponse(response.callerUid, response.code); 1580 1581 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1582 "IntentFilter verification with token:" + verificationId 1583 + " and userId:" + userId 1584 + " is settings verifier response with response code:" 1585 + response.code); 1586 1587 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1588 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1589 + response.getFailedDomainsString()); 1590 } 1591 1592 if (state.isVerificationComplete()) { 1593 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1594 } else { 1595 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1596 "IntentFilter verification with token:" + verificationId 1597 + " was not said to be complete"); 1598 } 1599 1600 break; 1601 } 1602 } 1603 } 1604 } 1605 1606 private StorageEventListener mStorageListener = new StorageEventListener() { 1607 @Override 1608 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1609 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1610 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1611 final String volumeUuid = vol.getFsUuid(); 1612 1613 // Clean up any users or apps that were removed or recreated 1614 // while this volume was missing 1615 reconcileUsers(volumeUuid); 1616 reconcileApps(volumeUuid); 1617 1618 // Clean up any install sessions that expired or were 1619 // cancelled while this volume was missing 1620 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1621 1622 loadPrivatePackages(vol); 1623 1624 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1625 unloadPrivatePackages(vol); 1626 } 1627 } 1628 1629 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1630 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1631 updateExternalMediaStatus(true, false); 1632 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1633 updateExternalMediaStatus(false, false); 1634 } 1635 } 1636 } 1637 1638 @Override 1639 public void onVolumeForgotten(String fsUuid) { 1640 // Remove any apps installed on the forgotten volume 1641 synchronized (mPackages) { 1642 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1643 for (PackageSetting ps : packages) { 1644 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1645 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1646 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1647 } 1648 1649 mSettings.writeLPr(); 1650 } 1651 } 1652 }; 1653 1654 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1655 if (userId >= UserHandle.USER_OWNER) { 1656 grantRequestedRuntimePermissionsForUser(pkg, userId); 1657 } else if (userId == UserHandle.USER_ALL) { 1658 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1659 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1660 } 1661 } 1662 1663 // We could have touched GID membership, so flush out packages.list 1664 synchronized (mPackages) { 1665 mSettings.writePackageListLPr(); 1666 } 1667 } 1668 1669 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1670 SettingBase sb = (SettingBase) pkg.mExtras; 1671 if (sb == null) { 1672 return; 1673 } 1674 1675 PermissionsState permissionsState = sb.getPermissionsState(); 1676 1677 for (String permission : pkg.requestedPermissions) { 1678 BasePermission bp = mSettings.mPermissions.get(permission); 1679 if (bp != null && bp.isRuntime()) { 1680 permissionsState.grantRuntimePermission(bp, userId); 1681 } 1682 } 1683 } 1684 1685 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1686 Bundle extras = null; 1687 switch (res.returnCode) { 1688 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1689 extras = new Bundle(); 1690 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1691 res.origPermission); 1692 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1693 res.origPackage); 1694 break; 1695 } 1696 case PackageManager.INSTALL_SUCCEEDED: { 1697 extras = new Bundle(); 1698 extras.putBoolean(Intent.EXTRA_REPLACING, 1699 res.removedInfo != null && res.removedInfo.removedPackage != null); 1700 break; 1701 } 1702 } 1703 return extras; 1704 } 1705 1706 void scheduleWriteSettingsLocked() { 1707 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1708 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1709 } 1710 } 1711 1712 void scheduleWritePackageRestrictionsLocked(int userId) { 1713 if (!sUserManager.exists(userId)) return; 1714 mDirtyUsers.add(userId); 1715 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1716 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1717 } 1718 } 1719 1720 public static PackageManagerService main(Context context, Installer installer, 1721 boolean factoryTest, boolean onlyCore) { 1722 PackageManagerService m = new PackageManagerService(context, installer, 1723 factoryTest, onlyCore); 1724 ServiceManager.addService("package", m); 1725 return m; 1726 } 1727 1728 static String[] splitString(String str, char sep) { 1729 int count = 1; 1730 int i = 0; 1731 while ((i=str.indexOf(sep, i)) >= 0) { 1732 count++; 1733 i++; 1734 } 1735 1736 String[] res = new String[count]; 1737 i=0; 1738 count = 0; 1739 int lastI=0; 1740 while ((i=str.indexOf(sep, i)) >= 0) { 1741 res[count] = str.substring(lastI, i); 1742 count++; 1743 i++; 1744 lastI = i; 1745 } 1746 res[count] = str.substring(lastI, str.length()); 1747 return res; 1748 } 1749 1750 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1751 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1752 Context.DISPLAY_SERVICE); 1753 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1754 } 1755 1756 public PackageManagerService(Context context, Installer installer, 1757 boolean factoryTest, boolean onlyCore) { 1758 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1759 SystemClock.uptimeMillis()); 1760 1761 if (mSdkVersion <= 0) { 1762 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1763 } 1764 1765 mContext = context; 1766 mFactoryTest = factoryTest; 1767 mOnlyCore = onlyCore; 1768 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1769 mMetrics = new DisplayMetrics(); 1770 mSettings = new Settings(mPackages); 1771 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1772 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1773 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1774 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1775 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1776 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1777 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1778 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1779 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1780 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1781 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1782 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1783 1784 // TODO: add a property to control this? 1785 long dexOptLRUThresholdInMinutes; 1786 if (mLazyDexOpt) { 1787 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1788 } else { 1789 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1790 } 1791 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1792 1793 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1794 if (separateProcesses != null && separateProcesses.length() > 0) { 1795 if ("*".equals(separateProcesses)) { 1796 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1797 mSeparateProcesses = null; 1798 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1799 } else { 1800 mDefParseFlags = 0; 1801 mSeparateProcesses = separateProcesses.split(","); 1802 Slog.w(TAG, "Running with debug.separate_processes: " 1803 + separateProcesses); 1804 } 1805 } else { 1806 mDefParseFlags = 0; 1807 mSeparateProcesses = null; 1808 } 1809 1810 mInstaller = installer; 1811 mPackageDexOptimizer = new PackageDexOptimizer(this); 1812 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1813 1814 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1815 FgThread.get().getLooper()); 1816 1817 getDefaultDisplayMetrics(context, mMetrics); 1818 1819 SystemConfig systemConfig = SystemConfig.getInstance(); 1820 mGlobalGids = systemConfig.getGlobalGids(); 1821 mSystemPermissions = systemConfig.getSystemPermissions(); 1822 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1823 1824 synchronized (mInstallLock) { 1825 // writer 1826 synchronized (mPackages) { 1827 mHandlerThread = new ServiceThread(TAG, 1828 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1829 mHandlerThread.start(); 1830 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1831 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1832 1833 File dataDir = Environment.getDataDirectory(); 1834 mAppDataDir = new File(dataDir, "data"); 1835 mAppInstallDir = new File(dataDir, "app"); 1836 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1837 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1838 mUserAppDataDir = new File(dataDir, "user"); 1839 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1840 1841 sUserManager = new UserManagerService(context, this, 1842 mInstallLock, mPackages); 1843 1844 // Propagate permission configuration in to package manager. 1845 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1846 = systemConfig.getPermissions(); 1847 for (int i=0; i<permConfig.size(); i++) { 1848 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1849 BasePermission bp = mSettings.mPermissions.get(perm.name); 1850 if (bp == null) { 1851 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1852 mSettings.mPermissions.put(perm.name, bp); 1853 } 1854 if (perm.gids != null) { 1855 bp.setGids(perm.gids, perm.perUser); 1856 } 1857 } 1858 1859 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1860 for (int i=0; i<libConfig.size(); i++) { 1861 mSharedLibraries.put(libConfig.keyAt(i), 1862 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1863 } 1864 1865 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1866 1867 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1868 mSdkVersion, mOnlyCore); 1869 1870 String customResolverActivity = Resources.getSystem().getString( 1871 R.string.config_customResolverActivity); 1872 if (TextUtils.isEmpty(customResolverActivity)) { 1873 customResolverActivity = null; 1874 } else { 1875 mCustomResolverComponentName = ComponentName.unflattenFromString( 1876 customResolverActivity); 1877 } 1878 1879 long startTime = SystemClock.uptimeMillis(); 1880 1881 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1882 startTime); 1883 1884 // Set flag to monitor and not change apk file paths when 1885 // scanning install directories. 1886 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1887 1888 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1889 1890 /** 1891 * Add everything in the in the boot class path to the 1892 * list of process files because dexopt will have been run 1893 * if necessary during zygote startup. 1894 */ 1895 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1896 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1897 1898 if (bootClassPath != null) { 1899 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1900 for (String element : bootClassPathElements) { 1901 alreadyDexOpted.add(element); 1902 } 1903 } else { 1904 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1905 } 1906 1907 if (systemServerClassPath != null) { 1908 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1909 for (String element : systemServerClassPathElements) { 1910 alreadyDexOpted.add(element); 1911 } 1912 } else { 1913 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1914 } 1915 1916 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1917 final String[] dexCodeInstructionSets = 1918 getDexCodeInstructionSets( 1919 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1920 1921 /** 1922 * Ensure all external libraries have had dexopt run on them. 1923 */ 1924 if (mSharedLibraries.size() > 0) { 1925 // NOTE: For now, we're compiling these system "shared libraries" 1926 // (and framework jars) into all available architectures. It's possible 1927 // to compile them only when we come across an app that uses them (there's 1928 // already logic for that in scanPackageLI) but that adds some complexity. 1929 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1930 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1931 final String lib = libEntry.path; 1932 if (lib == null) { 1933 continue; 1934 } 1935 1936 try { 1937 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1938 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1939 alreadyDexOpted.add(lib); 1940 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1941 } 1942 } catch (FileNotFoundException e) { 1943 Slog.w(TAG, "Library not found: " + lib); 1944 } catch (IOException e) { 1945 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1946 + e.getMessage()); 1947 } 1948 } 1949 } 1950 } 1951 1952 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1953 1954 // Gross hack for now: we know this file doesn't contain any 1955 // code, so don't dexopt it to avoid the resulting log spew. 1956 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1957 1958 // Gross hack for now: we know this file is only part of 1959 // the boot class path for art, so don't dexopt it to 1960 // avoid the resulting log spew. 1961 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1962 1963 /** 1964 * There are a number of commands implemented in Java, which 1965 * we currently need to do the dexopt on so that they can be 1966 * run from a non-root shell. 1967 */ 1968 String[] frameworkFiles = frameworkDir.list(); 1969 if (frameworkFiles != null) { 1970 // TODO: We could compile these only for the most preferred ABI. We should 1971 // first double check that the dex files for these commands are not referenced 1972 // by other system apps. 1973 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1974 for (int i=0; i<frameworkFiles.length; i++) { 1975 File libPath = new File(frameworkDir, frameworkFiles[i]); 1976 String path = libPath.getPath(); 1977 // Skip the file if we already did it. 1978 if (alreadyDexOpted.contains(path)) { 1979 continue; 1980 } 1981 // Skip the file if it is not a type we want to dexopt. 1982 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1983 continue; 1984 } 1985 try { 1986 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1987 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1988 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1989 } 1990 } catch (FileNotFoundException e) { 1991 Slog.w(TAG, "Jar not found: " + path); 1992 } catch (IOException e) { 1993 Slog.w(TAG, "Exception reading jar: " + path, e); 1994 } 1995 } 1996 } 1997 } 1998 1999 // Collect vendor overlay packages. 2000 // (Do this before scanning any apps.) 2001 // For security and version matching reason, only consider 2002 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2003 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2004 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2005 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2006 2007 // Find base frameworks (resource packages without code). 2008 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2009 | PackageParser.PARSE_IS_SYSTEM_DIR 2010 | PackageParser.PARSE_IS_PRIVILEGED, 2011 scanFlags | SCAN_NO_DEX, 0); 2012 2013 // Collected privileged system packages. 2014 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2015 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2016 | PackageParser.PARSE_IS_SYSTEM_DIR 2017 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2018 2019 // Collect ordinary system packages. 2020 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2021 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2022 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2023 2024 // Collect all vendor packages. 2025 File vendorAppDir = new File("/vendor/app"); 2026 try { 2027 vendorAppDir = vendorAppDir.getCanonicalFile(); 2028 } catch (IOException e) { 2029 // failed to look up canonical path, continue with original one 2030 } 2031 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2032 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2033 2034 // Collect all OEM packages. 2035 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2036 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2037 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2038 2039 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2040 mInstaller.moveFiles(); 2041 2042 // Prune any system packages that no longer exist. 2043 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2044 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2045 if (!mOnlyCore) { 2046 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2047 while (psit.hasNext()) { 2048 PackageSetting ps = psit.next(); 2049 2050 /* 2051 * If this is not a system app, it can't be a 2052 * disable system app. 2053 */ 2054 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2055 continue; 2056 } 2057 2058 /* 2059 * If the package is scanned, it's not erased. 2060 */ 2061 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2062 if (scannedPkg != null) { 2063 /* 2064 * If the system app is both scanned and in the 2065 * disabled packages list, then it must have been 2066 * added via OTA. Remove it from the currently 2067 * scanned package so the previously user-installed 2068 * application can be scanned. 2069 */ 2070 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2071 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2072 + ps.name + "; removing system app. Last known codePath=" 2073 + ps.codePathString + ", installStatus=" + ps.installStatus 2074 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2075 + scannedPkg.mVersionCode); 2076 removePackageLI(ps, true); 2077 expectingBetter.put(ps.name, ps.codePath); 2078 } 2079 2080 continue; 2081 } 2082 2083 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2084 psit.remove(); 2085 logCriticalInfo(Log.WARN, "System package " + ps.name 2086 + " no longer exists; wiping its data"); 2087 removeDataDirsLI(null, ps.name); 2088 } else { 2089 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2090 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2091 possiblyDeletedUpdatedSystemApps.add(ps.name); 2092 } 2093 } 2094 } 2095 } 2096 2097 //look for any incomplete package installations 2098 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2099 //clean up list 2100 for(int i = 0; i < deletePkgsList.size(); i++) { 2101 //clean up here 2102 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2103 } 2104 //delete tmp files 2105 deleteTempPackageFiles(); 2106 2107 // Remove any shared userIDs that have no associated packages 2108 mSettings.pruneSharedUsersLPw(); 2109 2110 if (!mOnlyCore) { 2111 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2112 SystemClock.uptimeMillis()); 2113 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2114 2115 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2116 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2117 2118 /** 2119 * Remove disable package settings for any updated system 2120 * apps that were removed via an OTA. If they're not a 2121 * previously-updated app, remove them completely. 2122 * Otherwise, just revoke their system-level permissions. 2123 */ 2124 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2125 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2126 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2127 2128 String msg; 2129 if (deletedPkg == null) { 2130 msg = "Updated system package " + deletedAppName 2131 + " no longer exists; wiping its data"; 2132 removeDataDirsLI(null, deletedAppName); 2133 } else { 2134 msg = "Updated system app + " + deletedAppName 2135 + " no longer present; removing system privileges for " 2136 + deletedAppName; 2137 2138 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2139 2140 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2141 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2142 } 2143 logCriticalInfo(Log.WARN, msg); 2144 } 2145 2146 /** 2147 * Make sure all system apps that we expected to appear on 2148 * the userdata partition actually showed up. If they never 2149 * appeared, crawl back and revive the system version. 2150 */ 2151 for (int i = 0; i < expectingBetter.size(); i++) { 2152 final String packageName = expectingBetter.keyAt(i); 2153 if (!mPackages.containsKey(packageName)) { 2154 final File scanFile = expectingBetter.valueAt(i); 2155 2156 logCriticalInfo(Log.WARN, "Expected better " + packageName 2157 + " but never showed up; reverting to system"); 2158 2159 final int reparseFlags; 2160 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2161 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2162 | PackageParser.PARSE_IS_SYSTEM_DIR 2163 | PackageParser.PARSE_IS_PRIVILEGED; 2164 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2165 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2166 | PackageParser.PARSE_IS_SYSTEM_DIR; 2167 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2168 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2169 | PackageParser.PARSE_IS_SYSTEM_DIR; 2170 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2171 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2172 | PackageParser.PARSE_IS_SYSTEM_DIR; 2173 } else { 2174 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2175 continue; 2176 } 2177 2178 mSettings.enableSystemPackageLPw(packageName); 2179 2180 try { 2181 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2182 } catch (PackageManagerException e) { 2183 Slog.e(TAG, "Failed to parse original system package: " 2184 + e.getMessage()); 2185 } 2186 } 2187 } 2188 } 2189 2190 // Now that we know all of the shared libraries, update all clients to have 2191 // the correct library paths. 2192 updateAllSharedLibrariesLPw(); 2193 2194 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2195 // NOTE: We ignore potential failures here during a system scan (like 2196 // the rest of the commands above) because there's precious little we 2197 // can do about it. A settings error is reported, though. 2198 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2199 false /* force dexopt */, false /* defer dexopt */); 2200 } 2201 2202 // Now that we know all the packages we are keeping, 2203 // read and update their last usage times. 2204 mPackageUsage.readLP(); 2205 2206 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2207 SystemClock.uptimeMillis()); 2208 Slog.i(TAG, "Time to scan packages: " 2209 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2210 + " seconds"); 2211 2212 // If the platform SDK has changed since the last time we booted, 2213 // we need to re-grant app permission to catch any new ones that 2214 // appear. This is really a hack, and means that apps can in some 2215 // cases get permissions that the user didn't initially explicitly 2216 // allow... it would be nice to have some better way to handle 2217 // this situation. 2218 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2219 != mSdkVersion; 2220 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2221 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2222 + "; regranting permissions for internal storage"); 2223 mSettings.mInternalSdkPlatform = mSdkVersion; 2224 2225 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2226 | (regrantPermissions 2227 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2228 : 0)); 2229 2230 // If this is the first boot, and it is a normal boot, then 2231 // we need to initialize the default preferred apps. 2232 if (!mRestoredSettings && !onlyCore) { 2233 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2234 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2235 } 2236 2237 // If this is first boot after an OTA, and a normal boot, then 2238 // we need to clear code cache directories. 2239 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2240 if (mIsUpgrade && !onlyCore) { 2241 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2242 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2243 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2244 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2245 } 2246 mSettings.mFingerprint = Build.FINGERPRINT; 2247 } 2248 2249 primeDomainVerificationsLPw(); 2250 checkDefaultBrowser(); 2251 2252 // All the changes are done during package scanning. 2253 mSettings.updateInternalDatabaseVersion(); 2254 2255 // can downgrade to reader 2256 mSettings.writeLPr(); 2257 2258 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2259 SystemClock.uptimeMillis()); 2260 2261 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2262 2263 mInstallerService = new PackageInstallerService(context, this); 2264 2265 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2266 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2267 mIntentFilterVerifierComponent); 2268 2269 } // synchronized (mPackages) 2270 } // synchronized (mInstallLock) 2271 2272 // Now after opening every single application zip, make sure they 2273 // are all flushed. Not really needed, but keeps things nice and 2274 // tidy. 2275 Runtime.getRuntime().gc(); 2276 2277 // Expose private service for system components to use. 2278 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2279 } 2280 2281 @Override 2282 public boolean isFirstBoot() { 2283 return !mRestoredSettings; 2284 } 2285 2286 @Override 2287 public boolean isOnlyCoreApps() { 2288 return mOnlyCore; 2289 } 2290 2291 @Override 2292 public boolean isUpgrade() { 2293 return mIsUpgrade; 2294 } 2295 2296 private String getRequiredVerifierLPr() { 2297 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2298 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2299 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2300 2301 String requiredVerifier = null; 2302 2303 final int N = receivers.size(); 2304 for (int i = 0; i < N; i++) { 2305 final ResolveInfo info = receivers.get(i); 2306 2307 if (info.activityInfo == null) { 2308 continue; 2309 } 2310 2311 final String packageName = info.activityInfo.packageName; 2312 2313 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2314 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2315 continue; 2316 } 2317 2318 if (requiredVerifier != null) { 2319 throw new RuntimeException("There can be only one required verifier"); 2320 } 2321 2322 requiredVerifier = packageName; 2323 } 2324 2325 return requiredVerifier; 2326 } 2327 2328 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2329 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2330 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2331 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2332 2333 ComponentName verifierComponentName = null; 2334 2335 int priority = -1000; 2336 final int N = receivers.size(); 2337 for (int i = 0; i < N; i++) { 2338 final ResolveInfo info = receivers.get(i); 2339 2340 if (info.activityInfo == null) { 2341 continue; 2342 } 2343 2344 final String packageName = info.activityInfo.packageName; 2345 2346 final PackageSetting ps = mSettings.mPackages.get(packageName); 2347 if (ps == null) { 2348 continue; 2349 } 2350 2351 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2352 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2353 continue; 2354 } 2355 2356 // Select the IntentFilterVerifier with the highest priority 2357 if (priority < info.priority) { 2358 priority = info.priority; 2359 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2360 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2361 + verifierComponentName + " with priority: " + info.priority); 2362 } 2363 } 2364 2365 return verifierComponentName; 2366 } 2367 2368 private void primeDomainVerificationsLPw() { 2369 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2370 boolean updated = false; 2371 ArraySet<String> allHostsSet = new ArraySet<>(); 2372 for (PackageParser.Package pkg : mPackages.values()) { 2373 final String packageName = pkg.packageName; 2374 if (!hasDomainURLs(pkg)) { 2375 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2376 "package with no domain URLs: " + packageName); 2377 continue; 2378 } 2379 if (!pkg.isSystemApp()) { 2380 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2381 "No priming domain verifications for a non system package : " + 2382 packageName); 2383 continue; 2384 } 2385 for (PackageParser.Activity a : pkg.activities) { 2386 for (ActivityIntentInfo filter : a.intents) { 2387 if (hasValidDomains(filter)) { 2388 allHostsSet.addAll(filter.getHostsList()); 2389 } 2390 } 2391 } 2392 if (allHostsSet.size() == 0) { 2393 allHostsSet.add("*"); 2394 } 2395 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2396 IntentFilterVerificationInfo ivi = 2397 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2398 if (ivi != null) { 2399 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2400 "Priming domain verifications for package: " + packageName + 2401 " with hosts:" + ivi.getDomainsString()); 2402 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2403 updated = true; 2404 } 2405 else { 2406 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2407 "No priming domain verifications for package: " + packageName); 2408 } 2409 allHostsSet.clear(); 2410 } 2411 if (updated) { 2412 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2413 "Will need to write primed domain verifications"); 2414 } 2415 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2416 } 2417 2418 private void applyFactoryDefaultBrowserLPw(int userId) { 2419 // The default browser app's package name is stored in a string resource, 2420 // with a product-specific overlay used for vendor customization. 2421 String browserPkg = mContext.getResources().getString( 2422 com.android.internal.R.string.default_browser); 2423 if (browserPkg != null) { 2424 // non-empty string => required to be a known package 2425 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2426 if (ps == null) { 2427 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2428 browserPkg = null; 2429 } else { 2430 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2431 } 2432 } 2433 2434 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2435 // default. If there's more than one, just leave everything alone. 2436 if (browserPkg == null) { 2437 calculateDefaultBrowserLPw(userId); 2438 } 2439 } 2440 2441 private void calculateDefaultBrowserLPw(int userId) { 2442 List<String> allBrowsers = resolveAllBrowserApps(userId); 2443 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2444 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2445 } 2446 2447 private List<String> resolveAllBrowserApps(int userId) { 2448 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2449 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2450 PackageManager.MATCH_ALL, userId); 2451 2452 final int count = list.size(); 2453 List<String> result = new ArrayList<String>(count); 2454 for (int i=0; i<count; i++) { 2455 ResolveInfo info = list.get(i); 2456 if (info.activityInfo == null 2457 || !info.handleAllWebDataURI 2458 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2459 || result.contains(info.activityInfo.packageName)) { 2460 continue; 2461 } 2462 result.add(info.activityInfo.packageName); 2463 } 2464 2465 return result; 2466 } 2467 2468 private boolean packageIsBrowser(String packageName, int userId) { 2469 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2470 PackageManager.MATCH_ALL, userId); 2471 final int N = list.size(); 2472 for (int i = 0; i < N; i++) { 2473 ResolveInfo info = list.get(i); 2474 if (packageName.equals(info.activityInfo.packageName)) { 2475 return true; 2476 } 2477 } 2478 return false; 2479 } 2480 2481 private void checkDefaultBrowser() { 2482 final int myUserId = UserHandle.myUserId(); 2483 final String packageName = getDefaultBrowserPackageName(myUserId); 2484 if (packageName != null) { 2485 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2486 if (info == null) { 2487 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2488 synchronized (mPackages) { 2489 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2490 } 2491 } 2492 } 2493 } 2494 2495 @Override 2496 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2497 throws RemoteException { 2498 try { 2499 return super.onTransact(code, data, reply, flags); 2500 } catch (RuntimeException e) { 2501 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2502 Slog.wtf(TAG, "Package Manager Crash", e); 2503 } 2504 throw e; 2505 } 2506 } 2507 2508 void cleanupInstallFailedPackage(PackageSetting ps) { 2509 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2510 2511 removeDataDirsLI(ps.volumeUuid, ps.name); 2512 if (ps.codePath != null) { 2513 if (ps.codePath.isDirectory()) { 2514 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2515 } else { 2516 ps.codePath.delete(); 2517 } 2518 } 2519 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2520 if (ps.resourcePath.isDirectory()) { 2521 FileUtils.deleteContents(ps.resourcePath); 2522 } 2523 ps.resourcePath.delete(); 2524 } 2525 mSettings.removePackageLPw(ps.name); 2526 } 2527 2528 static int[] appendInts(int[] cur, int[] add) { 2529 if (add == null) return cur; 2530 if (cur == null) return add; 2531 final int N = add.length; 2532 for (int i=0; i<N; i++) { 2533 cur = appendInt(cur, add[i]); 2534 } 2535 return cur; 2536 } 2537 2538 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2539 if (!sUserManager.exists(userId)) return null; 2540 final PackageSetting ps = (PackageSetting) p.mExtras; 2541 if (ps == null) { 2542 return null; 2543 } 2544 2545 final PermissionsState permissionsState = ps.getPermissionsState(); 2546 2547 final int[] gids = permissionsState.computeGids(userId); 2548 final Set<String> permissions = permissionsState.getPermissions(userId); 2549 final PackageUserState state = ps.readUserState(userId); 2550 2551 return PackageParser.generatePackageInfo(p, gids, flags, 2552 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2553 } 2554 2555 @Override 2556 public boolean isPackageFrozen(String packageName) { 2557 synchronized (mPackages) { 2558 final PackageSetting ps = mSettings.mPackages.get(packageName); 2559 if (ps != null) { 2560 return ps.frozen; 2561 } 2562 } 2563 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2564 return true; 2565 } 2566 2567 @Override 2568 public boolean isPackageAvailable(String packageName, int userId) { 2569 if (!sUserManager.exists(userId)) return false; 2570 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2571 synchronized (mPackages) { 2572 PackageParser.Package p = mPackages.get(packageName); 2573 if (p != null) { 2574 final PackageSetting ps = (PackageSetting) p.mExtras; 2575 if (ps != null) { 2576 final PackageUserState state = ps.readUserState(userId); 2577 if (state != null) { 2578 return PackageParser.isAvailable(state); 2579 } 2580 } 2581 } 2582 } 2583 return false; 2584 } 2585 2586 @Override 2587 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2588 if (!sUserManager.exists(userId)) return null; 2589 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2590 // reader 2591 synchronized (mPackages) { 2592 PackageParser.Package p = mPackages.get(packageName); 2593 if (DEBUG_PACKAGE_INFO) 2594 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2595 if (p != null) { 2596 return generatePackageInfo(p, flags, userId); 2597 } 2598 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2599 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2600 } 2601 } 2602 return null; 2603 } 2604 2605 @Override 2606 public String[] currentToCanonicalPackageNames(String[] names) { 2607 String[] out = new String[names.length]; 2608 // reader 2609 synchronized (mPackages) { 2610 for (int i=names.length-1; i>=0; i--) { 2611 PackageSetting ps = mSettings.mPackages.get(names[i]); 2612 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2613 } 2614 } 2615 return out; 2616 } 2617 2618 @Override 2619 public String[] canonicalToCurrentPackageNames(String[] names) { 2620 String[] out = new String[names.length]; 2621 // reader 2622 synchronized (mPackages) { 2623 for (int i=names.length-1; i>=0; i--) { 2624 String cur = mSettings.mRenamedPackages.get(names[i]); 2625 out[i] = cur != null ? cur : names[i]; 2626 } 2627 } 2628 return out; 2629 } 2630 2631 @Override 2632 public int getPackageUid(String packageName, int userId) { 2633 if (!sUserManager.exists(userId)) return -1; 2634 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2635 2636 // reader 2637 synchronized (mPackages) { 2638 PackageParser.Package p = mPackages.get(packageName); 2639 if(p != null) { 2640 return UserHandle.getUid(userId, p.applicationInfo.uid); 2641 } 2642 PackageSetting ps = mSettings.mPackages.get(packageName); 2643 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2644 return -1; 2645 } 2646 p = ps.pkg; 2647 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2648 } 2649 } 2650 2651 @Override 2652 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2653 if (!sUserManager.exists(userId)) { 2654 return null; 2655 } 2656 2657 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2658 "getPackageGids"); 2659 2660 // reader 2661 synchronized (mPackages) { 2662 PackageParser.Package p = mPackages.get(packageName); 2663 if (DEBUG_PACKAGE_INFO) { 2664 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2665 } 2666 if (p != null) { 2667 PackageSetting ps = (PackageSetting) p.mExtras; 2668 return ps.getPermissionsState().computeGids(userId); 2669 } 2670 } 2671 2672 return null; 2673 } 2674 2675 @Override 2676 public int getMountExternalMode(int uid) { 2677 if (Process.isIsolated(uid)) { 2678 return Zygote.MOUNT_EXTERNAL_NONE; 2679 } else { 2680 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2681 return Zygote.MOUNT_EXTERNAL_WRITE; 2682 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2683 return Zygote.MOUNT_EXTERNAL_READ; 2684 } else { 2685 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2686 } 2687 } 2688 } 2689 2690 static PermissionInfo generatePermissionInfo( 2691 BasePermission bp, int flags) { 2692 if (bp.perm != null) { 2693 return PackageParser.generatePermissionInfo(bp.perm, flags); 2694 } 2695 PermissionInfo pi = new PermissionInfo(); 2696 pi.name = bp.name; 2697 pi.packageName = bp.sourcePackage; 2698 pi.nonLocalizedLabel = bp.name; 2699 pi.protectionLevel = bp.protectionLevel; 2700 return pi; 2701 } 2702 2703 @Override 2704 public PermissionInfo getPermissionInfo(String name, int flags) { 2705 // reader 2706 synchronized (mPackages) { 2707 final BasePermission p = mSettings.mPermissions.get(name); 2708 if (p != null) { 2709 return generatePermissionInfo(p, flags); 2710 } 2711 return null; 2712 } 2713 } 2714 2715 @Override 2716 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2717 // reader 2718 synchronized (mPackages) { 2719 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2720 for (BasePermission p : mSettings.mPermissions.values()) { 2721 if (group == null) { 2722 if (p.perm == null || p.perm.info.group == null) { 2723 out.add(generatePermissionInfo(p, flags)); 2724 } 2725 } else { 2726 if (p.perm != null && group.equals(p.perm.info.group)) { 2727 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2728 } 2729 } 2730 } 2731 2732 if (out.size() > 0) { 2733 return out; 2734 } 2735 return mPermissionGroups.containsKey(group) ? out : null; 2736 } 2737 } 2738 2739 @Override 2740 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2741 // reader 2742 synchronized (mPackages) { 2743 return PackageParser.generatePermissionGroupInfo( 2744 mPermissionGroups.get(name), flags); 2745 } 2746 } 2747 2748 @Override 2749 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2750 // reader 2751 synchronized (mPackages) { 2752 final int N = mPermissionGroups.size(); 2753 ArrayList<PermissionGroupInfo> out 2754 = new ArrayList<PermissionGroupInfo>(N); 2755 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2756 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2757 } 2758 return out; 2759 } 2760 } 2761 2762 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2763 int userId) { 2764 if (!sUserManager.exists(userId)) return null; 2765 PackageSetting ps = mSettings.mPackages.get(packageName); 2766 if (ps != null) { 2767 if (ps.pkg == null) { 2768 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2769 flags, userId); 2770 if (pInfo != null) { 2771 return pInfo.applicationInfo; 2772 } 2773 return null; 2774 } 2775 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2776 ps.readUserState(userId), userId); 2777 } 2778 return null; 2779 } 2780 2781 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2782 int userId) { 2783 if (!sUserManager.exists(userId)) return null; 2784 PackageSetting ps = mSettings.mPackages.get(packageName); 2785 if (ps != null) { 2786 PackageParser.Package pkg = ps.pkg; 2787 if (pkg == null) { 2788 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2789 return null; 2790 } 2791 // Only data remains, so we aren't worried about code paths 2792 pkg = new PackageParser.Package(packageName); 2793 pkg.applicationInfo.packageName = packageName; 2794 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2795 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2796 pkg.applicationInfo.dataDir = Environment 2797 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2798 .getAbsolutePath(); 2799 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2800 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2801 } 2802 return generatePackageInfo(pkg, flags, userId); 2803 } 2804 return null; 2805 } 2806 2807 @Override 2808 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2809 if (!sUserManager.exists(userId)) return null; 2810 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2811 // writer 2812 synchronized (mPackages) { 2813 PackageParser.Package p = mPackages.get(packageName); 2814 if (DEBUG_PACKAGE_INFO) Log.v( 2815 TAG, "getApplicationInfo " + packageName 2816 + ": " + p); 2817 if (p != null) { 2818 PackageSetting ps = mSettings.mPackages.get(packageName); 2819 if (ps == null) return null; 2820 // Note: isEnabledLP() does not apply here - always return info 2821 return PackageParser.generateApplicationInfo( 2822 p, flags, ps.readUserState(userId), userId); 2823 } 2824 if ("android".equals(packageName)||"system".equals(packageName)) { 2825 return mAndroidApplication; 2826 } 2827 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2828 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2829 } 2830 } 2831 return null; 2832 } 2833 2834 @Override 2835 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2836 final IPackageDataObserver observer) { 2837 mContext.enforceCallingOrSelfPermission( 2838 android.Manifest.permission.CLEAR_APP_CACHE, null); 2839 // Queue up an async operation since clearing cache may take a little while. 2840 mHandler.post(new Runnable() { 2841 public void run() { 2842 mHandler.removeCallbacks(this); 2843 int retCode = -1; 2844 synchronized (mInstallLock) { 2845 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2846 if (retCode < 0) { 2847 Slog.w(TAG, "Couldn't clear application caches"); 2848 } 2849 } 2850 if (observer != null) { 2851 try { 2852 observer.onRemoveCompleted(null, (retCode >= 0)); 2853 } catch (RemoteException e) { 2854 Slog.w(TAG, "RemoveException when invoking call back"); 2855 } 2856 } 2857 } 2858 }); 2859 } 2860 2861 @Override 2862 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2863 final IntentSender pi) { 2864 mContext.enforceCallingOrSelfPermission( 2865 android.Manifest.permission.CLEAR_APP_CACHE, null); 2866 // Queue up an async operation since clearing cache may take a little while. 2867 mHandler.post(new Runnable() { 2868 public void run() { 2869 mHandler.removeCallbacks(this); 2870 int retCode = -1; 2871 synchronized (mInstallLock) { 2872 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2873 if (retCode < 0) { 2874 Slog.w(TAG, "Couldn't clear application caches"); 2875 } 2876 } 2877 if(pi != null) { 2878 try { 2879 // Callback via pending intent 2880 int code = (retCode >= 0) ? 1 : 0; 2881 pi.sendIntent(null, code, null, 2882 null, null); 2883 } catch (SendIntentException e1) { 2884 Slog.i(TAG, "Failed to send pending intent"); 2885 } 2886 } 2887 } 2888 }); 2889 } 2890 2891 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2892 synchronized (mInstallLock) { 2893 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2894 throw new IOException("Failed to free enough space"); 2895 } 2896 } 2897 } 2898 2899 @Override 2900 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2901 if (!sUserManager.exists(userId)) return null; 2902 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2903 synchronized (mPackages) { 2904 PackageParser.Activity a = mActivities.mActivities.get(component); 2905 2906 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2907 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2908 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2909 if (ps == null) return null; 2910 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2911 userId); 2912 } 2913 if (mResolveComponentName.equals(component)) { 2914 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2915 new PackageUserState(), userId); 2916 } 2917 } 2918 return null; 2919 } 2920 2921 @Override 2922 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2923 String resolvedType) { 2924 synchronized (mPackages) { 2925 PackageParser.Activity a = mActivities.mActivities.get(component); 2926 if (a == null) { 2927 return false; 2928 } 2929 for (int i=0; i<a.intents.size(); i++) { 2930 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2931 intent.getData(), intent.getCategories(), TAG) >= 0) { 2932 return true; 2933 } 2934 } 2935 return false; 2936 } 2937 } 2938 2939 @Override 2940 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2941 if (!sUserManager.exists(userId)) return null; 2942 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2943 synchronized (mPackages) { 2944 PackageParser.Activity a = mReceivers.mActivities.get(component); 2945 if (DEBUG_PACKAGE_INFO) Log.v( 2946 TAG, "getReceiverInfo " + component + ": " + a); 2947 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2948 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2949 if (ps == null) return null; 2950 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2951 userId); 2952 } 2953 } 2954 return null; 2955 } 2956 2957 @Override 2958 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2959 if (!sUserManager.exists(userId)) return null; 2960 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2961 synchronized (mPackages) { 2962 PackageParser.Service s = mServices.mServices.get(component); 2963 if (DEBUG_PACKAGE_INFO) Log.v( 2964 TAG, "getServiceInfo " + component + ": " + s); 2965 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2966 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2967 if (ps == null) return null; 2968 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2969 userId); 2970 } 2971 } 2972 return null; 2973 } 2974 2975 @Override 2976 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2977 if (!sUserManager.exists(userId)) return null; 2978 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2979 synchronized (mPackages) { 2980 PackageParser.Provider p = mProviders.mProviders.get(component); 2981 if (DEBUG_PACKAGE_INFO) Log.v( 2982 TAG, "getProviderInfo " + component + ": " + p); 2983 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2984 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2985 if (ps == null) return null; 2986 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2987 userId); 2988 } 2989 } 2990 return null; 2991 } 2992 2993 @Override 2994 public String[] getSystemSharedLibraryNames() { 2995 Set<String> libSet; 2996 synchronized (mPackages) { 2997 libSet = mSharedLibraries.keySet(); 2998 int size = libSet.size(); 2999 if (size > 0) { 3000 String[] libs = new String[size]; 3001 libSet.toArray(libs); 3002 return libs; 3003 } 3004 } 3005 return null; 3006 } 3007 3008 /** 3009 * @hide 3010 */ 3011 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3012 synchronized (mPackages) { 3013 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3014 if (lib != null && lib.apk != null) { 3015 return mPackages.get(lib.apk); 3016 } 3017 } 3018 return null; 3019 } 3020 3021 @Override 3022 public FeatureInfo[] getSystemAvailableFeatures() { 3023 Collection<FeatureInfo> featSet; 3024 synchronized (mPackages) { 3025 featSet = mAvailableFeatures.values(); 3026 int size = featSet.size(); 3027 if (size > 0) { 3028 FeatureInfo[] features = new FeatureInfo[size+1]; 3029 featSet.toArray(features); 3030 FeatureInfo fi = new FeatureInfo(); 3031 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3032 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3033 features[size] = fi; 3034 return features; 3035 } 3036 } 3037 return null; 3038 } 3039 3040 @Override 3041 public boolean hasSystemFeature(String name) { 3042 synchronized (mPackages) { 3043 return mAvailableFeatures.containsKey(name); 3044 } 3045 } 3046 3047 private void checkValidCaller(int uid, int userId) { 3048 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3049 return; 3050 3051 throw new SecurityException("Caller uid=" + uid 3052 + " is not privileged to communicate with user=" + userId); 3053 } 3054 3055 @Override 3056 public int checkPermission(String permName, String pkgName, int userId) { 3057 if (!sUserManager.exists(userId)) { 3058 return PackageManager.PERMISSION_DENIED; 3059 } 3060 3061 synchronized (mPackages) { 3062 final PackageParser.Package p = mPackages.get(pkgName); 3063 if (p != null && p.mExtras != null) { 3064 final PackageSetting ps = (PackageSetting) p.mExtras; 3065 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3066 return PackageManager.PERMISSION_GRANTED; 3067 } 3068 } 3069 } 3070 3071 return PackageManager.PERMISSION_DENIED; 3072 } 3073 3074 @Override 3075 public int checkUidPermission(String permName, int uid) { 3076 final int userId = UserHandle.getUserId(uid); 3077 3078 if (!sUserManager.exists(userId)) { 3079 return PackageManager.PERMISSION_DENIED; 3080 } 3081 3082 synchronized (mPackages) { 3083 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3084 if (obj != null) { 3085 final SettingBase ps = (SettingBase) obj; 3086 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3087 return PackageManager.PERMISSION_GRANTED; 3088 } 3089 } else { 3090 ArraySet<String> perms = mSystemPermissions.get(uid); 3091 if (perms != null && perms.contains(permName)) { 3092 return PackageManager.PERMISSION_GRANTED; 3093 } 3094 } 3095 } 3096 3097 return PackageManager.PERMISSION_DENIED; 3098 } 3099 3100 /** 3101 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3102 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3103 * @param checkShell TODO(yamasani): 3104 * @param message the message to log on security exception 3105 */ 3106 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3107 boolean checkShell, String message) { 3108 if (userId < 0) { 3109 throw new IllegalArgumentException("Invalid userId " + userId); 3110 } 3111 if (checkShell) { 3112 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3113 } 3114 if (userId == UserHandle.getUserId(callingUid)) return; 3115 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3116 if (requireFullPermission) { 3117 mContext.enforceCallingOrSelfPermission( 3118 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3119 } else { 3120 try { 3121 mContext.enforceCallingOrSelfPermission( 3122 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3123 } catch (SecurityException se) { 3124 mContext.enforceCallingOrSelfPermission( 3125 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3126 } 3127 } 3128 } 3129 } 3130 3131 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3132 if (callingUid == Process.SHELL_UID) { 3133 if (userHandle >= 0 3134 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3135 throw new SecurityException("Shell does not have permission to access user " 3136 + userHandle); 3137 } else if (userHandle < 0) { 3138 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3139 + Debug.getCallers(3)); 3140 } 3141 } 3142 } 3143 3144 private BasePermission findPermissionTreeLP(String permName) { 3145 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3146 if (permName.startsWith(bp.name) && 3147 permName.length() > bp.name.length() && 3148 permName.charAt(bp.name.length()) == '.') { 3149 return bp; 3150 } 3151 } 3152 return null; 3153 } 3154 3155 private BasePermission checkPermissionTreeLP(String permName) { 3156 if (permName != null) { 3157 BasePermission bp = findPermissionTreeLP(permName); 3158 if (bp != null) { 3159 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3160 return bp; 3161 } 3162 throw new SecurityException("Calling uid " 3163 + Binder.getCallingUid() 3164 + " is not allowed to add to permission tree " 3165 + bp.name + " owned by uid " + bp.uid); 3166 } 3167 } 3168 throw new SecurityException("No permission tree found for " + permName); 3169 } 3170 3171 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3172 if (s1 == null) { 3173 return s2 == null; 3174 } 3175 if (s2 == null) { 3176 return false; 3177 } 3178 if (s1.getClass() != s2.getClass()) { 3179 return false; 3180 } 3181 return s1.equals(s2); 3182 } 3183 3184 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3185 if (pi1.icon != pi2.icon) return false; 3186 if (pi1.logo != pi2.logo) return false; 3187 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3188 if (!compareStrings(pi1.name, pi2.name)) return false; 3189 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3190 // We'll take care of setting this one. 3191 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3192 // These are not currently stored in settings. 3193 //if (!compareStrings(pi1.group, pi2.group)) return false; 3194 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3195 //if (pi1.labelRes != pi2.labelRes) return false; 3196 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3197 return true; 3198 } 3199 3200 int permissionInfoFootprint(PermissionInfo info) { 3201 int size = info.name.length(); 3202 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3203 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3204 return size; 3205 } 3206 3207 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3208 int size = 0; 3209 for (BasePermission perm : mSettings.mPermissions.values()) { 3210 if (perm.uid == tree.uid) { 3211 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3212 } 3213 } 3214 return size; 3215 } 3216 3217 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3218 // We calculate the max size of permissions defined by this uid and throw 3219 // if that plus the size of 'info' would exceed our stated maximum. 3220 if (tree.uid != Process.SYSTEM_UID) { 3221 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3222 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3223 throw new SecurityException("Permission tree size cap exceeded"); 3224 } 3225 } 3226 } 3227 3228 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3229 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3230 throw new SecurityException("Label must be specified in permission"); 3231 } 3232 BasePermission tree = checkPermissionTreeLP(info.name); 3233 BasePermission bp = mSettings.mPermissions.get(info.name); 3234 boolean added = bp == null; 3235 boolean changed = true; 3236 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3237 if (added) { 3238 enforcePermissionCapLocked(info, tree); 3239 bp = new BasePermission(info.name, tree.sourcePackage, 3240 BasePermission.TYPE_DYNAMIC); 3241 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3242 throw new SecurityException( 3243 "Not allowed to modify non-dynamic permission " 3244 + info.name); 3245 } else { 3246 if (bp.protectionLevel == fixedLevel 3247 && bp.perm.owner.equals(tree.perm.owner) 3248 && bp.uid == tree.uid 3249 && comparePermissionInfos(bp.perm.info, info)) { 3250 changed = false; 3251 } 3252 } 3253 bp.protectionLevel = fixedLevel; 3254 info = new PermissionInfo(info); 3255 info.protectionLevel = fixedLevel; 3256 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3257 bp.perm.info.packageName = tree.perm.info.packageName; 3258 bp.uid = tree.uid; 3259 if (added) { 3260 mSettings.mPermissions.put(info.name, bp); 3261 } 3262 if (changed) { 3263 if (!async) { 3264 mSettings.writeLPr(); 3265 } else { 3266 scheduleWriteSettingsLocked(); 3267 } 3268 } 3269 return added; 3270 } 3271 3272 @Override 3273 public boolean addPermission(PermissionInfo info) { 3274 synchronized (mPackages) { 3275 return addPermissionLocked(info, false); 3276 } 3277 } 3278 3279 @Override 3280 public boolean addPermissionAsync(PermissionInfo info) { 3281 synchronized (mPackages) { 3282 return addPermissionLocked(info, true); 3283 } 3284 } 3285 3286 @Override 3287 public void removePermission(String name) { 3288 synchronized (mPackages) { 3289 checkPermissionTreeLP(name); 3290 BasePermission bp = mSettings.mPermissions.get(name); 3291 if (bp != null) { 3292 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3293 throw new SecurityException( 3294 "Not allowed to modify non-dynamic permission " 3295 + name); 3296 } 3297 mSettings.mPermissions.remove(name); 3298 mSettings.writeLPr(); 3299 } 3300 } 3301 } 3302 3303 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3304 BasePermission bp) { 3305 int index = pkg.requestedPermissions.indexOf(bp.name); 3306 if (index == -1) { 3307 throw new SecurityException("Package " + pkg.packageName 3308 + " has not requested permission " + bp.name); 3309 } 3310 if (!bp.isRuntime()) { 3311 throw new SecurityException("Permission " + bp.name 3312 + " is not a changeable permission type"); 3313 } 3314 } 3315 3316 @Override 3317 public void grantRuntimePermission(String packageName, String name, final int userId) { 3318 if (!sUserManager.exists(userId)) { 3319 Log.e(TAG, "No such user:" + userId); 3320 return; 3321 } 3322 3323 mContext.enforceCallingOrSelfPermission( 3324 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3325 "grantRuntimePermission"); 3326 3327 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3328 "grantRuntimePermission"); 3329 3330 final int uid; 3331 final SettingBase sb; 3332 3333 synchronized (mPackages) { 3334 final PackageParser.Package pkg = mPackages.get(packageName); 3335 if (pkg == null) { 3336 throw new IllegalArgumentException("Unknown package: " + packageName); 3337 } 3338 3339 final BasePermission bp = mSettings.mPermissions.get(name); 3340 if (bp == null) { 3341 throw new IllegalArgumentException("Unknown permission: " + name); 3342 } 3343 3344 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3345 3346 uid = pkg.applicationInfo.uid; 3347 sb = (SettingBase) pkg.mExtras; 3348 if (sb == null) { 3349 throw new IllegalArgumentException("Unknown package: " + packageName); 3350 } 3351 3352 final PermissionsState permissionsState = sb.getPermissionsState(); 3353 3354 final int flags = permissionsState.getPermissionFlags(name, userId); 3355 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3356 throw new SecurityException("Cannot grant system fixed permission: " 3357 + name + " for package: " + packageName); 3358 } 3359 3360 final int result = permissionsState.grantRuntimePermission(bp, userId); 3361 switch (result) { 3362 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3363 return; 3364 } 3365 3366 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3367 mHandler.post(new Runnable() { 3368 @Override 3369 public void run() { 3370 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3371 } 3372 }); 3373 } break; 3374 } 3375 3376 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3377 3378 // Not critical if that is lost - app has to request again. 3379 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3380 } 3381 3382 if (READ_EXTERNAL_STORAGE.equals(name) 3383 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3384 final long token = Binder.clearCallingIdentity(); 3385 try { 3386 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3387 storage.remountUid(uid); 3388 } finally { 3389 Binder.restoreCallingIdentity(token); 3390 } 3391 } 3392 } 3393 3394 @Override 3395 public void revokeRuntimePermission(String packageName, String name, int userId) { 3396 if (!sUserManager.exists(userId)) { 3397 Log.e(TAG, "No such user:" + userId); 3398 return; 3399 } 3400 3401 mContext.enforceCallingOrSelfPermission( 3402 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3403 "revokeRuntimePermission"); 3404 3405 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3406 "revokeRuntimePermission"); 3407 3408 final SettingBase sb; 3409 3410 synchronized (mPackages) { 3411 final PackageParser.Package pkg = mPackages.get(packageName); 3412 if (pkg == null) { 3413 throw new IllegalArgumentException("Unknown package: " + packageName); 3414 } 3415 3416 final BasePermission bp = mSettings.mPermissions.get(name); 3417 if (bp == null) { 3418 throw new IllegalArgumentException("Unknown permission: " + name); 3419 } 3420 3421 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3422 3423 sb = (SettingBase) pkg.mExtras; 3424 if (sb == null) { 3425 throw new IllegalArgumentException("Unknown package: " + packageName); 3426 } 3427 3428 final PermissionsState permissionsState = sb.getPermissionsState(); 3429 3430 final int flags = permissionsState.getPermissionFlags(name, userId); 3431 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3432 throw new SecurityException("Cannot revoke system fixed permission: " 3433 + name + " for package: " + packageName); 3434 } 3435 3436 if (permissionsState.revokeRuntimePermission(bp, userId) == 3437 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3438 return; 3439 } 3440 3441 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3442 3443 // Critical, after this call app should never have the permission. 3444 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3445 } 3446 3447 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3448 } 3449 3450 @Override 3451 public void resetRuntimePermissions() { 3452 mContext.enforceCallingOrSelfPermission( 3453 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3454 "revokeRuntimePermission"); 3455 3456 int callingUid = Binder.getCallingUid(); 3457 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3458 mContext.enforceCallingOrSelfPermission( 3459 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3460 "resetRuntimePermissions"); 3461 } 3462 3463 final int[] userIds; 3464 3465 synchronized (mPackages) { 3466 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3467 final int userCount = UserManagerService.getInstance().getUserIds().length; 3468 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3469 } 3470 3471 for (int userId : userIds) { 3472 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3473 } 3474 } 3475 3476 @Override 3477 public int getPermissionFlags(String name, String packageName, int userId) { 3478 if (!sUserManager.exists(userId)) { 3479 return 0; 3480 } 3481 3482 mContext.enforceCallingOrSelfPermission( 3483 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3484 "getPermissionFlags"); 3485 3486 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3487 "getPermissionFlags"); 3488 3489 synchronized (mPackages) { 3490 final PackageParser.Package pkg = mPackages.get(packageName); 3491 if (pkg == null) { 3492 throw new IllegalArgumentException("Unknown package: " + packageName); 3493 } 3494 3495 final BasePermission bp = mSettings.mPermissions.get(name); 3496 if (bp == null) { 3497 throw new IllegalArgumentException("Unknown permission: " + name); 3498 } 3499 3500 SettingBase sb = (SettingBase) pkg.mExtras; 3501 if (sb == null) { 3502 throw new IllegalArgumentException("Unknown package: " + packageName); 3503 } 3504 3505 PermissionsState permissionsState = sb.getPermissionsState(); 3506 return permissionsState.getPermissionFlags(name, userId); 3507 } 3508 } 3509 3510 @Override 3511 public void updatePermissionFlags(String name, String packageName, int flagMask, 3512 int flagValues, int userId) { 3513 if (!sUserManager.exists(userId)) { 3514 return; 3515 } 3516 3517 mContext.enforceCallingOrSelfPermission( 3518 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3519 "updatePermissionFlags"); 3520 3521 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3522 "updatePermissionFlags"); 3523 3524 // Only the system can change system fixed flags. 3525 if (getCallingUid() != Process.SYSTEM_UID) { 3526 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3527 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3528 } 3529 3530 synchronized (mPackages) { 3531 final PackageParser.Package pkg = mPackages.get(packageName); 3532 if (pkg == null) { 3533 throw new IllegalArgumentException("Unknown package: " + packageName); 3534 } 3535 3536 final BasePermission bp = mSettings.mPermissions.get(name); 3537 if (bp == null) { 3538 throw new IllegalArgumentException("Unknown permission: " + name); 3539 } 3540 3541 SettingBase sb = (SettingBase) pkg.mExtras; 3542 if (sb == null) { 3543 throw new IllegalArgumentException("Unknown package: " + packageName); 3544 } 3545 3546 PermissionsState permissionsState = sb.getPermissionsState(); 3547 3548 // Only the package manager can change flags for system component permissions. 3549 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3550 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3551 return; 3552 } 3553 3554 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3555 3556 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3557 // Install and runtime permissions are stored in different places, 3558 // so figure out what permission changed and persist the change. 3559 if (permissionsState.getInstallPermissionState(name) != null) { 3560 scheduleWriteSettingsLocked(); 3561 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3562 || hadState) { 3563 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3564 } 3565 } 3566 } 3567 } 3568 3569 /** 3570 * Update the permission flags for all packages and runtime permissions of a user in order 3571 * to allow device or profile owner to remove POLICY_FIXED. 3572 */ 3573 @Override 3574 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3575 if (!sUserManager.exists(userId)) { 3576 return; 3577 } 3578 3579 mContext.enforceCallingOrSelfPermission( 3580 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3581 "updatePermissionFlagsForAllApps"); 3582 3583 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3584 "updatePermissionFlagsForAllApps"); 3585 3586 // Only the system can change system fixed flags. 3587 if (getCallingUid() != Process.SYSTEM_UID) { 3588 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3589 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3590 } 3591 3592 synchronized (mPackages) { 3593 boolean changed = false; 3594 final int packageCount = mPackages.size(); 3595 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3596 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3597 SettingBase sb = (SettingBase) pkg.mExtras; 3598 if (sb == null) { 3599 continue; 3600 } 3601 PermissionsState permissionsState = sb.getPermissionsState(); 3602 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3603 userId, flagMask, flagValues); 3604 } 3605 if (changed) { 3606 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3607 } 3608 } 3609 } 3610 3611 @Override 3612 public boolean shouldShowRequestPermissionRationale(String permissionName, 3613 String packageName, int userId) { 3614 if (UserHandle.getCallingUserId() != userId) { 3615 mContext.enforceCallingPermission( 3616 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3617 "canShowRequestPermissionRationale for user " + userId); 3618 } 3619 3620 final int uid = getPackageUid(packageName, userId); 3621 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3622 return false; 3623 } 3624 3625 if (checkPermission(permissionName, packageName, userId) 3626 == PackageManager.PERMISSION_GRANTED) { 3627 return false; 3628 } 3629 3630 final int flags; 3631 3632 final long identity = Binder.clearCallingIdentity(); 3633 try { 3634 flags = getPermissionFlags(permissionName, 3635 packageName, userId); 3636 } finally { 3637 Binder.restoreCallingIdentity(identity); 3638 } 3639 3640 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3641 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3642 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3643 3644 if ((flags & fixedFlags) != 0) { 3645 return false; 3646 } 3647 3648 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3649 } 3650 3651 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3652 BasePermission bp = mSettings.mPermissions.get(permission); 3653 if (bp == null) { 3654 throw new SecurityException("Missing " + permission + " permission"); 3655 } 3656 3657 SettingBase sb = (SettingBase) pkg.mExtras; 3658 PermissionsState permissionsState = sb.getPermissionsState(); 3659 3660 if (permissionsState.grantInstallPermission(bp) != 3661 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3662 scheduleWriteSettingsLocked(); 3663 } 3664 } 3665 3666 @Override 3667 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3668 mContext.enforceCallingOrSelfPermission( 3669 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3670 "addOnPermissionsChangeListener"); 3671 3672 synchronized (mPackages) { 3673 mOnPermissionChangeListeners.addListenerLocked(listener); 3674 } 3675 } 3676 3677 @Override 3678 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3679 synchronized (mPackages) { 3680 mOnPermissionChangeListeners.removeListenerLocked(listener); 3681 } 3682 } 3683 3684 @Override 3685 public boolean isProtectedBroadcast(String actionName) { 3686 synchronized (mPackages) { 3687 return mProtectedBroadcasts.contains(actionName); 3688 } 3689 } 3690 3691 @Override 3692 public int checkSignatures(String pkg1, String pkg2) { 3693 synchronized (mPackages) { 3694 final PackageParser.Package p1 = mPackages.get(pkg1); 3695 final PackageParser.Package p2 = mPackages.get(pkg2); 3696 if (p1 == null || p1.mExtras == null 3697 || p2 == null || p2.mExtras == null) { 3698 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3699 } 3700 return compareSignatures(p1.mSignatures, p2.mSignatures); 3701 } 3702 } 3703 3704 @Override 3705 public int checkUidSignatures(int uid1, int uid2) { 3706 // Map to base uids. 3707 uid1 = UserHandle.getAppId(uid1); 3708 uid2 = UserHandle.getAppId(uid2); 3709 // reader 3710 synchronized (mPackages) { 3711 Signature[] s1; 3712 Signature[] s2; 3713 Object obj = mSettings.getUserIdLPr(uid1); 3714 if (obj != null) { 3715 if (obj instanceof SharedUserSetting) { 3716 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3717 } else if (obj instanceof PackageSetting) { 3718 s1 = ((PackageSetting)obj).signatures.mSignatures; 3719 } else { 3720 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3721 } 3722 } else { 3723 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3724 } 3725 obj = mSettings.getUserIdLPr(uid2); 3726 if (obj != null) { 3727 if (obj instanceof SharedUserSetting) { 3728 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3729 } else if (obj instanceof PackageSetting) { 3730 s2 = ((PackageSetting)obj).signatures.mSignatures; 3731 } else { 3732 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3733 } 3734 } else { 3735 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3736 } 3737 return compareSignatures(s1, s2); 3738 } 3739 } 3740 3741 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3742 final long identity = Binder.clearCallingIdentity(); 3743 try { 3744 if (sb instanceof SharedUserSetting) { 3745 SharedUserSetting sus = (SharedUserSetting) sb; 3746 final int packageCount = sus.packages.size(); 3747 for (int i = 0; i < packageCount; i++) { 3748 PackageSetting susPs = sus.packages.valueAt(i); 3749 if (userId == UserHandle.USER_ALL) { 3750 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3751 } else { 3752 final int uid = UserHandle.getUid(userId, susPs.appId); 3753 killUid(uid, reason); 3754 } 3755 } 3756 } else if (sb instanceof PackageSetting) { 3757 PackageSetting ps = (PackageSetting) sb; 3758 if (userId == UserHandle.USER_ALL) { 3759 killApplication(ps.pkg.packageName, ps.appId, reason); 3760 } else { 3761 final int uid = UserHandle.getUid(userId, ps.appId); 3762 killUid(uid, reason); 3763 } 3764 } 3765 } finally { 3766 Binder.restoreCallingIdentity(identity); 3767 } 3768 } 3769 3770 private static void killUid(int uid, String reason) { 3771 IActivityManager am = ActivityManagerNative.getDefault(); 3772 if (am != null) { 3773 try { 3774 am.killUid(uid, reason); 3775 } catch (RemoteException e) { 3776 /* ignore - same process */ 3777 } 3778 } 3779 } 3780 3781 /** 3782 * Compares two sets of signatures. Returns: 3783 * <br /> 3784 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3785 * <br /> 3786 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3787 * <br /> 3788 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3789 * <br /> 3790 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3791 * <br /> 3792 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3793 */ 3794 static int compareSignatures(Signature[] s1, Signature[] s2) { 3795 if (s1 == null) { 3796 return s2 == null 3797 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3798 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3799 } 3800 3801 if (s2 == null) { 3802 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3803 } 3804 3805 if (s1.length != s2.length) { 3806 return PackageManager.SIGNATURE_NO_MATCH; 3807 } 3808 3809 // Since both signature sets are of size 1, we can compare without HashSets. 3810 if (s1.length == 1) { 3811 return s1[0].equals(s2[0]) ? 3812 PackageManager.SIGNATURE_MATCH : 3813 PackageManager.SIGNATURE_NO_MATCH; 3814 } 3815 3816 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3817 for (Signature sig : s1) { 3818 set1.add(sig); 3819 } 3820 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3821 for (Signature sig : s2) { 3822 set2.add(sig); 3823 } 3824 // Make sure s2 contains all signatures in s1. 3825 if (set1.equals(set2)) { 3826 return PackageManager.SIGNATURE_MATCH; 3827 } 3828 return PackageManager.SIGNATURE_NO_MATCH; 3829 } 3830 3831 /** 3832 * If the database version for this type of package (internal storage or 3833 * external storage) is less than the version where package signatures 3834 * were updated, return true. 3835 */ 3836 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3837 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3838 DatabaseVersion.SIGNATURE_END_ENTITY)) 3839 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3840 DatabaseVersion.SIGNATURE_END_ENTITY)); 3841 } 3842 3843 /** 3844 * Used for backward compatibility to make sure any packages with 3845 * certificate chains get upgraded to the new style. {@code existingSigs} 3846 * will be in the old format (since they were stored on disk from before the 3847 * system upgrade) and {@code scannedSigs} will be in the newer format. 3848 */ 3849 private int compareSignaturesCompat(PackageSignatures existingSigs, 3850 PackageParser.Package scannedPkg) { 3851 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3852 return PackageManager.SIGNATURE_NO_MATCH; 3853 } 3854 3855 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3856 for (Signature sig : existingSigs.mSignatures) { 3857 existingSet.add(sig); 3858 } 3859 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3860 for (Signature sig : scannedPkg.mSignatures) { 3861 try { 3862 Signature[] chainSignatures = sig.getChainSignatures(); 3863 for (Signature chainSig : chainSignatures) { 3864 scannedCompatSet.add(chainSig); 3865 } 3866 } catch (CertificateEncodingException e) { 3867 scannedCompatSet.add(sig); 3868 } 3869 } 3870 /* 3871 * Make sure the expanded scanned set contains all signatures in the 3872 * existing one. 3873 */ 3874 if (scannedCompatSet.equals(existingSet)) { 3875 // Migrate the old signatures to the new scheme. 3876 existingSigs.assignSignatures(scannedPkg.mSignatures); 3877 // The new KeySets will be re-added later in the scanning process. 3878 synchronized (mPackages) { 3879 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3880 } 3881 return PackageManager.SIGNATURE_MATCH; 3882 } 3883 return PackageManager.SIGNATURE_NO_MATCH; 3884 } 3885 3886 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3887 if (isExternal(scannedPkg)) { 3888 return mSettings.isExternalDatabaseVersionOlderThan( 3889 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3890 } else { 3891 return mSettings.isInternalDatabaseVersionOlderThan( 3892 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3893 } 3894 } 3895 3896 private int compareSignaturesRecover(PackageSignatures existingSigs, 3897 PackageParser.Package scannedPkg) { 3898 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3899 return PackageManager.SIGNATURE_NO_MATCH; 3900 } 3901 3902 String msg = null; 3903 try { 3904 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3905 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3906 + scannedPkg.packageName); 3907 return PackageManager.SIGNATURE_MATCH; 3908 } 3909 } catch (CertificateException e) { 3910 msg = e.getMessage(); 3911 } 3912 3913 logCriticalInfo(Log.INFO, 3914 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3915 return PackageManager.SIGNATURE_NO_MATCH; 3916 } 3917 3918 @Override 3919 public String[] getPackagesForUid(int uid) { 3920 uid = UserHandle.getAppId(uid); 3921 // reader 3922 synchronized (mPackages) { 3923 Object obj = mSettings.getUserIdLPr(uid); 3924 if (obj instanceof SharedUserSetting) { 3925 final SharedUserSetting sus = (SharedUserSetting) obj; 3926 final int N = sus.packages.size(); 3927 final String[] res = new String[N]; 3928 final Iterator<PackageSetting> it = sus.packages.iterator(); 3929 int i = 0; 3930 while (it.hasNext()) { 3931 res[i++] = it.next().name; 3932 } 3933 return res; 3934 } else if (obj instanceof PackageSetting) { 3935 final PackageSetting ps = (PackageSetting) obj; 3936 return new String[] { ps.name }; 3937 } 3938 } 3939 return null; 3940 } 3941 3942 @Override 3943 public String getNameForUid(int uid) { 3944 // reader 3945 synchronized (mPackages) { 3946 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3947 if (obj instanceof SharedUserSetting) { 3948 final SharedUserSetting sus = (SharedUserSetting) obj; 3949 return sus.name + ":" + sus.userId; 3950 } else if (obj instanceof PackageSetting) { 3951 final PackageSetting ps = (PackageSetting) obj; 3952 return ps.name; 3953 } 3954 } 3955 return null; 3956 } 3957 3958 @Override 3959 public int getUidForSharedUser(String sharedUserName) { 3960 if(sharedUserName == null) { 3961 return -1; 3962 } 3963 // reader 3964 synchronized (mPackages) { 3965 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3966 if (suid == null) { 3967 return -1; 3968 } 3969 return suid.userId; 3970 } 3971 } 3972 3973 @Override 3974 public int getFlagsForUid(int uid) { 3975 synchronized (mPackages) { 3976 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3977 if (obj instanceof SharedUserSetting) { 3978 final SharedUserSetting sus = (SharedUserSetting) obj; 3979 return sus.pkgFlags; 3980 } else if (obj instanceof PackageSetting) { 3981 final PackageSetting ps = (PackageSetting) obj; 3982 return ps.pkgFlags; 3983 } 3984 } 3985 return 0; 3986 } 3987 3988 @Override 3989 public int getPrivateFlagsForUid(int uid) { 3990 synchronized (mPackages) { 3991 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3992 if (obj instanceof SharedUserSetting) { 3993 final SharedUserSetting sus = (SharedUserSetting) obj; 3994 return sus.pkgPrivateFlags; 3995 } else if (obj instanceof PackageSetting) { 3996 final PackageSetting ps = (PackageSetting) obj; 3997 return ps.pkgPrivateFlags; 3998 } 3999 } 4000 return 0; 4001 } 4002 4003 @Override 4004 public boolean isUidPrivileged(int uid) { 4005 uid = UserHandle.getAppId(uid); 4006 // reader 4007 synchronized (mPackages) { 4008 Object obj = mSettings.getUserIdLPr(uid); 4009 if (obj instanceof SharedUserSetting) { 4010 final SharedUserSetting sus = (SharedUserSetting) obj; 4011 final Iterator<PackageSetting> it = sus.packages.iterator(); 4012 while (it.hasNext()) { 4013 if (it.next().isPrivileged()) { 4014 return true; 4015 } 4016 } 4017 } else if (obj instanceof PackageSetting) { 4018 final PackageSetting ps = (PackageSetting) obj; 4019 return ps.isPrivileged(); 4020 } 4021 } 4022 return false; 4023 } 4024 4025 @Override 4026 public String[] getAppOpPermissionPackages(String permissionName) { 4027 synchronized (mPackages) { 4028 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4029 if (pkgs == null) { 4030 return null; 4031 } 4032 return pkgs.toArray(new String[pkgs.size()]); 4033 } 4034 } 4035 4036 @Override 4037 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4038 int flags, int userId) { 4039 if (!sUserManager.exists(userId)) return null; 4040 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4041 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4042 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4043 } 4044 4045 @Override 4046 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4047 IntentFilter filter, int match, ComponentName activity) { 4048 final int userId = UserHandle.getCallingUserId(); 4049 if (DEBUG_PREFERRED) { 4050 Log.v(TAG, "setLastChosenActivity intent=" + intent 4051 + " resolvedType=" + resolvedType 4052 + " flags=" + flags 4053 + " filter=" + filter 4054 + " match=" + match 4055 + " activity=" + activity); 4056 filter.dump(new PrintStreamPrinter(System.out), " "); 4057 } 4058 intent.setComponent(null); 4059 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4060 // Find any earlier preferred or last chosen entries and nuke them 4061 findPreferredActivity(intent, resolvedType, 4062 flags, query, 0, false, true, false, userId); 4063 // Add the new activity as the last chosen for this filter 4064 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4065 "Setting last chosen"); 4066 } 4067 4068 @Override 4069 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4070 final int userId = UserHandle.getCallingUserId(); 4071 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4072 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4073 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4074 false, false, false, userId); 4075 } 4076 4077 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4078 int flags, List<ResolveInfo> query, int userId) { 4079 if (query != null) { 4080 final int N = query.size(); 4081 if (N == 1) { 4082 return query.get(0); 4083 } else if (N > 1) { 4084 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4085 // If there is more than one activity with the same priority, 4086 // then let the user decide between them. 4087 ResolveInfo r0 = query.get(0); 4088 ResolveInfo r1 = query.get(1); 4089 if (DEBUG_INTENT_MATCHING || debug) { 4090 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4091 + r1.activityInfo.name + "=" + r1.priority); 4092 } 4093 // If the first activity has a higher priority, or a different 4094 // default, then it is always desireable to pick it. 4095 if (r0.priority != r1.priority 4096 || r0.preferredOrder != r1.preferredOrder 4097 || r0.isDefault != r1.isDefault) { 4098 return query.get(0); 4099 } 4100 // If we have saved a preference for a preferred activity for 4101 // this Intent, use that. 4102 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4103 flags, query, r0.priority, true, false, debug, userId); 4104 if (ri != null) { 4105 return ri; 4106 } 4107 if (userId != 0) { 4108 ri = new ResolveInfo(mResolveInfo); 4109 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4110 ri.activityInfo.applicationInfo = new ApplicationInfo( 4111 ri.activityInfo.applicationInfo); 4112 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4113 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4114 return ri; 4115 } 4116 return mResolveInfo; 4117 } 4118 } 4119 return null; 4120 } 4121 4122 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4123 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4124 final int N = query.size(); 4125 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4126 .get(userId); 4127 // Get the list of persistent preferred activities that handle the intent 4128 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4129 List<PersistentPreferredActivity> pprefs = ppir != null 4130 ? ppir.queryIntent(intent, resolvedType, 4131 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4132 : null; 4133 if (pprefs != null && pprefs.size() > 0) { 4134 final int M = pprefs.size(); 4135 for (int i=0; i<M; i++) { 4136 final PersistentPreferredActivity ppa = pprefs.get(i); 4137 if (DEBUG_PREFERRED || debug) { 4138 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4139 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4140 + "\n component=" + ppa.mComponent); 4141 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4142 } 4143 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4144 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4145 if (DEBUG_PREFERRED || debug) { 4146 Slog.v(TAG, "Found persistent preferred activity:"); 4147 if (ai != null) { 4148 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4149 } else { 4150 Slog.v(TAG, " null"); 4151 } 4152 } 4153 if (ai == null) { 4154 // This previously registered persistent preferred activity 4155 // component is no longer known. Ignore it and do NOT remove it. 4156 continue; 4157 } 4158 for (int j=0; j<N; j++) { 4159 final ResolveInfo ri = query.get(j); 4160 if (!ri.activityInfo.applicationInfo.packageName 4161 .equals(ai.applicationInfo.packageName)) { 4162 continue; 4163 } 4164 if (!ri.activityInfo.name.equals(ai.name)) { 4165 continue; 4166 } 4167 // Found a persistent preference that can handle the intent. 4168 if (DEBUG_PREFERRED || debug) { 4169 Slog.v(TAG, "Returning persistent preferred activity: " + 4170 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4171 } 4172 return ri; 4173 } 4174 } 4175 } 4176 return null; 4177 } 4178 4179 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4180 List<ResolveInfo> query, int priority, boolean always, 4181 boolean removeMatches, boolean debug, int userId) { 4182 if (!sUserManager.exists(userId)) return null; 4183 // writer 4184 synchronized (mPackages) { 4185 if (intent.getSelector() != null) { 4186 intent = intent.getSelector(); 4187 } 4188 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4189 4190 // Try to find a matching persistent preferred activity. 4191 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4192 debug, userId); 4193 4194 // If a persistent preferred activity matched, use it. 4195 if (pri != null) { 4196 return pri; 4197 } 4198 4199 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4200 // Get the list of preferred activities that handle the intent 4201 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4202 List<PreferredActivity> prefs = pir != null 4203 ? pir.queryIntent(intent, resolvedType, 4204 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4205 : null; 4206 if (prefs != null && prefs.size() > 0) { 4207 boolean changed = false; 4208 try { 4209 // First figure out how good the original match set is. 4210 // We will only allow preferred activities that came 4211 // from the same match quality. 4212 int match = 0; 4213 4214 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4215 4216 final int N = query.size(); 4217 for (int j=0; j<N; j++) { 4218 final ResolveInfo ri = query.get(j); 4219 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4220 + ": 0x" + Integer.toHexString(match)); 4221 if (ri.match > match) { 4222 match = ri.match; 4223 } 4224 } 4225 4226 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4227 + Integer.toHexString(match)); 4228 4229 match &= IntentFilter.MATCH_CATEGORY_MASK; 4230 final int M = prefs.size(); 4231 for (int i=0; i<M; i++) { 4232 final PreferredActivity pa = prefs.get(i); 4233 if (DEBUG_PREFERRED || debug) { 4234 Slog.v(TAG, "Checking PreferredActivity ds=" 4235 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4236 + "\n component=" + pa.mPref.mComponent); 4237 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4238 } 4239 if (pa.mPref.mMatch != match) { 4240 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4241 + Integer.toHexString(pa.mPref.mMatch)); 4242 continue; 4243 } 4244 // If it's not an "always" type preferred activity and that's what we're 4245 // looking for, skip it. 4246 if (always && !pa.mPref.mAlways) { 4247 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4248 continue; 4249 } 4250 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4251 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4252 if (DEBUG_PREFERRED || debug) { 4253 Slog.v(TAG, "Found preferred activity:"); 4254 if (ai != null) { 4255 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4256 } else { 4257 Slog.v(TAG, " null"); 4258 } 4259 } 4260 if (ai == null) { 4261 // This previously registered preferred activity 4262 // component is no longer known. Most likely an update 4263 // to the app was installed and in the new version this 4264 // component no longer exists. Clean it up by removing 4265 // it from the preferred activities list, and skip it. 4266 Slog.w(TAG, "Removing dangling preferred activity: " 4267 + pa.mPref.mComponent); 4268 pir.removeFilter(pa); 4269 changed = true; 4270 continue; 4271 } 4272 for (int j=0; j<N; j++) { 4273 final ResolveInfo ri = query.get(j); 4274 if (!ri.activityInfo.applicationInfo.packageName 4275 .equals(ai.applicationInfo.packageName)) { 4276 continue; 4277 } 4278 if (!ri.activityInfo.name.equals(ai.name)) { 4279 continue; 4280 } 4281 4282 if (removeMatches) { 4283 pir.removeFilter(pa); 4284 changed = true; 4285 if (DEBUG_PREFERRED) { 4286 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4287 } 4288 break; 4289 } 4290 4291 // Okay we found a previously set preferred or last chosen app. 4292 // If the result set is different from when this 4293 // was created, we need to clear it and re-ask the 4294 // user their preference, if we're looking for an "always" type entry. 4295 if (always && !pa.mPref.sameSet(query)) { 4296 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4297 + intent + " type " + resolvedType); 4298 if (DEBUG_PREFERRED) { 4299 Slog.v(TAG, "Removing preferred activity since set changed " 4300 + pa.mPref.mComponent); 4301 } 4302 pir.removeFilter(pa); 4303 // Re-add the filter as a "last chosen" entry (!always) 4304 PreferredActivity lastChosen = new PreferredActivity( 4305 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4306 pir.addFilter(lastChosen); 4307 changed = true; 4308 return null; 4309 } 4310 4311 // Yay! Either the set matched or we're looking for the last chosen 4312 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4313 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4314 return ri; 4315 } 4316 } 4317 } finally { 4318 if (changed) { 4319 if (DEBUG_PREFERRED) { 4320 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4321 } 4322 scheduleWritePackageRestrictionsLocked(userId); 4323 } 4324 } 4325 } 4326 } 4327 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4328 return null; 4329 } 4330 4331 /* 4332 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4333 */ 4334 @Override 4335 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4336 int targetUserId) { 4337 mContext.enforceCallingOrSelfPermission( 4338 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4339 List<CrossProfileIntentFilter> matches = 4340 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4341 if (matches != null) { 4342 int size = matches.size(); 4343 for (int i = 0; i < size; i++) { 4344 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4345 } 4346 } 4347 if (hasWebURI(intent)) { 4348 // cross-profile app linking works only towards the parent. 4349 final UserInfo parent = getProfileParent(sourceUserId); 4350 synchronized(mPackages) { 4351 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4352 parent.id) != null; 4353 } 4354 } 4355 return false; 4356 } 4357 4358 private UserInfo getProfileParent(int userId) { 4359 final long identity = Binder.clearCallingIdentity(); 4360 try { 4361 return sUserManager.getProfileParent(userId); 4362 } finally { 4363 Binder.restoreCallingIdentity(identity); 4364 } 4365 } 4366 4367 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4368 String resolvedType, int userId) { 4369 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4370 if (resolver != null) { 4371 return resolver.queryIntent(intent, resolvedType, false, userId); 4372 } 4373 return null; 4374 } 4375 4376 @Override 4377 public List<ResolveInfo> queryIntentActivities(Intent intent, 4378 String resolvedType, int flags, int userId) { 4379 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4380 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4381 ComponentName comp = intent.getComponent(); 4382 if (comp == null) { 4383 if (intent.getSelector() != null) { 4384 intent = intent.getSelector(); 4385 comp = intent.getComponent(); 4386 } 4387 } 4388 4389 if (comp != null) { 4390 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4391 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4392 if (ai != null) { 4393 final ResolveInfo ri = new ResolveInfo(); 4394 ri.activityInfo = ai; 4395 list.add(ri); 4396 } 4397 return list; 4398 } 4399 4400 // reader 4401 synchronized (mPackages) { 4402 final String pkgName = intent.getPackage(); 4403 if (pkgName == null) { 4404 List<CrossProfileIntentFilter> matchingFilters = 4405 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4406 // Check for results that need to skip the current profile. 4407 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4408 resolvedType, flags, userId); 4409 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4410 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4411 result.add(xpResolveInfo); 4412 return filterIfNotPrimaryUser(result, userId); 4413 } 4414 4415 // Check for results in the current profile. 4416 List<ResolveInfo> result = mActivities.queryIntent( 4417 intent, resolvedType, flags, userId); 4418 4419 // Check for cross profile results. 4420 xpResolveInfo = queryCrossProfileIntents( 4421 matchingFilters, intent, resolvedType, flags, userId); 4422 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4423 result.add(xpResolveInfo); 4424 Collections.sort(result, mResolvePrioritySorter); 4425 } 4426 result = filterIfNotPrimaryUser(result, userId); 4427 if (hasWebURI(intent)) { 4428 CrossProfileDomainInfo xpDomainInfo = null; 4429 final UserInfo parent = getProfileParent(userId); 4430 if (parent != null) { 4431 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4432 flags, userId, parent.id); 4433 } 4434 if (xpDomainInfo != null) { 4435 if (xpResolveInfo != null) { 4436 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4437 // in the result. 4438 result.remove(xpResolveInfo); 4439 } 4440 if (result.size() == 0) { 4441 result.add(xpDomainInfo.resolveInfo); 4442 return result; 4443 } 4444 } else if (result.size() <= 1) { 4445 return result; 4446 } 4447 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4448 xpDomainInfo); 4449 Collections.sort(result, mResolvePrioritySorter); 4450 } 4451 return result; 4452 } 4453 final PackageParser.Package pkg = mPackages.get(pkgName); 4454 if (pkg != null) { 4455 return filterIfNotPrimaryUser( 4456 mActivities.queryIntentForPackage( 4457 intent, resolvedType, flags, pkg.activities, userId), 4458 userId); 4459 } 4460 return new ArrayList<ResolveInfo>(); 4461 } 4462 } 4463 4464 private static class CrossProfileDomainInfo { 4465 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4466 ResolveInfo resolveInfo; 4467 /* Best domain verification status of the activities found in the other profile */ 4468 int bestDomainVerificationStatus; 4469 } 4470 4471 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4472 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4473 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4474 sourceUserId)) { 4475 return null; 4476 } 4477 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4478 resolvedType, flags, parentUserId); 4479 4480 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4481 return null; 4482 } 4483 CrossProfileDomainInfo result = null; 4484 int size = resultTargetUser.size(); 4485 for (int i = 0; i < size; i++) { 4486 ResolveInfo riTargetUser = resultTargetUser.get(i); 4487 // Intent filter verification is only for filters that specify a host. So don't return 4488 // those that handle all web uris. 4489 if (riTargetUser.handleAllWebDataURI) { 4490 continue; 4491 } 4492 String packageName = riTargetUser.activityInfo.packageName; 4493 PackageSetting ps = mSettings.mPackages.get(packageName); 4494 if (ps == null) { 4495 continue; 4496 } 4497 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4498 if (result == null) { 4499 result = new CrossProfileDomainInfo(); 4500 result.resolveInfo = 4501 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4502 result.bestDomainVerificationStatus = status; 4503 } else { 4504 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4505 result.bestDomainVerificationStatus); 4506 } 4507 } 4508 return result; 4509 } 4510 4511 /** 4512 * Verification statuses are ordered from the worse to the best, except for 4513 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4514 */ 4515 private int bestDomainVerificationStatus(int status1, int status2) { 4516 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4517 return status2; 4518 } 4519 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4520 return status1; 4521 } 4522 return (int) MathUtils.max(status1, status2); 4523 } 4524 4525 private boolean isUserEnabled(int userId) { 4526 long callingId = Binder.clearCallingIdentity(); 4527 try { 4528 UserInfo userInfo = sUserManager.getUserInfo(userId); 4529 return userInfo != null && userInfo.isEnabled(); 4530 } finally { 4531 Binder.restoreCallingIdentity(callingId); 4532 } 4533 } 4534 4535 /** 4536 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4537 * 4538 * @return filtered list 4539 */ 4540 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4541 if (userId == UserHandle.USER_OWNER) { 4542 return resolveInfos; 4543 } 4544 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4545 ResolveInfo info = resolveInfos.get(i); 4546 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4547 resolveInfos.remove(i); 4548 } 4549 } 4550 return resolveInfos; 4551 } 4552 4553 private static boolean hasWebURI(Intent intent) { 4554 if (intent.getData() == null) { 4555 return false; 4556 } 4557 final String scheme = intent.getScheme(); 4558 if (TextUtils.isEmpty(scheme)) { 4559 return false; 4560 } 4561 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4562 } 4563 4564 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4565 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4566 if (DEBUG_PREFERRED) { 4567 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4568 candidates.size()); 4569 } 4570 4571 final int userId = UserHandle.getCallingUserId(); 4572 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4573 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4574 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4575 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4576 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4577 4578 synchronized (mPackages) { 4579 final int count = candidates.size(); 4580 // First, try to use the domain preferred app. Partition the candidates into four lists: 4581 // one for the final results, one for the "do not use ever", one for "undefined status" 4582 // and finally one for "Browser App type". 4583 for (int n=0; n<count; n++) { 4584 ResolveInfo info = candidates.get(n); 4585 String packageName = info.activityInfo.packageName; 4586 PackageSetting ps = mSettings.mPackages.get(packageName); 4587 if (ps != null) { 4588 // Add to the special match all list (Browser use case) 4589 if (info.handleAllWebDataURI) { 4590 matchAllList.add(info); 4591 continue; 4592 } 4593 // Try to get the status from User settings first 4594 int status = getDomainVerificationStatusLPr(ps, userId); 4595 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4596 alwaysList.add(info); 4597 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4598 neverList.add(info); 4599 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4600 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4601 undefinedList.add(info); 4602 } 4603 } 4604 } 4605 // First try to add the "always" resolution for the current user if there is any 4606 if (alwaysList.size() > 0) { 4607 result.addAll(alwaysList); 4608 // if there is an "always" for the parent user, add it. 4609 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4610 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4611 result.add(xpDomainInfo.resolveInfo); 4612 } else { 4613 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4614 result.addAll(undefinedList); 4615 if (xpDomainInfo != null && ( 4616 xpDomainInfo.bestDomainVerificationStatus 4617 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4618 || xpDomainInfo.bestDomainVerificationStatus 4619 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4620 result.add(xpDomainInfo.resolveInfo); 4621 } 4622 // Also add Browsers (all of them or only the default one) 4623 if ((flags & MATCH_ALL) != 0) { 4624 result.addAll(matchAllList); 4625 } else { 4626 // Try to add the Default Browser if we can 4627 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4628 UserHandle.myUserId()); 4629 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4630 boolean defaultBrowserFound = false; 4631 final int browserCount = matchAllList.size(); 4632 for (int n=0; n<browserCount; n++) { 4633 ResolveInfo browser = matchAllList.get(n); 4634 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4635 result.add(browser); 4636 defaultBrowserFound = true; 4637 break; 4638 } 4639 } 4640 if (!defaultBrowserFound) { 4641 result.addAll(matchAllList); 4642 } 4643 } else { 4644 result.addAll(matchAllList); 4645 } 4646 } 4647 4648 // If there is nothing selected, add all candidates and remove the ones that the User 4649 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4650 if (result.size() == 0) { 4651 result.addAll(candidates); 4652 result.removeAll(neverList); 4653 } 4654 } 4655 } 4656 if (DEBUG_PREFERRED) { 4657 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4658 result.size()); 4659 } 4660 return result; 4661 } 4662 4663 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4664 int status = ps.getDomainVerificationStatusForUser(userId); 4665 // if none available, get the master status 4666 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4667 if (ps.getIntentFilterVerificationInfo() != null) { 4668 status = ps.getIntentFilterVerificationInfo().getStatus(); 4669 } 4670 } 4671 return status; 4672 } 4673 4674 private ResolveInfo querySkipCurrentProfileIntents( 4675 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4676 int flags, int sourceUserId) { 4677 if (matchingFilters != null) { 4678 int size = matchingFilters.size(); 4679 for (int i = 0; i < size; i ++) { 4680 CrossProfileIntentFilter filter = matchingFilters.get(i); 4681 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4682 // Checking if there are activities in the target user that can handle the 4683 // intent. 4684 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4685 flags, sourceUserId); 4686 if (resolveInfo != null) { 4687 return resolveInfo; 4688 } 4689 } 4690 } 4691 } 4692 return null; 4693 } 4694 4695 // Return matching ResolveInfo if any for skip current profile intent filters. 4696 private ResolveInfo queryCrossProfileIntents( 4697 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4698 int flags, int sourceUserId) { 4699 if (matchingFilters != null) { 4700 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4701 // match the same intent. For performance reasons, it is better not to 4702 // run queryIntent twice for the same userId 4703 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4704 int size = matchingFilters.size(); 4705 for (int i = 0; i < size; i++) { 4706 CrossProfileIntentFilter filter = matchingFilters.get(i); 4707 int targetUserId = filter.getTargetUserId(); 4708 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4709 && !alreadyTriedUserIds.get(targetUserId)) { 4710 // Checking if there are activities in the target user that can handle the 4711 // intent. 4712 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4713 flags, sourceUserId); 4714 if (resolveInfo != null) return resolveInfo; 4715 alreadyTriedUserIds.put(targetUserId, true); 4716 } 4717 } 4718 } 4719 return null; 4720 } 4721 4722 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4723 String resolvedType, int flags, int sourceUserId) { 4724 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4725 resolvedType, flags, filter.getTargetUserId()); 4726 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4727 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4728 } 4729 return null; 4730 } 4731 4732 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4733 int sourceUserId, int targetUserId) { 4734 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4735 String className; 4736 if (targetUserId == UserHandle.USER_OWNER) { 4737 className = FORWARD_INTENT_TO_USER_OWNER; 4738 } else { 4739 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4740 } 4741 ComponentName forwardingActivityComponentName = new ComponentName( 4742 mAndroidApplication.packageName, className); 4743 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4744 sourceUserId); 4745 if (targetUserId == UserHandle.USER_OWNER) { 4746 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4747 forwardingResolveInfo.noResourceId = true; 4748 } 4749 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4750 forwardingResolveInfo.priority = 0; 4751 forwardingResolveInfo.preferredOrder = 0; 4752 forwardingResolveInfo.match = 0; 4753 forwardingResolveInfo.isDefault = true; 4754 forwardingResolveInfo.filter = filter; 4755 forwardingResolveInfo.targetUserId = targetUserId; 4756 return forwardingResolveInfo; 4757 } 4758 4759 @Override 4760 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4761 Intent[] specifics, String[] specificTypes, Intent intent, 4762 String resolvedType, int flags, int userId) { 4763 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4764 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4765 false, "query intent activity options"); 4766 final String resultsAction = intent.getAction(); 4767 4768 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4769 | PackageManager.GET_RESOLVED_FILTER, userId); 4770 4771 if (DEBUG_INTENT_MATCHING) { 4772 Log.v(TAG, "Query " + intent + ": " + results); 4773 } 4774 4775 int specificsPos = 0; 4776 int N; 4777 4778 // todo: note that the algorithm used here is O(N^2). This 4779 // isn't a problem in our current environment, but if we start running 4780 // into situations where we have more than 5 or 10 matches then this 4781 // should probably be changed to something smarter... 4782 4783 // First we go through and resolve each of the specific items 4784 // that were supplied, taking care of removing any corresponding 4785 // duplicate items in the generic resolve list. 4786 if (specifics != null) { 4787 for (int i=0; i<specifics.length; i++) { 4788 final Intent sintent = specifics[i]; 4789 if (sintent == null) { 4790 continue; 4791 } 4792 4793 if (DEBUG_INTENT_MATCHING) { 4794 Log.v(TAG, "Specific #" + i + ": " + sintent); 4795 } 4796 4797 String action = sintent.getAction(); 4798 if (resultsAction != null && resultsAction.equals(action)) { 4799 // If this action was explicitly requested, then don't 4800 // remove things that have it. 4801 action = null; 4802 } 4803 4804 ResolveInfo ri = null; 4805 ActivityInfo ai = null; 4806 4807 ComponentName comp = sintent.getComponent(); 4808 if (comp == null) { 4809 ri = resolveIntent( 4810 sintent, 4811 specificTypes != null ? specificTypes[i] : null, 4812 flags, userId); 4813 if (ri == null) { 4814 continue; 4815 } 4816 if (ri == mResolveInfo) { 4817 // ACK! Must do something better with this. 4818 } 4819 ai = ri.activityInfo; 4820 comp = new ComponentName(ai.applicationInfo.packageName, 4821 ai.name); 4822 } else { 4823 ai = getActivityInfo(comp, flags, userId); 4824 if (ai == null) { 4825 continue; 4826 } 4827 } 4828 4829 // Look for any generic query activities that are duplicates 4830 // of this specific one, and remove them from the results. 4831 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4832 N = results.size(); 4833 int j; 4834 for (j=specificsPos; j<N; j++) { 4835 ResolveInfo sri = results.get(j); 4836 if ((sri.activityInfo.name.equals(comp.getClassName()) 4837 && sri.activityInfo.applicationInfo.packageName.equals( 4838 comp.getPackageName())) 4839 || (action != null && sri.filter.matchAction(action))) { 4840 results.remove(j); 4841 if (DEBUG_INTENT_MATCHING) Log.v( 4842 TAG, "Removing duplicate item from " + j 4843 + " due to specific " + specificsPos); 4844 if (ri == null) { 4845 ri = sri; 4846 } 4847 j--; 4848 N--; 4849 } 4850 } 4851 4852 // Add this specific item to its proper place. 4853 if (ri == null) { 4854 ri = new ResolveInfo(); 4855 ri.activityInfo = ai; 4856 } 4857 results.add(specificsPos, ri); 4858 ri.specificIndex = i; 4859 specificsPos++; 4860 } 4861 } 4862 4863 // Now we go through the remaining generic results and remove any 4864 // duplicate actions that are found here. 4865 N = results.size(); 4866 for (int i=specificsPos; i<N-1; i++) { 4867 final ResolveInfo rii = results.get(i); 4868 if (rii.filter == null) { 4869 continue; 4870 } 4871 4872 // Iterate over all of the actions of this result's intent 4873 // filter... typically this should be just one. 4874 final Iterator<String> it = rii.filter.actionsIterator(); 4875 if (it == null) { 4876 continue; 4877 } 4878 while (it.hasNext()) { 4879 final String action = it.next(); 4880 if (resultsAction != null && resultsAction.equals(action)) { 4881 // If this action was explicitly requested, then don't 4882 // remove things that have it. 4883 continue; 4884 } 4885 for (int j=i+1; j<N; j++) { 4886 final ResolveInfo rij = results.get(j); 4887 if (rij.filter != null && rij.filter.hasAction(action)) { 4888 results.remove(j); 4889 if (DEBUG_INTENT_MATCHING) Log.v( 4890 TAG, "Removing duplicate item from " + j 4891 + " due to action " + action + " at " + i); 4892 j--; 4893 N--; 4894 } 4895 } 4896 } 4897 4898 // If the caller didn't request filter information, drop it now 4899 // so we don't have to marshall/unmarshall it. 4900 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4901 rii.filter = null; 4902 } 4903 } 4904 4905 // Filter out the caller activity if so requested. 4906 if (caller != null) { 4907 N = results.size(); 4908 for (int i=0; i<N; i++) { 4909 ActivityInfo ainfo = results.get(i).activityInfo; 4910 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4911 && caller.getClassName().equals(ainfo.name)) { 4912 results.remove(i); 4913 break; 4914 } 4915 } 4916 } 4917 4918 // If the caller didn't request filter information, 4919 // drop them now so we don't have to 4920 // marshall/unmarshall it. 4921 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4922 N = results.size(); 4923 for (int i=0; i<N; i++) { 4924 results.get(i).filter = null; 4925 } 4926 } 4927 4928 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4929 return results; 4930 } 4931 4932 @Override 4933 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4934 int userId) { 4935 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4936 ComponentName comp = intent.getComponent(); 4937 if (comp == null) { 4938 if (intent.getSelector() != null) { 4939 intent = intent.getSelector(); 4940 comp = intent.getComponent(); 4941 } 4942 } 4943 if (comp != null) { 4944 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4945 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4946 if (ai != null) { 4947 ResolveInfo ri = new ResolveInfo(); 4948 ri.activityInfo = ai; 4949 list.add(ri); 4950 } 4951 return list; 4952 } 4953 4954 // reader 4955 synchronized (mPackages) { 4956 String pkgName = intent.getPackage(); 4957 if (pkgName == null) { 4958 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4959 } 4960 final PackageParser.Package pkg = mPackages.get(pkgName); 4961 if (pkg != null) { 4962 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4963 userId); 4964 } 4965 return null; 4966 } 4967 } 4968 4969 @Override 4970 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4971 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4972 if (!sUserManager.exists(userId)) return null; 4973 if (query != null) { 4974 if (query.size() >= 1) { 4975 // If there is more than one service with the same priority, 4976 // just arbitrarily pick the first one. 4977 return query.get(0); 4978 } 4979 } 4980 return null; 4981 } 4982 4983 @Override 4984 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4985 int userId) { 4986 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4987 ComponentName comp = intent.getComponent(); 4988 if (comp == null) { 4989 if (intent.getSelector() != null) { 4990 intent = intent.getSelector(); 4991 comp = intent.getComponent(); 4992 } 4993 } 4994 if (comp != null) { 4995 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4996 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4997 if (si != null) { 4998 final ResolveInfo ri = new ResolveInfo(); 4999 ri.serviceInfo = si; 5000 list.add(ri); 5001 } 5002 return list; 5003 } 5004 5005 // reader 5006 synchronized (mPackages) { 5007 String pkgName = intent.getPackage(); 5008 if (pkgName == null) { 5009 return mServices.queryIntent(intent, resolvedType, flags, userId); 5010 } 5011 final PackageParser.Package pkg = mPackages.get(pkgName); 5012 if (pkg != null) { 5013 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5014 userId); 5015 } 5016 return null; 5017 } 5018 } 5019 5020 @Override 5021 public List<ResolveInfo> queryIntentContentProviders( 5022 Intent intent, String resolvedType, int flags, int userId) { 5023 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5024 ComponentName comp = intent.getComponent(); 5025 if (comp == null) { 5026 if (intent.getSelector() != null) { 5027 intent = intent.getSelector(); 5028 comp = intent.getComponent(); 5029 } 5030 } 5031 if (comp != null) { 5032 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5033 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5034 if (pi != null) { 5035 final ResolveInfo ri = new ResolveInfo(); 5036 ri.providerInfo = pi; 5037 list.add(ri); 5038 } 5039 return list; 5040 } 5041 5042 // reader 5043 synchronized (mPackages) { 5044 String pkgName = intent.getPackage(); 5045 if (pkgName == null) { 5046 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5047 } 5048 final PackageParser.Package pkg = mPackages.get(pkgName); 5049 if (pkg != null) { 5050 return mProviders.queryIntentForPackage( 5051 intent, resolvedType, flags, pkg.providers, userId); 5052 } 5053 return null; 5054 } 5055 } 5056 5057 @Override 5058 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5059 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5060 5061 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5062 5063 // writer 5064 synchronized (mPackages) { 5065 ArrayList<PackageInfo> list; 5066 if (listUninstalled) { 5067 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5068 for (PackageSetting ps : mSettings.mPackages.values()) { 5069 PackageInfo pi; 5070 if (ps.pkg != null) { 5071 pi = generatePackageInfo(ps.pkg, flags, userId); 5072 } else { 5073 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5074 } 5075 if (pi != null) { 5076 list.add(pi); 5077 } 5078 } 5079 } else { 5080 list = new ArrayList<PackageInfo>(mPackages.size()); 5081 for (PackageParser.Package p : mPackages.values()) { 5082 PackageInfo pi = generatePackageInfo(p, flags, userId); 5083 if (pi != null) { 5084 list.add(pi); 5085 } 5086 } 5087 } 5088 5089 return new ParceledListSlice<PackageInfo>(list); 5090 } 5091 } 5092 5093 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5094 String[] permissions, boolean[] tmp, int flags, int userId) { 5095 int numMatch = 0; 5096 final PermissionsState permissionsState = ps.getPermissionsState(); 5097 for (int i=0; i<permissions.length; i++) { 5098 final String permission = permissions[i]; 5099 if (permissionsState.hasPermission(permission, userId)) { 5100 tmp[i] = true; 5101 numMatch++; 5102 } else { 5103 tmp[i] = false; 5104 } 5105 } 5106 if (numMatch == 0) { 5107 return; 5108 } 5109 PackageInfo pi; 5110 if (ps.pkg != null) { 5111 pi = generatePackageInfo(ps.pkg, flags, userId); 5112 } else { 5113 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5114 } 5115 // The above might return null in cases of uninstalled apps or install-state 5116 // skew across users/profiles. 5117 if (pi != null) { 5118 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5119 if (numMatch == permissions.length) { 5120 pi.requestedPermissions = permissions; 5121 } else { 5122 pi.requestedPermissions = new String[numMatch]; 5123 numMatch = 0; 5124 for (int i=0; i<permissions.length; i++) { 5125 if (tmp[i]) { 5126 pi.requestedPermissions[numMatch] = permissions[i]; 5127 numMatch++; 5128 } 5129 } 5130 } 5131 } 5132 list.add(pi); 5133 } 5134 } 5135 5136 @Override 5137 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5138 String[] permissions, int flags, int userId) { 5139 if (!sUserManager.exists(userId)) return null; 5140 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5141 5142 // writer 5143 synchronized (mPackages) { 5144 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5145 boolean[] tmpBools = new boolean[permissions.length]; 5146 if (listUninstalled) { 5147 for (PackageSetting ps : mSettings.mPackages.values()) { 5148 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5149 } 5150 } else { 5151 for (PackageParser.Package pkg : mPackages.values()) { 5152 PackageSetting ps = (PackageSetting)pkg.mExtras; 5153 if (ps != null) { 5154 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5155 userId); 5156 } 5157 } 5158 } 5159 5160 return new ParceledListSlice<PackageInfo>(list); 5161 } 5162 } 5163 5164 @Override 5165 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5166 if (!sUserManager.exists(userId)) return null; 5167 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5168 5169 // writer 5170 synchronized (mPackages) { 5171 ArrayList<ApplicationInfo> list; 5172 if (listUninstalled) { 5173 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5174 for (PackageSetting ps : mSettings.mPackages.values()) { 5175 ApplicationInfo ai; 5176 if (ps.pkg != null) { 5177 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5178 ps.readUserState(userId), userId); 5179 } else { 5180 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5181 } 5182 if (ai != null) { 5183 list.add(ai); 5184 } 5185 } 5186 } else { 5187 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5188 for (PackageParser.Package p : mPackages.values()) { 5189 if (p.mExtras != null) { 5190 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5191 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5192 if (ai != null) { 5193 list.add(ai); 5194 } 5195 } 5196 } 5197 } 5198 5199 return new ParceledListSlice<ApplicationInfo>(list); 5200 } 5201 } 5202 5203 public List<ApplicationInfo> getPersistentApplications(int flags) { 5204 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5205 5206 // reader 5207 synchronized (mPackages) { 5208 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5209 final int userId = UserHandle.getCallingUserId(); 5210 while (i.hasNext()) { 5211 final PackageParser.Package p = i.next(); 5212 if (p.applicationInfo != null 5213 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5214 && (!mSafeMode || isSystemApp(p))) { 5215 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5216 if (ps != null) { 5217 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5218 ps.readUserState(userId), userId); 5219 if (ai != null) { 5220 finalList.add(ai); 5221 } 5222 } 5223 } 5224 } 5225 } 5226 5227 return finalList; 5228 } 5229 5230 @Override 5231 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5232 if (!sUserManager.exists(userId)) return null; 5233 // reader 5234 synchronized (mPackages) { 5235 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5236 PackageSetting ps = provider != null 5237 ? mSettings.mPackages.get(provider.owner.packageName) 5238 : null; 5239 return ps != null 5240 && mSettings.isEnabledLPr(provider.info, flags, userId) 5241 && (!mSafeMode || (provider.info.applicationInfo.flags 5242 &ApplicationInfo.FLAG_SYSTEM) != 0) 5243 ? PackageParser.generateProviderInfo(provider, flags, 5244 ps.readUserState(userId), userId) 5245 : null; 5246 } 5247 } 5248 5249 /** 5250 * @deprecated 5251 */ 5252 @Deprecated 5253 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5254 // reader 5255 synchronized (mPackages) { 5256 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5257 .entrySet().iterator(); 5258 final int userId = UserHandle.getCallingUserId(); 5259 while (i.hasNext()) { 5260 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5261 PackageParser.Provider p = entry.getValue(); 5262 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5263 5264 if (ps != null && p.syncable 5265 && (!mSafeMode || (p.info.applicationInfo.flags 5266 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5267 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5268 ps.readUserState(userId), userId); 5269 if (info != null) { 5270 outNames.add(entry.getKey()); 5271 outInfo.add(info); 5272 } 5273 } 5274 } 5275 } 5276 } 5277 5278 @Override 5279 public List<ProviderInfo> queryContentProviders(String processName, 5280 int uid, int flags) { 5281 ArrayList<ProviderInfo> finalList = null; 5282 // reader 5283 synchronized (mPackages) { 5284 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5285 final int userId = processName != null ? 5286 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5287 while (i.hasNext()) { 5288 final PackageParser.Provider p = i.next(); 5289 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5290 if (ps != null && p.info.authority != null 5291 && (processName == null 5292 || (p.info.processName.equals(processName) 5293 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5294 && mSettings.isEnabledLPr(p.info, flags, userId) 5295 && (!mSafeMode 5296 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5297 if (finalList == null) { 5298 finalList = new ArrayList<ProviderInfo>(3); 5299 } 5300 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5301 ps.readUserState(userId), userId); 5302 if (info != null) { 5303 finalList.add(info); 5304 } 5305 } 5306 } 5307 } 5308 5309 if (finalList != null) { 5310 Collections.sort(finalList, mProviderInitOrderSorter); 5311 } 5312 5313 return finalList; 5314 } 5315 5316 @Override 5317 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5318 int flags) { 5319 // reader 5320 synchronized (mPackages) { 5321 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5322 return PackageParser.generateInstrumentationInfo(i, flags); 5323 } 5324 } 5325 5326 @Override 5327 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5328 int flags) { 5329 ArrayList<InstrumentationInfo> finalList = 5330 new ArrayList<InstrumentationInfo>(); 5331 5332 // reader 5333 synchronized (mPackages) { 5334 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5335 while (i.hasNext()) { 5336 final PackageParser.Instrumentation p = i.next(); 5337 if (targetPackage == null 5338 || targetPackage.equals(p.info.targetPackage)) { 5339 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5340 flags); 5341 if (ii != null) { 5342 finalList.add(ii); 5343 } 5344 } 5345 } 5346 } 5347 5348 return finalList; 5349 } 5350 5351 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5352 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5353 if (overlays == null) { 5354 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5355 return; 5356 } 5357 for (PackageParser.Package opkg : overlays.values()) { 5358 // Not much to do if idmap fails: we already logged the error 5359 // and we certainly don't want to abort installation of pkg simply 5360 // because an overlay didn't fit properly. For these reasons, 5361 // ignore the return value of createIdmapForPackagePairLI. 5362 createIdmapForPackagePairLI(pkg, opkg); 5363 } 5364 } 5365 5366 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5367 PackageParser.Package opkg) { 5368 if (!opkg.mTrustedOverlay) { 5369 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5370 opkg.baseCodePath + ": overlay not trusted"); 5371 return false; 5372 } 5373 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5374 if (overlaySet == null) { 5375 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5376 opkg.baseCodePath + " but target package has no known overlays"); 5377 return false; 5378 } 5379 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5380 // TODO: generate idmap for split APKs 5381 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5382 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5383 + opkg.baseCodePath); 5384 return false; 5385 } 5386 PackageParser.Package[] overlayArray = 5387 overlaySet.values().toArray(new PackageParser.Package[0]); 5388 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5389 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5390 return p1.mOverlayPriority - p2.mOverlayPriority; 5391 } 5392 }; 5393 Arrays.sort(overlayArray, cmp); 5394 5395 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5396 int i = 0; 5397 for (PackageParser.Package p : overlayArray) { 5398 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5399 } 5400 return true; 5401 } 5402 5403 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5404 final File[] files = dir.listFiles(); 5405 if (ArrayUtils.isEmpty(files)) { 5406 Log.d(TAG, "No files in app dir " + dir); 5407 return; 5408 } 5409 5410 if (DEBUG_PACKAGE_SCANNING) { 5411 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5412 + " flags=0x" + Integer.toHexString(parseFlags)); 5413 } 5414 5415 for (File file : files) { 5416 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5417 && !PackageInstallerService.isStageName(file.getName()); 5418 if (!isPackage) { 5419 // Ignore entries which are not packages 5420 continue; 5421 } 5422 try { 5423 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5424 scanFlags, currentTime, null); 5425 } catch (PackageManagerException e) { 5426 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5427 5428 // Delete invalid userdata apps 5429 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5430 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5431 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5432 if (file.isDirectory()) { 5433 mInstaller.rmPackageDir(file.getAbsolutePath()); 5434 } else { 5435 file.delete(); 5436 } 5437 } 5438 } 5439 } 5440 } 5441 5442 private static File getSettingsProblemFile() { 5443 File dataDir = Environment.getDataDirectory(); 5444 File systemDir = new File(dataDir, "system"); 5445 File fname = new File(systemDir, "uiderrors.txt"); 5446 return fname; 5447 } 5448 5449 static void reportSettingsProblem(int priority, String msg) { 5450 logCriticalInfo(priority, msg); 5451 } 5452 5453 static void logCriticalInfo(int priority, String msg) { 5454 Slog.println(priority, TAG, msg); 5455 EventLogTags.writePmCriticalInfo(msg); 5456 try { 5457 File fname = getSettingsProblemFile(); 5458 FileOutputStream out = new FileOutputStream(fname, true); 5459 PrintWriter pw = new FastPrintWriter(out); 5460 SimpleDateFormat formatter = new SimpleDateFormat(); 5461 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5462 pw.println(dateString + ": " + msg); 5463 pw.close(); 5464 FileUtils.setPermissions( 5465 fname.toString(), 5466 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5467 -1, -1); 5468 } catch (java.io.IOException e) { 5469 } 5470 } 5471 5472 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5473 PackageParser.Package pkg, File srcFile, int parseFlags) 5474 throws PackageManagerException { 5475 if (ps != null 5476 && ps.codePath.equals(srcFile) 5477 && ps.timeStamp == srcFile.lastModified() 5478 && !isCompatSignatureUpdateNeeded(pkg) 5479 && !isRecoverSignatureUpdateNeeded(pkg)) { 5480 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5481 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5482 ArraySet<PublicKey> signingKs; 5483 synchronized (mPackages) { 5484 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5485 } 5486 if (ps.signatures.mSignatures != null 5487 && ps.signatures.mSignatures.length != 0 5488 && signingKs != null) { 5489 // Optimization: reuse the existing cached certificates 5490 // if the package appears to be unchanged. 5491 pkg.mSignatures = ps.signatures.mSignatures; 5492 pkg.mSigningKeys = signingKs; 5493 return; 5494 } 5495 5496 Slog.w(TAG, "PackageSetting for " + ps.name 5497 + " is missing signatures. Collecting certs again to recover them."); 5498 } else { 5499 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5500 } 5501 5502 try { 5503 pp.collectCertificates(pkg, parseFlags); 5504 pp.collectManifestDigest(pkg); 5505 } catch (PackageParserException e) { 5506 throw PackageManagerException.from(e); 5507 } 5508 } 5509 5510 /* 5511 * Scan a package and return the newly parsed package. 5512 * Returns null in case of errors and the error code is stored in mLastScanError 5513 */ 5514 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5515 long currentTime, UserHandle user) throws PackageManagerException { 5516 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5517 parseFlags |= mDefParseFlags; 5518 PackageParser pp = new PackageParser(); 5519 pp.setSeparateProcesses(mSeparateProcesses); 5520 pp.setOnlyCoreApps(mOnlyCore); 5521 pp.setDisplayMetrics(mMetrics); 5522 5523 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5524 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5525 } 5526 5527 final PackageParser.Package pkg; 5528 try { 5529 pkg = pp.parsePackage(scanFile, parseFlags); 5530 } catch (PackageParserException e) { 5531 throw PackageManagerException.from(e); 5532 } 5533 5534 PackageSetting ps = null; 5535 PackageSetting updatedPkg; 5536 // reader 5537 synchronized (mPackages) { 5538 // Look to see if we already know about this package. 5539 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5540 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5541 // This package has been renamed to its original name. Let's 5542 // use that. 5543 ps = mSettings.peekPackageLPr(oldName); 5544 } 5545 // If there was no original package, see one for the real package name. 5546 if (ps == null) { 5547 ps = mSettings.peekPackageLPr(pkg.packageName); 5548 } 5549 // Check to see if this package could be hiding/updating a system 5550 // package. Must look for it either under the original or real 5551 // package name depending on our state. 5552 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5553 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5554 } 5555 boolean updatedPkgBetter = false; 5556 // First check if this is a system package that may involve an update 5557 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5558 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5559 // it needs to drop FLAG_PRIVILEGED. 5560 if (locationIsPrivileged(scanFile)) { 5561 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5562 } else { 5563 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5564 } 5565 5566 if (ps != null && !ps.codePath.equals(scanFile)) { 5567 // The path has changed from what was last scanned... check the 5568 // version of the new path against what we have stored to determine 5569 // what to do. 5570 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5571 if (pkg.mVersionCode <= ps.versionCode) { 5572 // The system package has been updated and the code path does not match 5573 // Ignore entry. Skip it. 5574 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5575 + " ignored: updated version " + ps.versionCode 5576 + " better than this " + pkg.mVersionCode); 5577 if (!updatedPkg.codePath.equals(scanFile)) { 5578 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5579 + ps.name + " changing from " + updatedPkg.codePathString 5580 + " to " + scanFile); 5581 updatedPkg.codePath = scanFile; 5582 updatedPkg.codePathString = scanFile.toString(); 5583 updatedPkg.resourcePath = scanFile; 5584 updatedPkg.resourcePathString = scanFile.toString(); 5585 } 5586 updatedPkg.pkg = pkg; 5587 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5588 } else { 5589 // The current app on the system partition is better than 5590 // what we have updated to on the data partition; switch 5591 // back to the system partition version. 5592 // At this point, its safely assumed that package installation for 5593 // apps in system partition will go through. If not there won't be a working 5594 // version of the app 5595 // writer 5596 synchronized (mPackages) { 5597 // Just remove the loaded entries from package lists. 5598 mPackages.remove(ps.name); 5599 } 5600 5601 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5602 + " reverting from " + ps.codePathString 5603 + ": new version " + pkg.mVersionCode 5604 + " better than installed " + ps.versionCode); 5605 5606 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5607 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5608 synchronized (mInstallLock) { 5609 args.cleanUpResourcesLI(); 5610 } 5611 synchronized (mPackages) { 5612 mSettings.enableSystemPackageLPw(ps.name); 5613 } 5614 updatedPkgBetter = true; 5615 } 5616 } 5617 } 5618 5619 if (updatedPkg != null) { 5620 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5621 // initially 5622 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5623 5624 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5625 // flag set initially 5626 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5627 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5628 } 5629 } 5630 5631 // Verify certificates against what was last scanned 5632 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5633 5634 /* 5635 * A new system app appeared, but we already had a non-system one of the 5636 * same name installed earlier. 5637 */ 5638 boolean shouldHideSystemApp = false; 5639 if (updatedPkg == null && ps != null 5640 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5641 /* 5642 * Check to make sure the signatures match first. If they don't, 5643 * wipe the installed application and its data. 5644 */ 5645 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5646 != PackageManager.SIGNATURE_MATCH) { 5647 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5648 + " signatures don't match existing userdata copy; removing"); 5649 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5650 ps = null; 5651 } else { 5652 /* 5653 * If the newly-added system app is an older version than the 5654 * already installed version, hide it. It will be scanned later 5655 * and re-added like an update. 5656 */ 5657 if (pkg.mVersionCode <= ps.versionCode) { 5658 shouldHideSystemApp = true; 5659 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5660 + " but new version " + pkg.mVersionCode + " better than installed " 5661 + ps.versionCode + "; hiding system"); 5662 } else { 5663 /* 5664 * The newly found system app is a newer version that the 5665 * one previously installed. Simply remove the 5666 * already-installed application and replace it with our own 5667 * while keeping the application data. 5668 */ 5669 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5670 + " reverting from " + ps.codePathString + ": new version " 5671 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5672 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5673 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5674 synchronized (mInstallLock) { 5675 args.cleanUpResourcesLI(); 5676 } 5677 } 5678 } 5679 } 5680 5681 // The apk is forward locked (not public) if its code and resources 5682 // are kept in different files. (except for app in either system or 5683 // vendor path). 5684 // TODO grab this value from PackageSettings 5685 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5686 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5687 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5688 } 5689 } 5690 5691 // TODO: extend to support forward-locked splits 5692 String resourcePath = null; 5693 String baseResourcePath = null; 5694 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5695 if (ps != null && ps.resourcePathString != null) { 5696 resourcePath = ps.resourcePathString; 5697 baseResourcePath = ps.resourcePathString; 5698 } else { 5699 // Should not happen at all. Just log an error. 5700 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5701 } 5702 } else { 5703 resourcePath = pkg.codePath; 5704 baseResourcePath = pkg.baseCodePath; 5705 } 5706 5707 // Set application objects path explicitly. 5708 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5709 pkg.applicationInfo.setCodePath(pkg.codePath); 5710 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5711 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5712 pkg.applicationInfo.setResourcePath(resourcePath); 5713 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5714 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5715 5716 // Note that we invoke the following method only if we are about to unpack an application 5717 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5718 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5719 5720 /* 5721 * If the system app should be overridden by a previously installed 5722 * data, hide the system app now and let the /data/app scan pick it up 5723 * again. 5724 */ 5725 if (shouldHideSystemApp) { 5726 synchronized (mPackages) { 5727 /* 5728 * We have to grant systems permissions before we hide, because 5729 * grantPermissions will assume the package update is trying to 5730 * expand its permissions. 5731 */ 5732 grantPermissionsLPw(pkg, true, pkg.packageName); 5733 mSettings.disableSystemPackageLPw(pkg.packageName); 5734 } 5735 } 5736 5737 return scannedPkg; 5738 } 5739 5740 private static String fixProcessName(String defProcessName, 5741 String processName, int uid) { 5742 if (processName == null) { 5743 return defProcessName; 5744 } 5745 return processName; 5746 } 5747 5748 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5749 throws PackageManagerException { 5750 if (pkgSetting.signatures.mSignatures != null) { 5751 // Already existing package. Make sure signatures match 5752 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5753 == PackageManager.SIGNATURE_MATCH; 5754 if (!match) { 5755 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5756 == PackageManager.SIGNATURE_MATCH; 5757 } 5758 if (!match) { 5759 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5760 == PackageManager.SIGNATURE_MATCH; 5761 } 5762 if (!match) { 5763 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5764 + pkg.packageName + " signatures do not match the " 5765 + "previously installed version; ignoring!"); 5766 } 5767 } 5768 5769 // Check for shared user signatures 5770 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5771 // Already existing package. Make sure signatures match 5772 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5773 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5774 if (!match) { 5775 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5776 == PackageManager.SIGNATURE_MATCH; 5777 } 5778 if (!match) { 5779 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5780 == PackageManager.SIGNATURE_MATCH; 5781 } 5782 if (!match) { 5783 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5784 "Package " + pkg.packageName 5785 + " has no signatures that match those in shared user " 5786 + pkgSetting.sharedUser.name + "; ignoring!"); 5787 } 5788 } 5789 } 5790 5791 /** 5792 * Enforces that only the system UID or root's UID can call a method exposed 5793 * via Binder. 5794 * 5795 * @param message used as message if SecurityException is thrown 5796 * @throws SecurityException if the caller is not system or root 5797 */ 5798 private static final void enforceSystemOrRoot(String message) { 5799 final int uid = Binder.getCallingUid(); 5800 if (uid != Process.SYSTEM_UID && uid != 0) { 5801 throw new SecurityException(message); 5802 } 5803 } 5804 5805 @Override 5806 public void performBootDexOpt() { 5807 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5808 5809 // Before everything else, see whether we need to fstrim. 5810 try { 5811 IMountService ms = PackageHelper.getMountService(); 5812 if (ms != null) { 5813 final boolean isUpgrade = isUpgrade(); 5814 boolean doTrim = isUpgrade; 5815 if (doTrim) { 5816 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5817 } else { 5818 final long interval = android.provider.Settings.Global.getLong( 5819 mContext.getContentResolver(), 5820 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5821 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5822 if (interval > 0) { 5823 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5824 if (timeSinceLast > interval) { 5825 doTrim = true; 5826 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5827 + "; running immediately"); 5828 } 5829 } 5830 } 5831 if (doTrim) { 5832 if (!isFirstBoot()) { 5833 try { 5834 ActivityManagerNative.getDefault().showBootMessage( 5835 mContext.getResources().getString( 5836 R.string.android_upgrading_fstrim), true); 5837 } catch (RemoteException e) { 5838 } 5839 } 5840 ms.runMaintenance(); 5841 } 5842 } else { 5843 Slog.e(TAG, "Mount service unavailable!"); 5844 } 5845 } catch (RemoteException e) { 5846 // Can't happen; MountService is local 5847 } 5848 5849 final ArraySet<PackageParser.Package> pkgs; 5850 synchronized (mPackages) { 5851 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5852 } 5853 5854 if (pkgs != null) { 5855 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5856 // in case the device runs out of space. 5857 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5858 // Give priority to core apps. 5859 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5860 PackageParser.Package pkg = it.next(); 5861 if (pkg.coreApp) { 5862 if (DEBUG_DEXOPT) { 5863 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5864 } 5865 sortedPkgs.add(pkg); 5866 it.remove(); 5867 } 5868 } 5869 // Give priority to system apps that listen for pre boot complete. 5870 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5871 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5872 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5873 PackageParser.Package pkg = it.next(); 5874 if (pkgNames.contains(pkg.packageName)) { 5875 if (DEBUG_DEXOPT) { 5876 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5877 } 5878 sortedPkgs.add(pkg); 5879 it.remove(); 5880 } 5881 } 5882 // Give priority to system apps. 5883 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5884 PackageParser.Package pkg = it.next(); 5885 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5886 if (DEBUG_DEXOPT) { 5887 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5888 } 5889 sortedPkgs.add(pkg); 5890 it.remove(); 5891 } 5892 } 5893 // Give priority to updated system apps. 5894 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5895 PackageParser.Package pkg = it.next(); 5896 if (pkg.isUpdatedSystemApp()) { 5897 if (DEBUG_DEXOPT) { 5898 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5899 } 5900 sortedPkgs.add(pkg); 5901 it.remove(); 5902 } 5903 } 5904 // Give priority to apps that listen for boot complete. 5905 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5906 pkgNames = getPackageNamesForIntent(intent); 5907 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5908 PackageParser.Package pkg = it.next(); 5909 if (pkgNames.contains(pkg.packageName)) { 5910 if (DEBUG_DEXOPT) { 5911 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5912 } 5913 sortedPkgs.add(pkg); 5914 it.remove(); 5915 } 5916 } 5917 // Filter out packages that aren't recently used. 5918 filterRecentlyUsedApps(pkgs); 5919 // Add all remaining apps. 5920 for (PackageParser.Package pkg : pkgs) { 5921 if (DEBUG_DEXOPT) { 5922 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5923 } 5924 sortedPkgs.add(pkg); 5925 } 5926 5927 // If we want to be lazy, filter everything that wasn't recently used. 5928 if (mLazyDexOpt) { 5929 filterRecentlyUsedApps(sortedPkgs); 5930 } 5931 5932 int i = 0; 5933 int total = sortedPkgs.size(); 5934 File dataDir = Environment.getDataDirectory(); 5935 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5936 if (lowThreshold == 0) { 5937 throw new IllegalStateException("Invalid low memory threshold"); 5938 } 5939 for (PackageParser.Package pkg : sortedPkgs) { 5940 long usableSpace = dataDir.getUsableSpace(); 5941 if (usableSpace < lowThreshold) { 5942 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5943 break; 5944 } 5945 performBootDexOpt(pkg, ++i, total); 5946 } 5947 } 5948 } 5949 5950 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5951 // Filter out packages that aren't recently used. 5952 // 5953 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5954 // should do a full dexopt. 5955 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5956 int total = pkgs.size(); 5957 int skipped = 0; 5958 long now = System.currentTimeMillis(); 5959 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5960 PackageParser.Package pkg = i.next(); 5961 long then = pkg.mLastPackageUsageTimeInMills; 5962 if (then + mDexOptLRUThresholdInMills < now) { 5963 if (DEBUG_DEXOPT) { 5964 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5965 ((then == 0) ? "never" : new Date(then))); 5966 } 5967 i.remove(); 5968 skipped++; 5969 } 5970 } 5971 if (DEBUG_DEXOPT) { 5972 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5973 } 5974 } 5975 } 5976 5977 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5978 List<ResolveInfo> ris = null; 5979 try { 5980 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5981 intent, null, 0, UserHandle.USER_OWNER); 5982 } catch (RemoteException e) { 5983 } 5984 ArraySet<String> pkgNames = new ArraySet<String>(); 5985 if (ris != null) { 5986 for (ResolveInfo ri : ris) { 5987 pkgNames.add(ri.activityInfo.packageName); 5988 } 5989 } 5990 return pkgNames; 5991 } 5992 5993 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5994 if (DEBUG_DEXOPT) { 5995 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5996 } 5997 if (!isFirstBoot()) { 5998 try { 5999 ActivityManagerNative.getDefault().showBootMessage( 6000 mContext.getResources().getString(R.string.android_upgrading_apk, 6001 curr, total), true); 6002 } catch (RemoteException e) { 6003 } 6004 } 6005 PackageParser.Package p = pkg; 6006 synchronized (mInstallLock) { 6007 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6008 false /* force dex */, false /* defer */, true /* include dependencies */); 6009 } 6010 } 6011 6012 @Override 6013 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6014 return performDexOpt(packageName, instructionSet, false); 6015 } 6016 6017 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6018 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6019 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6020 if (!dexopt && !updateUsage) { 6021 // We aren't going to dexopt or update usage, so bail early. 6022 return false; 6023 } 6024 PackageParser.Package p; 6025 final String targetInstructionSet; 6026 synchronized (mPackages) { 6027 p = mPackages.get(packageName); 6028 if (p == null) { 6029 return false; 6030 } 6031 if (updateUsage) { 6032 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6033 } 6034 mPackageUsage.write(false); 6035 if (!dexopt) { 6036 // We aren't going to dexopt, so bail early. 6037 return false; 6038 } 6039 6040 targetInstructionSet = instructionSet != null ? instructionSet : 6041 getPrimaryInstructionSet(p.applicationInfo); 6042 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6043 return false; 6044 } 6045 } 6046 6047 synchronized (mInstallLock) { 6048 final String[] instructionSets = new String[] { targetInstructionSet }; 6049 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6050 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6051 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6052 } 6053 } 6054 6055 public ArraySet<String> getPackagesThatNeedDexOpt() { 6056 ArraySet<String> pkgs = null; 6057 synchronized (mPackages) { 6058 for (PackageParser.Package p : mPackages.values()) { 6059 if (DEBUG_DEXOPT) { 6060 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6061 } 6062 if (!p.mDexOptPerformed.isEmpty()) { 6063 continue; 6064 } 6065 if (pkgs == null) { 6066 pkgs = new ArraySet<String>(); 6067 } 6068 pkgs.add(p.packageName); 6069 } 6070 } 6071 return pkgs; 6072 } 6073 6074 public void shutdown() { 6075 mPackageUsage.write(true); 6076 } 6077 6078 @Override 6079 public void forceDexOpt(String packageName) { 6080 enforceSystemOrRoot("forceDexOpt"); 6081 6082 PackageParser.Package pkg; 6083 synchronized (mPackages) { 6084 pkg = mPackages.get(packageName); 6085 if (pkg == null) { 6086 throw new IllegalArgumentException("Missing package: " + packageName); 6087 } 6088 } 6089 6090 synchronized (mInstallLock) { 6091 final String[] instructionSets = new String[] { 6092 getPrimaryInstructionSet(pkg.applicationInfo) }; 6093 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6094 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6095 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6096 throw new IllegalStateException("Failed to dexopt: " + res); 6097 } 6098 } 6099 } 6100 6101 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6102 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6103 Slog.w(TAG, "Unable to update from " + oldPkg.name 6104 + " to " + newPkg.packageName 6105 + ": old package not in system partition"); 6106 return false; 6107 } else if (mPackages.get(oldPkg.name) != null) { 6108 Slog.w(TAG, "Unable to update from " + oldPkg.name 6109 + " to " + newPkg.packageName 6110 + ": old package still exists"); 6111 return false; 6112 } 6113 return true; 6114 } 6115 6116 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6117 int[] users = sUserManager.getUserIds(); 6118 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6119 if (res < 0) { 6120 return res; 6121 } 6122 for (int user : users) { 6123 if (user != 0) { 6124 res = mInstaller.createUserData(volumeUuid, packageName, 6125 UserHandle.getUid(user, uid), user, seinfo); 6126 if (res < 0) { 6127 return res; 6128 } 6129 } 6130 } 6131 return res; 6132 } 6133 6134 private int removeDataDirsLI(String volumeUuid, String packageName) { 6135 int[] users = sUserManager.getUserIds(); 6136 int res = 0; 6137 for (int user : users) { 6138 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6139 if (resInner < 0) { 6140 res = resInner; 6141 } 6142 } 6143 6144 return res; 6145 } 6146 6147 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6148 int[] users = sUserManager.getUserIds(); 6149 int res = 0; 6150 for (int user : users) { 6151 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6152 if (resInner < 0) { 6153 res = resInner; 6154 } 6155 } 6156 return res; 6157 } 6158 6159 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6160 PackageParser.Package changingLib) { 6161 if (file.path != null) { 6162 usesLibraryFiles.add(file.path); 6163 return; 6164 } 6165 PackageParser.Package p = mPackages.get(file.apk); 6166 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6167 // If we are doing this while in the middle of updating a library apk, 6168 // then we need to make sure to use that new apk for determining the 6169 // dependencies here. (We haven't yet finished committing the new apk 6170 // to the package manager state.) 6171 if (p == null || p.packageName.equals(changingLib.packageName)) { 6172 p = changingLib; 6173 } 6174 } 6175 if (p != null) { 6176 usesLibraryFiles.addAll(p.getAllCodePaths()); 6177 } 6178 } 6179 6180 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6181 PackageParser.Package changingLib) throws PackageManagerException { 6182 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6183 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6184 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6185 for (int i=0; i<N; i++) { 6186 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6187 if (file == null) { 6188 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6189 "Package " + pkg.packageName + " requires unavailable shared library " 6190 + pkg.usesLibraries.get(i) + "; failing!"); 6191 } 6192 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6193 } 6194 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6195 for (int i=0; i<N; i++) { 6196 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6197 if (file == null) { 6198 Slog.w(TAG, "Package " + pkg.packageName 6199 + " desires unavailable shared library " 6200 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6201 } else { 6202 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6203 } 6204 } 6205 N = usesLibraryFiles.size(); 6206 if (N > 0) { 6207 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6208 } else { 6209 pkg.usesLibraryFiles = null; 6210 } 6211 } 6212 } 6213 6214 private static boolean hasString(List<String> list, List<String> which) { 6215 if (list == null) { 6216 return false; 6217 } 6218 for (int i=list.size()-1; i>=0; i--) { 6219 for (int j=which.size()-1; j>=0; j--) { 6220 if (which.get(j).equals(list.get(i))) { 6221 return true; 6222 } 6223 } 6224 } 6225 return false; 6226 } 6227 6228 private void updateAllSharedLibrariesLPw() { 6229 for (PackageParser.Package pkg : mPackages.values()) { 6230 try { 6231 updateSharedLibrariesLPw(pkg, null); 6232 } catch (PackageManagerException e) { 6233 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6234 } 6235 } 6236 } 6237 6238 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6239 PackageParser.Package changingPkg) { 6240 ArrayList<PackageParser.Package> res = null; 6241 for (PackageParser.Package pkg : mPackages.values()) { 6242 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6243 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6244 if (res == null) { 6245 res = new ArrayList<PackageParser.Package>(); 6246 } 6247 res.add(pkg); 6248 try { 6249 updateSharedLibrariesLPw(pkg, changingPkg); 6250 } catch (PackageManagerException e) { 6251 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6252 } 6253 } 6254 } 6255 return res; 6256 } 6257 6258 /** 6259 * Derive the value of the {@code cpuAbiOverride} based on the provided 6260 * value and an optional stored value from the package settings. 6261 */ 6262 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6263 String cpuAbiOverride = null; 6264 6265 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6266 cpuAbiOverride = null; 6267 } else if (abiOverride != null) { 6268 cpuAbiOverride = abiOverride; 6269 } else if (settings != null) { 6270 cpuAbiOverride = settings.cpuAbiOverrideString; 6271 } 6272 6273 return cpuAbiOverride; 6274 } 6275 6276 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6277 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6278 boolean success = false; 6279 try { 6280 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6281 currentTime, user); 6282 success = true; 6283 return res; 6284 } finally { 6285 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6286 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6287 } 6288 } 6289 } 6290 6291 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6292 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6293 final File scanFile = new File(pkg.codePath); 6294 if (pkg.applicationInfo.getCodePath() == null || 6295 pkg.applicationInfo.getResourcePath() == null) { 6296 // Bail out. The resource and code paths haven't been set. 6297 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6298 "Code and resource paths haven't been set correctly"); 6299 } 6300 6301 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6302 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6303 } else { 6304 // Only allow system apps to be flagged as core apps. 6305 pkg.coreApp = false; 6306 } 6307 6308 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6309 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6310 } 6311 6312 if (mCustomResolverComponentName != null && 6313 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6314 setUpCustomResolverActivity(pkg); 6315 } 6316 6317 if (pkg.packageName.equals("android")) { 6318 synchronized (mPackages) { 6319 if (mAndroidApplication != null) { 6320 Slog.w(TAG, "*************************************************"); 6321 Slog.w(TAG, "Core android package being redefined. Skipping."); 6322 Slog.w(TAG, " file=" + scanFile); 6323 Slog.w(TAG, "*************************************************"); 6324 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6325 "Core android package being redefined. Skipping."); 6326 } 6327 6328 // Set up information for our fall-back user intent resolution activity. 6329 mPlatformPackage = pkg; 6330 pkg.mVersionCode = mSdkVersion; 6331 mAndroidApplication = pkg.applicationInfo; 6332 6333 if (!mResolverReplaced) { 6334 mResolveActivity.applicationInfo = mAndroidApplication; 6335 mResolveActivity.name = ResolverActivity.class.getName(); 6336 mResolveActivity.packageName = mAndroidApplication.packageName; 6337 mResolveActivity.processName = "system:ui"; 6338 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6339 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6340 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6341 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6342 mResolveActivity.exported = true; 6343 mResolveActivity.enabled = true; 6344 mResolveInfo.activityInfo = mResolveActivity; 6345 mResolveInfo.priority = 0; 6346 mResolveInfo.preferredOrder = 0; 6347 mResolveInfo.match = 0; 6348 mResolveComponentName = new ComponentName( 6349 mAndroidApplication.packageName, mResolveActivity.name); 6350 } 6351 } 6352 } 6353 6354 if (DEBUG_PACKAGE_SCANNING) { 6355 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6356 Log.d(TAG, "Scanning package " + pkg.packageName); 6357 } 6358 6359 if (mPackages.containsKey(pkg.packageName) 6360 || mSharedLibraries.containsKey(pkg.packageName)) { 6361 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6362 "Application package " + pkg.packageName 6363 + " already installed. Skipping duplicate."); 6364 } 6365 6366 // If we're only installing presumed-existing packages, require that the 6367 // scanned APK is both already known and at the path previously established 6368 // for it. Previously unknown packages we pick up normally, but if we have an 6369 // a priori expectation about this package's install presence, enforce it. 6370 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6371 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6372 if (known != null) { 6373 if (DEBUG_PACKAGE_SCANNING) { 6374 Log.d(TAG, "Examining " + pkg.codePath 6375 + " and requiring known paths " + known.codePathString 6376 + " & " + known.resourcePathString); 6377 } 6378 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6379 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6380 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6381 "Application package " + pkg.packageName 6382 + " found at " + pkg.applicationInfo.getCodePath() 6383 + " but expected at " + known.codePathString + "; ignoring."); 6384 } 6385 } 6386 } 6387 6388 // Initialize package source and resource directories 6389 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6390 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6391 6392 SharedUserSetting suid = null; 6393 PackageSetting pkgSetting = null; 6394 6395 if (!isSystemApp(pkg)) { 6396 // Only system apps can use these features. 6397 pkg.mOriginalPackages = null; 6398 pkg.mRealPackage = null; 6399 pkg.mAdoptPermissions = null; 6400 } 6401 6402 // writer 6403 synchronized (mPackages) { 6404 if (pkg.mSharedUserId != null) { 6405 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6406 if (suid == null) { 6407 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6408 "Creating application package " + pkg.packageName 6409 + " for shared user failed"); 6410 } 6411 if (DEBUG_PACKAGE_SCANNING) { 6412 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6413 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6414 + "): packages=" + suid.packages); 6415 } 6416 } 6417 6418 // Check if we are renaming from an original package name. 6419 PackageSetting origPackage = null; 6420 String realName = null; 6421 if (pkg.mOriginalPackages != null) { 6422 // This package may need to be renamed to a previously 6423 // installed name. Let's check on that... 6424 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6425 if (pkg.mOriginalPackages.contains(renamed)) { 6426 // This package had originally been installed as the 6427 // original name, and we have already taken care of 6428 // transitioning to the new one. Just update the new 6429 // one to continue using the old name. 6430 realName = pkg.mRealPackage; 6431 if (!pkg.packageName.equals(renamed)) { 6432 // Callers into this function may have already taken 6433 // care of renaming the package; only do it here if 6434 // it is not already done. 6435 pkg.setPackageName(renamed); 6436 } 6437 6438 } else { 6439 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6440 if ((origPackage = mSettings.peekPackageLPr( 6441 pkg.mOriginalPackages.get(i))) != null) { 6442 // We do have the package already installed under its 6443 // original name... should we use it? 6444 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6445 // New package is not compatible with original. 6446 origPackage = null; 6447 continue; 6448 } else if (origPackage.sharedUser != null) { 6449 // Make sure uid is compatible between packages. 6450 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6451 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6452 + " to " + pkg.packageName + ": old uid " 6453 + origPackage.sharedUser.name 6454 + " differs from " + pkg.mSharedUserId); 6455 origPackage = null; 6456 continue; 6457 } 6458 } else { 6459 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6460 + pkg.packageName + " to old name " + origPackage.name); 6461 } 6462 break; 6463 } 6464 } 6465 } 6466 } 6467 6468 if (mTransferedPackages.contains(pkg.packageName)) { 6469 Slog.w(TAG, "Package " + pkg.packageName 6470 + " was transferred to another, but its .apk remains"); 6471 } 6472 6473 // Just create the setting, don't add it yet. For already existing packages 6474 // the PkgSetting exists already and doesn't have to be created. 6475 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6476 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6477 pkg.applicationInfo.primaryCpuAbi, 6478 pkg.applicationInfo.secondaryCpuAbi, 6479 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6480 user, false); 6481 if (pkgSetting == null) { 6482 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6483 "Creating application package " + pkg.packageName + " failed"); 6484 } 6485 6486 if (pkgSetting.origPackage != null) { 6487 // If we are first transitioning from an original package, 6488 // fix up the new package's name now. We need to do this after 6489 // looking up the package under its new name, so getPackageLP 6490 // can take care of fiddling things correctly. 6491 pkg.setPackageName(origPackage.name); 6492 6493 // File a report about this. 6494 String msg = "New package " + pkgSetting.realName 6495 + " renamed to replace old package " + pkgSetting.name; 6496 reportSettingsProblem(Log.WARN, msg); 6497 6498 // Make a note of it. 6499 mTransferedPackages.add(origPackage.name); 6500 6501 // No longer need to retain this. 6502 pkgSetting.origPackage = null; 6503 } 6504 6505 if (realName != null) { 6506 // Make a note of it. 6507 mTransferedPackages.add(pkg.packageName); 6508 } 6509 6510 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6511 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6512 } 6513 6514 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6515 // Check all shared libraries and map to their actual file path. 6516 // We only do this here for apps not on a system dir, because those 6517 // are the only ones that can fail an install due to this. We 6518 // will take care of the system apps by updating all of their 6519 // library paths after the scan is done. 6520 updateSharedLibrariesLPw(pkg, null); 6521 } 6522 6523 if (mFoundPolicyFile) { 6524 SELinuxMMAC.assignSeinfoValue(pkg); 6525 } 6526 6527 pkg.applicationInfo.uid = pkgSetting.appId; 6528 pkg.mExtras = pkgSetting; 6529 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6530 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6531 // We just determined the app is signed correctly, so bring 6532 // over the latest parsed certs. 6533 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6534 } else { 6535 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6536 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6537 "Package " + pkg.packageName + " upgrade keys do not match the " 6538 + "previously installed version"); 6539 } else { 6540 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6541 String msg = "System package " + pkg.packageName 6542 + " signature changed; retaining data."; 6543 reportSettingsProblem(Log.WARN, msg); 6544 } 6545 } 6546 } else { 6547 try { 6548 verifySignaturesLP(pkgSetting, pkg); 6549 // We just determined the app is signed correctly, so bring 6550 // over the latest parsed certs. 6551 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6552 } catch (PackageManagerException e) { 6553 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6554 throw e; 6555 } 6556 // The signature has changed, but this package is in the system 6557 // image... let's recover! 6558 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6559 // However... if this package is part of a shared user, but it 6560 // doesn't match the signature of the shared user, let's fail. 6561 // What this means is that you can't change the signatures 6562 // associated with an overall shared user, which doesn't seem all 6563 // that unreasonable. 6564 if (pkgSetting.sharedUser != null) { 6565 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6566 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6567 throw new PackageManagerException( 6568 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6569 "Signature mismatch for shared user : " 6570 + pkgSetting.sharedUser); 6571 } 6572 } 6573 // File a report about this. 6574 String msg = "System package " + pkg.packageName 6575 + " signature changed; retaining data."; 6576 reportSettingsProblem(Log.WARN, msg); 6577 } 6578 } 6579 // Verify that this new package doesn't have any content providers 6580 // that conflict with existing packages. Only do this if the 6581 // package isn't already installed, since we don't want to break 6582 // things that are installed. 6583 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6584 final int N = pkg.providers.size(); 6585 int i; 6586 for (i=0; i<N; i++) { 6587 PackageParser.Provider p = pkg.providers.get(i); 6588 if (p.info.authority != null) { 6589 String names[] = p.info.authority.split(";"); 6590 for (int j = 0; j < names.length; j++) { 6591 if (mProvidersByAuthority.containsKey(names[j])) { 6592 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6593 final String otherPackageName = 6594 ((other != null && other.getComponentName() != null) ? 6595 other.getComponentName().getPackageName() : "?"); 6596 throw new PackageManagerException( 6597 INSTALL_FAILED_CONFLICTING_PROVIDER, 6598 "Can't install because provider name " + names[j] 6599 + " (in package " + pkg.applicationInfo.packageName 6600 + ") is already used by " + otherPackageName); 6601 } 6602 } 6603 } 6604 } 6605 } 6606 6607 if (pkg.mAdoptPermissions != null) { 6608 // This package wants to adopt ownership of permissions from 6609 // another package. 6610 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6611 final String origName = pkg.mAdoptPermissions.get(i); 6612 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6613 if (orig != null) { 6614 if (verifyPackageUpdateLPr(orig, pkg)) { 6615 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6616 + pkg.packageName); 6617 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6618 } 6619 } 6620 } 6621 } 6622 } 6623 6624 final String pkgName = pkg.packageName; 6625 6626 final long scanFileTime = scanFile.lastModified(); 6627 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6628 pkg.applicationInfo.processName = fixProcessName( 6629 pkg.applicationInfo.packageName, 6630 pkg.applicationInfo.processName, 6631 pkg.applicationInfo.uid); 6632 6633 File dataPath; 6634 if (mPlatformPackage == pkg) { 6635 // The system package is special. 6636 dataPath = new File(Environment.getDataDirectory(), "system"); 6637 6638 pkg.applicationInfo.dataDir = dataPath.getPath(); 6639 6640 } else { 6641 // This is a normal package, need to make its data directory. 6642 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6643 UserHandle.USER_OWNER, pkg.packageName); 6644 6645 boolean uidError = false; 6646 if (dataPath.exists()) { 6647 int currentUid = 0; 6648 try { 6649 StructStat stat = Os.stat(dataPath.getPath()); 6650 currentUid = stat.st_uid; 6651 } catch (ErrnoException e) { 6652 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6653 } 6654 6655 // If we have mismatched owners for the data path, we have a problem. 6656 if (currentUid != pkg.applicationInfo.uid) { 6657 boolean recovered = false; 6658 if (currentUid == 0) { 6659 // The directory somehow became owned by root. Wow. 6660 // This is probably because the system was stopped while 6661 // installd was in the middle of messing with its libs 6662 // directory. Ask installd to fix that. 6663 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6664 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6665 if (ret >= 0) { 6666 recovered = true; 6667 String msg = "Package " + pkg.packageName 6668 + " unexpectedly changed to uid 0; recovered to " + 6669 + pkg.applicationInfo.uid; 6670 reportSettingsProblem(Log.WARN, msg); 6671 } 6672 } 6673 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6674 || (scanFlags&SCAN_BOOTING) != 0)) { 6675 // If this is a system app, we can at least delete its 6676 // current data so the application will still work. 6677 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6678 if (ret >= 0) { 6679 // TODO: Kill the processes first 6680 // Old data gone! 6681 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6682 ? "System package " : "Third party package "; 6683 String msg = prefix + pkg.packageName 6684 + " has changed from uid: " 6685 + currentUid + " to " 6686 + pkg.applicationInfo.uid + "; old data erased"; 6687 reportSettingsProblem(Log.WARN, msg); 6688 recovered = true; 6689 6690 // And now re-install the app. 6691 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6692 pkg.applicationInfo.seinfo); 6693 if (ret == -1) { 6694 // Ack should not happen! 6695 msg = prefix + pkg.packageName 6696 + " could not have data directory re-created after delete."; 6697 reportSettingsProblem(Log.WARN, msg); 6698 throw new PackageManagerException( 6699 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6700 } 6701 } 6702 if (!recovered) { 6703 mHasSystemUidErrors = true; 6704 } 6705 } else if (!recovered) { 6706 // If we allow this install to proceed, we will be broken. 6707 // Abort, abort! 6708 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6709 "scanPackageLI"); 6710 } 6711 if (!recovered) { 6712 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6713 + pkg.applicationInfo.uid + "/fs_" 6714 + currentUid; 6715 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6716 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6717 String msg = "Package " + pkg.packageName 6718 + " has mismatched uid: " 6719 + currentUid + " on disk, " 6720 + pkg.applicationInfo.uid + " in settings"; 6721 // writer 6722 synchronized (mPackages) { 6723 mSettings.mReadMessages.append(msg); 6724 mSettings.mReadMessages.append('\n'); 6725 uidError = true; 6726 if (!pkgSetting.uidError) { 6727 reportSettingsProblem(Log.ERROR, msg); 6728 } 6729 } 6730 } 6731 } 6732 pkg.applicationInfo.dataDir = dataPath.getPath(); 6733 if (mShouldRestoreconData) { 6734 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6735 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6736 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6737 } 6738 } else { 6739 if (DEBUG_PACKAGE_SCANNING) { 6740 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6741 Log.v(TAG, "Want this data dir: " + dataPath); 6742 } 6743 //invoke installer to do the actual installation 6744 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6745 pkg.applicationInfo.seinfo); 6746 if (ret < 0) { 6747 // Error from installer 6748 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6749 "Unable to create data dirs [errorCode=" + ret + "]"); 6750 } 6751 6752 if (dataPath.exists()) { 6753 pkg.applicationInfo.dataDir = dataPath.getPath(); 6754 } else { 6755 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6756 pkg.applicationInfo.dataDir = null; 6757 } 6758 } 6759 6760 pkgSetting.uidError = uidError; 6761 } 6762 6763 final String path = scanFile.getPath(); 6764 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6765 6766 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6767 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6768 6769 // Some system apps still use directory structure for native libraries 6770 // in which case we might end up not detecting abi solely based on apk 6771 // structure. Try to detect abi based on directory structure. 6772 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6773 pkg.applicationInfo.primaryCpuAbi == null) { 6774 setBundledAppAbisAndRoots(pkg, pkgSetting); 6775 setNativeLibraryPaths(pkg); 6776 } 6777 6778 } else { 6779 if ((scanFlags & SCAN_MOVE) != 0) { 6780 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6781 // but we already have this packages package info in the PackageSetting. We just 6782 // use that and derive the native library path based on the new codepath. 6783 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6784 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6785 } 6786 6787 // Set native library paths again. For moves, the path will be updated based on the 6788 // ABIs we've determined above. For non-moves, the path will be updated based on the 6789 // ABIs we determined during compilation, but the path will depend on the final 6790 // package path (after the rename away from the stage path). 6791 setNativeLibraryPaths(pkg); 6792 } 6793 6794 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6795 final int[] userIds = sUserManager.getUserIds(); 6796 synchronized (mInstallLock) { 6797 // Make sure all user data directories are ready to roll; we're okay 6798 // if they already exist 6799 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6800 for (int userId : userIds) { 6801 if (userId != 0) { 6802 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6803 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6804 pkg.applicationInfo.seinfo); 6805 } 6806 } 6807 } 6808 6809 // Create a native library symlink only if we have native libraries 6810 // and if the native libraries are 32 bit libraries. We do not provide 6811 // this symlink for 64 bit libraries. 6812 if (pkg.applicationInfo.primaryCpuAbi != null && 6813 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6814 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6815 for (int userId : userIds) { 6816 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6817 nativeLibPath, userId) < 0) { 6818 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6819 "Failed linking native library dir (user=" + userId + ")"); 6820 } 6821 } 6822 } 6823 } 6824 6825 // This is a special case for the "system" package, where the ABI is 6826 // dictated by the zygote configuration (and init.rc). We should keep track 6827 // of this ABI so that we can deal with "normal" applications that run under 6828 // the same UID correctly. 6829 if (mPlatformPackage == pkg) { 6830 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6831 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6832 } 6833 6834 // If there's a mismatch between the abi-override in the package setting 6835 // and the abiOverride specified for the install. Warn about this because we 6836 // would've already compiled the app without taking the package setting into 6837 // account. 6838 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6839 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6840 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6841 " for package: " + pkg.packageName); 6842 } 6843 } 6844 6845 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6846 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6847 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6848 6849 // Copy the derived override back to the parsed package, so that we can 6850 // update the package settings accordingly. 6851 pkg.cpuAbiOverride = cpuAbiOverride; 6852 6853 if (DEBUG_ABI_SELECTION) { 6854 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6855 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6856 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6857 } 6858 6859 // Push the derived path down into PackageSettings so we know what to 6860 // clean up at uninstall time. 6861 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6862 6863 if (DEBUG_ABI_SELECTION) { 6864 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6865 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6866 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6867 } 6868 6869 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6870 // We don't do this here during boot because we can do it all 6871 // at once after scanning all existing packages. 6872 // 6873 // We also do this *before* we perform dexopt on this package, so that 6874 // we can avoid redundant dexopts, and also to make sure we've got the 6875 // code and package path correct. 6876 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6877 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6878 } 6879 6880 if ((scanFlags & SCAN_NO_DEX) == 0) { 6881 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6882 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6883 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6884 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6885 } 6886 } 6887 if (mFactoryTest && pkg.requestedPermissions.contains( 6888 android.Manifest.permission.FACTORY_TEST)) { 6889 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6890 } 6891 6892 ArrayList<PackageParser.Package> clientLibPkgs = null; 6893 6894 // writer 6895 synchronized (mPackages) { 6896 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6897 // Only system apps can add new shared libraries. 6898 if (pkg.libraryNames != null) { 6899 for (int i=0; i<pkg.libraryNames.size(); i++) { 6900 String name = pkg.libraryNames.get(i); 6901 boolean allowed = false; 6902 if (pkg.isUpdatedSystemApp()) { 6903 // New library entries can only be added through the 6904 // system image. This is important to get rid of a lot 6905 // of nasty edge cases: for example if we allowed a non- 6906 // system update of the app to add a library, then uninstalling 6907 // the update would make the library go away, and assumptions 6908 // we made such as through app install filtering would now 6909 // have allowed apps on the device which aren't compatible 6910 // with it. Better to just have the restriction here, be 6911 // conservative, and create many fewer cases that can negatively 6912 // impact the user experience. 6913 final PackageSetting sysPs = mSettings 6914 .getDisabledSystemPkgLPr(pkg.packageName); 6915 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6916 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6917 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6918 allowed = true; 6919 allowed = true; 6920 break; 6921 } 6922 } 6923 } 6924 } else { 6925 allowed = true; 6926 } 6927 if (allowed) { 6928 if (!mSharedLibraries.containsKey(name)) { 6929 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6930 } else if (!name.equals(pkg.packageName)) { 6931 Slog.w(TAG, "Package " + pkg.packageName + " library " 6932 + name + " already exists; skipping"); 6933 } 6934 } else { 6935 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6936 + name + " that is not declared on system image; skipping"); 6937 } 6938 } 6939 if ((scanFlags&SCAN_BOOTING) == 0) { 6940 // If we are not booting, we need to update any applications 6941 // that are clients of our shared library. If we are booting, 6942 // this will all be done once the scan is complete. 6943 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6944 } 6945 } 6946 } 6947 } 6948 6949 // We also need to dexopt any apps that are dependent on this library. Note that 6950 // if these fail, we should abort the install since installing the library will 6951 // result in some apps being broken. 6952 if (clientLibPkgs != null) { 6953 if ((scanFlags & SCAN_NO_DEX) == 0) { 6954 for (int i = 0; i < clientLibPkgs.size(); i++) { 6955 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6956 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6957 null /* instruction sets */, forceDex, 6958 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6959 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6960 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6961 "scanPackageLI failed to dexopt clientLibPkgs"); 6962 } 6963 } 6964 } 6965 } 6966 6967 // Also need to kill any apps that are dependent on the library. 6968 if (clientLibPkgs != null) { 6969 for (int i=0; i<clientLibPkgs.size(); i++) { 6970 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6971 killApplication(clientPkg.applicationInfo.packageName, 6972 clientPkg.applicationInfo.uid, "update lib"); 6973 } 6974 } 6975 6976 // Make sure we're not adding any bogus keyset info 6977 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6978 ksms.assertScannedPackageValid(pkg); 6979 6980 // writer 6981 synchronized (mPackages) { 6982 // We don't expect installation to fail beyond this point 6983 6984 // Add the new setting to mSettings 6985 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6986 // Add the new setting to mPackages 6987 mPackages.put(pkg.applicationInfo.packageName, pkg); 6988 // Make sure we don't accidentally delete its data. 6989 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6990 while (iter.hasNext()) { 6991 PackageCleanItem item = iter.next(); 6992 if (pkgName.equals(item.packageName)) { 6993 iter.remove(); 6994 } 6995 } 6996 6997 // Take care of first install / last update times. 6998 if (currentTime != 0) { 6999 if (pkgSetting.firstInstallTime == 0) { 7000 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7001 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7002 pkgSetting.lastUpdateTime = currentTime; 7003 } 7004 } else if (pkgSetting.firstInstallTime == 0) { 7005 // We need *something*. Take time time stamp of the file. 7006 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7007 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7008 if (scanFileTime != pkgSetting.timeStamp) { 7009 // A package on the system image has changed; consider this 7010 // to be an update. 7011 pkgSetting.lastUpdateTime = scanFileTime; 7012 } 7013 } 7014 7015 // Add the package's KeySets to the global KeySetManagerService 7016 ksms.addScannedPackageLPw(pkg); 7017 7018 int N = pkg.providers.size(); 7019 StringBuilder r = null; 7020 int i; 7021 for (i=0; i<N; i++) { 7022 PackageParser.Provider p = pkg.providers.get(i); 7023 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7024 p.info.processName, pkg.applicationInfo.uid); 7025 mProviders.addProvider(p); 7026 p.syncable = p.info.isSyncable; 7027 if (p.info.authority != null) { 7028 String names[] = p.info.authority.split(";"); 7029 p.info.authority = null; 7030 for (int j = 0; j < names.length; j++) { 7031 if (j == 1 && p.syncable) { 7032 // We only want the first authority for a provider to possibly be 7033 // syncable, so if we already added this provider using a different 7034 // authority clear the syncable flag. We copy the provider before 7035 // changing it because the mProviders object contains a reference 7036 // to a provider that we don't want to change. 7037 // Only do this for the second authority since the resulting provider 7038 // object can be the same for all future authorities for this provider. 7039 p = new PackageParser.Provider(p); 7040 p.syncable = false; 7041 } 7042 if (!mProvidersByAuthority.containsKey(names[j])) { 7043 mProvidersByAuthority.put(names[j], p); 7044 if (p.info.authority == null) { 7045 p.info.authority = names[j]; 7046 } else { 7047 p.info.authority = p.info.authority + ";" + names[j]; 7048 } 7049 if (DEBUG_PACKAGE_SCANNING) { 7050 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7051 Log.d(TAG, "Registered content provider: " + names[j] 7052 + ", className = " + p.info.name + ", isSyncable = " 7053 + p.info.isSyncable); 7054 } 7055 } else { 7056 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7057 Slog.w(TAG, "Skipping provider name " + names[j] + 7058 " (in package " + pkg.applicationInfo.packageName + 7059 "): name already used by " 7060 + ((other != null && other.getComponentName() != null) 7061 ? other.getComponentName().getPackageName() : "?")); 7062 } 7063 } 7064 } 7065 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7066 if (r == null) { 7067 r = new StringBuilder(256); 7068 } else { 7069 r.append(' '); 7070 } 7071 r.append(p.info.name); 7072 } 7073 } 7074 if (r != null) { 7075 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7076 } 7077 7078 N = pkg.services.size(); 7079 r = null; 7080 for (i=0; i<N; i++) { 7081 PackageParser.Service s = pkg.services.get(i); 7082 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7083 s.info.processName, pkg.applicationInfo.uid); 7084 mServices.addService(s); 7085 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7086 if (r == null) { 7087 r = new StringBuilder(256); 7088 } else { 7089 r.append(' '); 7090 } 7091 r.append(s.info.name); 7092 } 7093 } 7094 if (r != null) { 7095 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7096 } 7097 7098 N = pkg.receivers.size(); 7099 r = null; 7100 for (i=0; i<N; i++) { 7101 PackageParser.Activity a = pkg.receivers.get(i); 7102 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7103 a.info.processName, pkg.applicationInfo.uid); 7104 mReceivers.addActivity(a, "receiver"); 7105 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7106 if (r == null) { 7107 r = new StringBuilder(256); 7108 } else { 7109 r.append(' '); 7110 } 7111 r.append(a.info.name); 7112 } 7113 } 7114 if (r != null) { 7115 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7116 } 7117 7118 N = pkg.activities.size(); 7119 r = null; 7120 for (i=0; i<N; i++) { 7121 PackageParser.Activity a = pkg.activities.get(i); 7122 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7123 a.info.processName, pkg.applicationInfo.uid); 7124 mActivities.addActivity(a, "activity"); 7125 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7126 if (r == null) { 7127 r = new StringBuilder(256); 7128 } else { 7129 r.append(' '); 7130 } 7131 r.append(a.info.name); 7132 } 7133 } 7134 if (r != null) { 7135 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7136 } 7137 7138 N = pkg.permissionGroups.size(); 7139 r = null; 7140 for (i=0; i<N; i++) { 7141 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7142 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7143 if (cur == null) { 7144 mPermissionGroups.put(pg.info.name, pg); 7145 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7146 if (r == null) { 7147 r = new StringBuilder(256); 7148 } else { 7149 r.append(' '); 7150 } 7151 r.append(pg.info.name); 7152 } 7153 } else { 7154 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7155 + pg.info.packageName + " ignored: original from " 7156 + cur.info.packageName); 7157 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7158 if (r == null) { 7159 r = new StringBuilder(256); 7160 } else { 7161 r.append(' '); 7162 } 7163 r.append("DUP:"); 7164 r.append(pg.info.name); 7165 } 7166 } 7167 } 7168 if (r != null) { 7169 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7170 } 7171 7172 N = pkg.permissions.size(); 7173 r = null; 7174 for (i=0; i<N; i++) { 7175 PackageParser.Permission p = pkg.permissions.get(i); 7176 7177 // Now that permission groups have a special meaning, we ignore permission 7178 // groups for legacy apps to prevent unexpected behavior. In particular, 7179 // permissions for one app being granted to someone just becuase they happen 7180 // to be in a group defined by another app (before this had no implications). 7181 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7182 p.group = mPermissionGroups.get(p.info.group); 7183 // Warn for a permission in an unknown group. 7184 if (p.info.group != null && p.group == null) { 7185 Slog.w(TAG, "Permission " + p.info.name + " from package " 7186 + p.info.packageName + " in an unknown group " + p.info.group); 7187 } 7188 } 7189 7190 ArrayMap<String, BasePermission> permissionMap = 7191 p.tree ? mSettings.mPermissionTrees 7192 : mSettings.mPermissions; 7193 BasePermission bp = permissionMap.get(p.info.name); 7194 7195 // Allow system apps to redefine non-system permissions 7196 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7197 final boolean currentOwnerIsSystem = (bp.perm != null 7198 && isSystemApp(bp.perm.owner)); 7199 if (isSystemApp(p.owner)) { 7200 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7201 // It's a built-in permission and no owner, take ownership now 7202 bp.packageSetting = pkgSetting; 7203 bp.perm = p; 7204 bp.uid = pkg.applicationInfo.uid; 7205 bp.sourcePackage = p.info.packageName; 7206 } else if (!currentOwnerIsSystem) { 7207 String msg = "New decl " + p.owner + " of permission " 7208 + p.info.name + " is system; overriding " + bp.sourcePackage; 7209 reportSettingsProblem(Log.WARN, msg); 7210 bp = null; 7211 } 7212 } 7213 } 7214 7215 if (bp == null) { 7216 bp = new BasePermission(p.info.name, p.info.packageName, 7217 BasePermission.TYPE_NORMAL); 7218 permissionMap.put(p.info.name, bp); 7219 } 7220 7221 if (bp.perm == null) { 7222 if (bp.sourcePackage == null 7223 || bp.sourcePackage.equals(p.info.packageName)) { 7224 BasePermission tree = findPermissionTreeLP(p.info.name); 7225 if (tree == null 7226 || tree.sourcePackage.equals(p.info.packageName)) { 7227 bp.packageSetting = pkgSetting; 7228 bp.perm = p; 7229 bp.uid = pkg.applicationInfo.uid; 7230 bp.sourcePackage = p.info.packageName; 7231 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7232 if (r == null) { 7233 r = new StringBuilder(256); 7234 } else { 7235 r.append(' '); 7236 } 7237 r.append(p.info.name); 7238 } 7239 } else { 7240 Slog.w(TAG, "Permission " + p.info.name + " from package " 7241 + p.info.packageName + " ignored: base tree " 7242 + tree.name + " is from package " 7243 + tree.sourcePackage); 7244 } 7245 } else { 7246 Slog.w(TAG, "Permission " + p.info.name + " from package " 7247 + p.info.packageName + " ignored: original from " 7248 + bp.sourcePackage); 7249 } 7250 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7251 if (r == null) { 7252 r = new StringBuilder(256); 7253 } else { 7254 r.append(' '); 7255 } 7256 r.append("DUP:"); 7257 r.append(p.info.name); 7258 } 7259 if (bp.perm == p) { 7260 bp.protectionLevel = p.info.protectionLevel; 7261 } 7262 } 7263 7264 if (r != null) { 7265 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7266 } 7267 7268 N = pkg.instrumentation.size(); 7269 r = null; 7270 for (i=0; i<N; i++) { 7271 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7272 a.info.packageName = pkg.applicationInfo.packageName; 7273 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7274 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7275 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7276 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7277 a.info.dataDir = pkg.applicationInfo.dataDir; 7278 7279 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7280 // need other information about the application, like the ABI and what not ? 7281 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7282 mInstrumentation.put(a.getComponentName(), a); 7283 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7284 if (r == null) { 7285 r = new StringBuilder(256); 7286 } else { 7287 r.append(' '); 7288 } 7289 r.append(a.info.name); 7290 } 7291 } 7292 if (r != null) { 7293 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7294 } 7295 7296 if (pkg.protectedBroadcasts != null) { 7297 N = pkg.protectedBroadcasts.size(); 7298 for (i=0; i<N; i++) { 7299 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7300 } 7301 } 7302 7303 pkgSetting.setTimeStamp(scanFileTime); 7304 7305 // Create idmap files for pairs of (packages, overlay packages). 7306 // Note: "android", ie framework-res.apk, is handled by native layers. 7307 if (pkg.mOverlayTarget != null) { 7308 // This is an overlay package. 7309 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7310 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7311 mOverlays.put(pkg.mOverlayTarget, 7312 new ArrayMap<String, PackageParser.Package>()); 7313 } 7314 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7315 map.put(pkg.packageName, pkg); 7316 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7317 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7318 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7319 "scanPackageLI failed to createIdmap"); 7320 } 7321 } 7322 } else if (mOverlays.containsKey(pkg.packageName) && 7323 !pkg.packageName.equals("android")) { 7324 // This is a regular package, with one or more known overlay packages. 7325 createIdmapsForPackageLI(pkg); 7326 } 7327 } 7328 7329 return pkg; 7330 } 7331 7332 /** 7333 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7334 * is derived purely on the basis of the contents of {@code scanFile} and 7335 * {@code cpuAbiOverride}. 7336 * 7337 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7338 */ 7339 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7340 String cpuAbiOverride, boolean extractLibs) 7341 throws PackageManagerException { 7342 // TODO: We can probably be smarter about this stuff. For installed apps, 7343 // we can calculate this information at install time once and for all. For 7344 // system apps, we can probably assume that this information doesn't change 7345 // after the first boot scan. As things stand, we do lots of unnecessary work. 7346 7347 // Give ourselves some initial paths; we'll come back for another 7348 // pass once we've determined ABI below. 7349 setNativeLibraryPaths(pkg); 7350 7351 // We would never need to extract libs for forward-locked and external packages, 7352 // since the container service will do it for us. We shouldn't attempt to 7353 // extract libs from system app when it was not updated. 7354 if (pkg.isForwardLocked() || isExternal(pkg) || 7355 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7356 extractLibs = false; 7357 } 7358 7359 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7360 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7361 7362 NativeLibraryHelper.Handle handle = null; 7363 try { 7364 handle = NativeLibraryHelper.Handle.create(pkg); 7365 // TODO(multiArch): This can be null for apps that didn't go through the 7366 // usual installation process. We can calculate it again, like we 7367 // do during install time. 7368 // 7369 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7370 // unnecessary. 7371 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7372 7373 // Null out the abis so that they can be recalculated. 7374 pkg.applicationInfo.primaryCpuAbi = null; 7375 pkg.applicationInfo.secondaryCpuAbi = null; 7376 if (isMultiArch(pkg.applicationInfo)) { 7377 // Warn if we've set an abiOverride for multi-lib packages.. 7378 // By definition, we need to copy both 32 and 64 bit libraries for 7379 // such packages. 7380 if (pkg.cpuAbiOverride != null 7381 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7382 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7383 } 7384 7385 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7386 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7387 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7388 if (extractLibs) { 7389 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7390 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7391 useIsaSpecificSubdirs); 7392 } else { 7393 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7394 } 7395 } 7396 7397 maybeThrowExceptionForMultiArchCopy( 7398 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7399 7400 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7401 if (extractLibs) { 7402 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7403 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7404 useIsaSpecificSubdirs); 7405 } else { 7406 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7407 } 7408 } 7409 7410 maybeThrowExceptionForMultiArchCopy( 7411 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7412 7413 if (abi64 >= 0) { 7414 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7415 } 7416 7417 if (abi32 >= 0) { 7418 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7419 if (abi64 >= 0) { 7420 pkg.applicationInfo.secondaryCpuAbi = abi; 7421 } else { 7422 pkg.applicationInfo.primaryCpuAbi = abi; 7423 } 7424 } 7425 } else { 7426 String[] abiList = (cpuAbiOverride != null) ? 7427 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7428 7429 // Enable gross and lame hacks for apps that are built with old 7430 // SDK tools. We must scan their APKs for renderscript bitcode and 7431 // not launch them if it's present. Don't bother checking on devices 7432 // that don't have 64 bit support. 7433 boolean needsRenderScriptOverride = false; 7434 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7435 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7436 abiList = Build.SUPPORTED_32_BIT_ABIS; 7437 needsRenderScriptOverride = true; 7438 } 7439 7440 final int copyRet; 7441 if (extractLibs) { 7442 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7443 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7444 } else { 7445 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7446 } 7447 7448 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7449 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7450 "Error unpackaging native libs for app, errorCode=" + copyRet); 7451 } 7452 7453 if (copyRet >= 0) { 7454 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7455 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7456 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7457 } else if (needsRenderScriptOverride) { 7458 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7459 } 7460 } 7461 } catch (IOException ioe) { 7462 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7463 } finally { 7464 IoUtils.closeQuietly(handle); 7465 } 7466 7467 // Now that we've calculated the ABIs and determined if it's an internal app, 7468 // we will go ahead and populate the nativeLibraryPath. 7469 setNativeLibraryPaths(pkg); 7470 } 7471 7472 /** 7473 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7474 * i.e, so that all packages can be run inside a single process if required. 7475 * 7476 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7477 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7478 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7479 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7480 * updating a package that belongs to a shared user. 7481 * 7482 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7483 * adds unnecessary complexity. 7484 */ 7485 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7486 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7487 String requiredInstructionSet = null; 7488 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7489 requiredInstructionSet = VMRuntime.getInstructionSet( 7490 scannedPackage.applicationInfo.primaryCpuAbi); 7491 } 7492 7493 PackageSetting requirer = null; 7494 for (PackageSetting ps : packagesForUser) { 7495 // If packagesForUser contains scannedPackage, we skip it. This will happen 7496 // when scannedPackage is an update of an existing package. Without this check, 7497 // we will never be able to change the ABI of any package belonging to a shared 7498 // user, even if it's compatible with other packages. 7499 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7500 if (ps.primaryCpuAbiString == null) { 7501 continue; 7502 } 7503 7504 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7505 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7506 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7507 // this but there's not much we can do. 7508 String errorMessage = "Instruction set mismatch, " 7509 + ((requirer == null) ? "[caller]" : requirer) 7510 + " requires " + requiredInstructionSet + " whereas " + ps 7511 + " requires " + instructionSet; 7512 Slog.w(TAG, errorMessage); 7513 } 7514 7515 if (requiredInstructionSet == null) { 7516 requiredInstructionSet = instructionSet; 7517 requirer = ps; 7518 } 7519 } 7520 } 7521 7522 if (requiredInstructionSet != null) { 7523 String adjustedAbi; 7524 if (requirer != null) { 7525 // requirer != null implies that either scannedPackage was null or that scannedPackage 7526 // did not require an ABI, in which case we have to adjust scannedPackage to match 7527 // the ABI of the set (which is the same as requirer's ABI) 7528 adjustedAbi = requirer.primaryCpuAbiString; 7529 if (scannedPackage != null) { 7530 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7531 } 7532 } else { 7533 // requirer == null implies that we're updating all ABIs in the set to 7534 // match scannedPackage. 7535 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7536 } 7537 7538 for (PackageSetting ps : packagesForUser) { 7539 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7540 if (ps.primaryCpuAbiString != null) { 7541 continue; 7542 } 7543 7544 ps.primaryCpuAbiString = adjustedAbi; 7545 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7546 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7547 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7548 7549 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7550 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7551 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7552 ps.primaryCpuAbiString = null; 7553 ps.pkg.applicationInfo.primaryCpuAbi = null; 7554 return; 7555 } else { 7556 mInstaller.rmdex(ps.codePathString, 7557 getDexCodeInstructionSet(getPreferredInstructionSet())); 7558 } 7559 } 7560 } 7561 } 7562 } 7563 } 7564 7565 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7566 synchronized (mPackages) { 7567 mResolverReplaced = true; 7568 // Set up information for custom user intent resolution activity. 7569 mResolveActivity.applicationInfo = pkg.applicationInfo; 7570 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7571 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7572 mResolveActivity.processName = pkg.applicationInfo.packageName; 7573 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7574 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7575 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7576 mResolveActivity.theme = 0; 7577 mResolveActivity.exported = true; 7578 mResolveActivity.enabled = true; 7579 mResolveInfo.activityInfo = mResolveActivity; 7580 mResolveInfo.priority = 0; 7581 mResolveInfo.preferredOrder = 0; 7582 mResolveInfo.match = 0; 7583 mResolveComponentName = mCustomResolverComponentName; 7584 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7585 mResolveComponentName); 7586 } 7587 } 7588 7589 private static String calculateBundledApkRoot(final String codePathString) { 7590 final File codePath = new File(codePathString); 7591 final File codeRoot; 7592 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7593 codeRoot = Environment.getRootDirectory(); 7594 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7595 codeRoot = Environment.getOemDirectory(); 7596 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7597 codeRoot = Environment.getVendorDirectory(); 7598 } else { 7599 // Unrecognized code path; take its top real segment as the apk root: 7600 // e.g. /something/app/blah.apk => /something 7601 try { 7602 File f = codePath.getCanonicalFile(); 7603 File parent = f.getParentFile(); // non-null because codePath is a file 7604 File tmp; 7605 while ((tmp = parent.getParentFile()) != null) { 7606 f = parent; 7607 parent = tmp; 7608 } 7609 codeRoot = f; 7610 Slog.w(TAG, "Unrecognized code path " 7611 + codePath + " - using " + codeRoot); 7612 } catch (IOException e) { 7613 // Can't canonicalize the code path -- shenanigans? 7614 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7615 return Environment.getRootDirectory().getPath(); 7616 } 7617 } 7618 return codeRoot.getPath(); 7619 } 7620 7621 /** 7622 * Derive and set the location of native libraries for the given package, 7623 * which varies depending on where and how the package was installed. 7624 */ 7625 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7626 final ApplicationInfo info = pkg.applicationInfo; 7627 final String codePath = pkg.codePath; 7628 final File codeFile = new File(codePath); 7629 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7630 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7631 7632 info.nativeLibraryRootDir = null; 7633 info.nativeLibraryRootRequiresIsa = false; 7634 info.nativeLibraryDir = null; 7635 info.secondaryNativeLibraryDir = null; 7636 7637 if (isApkFile(codeFile)) { 7638 // Monolithic install 7639 if (bundledApp) { 7640 // If "/system/lib64/apkname" exists, assume that is the per-package 7641 // native library directory to use; otherwise use "/system/lib/apkname". 7642 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7643 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7644 getPrimaryInstructionSet(info)); 7645 7646 // This is a bundled system app so choose the path based on the ABI. 7647 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7648 // is just the default path. 7649 final String apkName = deriveCodePathName(codePath); 7650 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7651 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7652 apkName).getAbsolutePath(); 7653 7654 if (info.secondaryCpuAbi != null) { 7655 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7656 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7657 secondaryLibDir, apkName).getAbsolutePath(); 7658 } 7659 } else if (asecApp) { 7660 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7661 .getAbsolutePath(); 7662 } else { 7663 final String apkName = deriveCodePathName(codePath); 7664 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7665 .getAbsolutePath(); 7666 } 7667 7668 info.nativeLibraryRootRequiresIsa = false; 7669 info.nativeLibraryDir = info.nativeLibraryRootDir; 7670 } else { 7671 // Cluster install 7672 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7673 info.nativeLibraryRootRequiresIsa = true; 7674 7675 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7676 getPrimaryInstructionSet(info)).getAbsolutePath(); 7677 7678 if (info.secondaryCpuAbi != null) { 7679 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7680 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7681 } 7682 } 7683 } 7684 7685 /** 7686 * Calculate the abis and roots for a bundled app. These can uniquely 7687 * be determined from the contents of the system partition, i.e whether 7688 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7689 * of this information, and instead assume that the system was built 7690 * sensibly. 7691 */ 7692 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7693 PackageSetting pkgSetting) { 7694 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7695 7696 // If "/system/lib64/apkname" exists, assume that is the per-package 7697 // native library directory to use; otherwise use "/system/lib/apkname". 7698 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7699 setBundledAppAbi(pkg, apkRoot, apkName); 7700 // pkgSetting might be null during rescan following uninstall of updates 7701 // to a bundled app, so accommodate that possibility. The settings in 7702 // that case will be established later from the parsed package. 7703 // 7704 // If the settings aren't null, sync them up with what we've just derived. 7705 // note that apkRoot isn't stored in the package settings. 7706 if (pkgSetting != null) { 7707 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7708 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7709 } 7710 } 7711 7712 /** 7713 * Deduces the ABI of a bundled app and sets the relevant fields on the 7714 * parsed pkg object. 7715 * 7716 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7717 * under which system libraries are installed. 7718 * @param apkName the name of the installed package. 7719 */ 7720 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7721 final File codeFile = new File(pkg.codePath); 7722 7723 final boolean has64BitLibs; 7724 final boolean has32BitLibs; 7725 if (isApkFile(codeFile)) { 7726 // Monolithic install 7727 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7728 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7729 } else { 7730 // Cluster install 7731 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7732 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7733 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7734 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7735 has64BitLibs = (new File(rootDir, isa)).exists(); 7736 } else { 7737 has64BitLibs = false; 7738 } 7739 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7740 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7741 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7742 has32BitLibs = (new File(rootDir, isa)).exists(); 7743 } else { 7744 has32BitLibs = false; 7745 } 7746 } 7747 7748 if (has64BitLibs && !has32BitLibs) { 7749 // The package has 64 bit libs, but not 32 bit libs. Its primary 7750 // ABI should be 64 bit. We can safely assume here that the bundled 7751 // native libraries correspond to the most preferred ABI in the list. 7752 7753 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7754 pkg.applicationInfo.secondaryCpuAbi = null; 7755 } else if (has32BitLibs && !has64BitLibs) { 7756 // The package has 32 bit libs but not 64 bit libs. Its primary 7757 // ABI should be 32 bit. 7758 7759 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7760 pkg.applicationInfo.secondaryCpuAbi = null; 7761 } else if (has32BitLibs && has64BitLibs) { 7762 // The application has both 64 and 32 bit bundled libraries. We check 7763 // here that the app declares multiArch support, and warn if it doesn't. 7764 // 7765 // We will be lenient here and record both ABIs. The primary will be the 7766 // ABI that's higher on the list, i.e, a device that's configured to prefer 7767 // 64 bit apps will see a 64 bit primary ABI, 7768 7769 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7770 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7771 } 7772 7773 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7774 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7775 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7776 } else { 7777 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7778 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7779 } 7780 } else { 7781 pkg.applicationInfo.primaryCpuAbi = null; 7782 pkg.applicationInfo.secondaryCpuAbi = null; 7783 } 7784 } 7785 7786 private void killApplication(String pkgName, int appId, String reason) { 7787 // Request the ActivityManager to kill the process(only for existing packages) 7788 // so that we do not end up in a confused state while the user is still using the older 7789 // version of the application while the new one gets installed. 7790 IActivityManager am = ActivityManagerNative.getDefault(); 7791 if (am != null) { 7792 try { 7793 am.killApplicationWithAppId(pkgName, appId, reason); 7794 } catch (RemoteException e) { 7795 } 7796 } 7797 } 7798 7799 void removePackageLI(PackageSetting ps, boolean chatty) { 7800 if (DEBUG_INSTALL) { 7801 if (chatty) 7802 Log.d(TAG, "Removing package " + ps.name); 7803 } 7804 7805 // writer 7806 synchronized (mPackages) { 7807 mPackages.remove(ps.name); 7808 final PackageParser.Package pkg = ps.pkg; 7809 if (pkg != null) { 7810 cleanPackageDataStructuresLILPw(pkg, chatty); 7811 } 7812 } 7813 } 7814 7815 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7816 if (DEBUG_INSTALL) { 7817 if (chatty) 7818 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7819 } 7820 7821 // writer 7822 synchronized (mPackages) { 7823 mPackages.remove(pkg.applicationInfo.packageName); 7824 cleanPackageDataStructuresLILPw(pkg, chatty); 7825 } 7826 } 7827 7828 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7829 int N = pkg.providers.size(); 7830 StringBuilder r = null; 7831 int i; 7832 for (i=0; i<N; i++) { 7833 PackageParser.Provider p = pkg.providers.get(i); 7834 mProviders.removeProvider(p); 7835 if (p.info.authority == null) { 7836 7837 /* There was another ContentProvider with this authority when 7838 * this app was installed so this authority is null, 7839 * Ignore it as we don't have to unregister the provider. 7840 */ 7841 continue; 7842 } 7843 String names[] = p.info.authority.split(";"); 7844 for (int j = 0; j < names.length; j++) { 7845 if (mProvidersByAuthority.get(names[j]) == p) { 7846 mProvidersByAuthority.remove(names[j]); 7847 if (DEBUG_REMOVE) { 7848 if (chatty) 7849 Log.d(TAG, "Unregistered content provider: " + names[j] 7850 + ", className = " + p.info.name + ", isSyncable = " 7851 + p.info.isSyncable); 7852 } 7853 } 7854 } 7855 if (DEBUG_REMOVE && chatty) { 7856 if (r == null) { 7857 r = new StringBuilder(256); 7858 } else { 7859 r.append(' '); 7860 } 7861 r.append(p.info.name); 7862 } 7863 } 7864 if (r != null) { 7865 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7866 } 7867 7868 N = pkg.services.size(); 7869 r = null; 7870 for (i=0; i<N; i++) { 7871 PackageParser.Service s = pkg.services.get(i); 7872 mServices.removeService(s); 7873 if (chatty) { 7874 if (r == null) { 7875 r = new StringBuilder(256); 7876 } else { 7877 r.append(' '); 7878 } 7879 r.append(s.info.name); 7880 } 7881 } 7882 if (r != null) { 7883 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7884 } 7885 7886 N = pkg.receivers.size(); 7887 r = null; 7888 for (i=0; i<N; i++) { 7889 PackageParser.Activity a = pkg.receivers.get(i); 7890 mReceivers.removeActivity(a, "receiver"); 7891 if (DEBUG_REMOVE && chatty) { 7892 if (r == null) { 7893 r = new StringBuilder(256); 7894 } else { 7895 r.append(' '); 7896 } 7897 r.append(a.info.name); 7898 } 7899 } 7900 if (r != null) { 7901 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7902 } 7903 7904 N = pkg.activities.size(); 7905 r = null; 7906 for (i=0; i<N; i++) { 7907 PackageParser.Activity a = pkg.activities.get(i); 7908 mActivities.removeActivity(a, "activity"); 7909 if (DEBUG_REMOVE && chatty) { 7910 if (r == null) { 7911 r = new StringBuilder(256); 7912 } else { 7913 r.append(' '); 7914 } 7915 r.append(a.info.name); 7916 } 7917 } 7918 if (r != null) { 7919 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7920 } 7921 7922 N = pkg.permissions.size(); 7923 r = null; 7924 for (i=0; i<N; i++) { 7925 PackageParser.Permission p = pkg.permissions.get(i); 7926 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7927 if (bp == null) { 7928 bp = mSettings.mPermissionTrees.get(p.info.name); 7929 } 7930 if (bp != null && bp.perm == p) { 7931 bp.perm = null; 7932 if (DEBUG_REMOVE && chatty) { 7933 if (r == null) { 7934 r = new StringBuilder(256); 7935 } else { 7936 r.append(' '); 7937 } 7938 r.append(p.info.name); 7939 } 7940 } 7941 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7942 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7943 if (appOpPerms != null) { 7944 appOpPerms.remove(pkg.packageName); 7945 } 7946 } 7947 } 7948 if (r != null) { 7949 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7950 } 7951 7952 N = pkg.requestedPermissions.size(); 7953 r = null; 7954 for (i=0; i<N; i++) { 7955 String perm = pkg.requestedPermissions.get(i); 7956 BasePermission bp = mSettings.mPermissions.get(perm); 7957 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7958 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7959 if (appOpPerms != null) { 7960 appOpPerms.remove(pkg.packageName); 7961 if (appOpPerms.isEmpty()) { 7962 mAppOpPermissionPackages.remove(perm); 7963 } 7964 } 7965 } 7966 } 7967 if (r != null) { 7968 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7969 } 7970 7971 N = pkg.instrumentation.size(); 7972 r = null; 7973 for (i=0; i<N; i++) { 7974 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7975 mInstrumentation.remove(a.getComponentName()); 7976 if (DEBUG_REMOVE && chatty) { 7977 if (r == null) { 7978 r = new StringBuilder(256); 7979 } else { 7980 r.append(' '); 7981 } 7982 r.append(a.info.name); 7983 } 7984 } 7985 if (r != null) { 7986 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7987 } 7988 7989 r = null; 7990 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7991 // Only system apps can hold shared libraries. 7992 if (pkg.libraryNames != null) { 7993 for (i=0; i<pkg.libraryNames.size(); i++) { 7994 String name = pkg.libraryNames.get(i); 7995 SharedLibraryEntry cur = mSharedLibraries.get(name); 7996 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7997 mSharedLibraries.remove(name); 7998 if (DEBUG_REMOVE && chatty) { 7999 if (r == null) { 8000 r = new StringBuilder(256); 8001 } else { 8002 r.append(' '); 8003 } 8004 r.append(name); 8005 } 8006 } 8007 } 8008 } 8009 } 8010 if (r != null) { 8011 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8012 } 8013 } 8014 8015 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8016 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8017 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8018 return true; 8019 } 8020 } 8021 return false; 8022 } 8023 8024 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8025 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8026 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8027 8028 private void updatePermissionsLPw(String changingPkg, 8029 PackageParser.Package pkgInfo, int flags) { 8030 // Make sure there are no dangling permission trees. 8031 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8032 while (it.hasNext()) { 8033 final BasePermission bp = it.next(); 8034 if (bp.packageSetting == null) { 8035 // We may not yet have parsed the package, so just see if 8036 // we still know about its settings. 8037 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8038 } 8039 if (bp.packageSetting == null) { 8040 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8041 + " from package " + bp.sourcePackage); 8042 it.remove(); 8043 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8044 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8045 Slog.i(TAG, "Removing old permission tree: " + bp.name 8046 + " from package " + bp.sourcePackage); 8047 flags |= UPDATE_PERMISSIONS_ALL; 8048 it.remove(); 8049 } 8050 } 8051 } 8052 8053 // Make sure all dynamic permissions have been assigned to a package, 8054 // and make sure there are no dangling permissions. 8055 it = mSettings.mPermissions.values().iterator(); 8056 while (it.hasNext()) { 8057 final BasePermission bp = it.next(); 8058 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8059 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8060 + bp.name + " pkg=" + bp.sourcePackage 8061 + " info=" + bp.pendingInfo); 8062 if (bp.packageSetting == null && bp.pendingInfo != null) { 8063 final BasePermission tree = findPermissionTreeLP(bp.name); 8064 if (tree != null && tree.perm != null) { 8065 bp.packageSetting = tree.packageSetting; 8066 bp.perm = new PackageParser.Permission(tree.perm.owner, 8067 new PermissionInfo(bp.pendingInfo)); 8068 bp.perm.info.packageName = tree.perm.info.packageName; 8069 bp.perm.info.name = bp.name; 8070 bp.uid = tree.uid; 8071 } 8072 } 8073 } 8074 if (bp.packageSetting == null) { 8075 // We may not yet have parsed the package, so just see if 8076 // we still know about its settings. 8077 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8078 } 8079 if (bp.packageSetting == null) { 8080 Slog.w(TAG, "Removing dangling permission: " + bp.name 8081 + " from package " + bp.sourcePackage); 8082 it.remove(); 8083 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8084 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8085 Slog.i(TAG, "Removing old permission: " + bp.name 8086 + " from package " + bp.sourcePackage); 8087 flags |= UPDATE_PERMISSIONS_ALL; 8088 it.remove(); 8089 } 8090 } 8091 } 8092 8093 // Now update the permissions for all packages, in particular 8094 // replace the granted permissions of the system packages. 8095 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8096 for (PackageParser.Package pkg : mPackages.values()) { 8097 if (pkg != pkgInfo) { 8098 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8099 changingPkg); 8100 } 8101 } 8102 } 8103 8104 if (pkgInfo != null) { 8105 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8106 } 8107 } 8108 8109 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8110 String packageOfInterest) { 8111 // IMPORTANT: There are two types of permissions: install and runtime. 8112 // Install time permissions are granted when the app is installed to 8113 // all device users and users added in the future. Runtime permissions 8114 // are granted at runtime explicitly to specific users. Normal and signature 8115 // protected permissions are install time permissions. Dangerous permissions 8116 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8117 // otherwise they are runtime permissions. This function does not manage 8118 // runtime permissions except for the case an app targeting Lollipop MR1 8119 // being upgraded to target a newer SDK, in which case dangerous permissions 8120 // are transformed from install time to runtime ones. 8121 8122 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8123 if (ps == null) { 8124 return; 8125 } 8126 8127 PermissionsState permissionsState = ps.getPermissionsState(); 8128 PermissionsState origPermissions = permissionsState; 8129 8130 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8131 8132 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8133 8134 boolean changedInstallPermission = false; 8135 8136 if (replace) { 8137 ps.installPermissionsFixed = false; 8138 if (!ps.isSharedUser()) { 8139 origPermissions = new PermissionsState(permissionsState); 8140 permissionsState.reset(); 8141 } 8142 } 8143 8144 permissionsState.setGlobalGids(mGlobalGids); 8145 8146 final int N = pkg.requestedPermissions.size(); 8147 for (int i=0; i<N; i++) { 8148 final String name = pkg.requestedPermissions.get(i); 8149 final BasePermission bp = mSettings.mPermissions.get(name); 8150 8151 if (DEBUG_INSTALL) { 8152 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8153 } 8154 8155 if (bp == null || bp.packageSetting == null) { 8156 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8157 Slog.w(TAG, "Unknown permission " + name 8158 + " in package " + pkg.packageName); 8159 } 8160 continue; 8161 } 8162 8163 final String perm = bp.name; 8164 boolean allowedSig = false; 8165 int grant = GRANT_DENIED; 8166 8167 // Keep track of app op permissions. 8168 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8169 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8170 if (pkgs == null) { 8171 pkgs = new ArraySet<>(); 8172 mAppOpPermissionPackages.put(bp.name, pkgs); 8173 } 8174 pkgs.add(pkg.packageName); 8175 } 8176 8177 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8178 switch (level) { 8179 case PermissionInfo.PROTECTION_NORMAL: { 8180 // For all apps normal permissions are install time ones. 8181 grant = GRANT_INSTALL; 8182 } break; 8183 8184 case PermissionInfo.PROTECTION_DANGEROUS: { 8185 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8186 // For legacy apps dangerous permissions are install time ones. 8187 grant = GRANT_INSTALL_LEGACY; 8188 } else if (origPermissions.hasInstallPermission(bp.name)) { 8189 // For legacy apps that became modern, install becomes runtime. 8190 grant = GRANT_UPGRADE; 8191 } else { 8192 // For modern apps keep runtime permissions unchanged. 8193 grant = GRANT_RUNTIME; 8194 } 8195 } break; 8196 8197 case PermissionInfo.PROTECTION_SIGNATURE: { 8198 // For all apps signature permissions are install time ones. 8199 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8200 if (allowedSig) { 8201 grant = GRANT_INSTALL; 8202 } 8203 } break; 8204 } 8205 8206 if (DEBUG_INSTALL) { 8207 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8208 } 8209 8210 if (grant != GRANT_DENIED) { 8211 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8212 // If this is an existing, non-system package, then 8213 // we can't add any new permissions to it. 8214 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8215 // Except... if this is a permission that was added 8216 // to the platform (note: need to only do this when 8217 // updating the platform). 8218 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8219 grant = GRANT_DENIED; 8220 } 8221 } 8222 } 8223 8224 switch (grant) { 8225 case GRANT_INSTALL: { 8226 // Revoke this as runtime permission to handle the case of 8227 // a runtime permission being downgraded to an install one. 8228 for (int userId : UserManagerService.getInstance().getUserIds()) { 8229 if (origPermissions.getRuntimePermissionState( 8230 bp.name, userId) != null) { 8231 // Revoke the runtime permission and clear the flags. 8232 origPermissions.revokeRuntimePermission(bp, userId); 8233 origPermissions.updatePermissionFlags(bp, userId, 8234 PackageManager.MASK_PERMISSION_FLAGS, 0); 8235 // If we revoked a permission permission, we have to write. 8236 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8237 changedRuntimePermissionUserIds, userId); 8238 } 8239 } 8240 // Grant an install permission. 8241 if (permissionsState.grantInstallPermission(bp) != 8242 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8243 changedInstallPermission = true; 8244 } 8245 } break; 8246 8247 case GRANT_INSTALL_LEGACY: { 8248 // Grant an install permission. 8249 if (permissionsState.grantInstallPermission(bp) != 8250 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8251 changedInstallPermission = true; 8252 } 8253 } break; 8254 8255 case GRANT_RUNTIME: { 8256 // Grant previously granted runtime permissions. 8257 for (int userId : UserManagerService.getInstance().getUserIds()) { 8258 PermissionState permissionState = origPermissions 8259 .getRuntimePermissionState(bp.name, userId); 8260 final int flags = permissionState != null 8261 ? permissionState.getFlags() : 0; 8262 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8263 if (permissionsState.grantRuntimePermission(bp, userId) == 8264 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8265 // If we cannot put the permission as it was, we have to write. 8266 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8267 changedRuntimePermissionUserIds, userId); 8268 } 8269 } 8270 // Propagate the permission flags. 8271 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8272 } 8273 } break; 8274 8275 case GRANT_UPGRADE: { 8276 // Grant runtime permissions for a previously held install permission. 8277 PermissionState permissionState = origPermissions 8278 .getInstallPermissionState(bp.name); 8279 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8280 8281 if (origPermissions.revokeInstallPermission(bp) 8282 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8283 // We will be transferring the permission flags, so clear them. 8284 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8285 PackageManager.MASK_PERMISSION_FLAGS, 0); 8286 changedInstallPermission = true; 8287 } 8288 8289 // If the permission is not to be promoted to runtime we ignore it and 8290 // also its other flags as they are not applicable to install permissions. 8291 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8292 for (int userId : currentUserIds) { 8293 if (permissionsState.grantRuntimePermission(bp, userId) != 8294 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8295 // Transfer the permission flags. 8296 permissionsState.updatePermissionFlags(bp, userId, 8297 flags, flags); 8298 // If we granted the permission, we have to write. 8299 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8300 changedRuntimePermissionUserIds, userId); 8301 } 8302 } 8303 } 8304 } break; 8305 8306 default: { 8307 if (packageOfInterest == null 8308 || packageOfInterest.equals(pkg.packageName)) { 8309 Slog.w(TAG, "Not granting permission " + perm 8310 + " to package " + pkg.packageName 8311 + " because it was previously installed without"); 8312 } 8313 } break; 8314 } 8315 } else { 8316 if (permissionsState.revokeInstallPermission(bp) != 8317 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8318 // Also drop the permission flags. 8319 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8320 PackageManager.MASK_PERMISSION_FLAGS, 0); 8321 changedInstallPermission = true; 8322 Slog.i(TAG, "Un-granting permission " + perm 8323 + " from package " + pkg.packageName 8324 + " (protectionLevel=" + bp.protectionLevel 8325 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8326 + ")"); 8327 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8328 // Don't print warning for app op permissions, since it is fine for them 8329 // not to be granted, there is a UI for the user to decide. 8330 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8331 Slog.w(TAG, "Not granting permission " + perm 8332 + " to package " + pkg.packageName 8333 + " (protectionLevel=" + bp.protectionLevel 8334 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8335 + ")"); 8336 } 8337 } 8338 } 8339 } 8340 8341 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8342 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8343 // This is the first that we have heard about this package, so the 8344 // permissions we have now selected are fixed until explicitly 8345 // changed. 8346 ps.installPermissionsFixed = true; 8347 } 8348 8349 // Persist the runtime permissions state for users with changes. 8350 for (int userId : changedRuntimePermissionUserIds) { 8351 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8352 } 8353 } 8354 8355 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8356 boolean allowed = false; 8357 final int NP = PackageParser.NEW_PERMISSIONS.length; 8358 for (int ip=0; ip<NP; ip++) { 8359 final PackageParser.NewPermissionInfo npi 8360 = PackageParser.NEW_PERMISSIONS[ip]; 8361 if (npi.name.equals(perm) 8362 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8363 allowed = true; 8364 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8365 + pkg.packageName); 8366 break; 8367 } 8368 } 8369 return allowed; 8370 } 8371 8372 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8373 BasePermission bp, PermissionsState origPermissions) { 8374 boolean allowed; 8375 allowed = (compareSignatures( 8376 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8377 == PackageManager.SIGNATURE_MATCH) 8378 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8379 == PackageManager.SIGNATURE_MATCH); 8380 if (!allowed && (bp.protectionLevel 8381 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8382 if (isSystemApp(pkg)) { 8383 // For updated system applications, a system permission 8384 // is granted only if it had been defined by the original application. 8385 if (pkg.isUpdatedSystemApp()) { 8386 final PackageSetting sysPs = mSettings 8387 .getDisabledSystemPkgLPr(pkg.packageName); 8388 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8389 // If the original was granted this permission, we take 8390 // that grant decision as read and propagate it to the 8391 // update. 8392 if (sysPs.isPrivileged()) { 8393 allowed = true; 8394 } 8395 } else { 8396 // The system apk may have been updated with an older 8397 // version of the one on the data partition, but which 8398 // granted a new system permission that it didn't have 8399 // before. In this case we do want to allow the app to 8400 // now get the new permission if the ancestral apk is 8401 // privileged to get it. 8402 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8403 for (int j=0; 8404 j<sysPs.pkg.requestedPermissions.size(); j++) { 8405 if (perm.equals( 8406 sysPs.pkg.requestedPermissions.get(j))) { 8407 allowed = true; 8408 break; 8409 } 8410 } 8411 } 8412 } 8413 } else { 8414 allowed = isPrivilegedApp(pkg); 8415 } 8416 } 8417 } 8418 if (!allowed && (bp.protectionLevel 8419 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8420 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8421 // If this was a previously normal/dangerous permission that got moved 8422 // to a system permission as part of the runtime permission redesign, then 8423 // we still want to blindly grant it to old apps. 8424 allowed = true; 8425 } 8426 if (!allowed && (bp.protectionLevel 8427 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8428 // For development permissions, a development permission 8429 // is granted only if it was already granted. 8430 allowed = origPermissions.hasInstallPermission(perm); 8431 } 8432 return allowed; 8433 } 8434 8435 final class ActivityIntentResolver 8436 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8437 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8438 boolean defaultOnly, int userId) { 8439 if (!sUserManager.exists(userId)) return null; 8440 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8441 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8442 } 8443 8444 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8445 int userId) { 8446 if (!sUserManager.exists(userId)) return null; 8447 mFlags = flags; 8448 return super.queryIntent(intent, resolvedType, 8449 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8450 } 8451 8452 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8453 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8454 if (!sUserManager.exists(userId)) return null; 8455 if (packageActivities == null) { 8456 return null; 8457 } 8458 mFlags = flags; 8459 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8460 final int N = packageActivities.size(); 8461 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8462 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8463 8464 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8465 for (int i = 0; i < N; ++i) { 8466 intentFilters = packageActivities.get(i).intents; 8467 if (intentFilters != null && intentFilters.size() > 0) { 8468 PackageParser.ActivityIntentInfo[] array = 8469 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8470 intentFilters.toArray(array); 8471 listCut.add(array); 8472 } 8473 } 8474 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8475 } 8476 8477 public final void addActivity(PackageParser.Activity a, String type) { 8478 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8479 mActivities.put(a.getComponentName(), a); 8480 if (DEBUG_SHOW_INFO) 8481 Log.v( 8482 TAG, " " + type + " " + 8483 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8484 if (DEBUG_SHOW_INFO) 8485 Log.v(TAG, " Class=" + a.info.name); 8486 final int NI = a.intents.size(); 8487 for (int j=0; j<NI; j++) { 8488 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8489 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8490 intent.setPriority(0); 8491 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8492 + a.className + " with priority > 0, forcing to 0"); 8493 } 8494 if (DEBUG_SHOW_INFO) { 8495 Log.v(TAG, " IntentFilter:"); 8496 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8497 } 8498 if (!intent.debugCheck()) { 8499 Log.w(TAG, "==> For Activity " + a.info.name); 8500 } 8501 addFilter(intent); 8502 } 8503 } 8504 8505 public final void removeActivity(PackageParser.Activity a, String type) { 8506 mActivities.remove(a.getComponentName()); 8507 if (DEBUG_SHOW_INFO) { 8508 Log.v(TAG, " " + type + " " 8509 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8510 : a.info.name) + ":"); 8511 Log.v(TAG, " Class=" + a.info.name); 8512 } 8513 final int NI = a.intents.size(); 8514 for (int j=0; j<NI; j++) { 8515 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8516 if (DEBUG_SHOW_INFO) { 8517 Log.v(TAG, " IntentFilter:"); 8518 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8519 } 8520 removeFilter(intent); 8521 } 8522 } 8523 8524 @Override 8525 protected boolean allowFilterResult( 8526 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8527 ActivityInfo filterAi = filter.activity.info; 8528 for (int i=dest.size()-1; i>=0; i--) { 8529 ActivityInfo destAi = dest.get(i).activityInfo; 8530 if (destAi.name == filterAi.name 8531 && destAi.packageName == filterAi.packageName) { 8532 return false; 8533 } 8534 } 8535 return true; 8536 } 8537 8538 @Override 8539 protected ActivityIntentInfo[] newArray(int size) { 8540 return new ActivityIntentInfo[size]; 8541 } 8542 8543 @Override 8544 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8545 if (!sUserManager.exists(userId)) return true; 8546 PackageParser.Package p = filter.activity.owner; 8547 if (p != null) { 8548 PackageSetting ps = (PackageSetting)p.mExtras; 8549 if (ps != null) { 8550 // System apps are never considered stopped for purposes of 8551 // filtering, because there may be no way for the user to 8552 // actually re-launch them. 8553 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8554 && ps.getStopped(userId); 8555 } 8556 } 8557 return false; 8558 } 8559 8560 @Override 8561 protected boolean isPackageForFilter(String packageName, 8562 PackageParser.ActivityIntentInfo info) { 8563 return packageName.equals(info.activity.owner.packageName); 8564 } 8565 8566 @Override 8567 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8568 int match, int userId) { 8569 if (!sUserManager.exists(userId)) return null; 8570 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8571 return null; 8572 } 8573 final PackageParser.Activity activity = info.activity; 8574 if (mSafeMode && (activity.info.applicationInfo.flags 8575 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8576 return null; 8577 } 8578 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8579 if (ps == null) { 8580 return null; 8581 } 8582 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8583 ps.readUserState(userId), userId); 8584 if (ai == null) { 8585 return null; 8586 } 8587 final ResolveInfo res = new ResolveInfo(); 8588 res.activityInfo = ai; 8589 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8590 res.filter = info; 8591 } 8592 if (info != null) { 8593 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8594 } 8595 res.priority = info.getPriority(); 8596 res.preferredOrder = activity.owner.mPreferredOrder; 8597 //System.out.println("Result: " + res.activityInfo.className + 8598 // " = " + res.priority); 8599 res.match = match; 8600 res.isDefault = info.hasDefault; 8601 res.labelRes = info.labelRes; 8602 res.nonLocalizedLabel = info.nonLocalizedLabel; 8603 if (userNeedsBadging(userId)) { 8604 res.noResourceId = true; 8605 } else { 8606 res.icon = info.icon; 8607 } 8608 res.iconResourceId = info.icon; 8609 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8610 return res; 8611 } 8612 8613 @Override 8614 protected void sortResults(List<ResolveInfo> results) { 8615 Collections.sort(results, mResolvePrioritySorter); 8616 } 8617 8618 @Override 8619 protected void dumpFilter(PrintWriter out, String prefix, 8620 PackageParser.ActivityIntentInfo filter) { 8621 out.print(prefix); out.print( 8622 Integer.toHexString(System.identityHashCode(filter.activity))); 8623 out.print(' '); 8624 filter.activity.printComponentShortName(out); 8625 out.print(" filter "); 8626 out.println(Integer.toHexString(System.identityHashCode(filter))); 8627 } 8628 8629 @Override 8630 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8631 return filter.activity; 8632 } 8633 8634 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8635 PackageParser.Activity activity = (PackageParser.Activity)label; 8636 out.print(prefix); out.print( 8637 Integer.toHexString(System.identityHashCode(activity))); 8638 out.print(' '); 8639 activity.printComponentShortName(out); 8640 if (count > 1) { 8641 out.print(" ("); out.print(count); out.print(" filters)"); 8642 } 8643 out.println(); 8644 } 8645 8646// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8647// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8648// final List<ResolveInfo> retList = Lists.newArrayList(); 8649// while (i.hasNext()) { 8650// final ResolveInfo resolveInfo = i.next(); 8651// if (isEnabledLP(resolveInfo.activityInfo)) { 8652// retList.add(resolveInfo); 8653// } 8654// } 8655// return retList; 8656// } 8657 8658 // Keys are String (activity class name), values are Activity. 8659 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8660 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8661 private int mFlags; 8662 } 8663 8664 private final class ServiceIntentResolver 8665 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8666 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8667 boolean defaultOnly, int userId) { 8668 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8669 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8670 } 8671 8672 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8673 int userId) { 8674 if (!sUserManager.exists(userId)) return null; 8675 mFlags = flags; 8676 return super.queryIntent(intent, resolvedType, 8677 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8678 } 8679 8680 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8681 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8682 if (!sUserManager.exists(userId)) return null; 8683 if (packageServices == null) { 8684 return null; 8685 } 8686 mFlags = flags; 8687 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8688 final int N = packageServices.size(); 8689 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8690 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8691 8692 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8693 for (int i = 0; i < N; ++i) { 8694 intentFilters = packageServices.get(i).intents; 8695 if (intentFilters != null && intentFilters.size() > 0) { 8696 PackageParser.ServiceIntentInfo[] array = 8697 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8698 intentFilters.toArray(array); 8699 listCut.add(array); 8700 } 8701 } 8702 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8703 } 8704 8705 public final void addService(PackageParser.Service s) { 8706 mServices.put(s.getComponentName(), s); 8707 if (DEBUG_SHOW_INFO) { 8708 Log.v(TAG, " " 8709 + (s.info.nonLocalizedLabel != null 8710 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8711 Log.v(TAG, " Class=" + s.info.name); 8712 } 8713 final int NI = s.intents.size(); 8714 int j; 8715 for (j=0; j<NI; j++) { 8716 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8717 if (DEBUG_SHOW_INFO) { 8718 Log.v(TAG, " IntentFilter:"); 8719 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8720 } 8721 if (!intent.debugCheck()) { 8722 Log.w(TAG, "==> For Service " + s.info.name); 8723 } 8724 addFilter(intent); 8725 } 8726 } 8727 8728 public final void removeService(PackageParser.Service s) { 8729 mServices.remove(s.getComponentName()); 8730 if (DEBUG_SHOW_INFO) { 8731 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8732 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8733 Log.v(TAG, " Class=" + s.info.name); 8734 } 8735 final int NI = s.intents.size(); 8736 int j; 8737 for (j=0; j<NI; j++) { 8738 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8739 if (DEBUG_SHOW_INFO) { 8740 Log.v(TAG, " IntentFilter:"); 8741 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8742 } 8743 removeFilter(intent); 8744 } 8745 } 8746 8747 @Override 8748 protected boolean allowFilterResult( 8749 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8750 ServiceInfo filterSi = filter.service.info; 8751 for (int i=dest.size()-1; i>=0; i--) { 8752 ServiceInfo destAi = dest.get(i).serviceInfo; 8753 if (destAi.name == filterSi.name 8754 && destAi.packageName == filterSi.packageName) { 8755 return false; 8756 } 8757 } 8758 return true; 8759 } 8760 8761 @Override 8762 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8763 return new PackageParser.ServiceIntentInfo[size]; 8764 } 8765 8766 @Override 8767 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8768 if (!sUserManager.exists(userId)) return true; 8769 PackageParser.Package p = filter.service.owner; 8770 if (p != null) { 8771 PackageSetting ps = (PackageSetting)p.mExtras; 8772 if (ps != null) { 8773 // System apps are never considered stopped for purposes of 8774 // filtering, because there may be no way for the user to 8775 // actually re-launch them. 8776 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8777 && ps.getStopped(userId); 8778 } 8779 } 8780 return false; 8781 } 8782 8783 @Override 8784 protected boolean isPackageForFilter(String packageName, 8785 PackageParser.ServiceIntentInfo info) { 8786 return packageName.equals(info.service.owner.packageName); 8787 } 8788 8789 @Override 8790 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8791 int match, int userId) { 8792 if (!sUserManager.exists(userId)) return null; 8793 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8794 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8795 return null; 8796 } 8797 final PackageParser.Service service = info.service; 8798 if (mSafeMode && (service.info.applicationInfo.flags 8799 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8800 return null; 8801 } 8802 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8803 if (ps == null) { 8804 return null; 8805 } 8806 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8807 ps.readUserState(userId), userId); 8808 if (si == null) { 8809 return null; 8810 } 8811 final ResolveInfo res = new ResolveInfo(); 8812 res.serviceInfo = si; 8813 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8814 res.filter = filter; 8815 } 8816 res.priority = info.getPriority(); 8817 res.preferredOrder = service.owner.mPreferredOrder; 8818 res.match = match; 8819 res.isDefault = info.hasDefault; 8820 res.labelRes = info.labelRes; 8821 res.nonLocalizedLabel = info.nonLocalizedLabel; 8822 res.icon = info.icon; 8823 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8824 return res; 8825 } 8826 8827 @Override 8828 protected void sortResults(List<ResolveInfo> results) { 8829 Collections.sort(results, mResolvePrioritySorter); 8830 } 8831 8832 @Override 8833 protected void dumpFilter(PrintWriter out, String prefix, 8834 PackageParser.ServiceIntentInfo filter) { 8835 out.print(prefix); out.print( 8836 Integer.toHexString(System.identityHashCode(filter.service))); 8837 out.print(' '); 8838 filter.service.printComponentShortName(out); 8839 out.print(" filter "); 8840 out.println(Integer.toHexString(System.identityHashCode(filter))); 8841 } 8842 8843 @Override 8844 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8845 return filter.service; 8846 } 8847 8848 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8849 PackageParser.Service service = (PackageParser.Service)label; 8850 out.print(prefix); out.print( 8851 Integer.toHexString(System.identityHashCode(service))); 8852 out.print(' '); 8853 service.printComponentShortName(out); 8854 if (count > 1) { 8855 out.print(" ("); out.print(count); out.print(" filters)"); 8856 } 8857 out.println(); 8858 } 8859 8860// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8861// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8862// final List<ResolveInfo> retList = Lists.newArrayList(); 8863// while (i.hasNext()) { 8864// final ResolveInfo resolveInfo = (ResolveInfo) i; 8865// if (isEnabledLP(resolveInfo.serviceInfo)) { 8866// retList.add(resolveInfo); 8867// } 8868// } 8869// return retList; 8870// } 8871 8872 // Keys are String (activity class name), values are Activity. 8873 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8874 = new ArrayMap<ComponentName, PackageParser.Service>(); 8875 private int mFlags; 8876 }; 8877 8878 private final class ProviderIntentResolver 8879 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8880 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8881 boolean defaultOnly, int userId) { 8882 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8883 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8884 } 8885 8886 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8887 int userId) { 8888 if (!sUserManager.exists(userId)) 8889 return null; 8890 mFlags = flags; 8891 return super.queryIntent(intent, resolvedType, 8892 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8893 } 8894 8895 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8896 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8897 if (!sUserManager.exists(userId)) 8898 return null; 8899 if (packageProviders == null) { 8900 return null; 8901 } 8902 mFlags = flags; 8903 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8904 final int N = packageProviders.size(); 8905 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8906 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8907 8908 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8909 for (int i = 0; i < N; ++i) { 8910 intentFilters = packageProviders.get(i).intents; 8911 if (intentFilters != null && intentFilters.size() > 0) { 8912 PackageParser.ProviderIntentInfo[] array = 8913 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8914 intentFilters.toArray(array); 8915 listCut.add(array); 8916 } 8917 } 8918 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8919 } 8920 8921 public final void addProvider(PackageParser.Provider p) { 8922 if (mProviders.containsKey(p.getComponentName())) { 8923 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8924 return; 8925 } 8926 8927 mProviders.put(p.getComponentName(), p); 8928 if (DEBUG_SHOW_INFO) { 8929 Log.v(TAG, " " 8930 + (p.info.nonLocalizedLabel != null 8931 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8932 Log.v(TAG, " Class=" + p.info.name); 8933 } 8934 final int NI = p.intents.size(); 8935 int j; 8936 for (j = 0; j < NI; j++) { 8937 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8938 if (DEBUG_SHOW_INFO) { 8939 Log.v(TAG, " IntentFilter:"); 8940 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8941 } 8942 if (!intent.debugCheck()) { 8943 Log.w(TAG, "==> For Provider " + p.info.name); 8944 } 8945 addFilter(intent); 8946 } 8947 } 8948 8949 public final void removeProvider(PackageParser.Provider p) { 8950 mProviders.remove(p.getComponentName()); 8951 if (DEBUG_SHOW_INFO) { 8952 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8953 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8954 Log.v(TAG, " Class=" + p.info.name); 8955 } 8956 final int NI = p.intents.size(); 8957 int j; 8958 for (j = 0; j < NI; j++) { 8959 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8960 if (DEBUG_SHOW_INFO) { 8961 Log.v(TAG, " IntentFilter:"); 8962 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8963 } 8964 removeFilter(intent); 8965 } 8966 } 8967 8968 @Override 8969 protected boolean allowFilterResult( 8970 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8971 ProviderInfo filterPi = filter.provider.info; 8972 for (int i = dest.size() - 1; i >= 0; i--) { 8973 ProviderInfo destPi = dest.get(i).providerInfo; 8974 if (destPi.name == filterPi.name 8975 && destPi.packageName == filterPi.packageName) { 8976 return false; 8977 } 8978 } 8979 return true; 8980 } 8981 8982 @Override 8983 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8984 return new PackageParser.ProviderIntentInfo[size]; 8985 } 8986 8987 @Override 8988 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8989 if (!sUserManager.exists(userId)) 8990 return true; 8991 PackageParser.Package p = filter.provider.owner; 8992 if (p != null) { 8993 PackageSetting ps = (PackageSetting) p.mExtras; 8994 if (ps != null) { 8995 // System apps are never considered stopped for purposes of 8996 // filtering, because there may be no way for the user to 8997 // actually re-launch them. 8998 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8999 && ps.getStopped(userId); 9000 } 9001 } 9002 return false; 9003 } 9004 9005 @Override 9006 protected boolean isPackageForFilter(String packageName, 9007 PackageParser.ProviderIntentInfo info) { 9008 return packageName.equals(info.provider.owner.packageName); 9009 } 9010 9011 @Override 9012 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9013 int match, int userId) { 9014 if (!sUserManager.exists(userId)) 9015 return null; 9016 final PackageParser.ProviderIntentInfo info = filter; 9017 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9018 return null; 9019 } 9020 final PackageParser.Provider provider = info.provider; 9021 if (mSafeMode && (provider.info.applicationInfo.flags 9022 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9023 return null; 9024 } 9025 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9026 if (ps == null) { 9027 return null; 9028 } 9029 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9030 ps.readUserState(userId), userId); 9031 if (pi == null) { 9032 return null; 9033 } 9034 final ResolveInfo res = new ResolveInfo(); 9035 res.providerInfo = pi; 9036 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9037 res.filter = filter; 9038 } 9039 res.priority = info.getPriority(); 9040 res.preferredOrder = provider.owner.mPreferredOrder; 9041 res.match = match; 9042 res.isDefault = info.hasDefault; 9043 res.labelRes = info.labelRes; 9044 res.nonLocalizedLabel = info.nonLocalizedLabel; 9045 res.icon = info.icon; 9046 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9047 return res; 9048 } 9049 9050 @Override 9051 protected void sortResults(List<ResolveInfo> results) { 9052 Collections.sort(results, mResolvePrioritySorter); 9053 } 9054 9055 @Override 9056 protected void dumpFilter(PrintWriter out, String prefix, 9057 PackageParser.ProviderIntentInfo filter) { 9058 out.print(prefix); 9059 out.print( 9060 Integer.toHexString(System.identityHashCode(filter.provider))); 9061 out.print(' '); 9062 filter.provider.printComponentShortName(out); 9063 out.print(" filter "); 9064 out.println(Integer.toHexString(System.identityHashCode(filter))); 9065 } 9066 9067 @Override 9068 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9069 return filter.provider; 9070 } 9071 9072 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9073 PackageParser.Provider provider = (PackageParser.Provider)label; 9074 out.print(prefix); out.print( 9075 Integer.toHexString(System.identityHashCode(provider))); 9076 out.print(' '); 9077 provider.printComponentShortName(out); 9078 if (count > 1) { 9079 out.print(" ("); out.print(count); out.print(" filters)"); 9080 } 9081 out.println(); 9082 } 9083 9084 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9085 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9086 private int mFlags; 9087 }; 9088 9089 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9090 new Comparator<ResolveInfo>() { 9091 public int compare(ResolveInfo r1, ResolveInfo r2) { 9092 int v1 = r1.priority; 9093 int v2 = r2.priority; 9094 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9095 if (v1 != v2) { 9096 return (v1 > v2) ? -1 : 1; 9097 } 9098 v1 = r1.preferredOrder; 9099 v2 = r2.preferredOrder; 9100 if (v1 != v2) { 9101 return (v1 > v2) ? -1 : 1; 9102 } 9103 if (r1.isDefault != r2.isDefault) { 9104 return r1.isDefault ? -1 : 1; 9105 } 9106 v1 = r1.match; 9107 v2 = r2.match; 9108 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9109 if (v1 != v2) { 9110 return (v1 > v2) ? -1 : 1; 9111 } 9112 if (r1.system != r2.system) { 9113 return r1.system ? -1 : 1; 9114 } 9115 return 0; 9116 } 9117 }; 9118 9119 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9120 new Comparator<ProviderInfo>() { 9121 public int compare(ProviderInfo p1, ProviderInfo p2) { 9122 final int v1 = p1.initOrder; 9123 final int v2 = p2.initOrder; 9124 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9125 } 9126 }; 9127 9128 final void sendPackageBroadcast(final String action, final String pkg, 9129 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9130 final int[] userIds) { 9131 mHandler.post(new Runnable() { 9132 @Override 9133 public void run() { 9134 try { 9135 final IActivityManager am = ActivityManagerNative.getDefault(); 9136 if (am == null) return; 9137 final int[] resolvedUserIds; 9138 if (userIds == null) { 9139 resolvedUserIds = am.getRunningUserIds(); 9140 } else { 9141 resolvedUserIds = userIds; 9142 } 9143 for (int id : resolvedUserIds) { 9144 final Intent intent = new Intent(action, 9145 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9146 if (extras != null) { 9147 intent.putExtras(extras); 9148 } 9149 if (targetPkg != null) { 9150 intent.setPackage(targetPkg); 9151 } 9152 // Modify the UID when posting to other users 9153 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9154 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9155 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9156 intent.putExtra(Intent.EXTRA_UID, uid); 9157 } 9158 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9159 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9160 if (DEBUG_BROADCASTS) { 9161 RuntimeException here = new RuntimeException("here"); 9162 here.fillInStackTrace(); 9163 Slog.d(TAG, "Sending to user " + id + ": " 9164 + intent.toShortString(false, true, false, false) 9165 + " " + intent.getExtras(), here); 9166 } 9167 am.broadcastIntent(null, intent, null, finishedReceiver, 9168 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9169 null, finishedReceiver != null, false, id); 9170 } 9171 } catch (RemoteException ex) { 9172 } 9173 } 9174 }); 9175 } 9176 9177 /** 9178 * Check if the external storage media is available. This is true if there 9179 * is a mounted external storage medium or if the external storage is 9180 * emulated. 9181 */ 9182 private boolean isExternalMediaAvailable() { 9183 return mMediaMounted || Environment.isExternalStorageEmulated(); 9184 } 9185 9186 @Override 9187 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9188 // writer 9189 synchronized (mPackages) { 9190 if (!isExternalMediaAvailable()) { 9191 // If the external storage is no longer mounted at this point, 9192 // the caller may not have been able to delete all of this 9193 // packages files and can not delete any more. Bail. 9194 return null; 9195 } 9196 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9197 if (lastPackage != null) { 9198 pkgs.remove(lastPackage); 9199 } 9200 if (pkgs.size() > 0) { 9201 return pkgs.get(0); 9202 } 9203 } 9204 return null; 9205 } 9206 9207 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9208 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9209 userId, andCode ? 1 : 0, packageName); 9210 if (mSystemReady) { 9211 msg.sendToTarget(); 9212 } else { 9213 if (mPostSystemReadyMessages == null) { 9214 mPostSystemReadyMessages = new ArrayList<>(); 9215 } 9216 mPostSystemReadyMessages.add(msg); 9217 } 9218 } 9219 9220 void startCleaningPackages() { 9221 // reader 9222 synchronized (mPackages) { 9223 if (!isExternalMediaAvailable()) { 9224 return; 9225 } 9226 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9227 return; 9228 } 9229 } 9230 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9231 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9232 IActivityManager am = ActivityManagerNative.getDefault(); 9233 if (am != null) { 9234 try { 9235 am.startService(null, intent, null, mContext.getOpPackageName(), 9236 UserHandle.USER_OWNER); 9237 } catch (RemoteException e) { 9238 } 9239 } 9240 } 9241 9242 @Override 9243 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9244 int installFlags, String installerPackageName, VerificationParams verificationParams, 9245 String packageAbiOverride) { 9246 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9247 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9248 } 9249 9250 @Override 9251 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9252 int installFlags, String installerPackageName, VerificationParams verificationParams, 9253 String packageAbiOverride, int userId) { 9254 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9255 9256 final int callingUid = Binder.getCallingUid(); 9257 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9258 9259 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9260 try { 9261 if (observer != null) { 9262 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9263 } 9264 } catch (RemoteException re) { 9265 } 9266 return; 9267 } 9268 9269 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9270 installFlags |= PackageManager.INSTALL_FROM_ADB; 9271 9272 } else { 9273 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9274 // about installerPackageName. 9275 9276 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9277 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9278 } 9279 9280 UserHandle user; 9281 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9282 user = UserHandle.ALL; 9283 } else { 9284 user = new UserHandle(userId); 9285 } 9286 9287 // Only system components can circumvent runtime permissions when installing. 9288 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9289 && mContext.checkCallingOrSelfPermission(Manifest.permission 9290 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9291 throw new SecurityException("You need the " 9292 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9293 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9294 } 9295 9296 verificationParams.setInstallerUid(callingUid); 9297 9298 final File originFile = new File(originPath); 9299 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9300 9301 final Message msg = mHandler.obtainMessage(INIT_COPY); 9302 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9303 null, verificationParams, user, packageAbiOverride); 9304 mHandler.sendMessage(msg); 9305 } 9306 9307 void installStage(String packageName, File stagedDir, String stagedCid, 9308 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9309 String installerPackageName, int installerUid, UserHandle user) { 9310 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9311 params.referrerUri, installerUid, null); 9312 verifParams.setInstallerUid(installerUid); 9313 9314 final OriginInfo origin; 9315 if (stagedDir != null) { 9316 origin = OriginInfo.fromStagedFile(stagedDir); 9317 } else { 9318 origin = OriginInfo.fromStagedContainer(stagedCid); 9319 } 9320 9321 final Message msg = mHandler.obtainMessage(INIT_COPY); 9322 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9323 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9324 mHandler.sendMessage(msg); 9325 } 9326 9327 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9328 Bundle extras = new Bundle(1); 9329 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9330 9331 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9332 packageName, extras, null, null, new int[] {userId}); 9333 try { 9334 IActivityManager am = ActivityManagerNative.getDefault(); 9335 final boolean isSystem = 9336 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9337 if (isSystem && am.isUserRunning(userId, false)) { 9338 // The just-installed/enabled app is bundled on the system, so presumed 9339 // to be able to run automatically without needing an explicit launch. 9340 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9341 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9342 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9343 .setPackage(packageName); 9344 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9345 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9346 } 9347 } catch (RemoteException e) { 9348 // shouldn't happen 9349 Slog.w(TAG, "Unable to bootstrap installed package", e); 9350 } 9351 } 9352 9353 @Override 9354 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9355 int userId) { 9356 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9357 PackageSetting pkgSetting; 9358 final int uid = Binder.getCallingUid(); 9359 enforceCrossUserPermission(uid, userId, true, true, 9360 "setApplicationHiddenSetting for user " + userId); 9361 9362 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9363 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9364 return false; 9365 } 9366 9367 long callingId = Binder.clearCallingIdentity(); 9368 try { 9369 boolean sendAdded = false; 9370 boolean sendRemoved = false; 9371 // writer 9372 synchronized (mPackages) { 9373 pkgSetting = mSettings.mPackages.get(packageName); 9374 if (pkgSetting == null) { 9375 return false; 9376 } 9377 if (pkgSetting.getHidden(userId) != hidden) { 9378 pkgSetting.setHidden(hidden, userId); 9379 mSettings.writePackageRestrictionsLPr(userId); 9380 if (hidden) { 9381 sendRemoved = true; 9382 } else { 9383 sendAdded = true; 9384 } 9385 } 9386 } 9387 if (sendAdded) { 9388 sendPackageAddedForUser(packageName, pkgSetting, userId); 9389 return true; 9390 } 9391 if (sendRemoved) { 9392 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9393 "hiding pkg"); 9394 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9395 } 9396 } finally { 9397 Binder.restoreCallingIdentity(callingId); 9398 } 9399 return false; 9400 } 9401 9402 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9403 int userId) { 9404 final PackageRemovedInfo info = new PackageRemovedInfo(); 9405 info.removedPackage = packageName; 9406 info.removedUsers = new int[] {userId}; 9407 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9408 info.sendBroadcast(false, false, false); 9409 } 9410 9411 /** 9412 * Returns true if application is not found or there was an error. Otherwise it returns 9413 * the hidden state of the package for the given user. 9414 */ 9415 @Override 9416 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9417 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9418 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9419 false, "getApplicationHidden for user " + userId); 9420 PackageSetting pkgSetting; 9421 long callingId = Binder.clearCallingIdentity(); 9422 try { 9423 // writer 9424 synchronized (mPackages) { 9425 pkgSetting = mSettings.mPackages.get(packageName); 9426 if (pkgSetting == null) { 9427 return true; 9428 } 9429 return pkgSetting.getHidden(userId); 9430 } 9431 } finally { 9432 Binder.restoreCallingIdentity(callingId); 9433 } 9434 } 9435 9436 /** 9437 * @hide 9438 */ 9439 @Override 9440 public int installExistingPackageAsUser(String packageName, int userId) { 9441 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9442 null); 9443 PackageSetting pkgSetting; 9444 final int uid = Binder.getCallingUid(); 9445 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9446 + userId); 9447 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9448 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9449 } 9450 9451 long callingId = Binder.clearCallingIdentity(); 9452 try { 9453 boolean sendAdded = false; 9454 9455 // writer 9456 synchronized (mPackages) { 9457 pkgSetting = mSettings.mPackages.get(packageName); 9458 if (pkgSetting == null) { 9459 return PackageManager.INSTALL_FAILED_INVALID_URI; 9460 } 9461 if (!pkgSetting.getInstalled(userId)) { 9462 pkgSetting.setInstalled(true, userId); 9463 pkgSetting.setHidden(false, userId); 9464 mSettings.writePackageRestrictionsLPr(userId); 9465 sendAdded = true; 9466 } 9467 } 9468 9469 if (sendAdded) { 9470 sendPackageAddedForUser(packageName, pkgSetting, userId); 9471 } 9472 } finally { 9473 Binder.restoreCallingIdentity(callingId); 9474 } 9475 9476 return PackageManager.INSTALL_SUCCEEDED; 9477 } 9478 9479 boolean isUserRestricted(int userId, String restrictionKey) { 9480 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9481 if (restrictions.getBoolean(restrictionKey, false)) { 9482 Log.w(TAG, "User is restricted: " + restrictionKey); 9483 return true; 9484 } 9485 return false; 9486 } 9487 9488 @Override 9489 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9490 mContext.enforceCallingOrSelfPermission( 9491 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9492 "Only package verification agents can verify applications"); 9493 9494 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9495 final PackageVerificationResponse response = new PackageVerificationResponse( 9496 verificationCode, Binder.getCallingUid()); 9497 msg.arg1 = id; 9498 msg.obj = response; 9499 mHandler.sendMessage(msg); 9500 } 9501 9502 @Override 9503 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9504 long millisecondsToDelay) { 9505 mContext.enforceCallingOrSelfPermission( 9506 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9507 "Only package verification agents can extend verification timeouts"); 9508 9509 final PackageVerificationState state = mPendingVerification.get(id); 9510 final PackageVerificationResponse response = new PackageVerificationResponse( 9511 verificationCodeAtTimeout, Binder.getCallingUid()); 9512 9513 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9514 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9515 } 9516 if (millisecondsToDelay < 0) { 9517 millisecondsToDelay = 0; 9518 } 9519 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9520 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9521 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9522 } 9523 9524 if ((state != null) && !state.timeoutExtended()) { 9525 state.extendTimeout(); 9526 9527 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9528 msg.arg1 = id; 9529 msg.obj = response; 9530 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9531 } 9532 } 9533 9534 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9535 int verificationCode, UserHandle user) { 9536 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9537 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9538 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9539 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9540 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9541 9542 mContext.sendBroadcastAsUser(intent, user, 9543 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9544 } 9545 9546 private ComponentName matchComponentForVerifier(String packageName, 9547 List<ResolveInfo> receivers) { 9548 ActivityInfo targetReceiver = null; 9549 9550 final int NR = receivers.size(); 9551 for (int i = 0; i < NR; i++) { 9552 final ResolveInfo info = receivers.get(i); 9553 if (info.activityInfo == null) { 9554 continue; 9555 } 9556 9557 if (packageName.equals(info.activityInfo.packageName)) { 9558 targetReceiver = info.activityInfo; 9559 break; 9560 } 9561 } 9562 9563 if (targetReceiver == null) { 9564 return null; 9565 } 9566 9567 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9568 } 9569 9570 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9571 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9572 if (pkgInfo.verifiers.length == 0) { 9573 return null; 9574 } 9575 9576 final int N = pkgInfo.verifiers.length; 9577 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9578 for (int i = 0; i < N; i++) { 9579 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9580 9581 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9582 receivers); 9583 if (comp == null) { 9584 continue; 9585 } 9586 9587 final int verifierUid = getUidForVerifier(verifierInfo); 9588 if (verifierUid == -1) { 9589 continue; 9590 } 9591 9592 if (DEBUG_VERIFY) { 9593 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9594 + " with the correct signature"); 9595 } 9596 sufficientVerifiers.add(comp); 9597 verificationState.addSufficientVerifier(verifierUid); 9598 } 9599 9600 return sufficientVerifiers; 9601 } 9602 9603 private int getUidForVerifier(VerifierInfo verifierInfo) { 9604 synchronized (mPackages) { 9605 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9606 if (pkg == null) { 9607 return -1; 9608 } else if (pkg.mSignatures.length != 1) { 9609 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9610 + " has more than one signature; ignoring"); 9611 return -1; 9612 } 9613 9614 /* 9615 * If the public key of the package's signature does not match 9616 * our expected public key, then this is a different package and 9617 * we should skip. 9618 */ 9619 9620 final byte[] expectedPublicKey; 9621 try { 9622 final Signature verifierSig = pkg.mSignatures[0]; 9623 final PublicKey publicKey = verifierSig.getPublicKey(); 9624 expectedPublicKey = publicKey.getEncoded(); 9625 } catch (CertificateException e) { 9626 return -1; 9627 } 9628 9629 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9630 9631 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9632 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9633 + " does not have the expected public key; ignoring"); 9634 return -1; 9635 } 9636 9637 return pkg.applicationInfo.uid; 9638 } 9639 } 9640 9641 @Override 9642 public void finishPackageInstall(int token) { 9643 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9644 9645 if (DEBUG_INSTALL) { 9646 Slog.v(TAG, "BM finishing package install for " + token); 9647 } 9648 9649 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9650 mHandler.sendMessage(msg); 9651 } 9652 9653 /** 9654 * Get the verification agent timeout. 9655 * 9656 * @return verification timeout in milliseconds 9657 */ 9658 private long getVerificationTimeout() { 9659 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9660 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9661 DEFAULT_VERIFICATION_TIMEOUT); 9662 } 9663 9664 /** 9665 * Get the default verification agent response code. 9666 * 9667 * @return default verification response code 9668 */ 9669 private int getDefaultVerificationResponse() { 9670 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9671 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9672 DEFAULT_VERIFICATION_RESPONSE); 9673 } 9674 9675 /** 9676 * Check whether or not package verification has been enabled. 9677 * 9678 * @return true if verification should be performed 9679 */ 9680 private boolean isVerificationEnabled(int userId, int installFlags) { 9681 if (!DEFAULT_VERIFY_ENABLE) { 9682 return false; 9683 } 9684 9685 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9686 9687 // Check if installing from ADB 9688 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9689 // Do not run verification in a test harness environment 9690 if (ActivityManager.isRunningInTestHarness()) { 9691 return false; 9692 } 9693 if (ensureVerifyAppsEnabled) { 9694 return true; 9695 } 9696 // Check if the developer does not want package verification for ADB installs 9697 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9698 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9699 return false; 9700 } 9701 } 9702 9703 if (ensureVerifyAppsEnabled) { 9704 return true; 9705 } 9706 9707 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9708 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9709 } 9710 9711 @Override 9712 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9713 throws RemoteException { 9714 mContext.enforceCallingOrSelfPermission( 9715 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9716 "Only intentfilter verification agents can verify applications"); 9717 9718 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9719 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9720 Binder.getCallingUid(), verificationCode, failedDomains); 9721 msg.arg1 = id; 9722 msg.obj = response; 9723 mHandler.sendMessage(msg); 9724 } 9725 9726 @Override 9727 public int getIntentVerificationStatus(String packageName, int userId) { 9728 synchronized (mPackages) { 9729 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9730 } 9731 } 9732 9733 @Override 9734 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9735 mContext.enforceCallingOrSelfPermission( 9736 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9737 9738 boolean result = false; 9739 synchronized (mPackages) { 9740 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9741 } 9742 if (result) { 9743 scheduleWritePackageRestrictionsLocked(userId); 9744 } 9745 return result; 9746 } 9747 9748 @Override 9749 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9750 synchronized (mPackages) { 9751 return mSettings.getIntentFilterVerificationsLPr(packageName); 9752 } 9753 } 9754 9755 @Override 9756 public List<IntentFilter> getAllIntentFilters(String packageName) { 9757 if (TextUtils.isEmpty(packageName)) { 9758 return Collections.<IntentFilter>emptyList(); 9759 } 9760 synchronized (mPackages) { 9761 PackageParser.Package pkg = mPackages.get(packageName); 9762 if (pkg == null || pkg.activities == null) { 9763 return Collections.<IntentFilter>emptyList(); 9764 } 9765 final int count = pkg.activities.size(); 9766 ArrayList<IntentFilter> result = new ArrayList<>(); 9767 for (int n=0; n<count; n++) { 9768 PackageParser.Activity activity = pkg.activities.get(n); 9769 if (activity.intents != null || activity.intents.size() > 0) { 9770 result.addAll(activity.intents); 9771 } 9772 } 9773 return result; 9774 } 9775 } 9776 9777 @Override 9778 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9779 mContext.enforceCallingOrSelfPermission( 9780 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9781 9782 synchronized (mPackages) { 9783 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9784 if (packageName != null) { 9785 result |= updateIntentVerificationStatus(packageName, 9786 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9787 UserHandle.myUserId()); 9788 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9789 packageName, userId); 9790 } 9791 return result; 9792 } 9793 } 9794 9795 @Override 9796 public String getDefaultBrowserPackageName(int userId) { 9797 synchronized (mPackages) { 9798 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9799 } 9800 } 9801 9802 /** 9803 * Get the "allow unknown sources" setting. 9804 * 9805 * @return the current "allow unknown sources" setting 9806 */ 9807 private int getUnknownSourcesSettings() { 9808 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9809 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9810 -1); 9811 } 9812 9813 @Override 9814 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9815 final int uid = Binder.getCallingUid(); 9816 // writer 9817 synchronized (mPackages) { 9818 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9819 if (targetPackageSetting == null) { 9820 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9821 } 9822 9823 PackageSetting installerPackageSetting; 9824 if (installerPackageName != null) { 9825 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9826 if (installerPackageSetting == null) { 9827 throw new IllegalArgumentException("Unknown installer package: " 9828 + installerPackageName); 9829 } 9830 } else { 9831 installerPackageSetting = null; 9832 } 9833 9834 Signature[] callerSignature; 9835 Object obj = mSettings.getUserIdLPr(uid); 9836 if (obj != null) { 9837 if (obj instanceof SharedUserSetting) { 9838 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9839 } else if (obj instanceof PackageSetting) { 9840 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9841 } else { 9842 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9843 } 9844 } else { 9845 throw new SecurityException("Unknown calling uid " + uid); 9846 } 9847 9848 // Verify: can't set installerPackageName to a package that is 9849 // not signed with the same cert as the caller. 9850 if (installerPackageSetting != null) { 9851 if (compareSignatures(callerSignature, 9852 installerPackageSetting.signatures.mSignatures) 9853 != PackageManager.SIGNATURE_MATCH) { 9854 throw new SecurityException( 9855 "Caller does not have same cert as new installer package " 9856 + installerPackageName); 9857 } 9858 } 9859 9860 // Verify: if target already has an installer package, it must 9861 // be signed with the same cert as the caller. 9862 if (targetPackageSetting.installerPackageName != null) { 9863 PackageSetting setting = mSettings.mPackages.get( 9864 targetPackageSetting.installerPackageName); 9865 // If the currently set package isn't valid, then it's always 9866 // okay to change it. 9867 if (setting != null) { 9868 if (compareSignatures(callerSignature, 9869 setting.signatures.mSignatures) 9870 != PackageManager.SIGNATURE_MATCH) { 9871 throw new SecurityException( 9872 "Caller does not have same cert as old installer package " 9873 + targetPackageSetting.installerPackageName); 9874 } 9875 } 9876 } 9877 9878 // Okay! 9879 targetPackageSetting.installerPackageName = installerPackageName; 9880 scheduleWriteSettingsLocked(); 9881 } 9882 } 9883 9884 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9885 // Queue up an async operation since the package installation may take a little while. 9886 mHandler.post(new Runnable() { 9887 public void run() { 9888 mHandler.removeCallbacks(this); 9889 // Result object to be returned 9890 PackageInstalledInfo res = new PackageInstalledInfo(); 9891 res.returnCode = currentStatus; 9892 res.uid = -1; 9893 res.pkg = null; 9894 res.removedInfo = new PackageRemovedInfo(); 9895 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9896 args.doPreInstall(res.returnCode); 9897 synchronized (mInstallLock) { 9898 installPackageLI(args, res); 9899 } 9900 args.doPostInstall(res.returnCode, res.uid); 9901 } 9902 9903 // A restore should be performed at this point if (a) the install 9904 // succeeded, (b) the operation is not an update, and (c) the new 9905 // package has not opted out of backup participation. 9906 final boolean update = res.removedInfo.removedPackage != null; 9907 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9908 boolean doRestore = !update 9909 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9910 9911 // Set up the post-install work request bookkeeping. This will be used 9912 // and cleaned up by the post-install event handling regardless of whether 9913 // there's a restore pass performed. Token values are >= 1. 9914 int token; 9915 if (mNextInstallToken < 0) mNextInstallToken = 1; 9916 token = mNextInstallToken++; 9917 9918 PostInstallData data = new PostInstallData(args, res); 9919 mRunningInstalls.put(token, data); 9920 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9921 9922 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9923 // Pass responsibility to the Backup Manager. It will perform a 9924 // restore if appropriate, then pass responsibility back to the 9925 // Package Manager to run the post-install observer callbacks 9926 // and broadcasts. 9927 IBackupManager bm = IBackupManager.Stub.asInterface( 9928 ServiceManager.getService(Context.BACKUP_SERVICE)); 9929 if (bm != null) { 9930 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9931 + " to BM for possible restore"); 9932 try { 9933 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9934 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9935 } else { 9936 doRestore = false; 9937 } 9938 } catch (RemoteException e) { 9939 // can't happen; the backup manager is local 9940 } catch (Exception e) { 9941 Slog.e(TAG, "Exception trying to enqueue restore", e); 9942 doRestore = false; 9943 } 9944 } else { 9945 Slog.e(TAG, "Backup Manager not found!"); 9946 doRestore = false; 9947 } 9948 } 9949 9950 if (!doRestore) { 9951 // No restore possible, or the Backup Manager was mysteriously not 9952 // available -- just fire the post-install work request directly. 9953 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9954 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9955 mHandler.sendMessage(msg); 9956 } 9957 } 9958 }); 9959 } 9960 9961 private abstract class HandlerParams { 9962 private static final int MAX_RETRIES = 4; 9963 9964 /** 9965 * Number of times startCopy() has been attempted and had a non-fatal 9966 * error. 9967 */ 9968 private int mRetries = 0; 9969 9970 /** User handle for the user requesting the information or installation. */ 9971 private final UserHandle mUser; 9972 9973 HandlerParams(UserHandle user) { 9974 mUser = user; 9975 } 9976 9977 UserHandle getUser() { 9978 return mUser; 9979 } 9980 9981 final boolean startCopy() { 9982 boolean res; 9983 try { 9984 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9985 9986 if (++mRetries > MAX_RETRIES) { 9987 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9988 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9989 handleServiceError(); 9990 return false; 9991 } else { 9992 handleStartCopy(); 9993 res = true; 9994 } 9995 } catch (RemoteException e) { 9996 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9997 mHandler.sendEmptyMessage(MCS_RECONNECT); 9998 res = false; 9999 } 10000 handleReturnCode(); 10001 return res; 10002 } 10003 10004 final void serviceError() { 10005 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10006 handleServiceError(); 10007 handleReturnCode(); 10008 } 10009 10010 abstract void handleStartCopy() throws RemoteException; 10011 abstract void handleServiceError(); 10012 abstract void handleReturnCode(); 10013 } 10014 10015 class MeasureParams extends HandlerParams { 10016 private final PackageStats mStats; 10017 private boolean mSuccess; 10018 10019 private final IPackageStatsObserver mObserver; 10020 10021 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10022 super(new UserHandle(stats.userHandle)); 10023 mObserver = observer; 10024 mStats = stats; 10025 } 10026 10027 @Override 10028 public String toString() { 10029 return "MeasureParams{" 10030 + Integer.toHexString(System.identityHashCode(this)) 10031 + " " + mStats.packageName + "}"; 10032 } 10033 10034 @Override 10035 void handleStartCopy() throws RemoteException { 10036 synchronized (mInstallLock) { 10037 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10038 } 10039 10040 if (mSuccess) { 10041 final boolean mounted; 10042 if (Environment.isExternalStorageEmulated()) { 10043 mounted = true; 10044 } else { 10045 final String status = Environment.getExternalStorageState(); 10046 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10047 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10048 } 10049 10050 if (mounted) { 10051 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10052 10053 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10054 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10055 10056 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10057 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10058 10059 // Always subtract cache size, since it's a subdirectory 10060 mStats.externalDataSize -= mStats.externalCacheSize; 10061 10062 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10063 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10064 10065 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10066 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10067 } 10068 } 10069 } 10070 10071 @Override 10072 void handleReturnCode() { 10073 if (mObserver != null) { 10074 try { 10075 mObserver.onGetStatsCompleted(mStats, mSuccess); 10076 } catch (RemoteException e) { 10077 Slog.i(TAG, "Observer no longer exists."); 10078 } 10079 } 10080 } 10081 10082 @Override 10083 void handleServiceError() { 10084 Slog.e(TAG, "Could not measure application " + mStats.packageName 10085 + " external storage"); 10086 } 10087 } 10088 10089 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10090 throws RemoteException { 10091 long result = 0; 10092 for (File path : paths) { 10093 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10094 } 10095 return result; 10096 } 10097 10098 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10099 for (File path : paths) { 10100 try { 10101 mcs.clearDirectory(path.getAbsolutePath()); 10102 } catch (RemoteException e) { 10103 } 10104 } 10105 } 10106 10107 static class OriginInfo { 10108 /** 10109 * Location where install is coming from, before it has been 10110 * copied/renamed into place. This could be a single monolithic APK 10111 * file, or a cluster directory. This location may be untrusted. 10112 */ 10113 final File file; 10114 final String cid; 10115 10116 /** 10117 * Flag indicating that {@link #file} or {@link #cid} has already been 10118 * staged, meaning downstream users don't need to defensively copy the 10119 * contents. 10120 */ 10121 final boolean staged; 10122 10123 /** 10124 * Flag indicating that {@link #file} or {@link #cid} is an already 10125 * installed app that is being moved. 10126 */ 10127 final boolean existing; 10128 10129 final String resolvedPath; 10130 final File resolvedFile; 10131 10132 static OriginInfo fromNothing() { 10133 return new OriginInfo(null, null, false, false); 10134 } 10135 10136 static OriginInfo fromUntrustedFile(File file) { 10137 return new OriginInfo(file, null, false, false); 10138 } 10139 10140 static OriginInfo fromExistingFile(File file) { 10141 return new OriginInfo(file, null, false, true); 10142 } 10143 10144 static OriginInfo fromStagedFile(File file) { 10145 return new OriginInfo(file, null, true, false); 10146 } 10147 10148 static OriginInfo fromStagedContainer(String cid) { 10149 return new OriginInfo(null, cid, true, false); 10150 } 10151 10152 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10153 this.file = file; 10154 this.cid = cid; 10155 this.staged = staged; 10156 this.existing = existing; 10157 10158 if (cid != null) { 10159 resolvedPath = PackageHelper.getSdDir(cid); 10160 resolvedFile = new File(resolvedPath); 10161 } else if (file != null) { 10162 resolvedPath = file.getAbsolutePath(); 10163 resolvedFile = file; 10164 } else { 10165 resolvedPath = null; 10166 resolvedFile = null; 10167 } 10168 } 10169 } 10170 10171 class MoveInfo { 10172 final int moveId; 10173 final String fromUuid; 10174 final String toUuid; 10175 final String packageName; 10176 final String dataAppName; 10177 final int appId; 10178 final String seinfo; 10179 10180 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10181 String dataAppName, int appId, String seinfo) { 10182 this.moveId = moveId; 10183 this.fromUuid = fromUuid; 10184 this.toUuid = toUuid; 10185 this.packageName = packageName; 10186 this.dataAppName = dataAppName; 10187 this.appId = appId; 10188 this.seinfo = seinfo; 10189 } 10190 } 10191 10192 class InstallParams extends HandlerParams { 10193 final OriginInfo origin; 10194 final MoveInfo move; 10195 final IPackageInstallObserver2 observer; 10196 int installFlags; 10197 final String installerPackageName; 10198 final String volumeUuid; 10199 final VerificationParams verificationParams; 10200 private InstallArgs mArgs; 10201 private int mRet; 10202 final String packageAbiOverride; 10203 10204 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10205 int installFlags, String installerPackageName, String volumeUuid, 10206 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10207 super(user); 10208 this.origin = origin; 10209 this.move = move; 10210 this.observer = observer; 10211 this.installFlags = installFlags; 10212 this.installerPackageName = installerPackageName; 10213 this.volumeUuid = volumeUuid; 10214 this.verificationParams = verificationParams; 10215 this.packageAbiOverride = packageAbiOverride; 10216 } 10217 10218 @Override 10219 public String toString() { 10220 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10221 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10222 } 10223 10224 public ManifestDigest getManifestDigest() { 10225 if (verificationParams == null) { 10226 return null; 10227 } 10228 return verificationParams.getManifestDigest(); 10229 } 10230 10231 private int installLocationPolicy(PackageInfoLite pkgLite) { 10232 String packageName = pkgLite.packageName; 10233 int installLocation = pkgLite.installLocation; 10234 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10235 // reader 10236 synchronized (mPackages) { 10237 PackageParser.Package pkg = mPackages.get(packageName); 10238 if (pkg != null) { 10239 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10240 // Check for downgrading. 10241 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10242 try { 10243 checkDowngrade(pkg, pkgLite); 10244 } catch (PackageManagerException e) { 10245 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10246 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10247 } 10248 } 10249 // Check for updated system application. 10250 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10251 if (onSd) { 10252 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10253 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10254 } 10255 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10256 } else { 10257 if (onSd) { 10258 // Install flag overrides everything. 10259 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10260 } 10261 // If current upgrade specifies particular preference 10262 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10263 // Application explicitly specified internal. 10264 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10265 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10266 // App explictly prefers external. Let policy decide 10267 } else { 10268 // Prefer previous location 10269 if (isExternal(pkg)) { 10270 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10271 } 10272 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10273 } 10274 } 10275 } else { 10276 // Invalid install. Return error code 10277 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10278 } 10279 } 10280 } 10281 // All the special cases have been taken care of. 10282 // Return result based on recommended install location. 10283 if (onSd) { 10284 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10285 } 10286 return pkgLite.recommendedInstallLocation; 10287 } 10288 10289 /* 10290 * Invoke remote method to get package information and install 10291 * location values. Override install location based on default 10292 * policy if needed and then create install arguments based 10293 * on the install location. 10294 */ 10295 public void handleStartCopy() throws RemoteException { 10296 int ret = PackageManager.INSTALL_SUCCEEDED; 10297 10298 // If we're already staged, we've firmly committed to an install location 10299 if (origin.staged) { 10300 if (origin.file != null) { 10301 installFlags |= PackageManager.INSTALL_INTERNAL; 10302 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10303 } else if (origin.cid != null) { 10304 installFlags |= PackageManager.INSTALL_EXTERNAL; 10305 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10306 } else { 10307 throw new IllegalStateException("Invalid stage location"); 10308 } 10309 } 10310 10311 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10312 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10313 10314 PackageInfoLite pkgLite = null; 10315 10316 if (onInt && onSd) { 10317 // Check if both bits are set. 10318 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10319 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10320 } else { 10321 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10322 packageAbiOverride); 10323 10324 /* 10325 * If we have too little free space, try to free cache 10326 * before giving up. 10327 */ 10328 if (!origin.staged && pkgLite.recommendedInstallLocation 10329 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10330 // TODO: focus freeing disk space on the target device 10331 final StorageManager storage = StorageManager.from(mContext); 10332 final long lowThreshold = storage.getStorageLowBytes( 10333 Environment.getDataDirectory()); 10334 10335 final long sizeBytes = mContainerService.calculateInstalledSize( 10336 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10337 10338 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10339 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10340 installFlags, packageAbiOverride); 10341 } 10342 10343 /* 10344 * The cache free must have deleted the file we 10345 * downloaded to install. 10346 * 10347 * TODO: fix the "freeCache" call to not delete 10348 * the file we care about. 10349 */ 10350 if (pkgLite.recommendedInstallLocation 10351 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10352 pkgLite.recommendedInstallLocation 10353 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10354 } 10355 } 10356 } 10357 10358 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10359 int loc = pkgLite.recommendedInstallLocation; 10360 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10361 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10362 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10363 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10364 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10365 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10366 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10367 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10368 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10369 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10370 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10371 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10372 } else { 10373 // Override with defaults if needed. 10374 loc = installLocationPolicy(pkgLite); 10375 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10376 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10377 } else if (!onSd && !onInt) { 10378 // Override install location with flags 10379 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10380 // Set the flag to install on external media. 10381 installFlags |= PackageManager.INSTALL_EXTERNAL; 10382 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10383 } else { 10384 // Make sure the flag for installing on external 10385 // media is unset 10386 installFlags |= PackageManager.INSTALL_INTERNAL; 10387 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10388 } 10389 } 10390 } 10391 } 10392 10393 final InstallArgs args = createInstallArgs(this); 10394 mArgs = args; 10395 10396 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10397 /* 10398 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10399 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10400 */ 10401 int userIdentifier = getUser().getIdentifier(); 10402 if (userIdentifier == UserHandle.USER_ALL 10403 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10404 userIdentifier = UserHandle.USER_OWNER; 10405 } 10406 10407 /* 10408 * Determine if we have any installed package verifiers. If we 10409 * do, then we'll defer to them to verify the packages. 10410 */ 10411 final int requiredUid = mRequiredVerifierPackage == null ? -1 10412 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10413 if (!origin.existing && requiredUid != -1 10414 && isVerificationEnabled(userIdentifier, installFlags)) { 10415 final Intent verification = new Intent( 10416 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10417 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10418 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10419 PACKAGE_MIME_TYPE); 10420 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10421 10422 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10423 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10424 0 /* TODO: Which userId? */); 10425 10426 if (DEBUG_VERIFY) { 10427 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10428 + verification.toString() + " with " + pkgLite.verifiers.length 10429 + " optional verifiers"); 10430 } 10431 10432 final int verificationId = mPendingVerificationToken++; 10433 10434 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10435 10436 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10437 installerPackageName); 10438 10439 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10440 installFlags); 10441 10442 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10443 pkgLite.packageName); 10444 10445 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10446 pkgLite.versionCode); 10447 10448 if (verificationParams != null) { 10449 if (verificationParams.getVerificationURI() != null) { 10450 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10451 verificationParams.getVerificationURI()); 10452 } 10453 if (verificationParams.getOriginatingURI() != null) { 10454 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10455 verificationParams.getOriginatingURI()); 10456 } 10457 if (verificationParams.getReferrer() != null) { 10458 verification.putExtra(Intent.EXTRA_REFERRER, 10459 verificationParams.getReferrer()); 10460 } 10461 if (verificationParams.getOriginatingUid() >= 0) { 10462 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10463 verificationParams.getOriginatingUid()); 10464 } 10465 if (verificationParams.getInstallerUid() >= 0) { 10466 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10467 verificationParams.getInstallerUid()); 10468 } 10469 } 10470 10471 final PackageVerificationState verificationState = new PackageVerificationState( 10472 requiredUid, args); 10473 10474 mPendingVerification.append(verificationId, verificationState); 10475 10476 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10477 receivers, verificationState); 10478 10479 /* 10480 * If any sufficient verifiers were listed in the package 10481 * manifest, attempt to ask them. 10482 */ 10483 if (sufficientVerifiers != null) { 10484 final int N = sufficientVerifiers.size(); 10485 if (N == 0) { 10486 Slog.i(TAG, "Additional verifiers required, but none installed."); 10487 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10488 } else { 10489 for (int i = 0; i < N; i++) { 10490 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10491 10492 final Intent sufficientIntent = new Intent(verification); 10493 sufficientIntent.setComponent(verifierComponent); 10494 10495 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10496 } 10497 } 10498 } 10499 10500 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10501 mRequiredVerifierPackage, receivers); 10502 if (ret == PackageManager.INSTALL_SUCCEEDED 10503 && mRequiredVerifierPackage != null) { 10504 /* 10505 * Send the intent to the required verification agent, 10506 * but only start the verification timeout after the 10507 * target BroadcastReceivers have run. 10508 */ 10509 verification.setComponent(requiredVerifierComponent); 10510 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10511 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10512 new BroadcastReceiver() { 10513 @Override 10514 public void onReceive(Context context, Intent intent) { 10515 final Message msg = mHandler 10516 .obtainMessage(CHECK_PENDING_VERIFICATION); 10517 msg.arg1 = verificationId; 10518 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10519 } 10520 }, null, 0, null, null); 10521 10522 /* 10523 * We don't want the copy to proceed until verification 10524 * succeeds, so null out this field. 10525 */ 10526 mArgs = null; 10527 } 10528 } else { 10529 /* 10530 * No package verification is enabled, so immediately start 10531 * the remote call to initiate copy using temporary file. 10532 */ 10533 ret = args.copyApk(mContainerService, true); 10534 } 10535 } 10536 10537 mRet = ret; 10538 } 10539 10540 @Override 10541 void handleReturnCode() { 10542 // If mArgs is null, then MCS couldn't be reached. When it 10543 // reconnects, it will try again to install. At that point, this 10544 // will succeed. 10545 if (mArgs != null) { 10546 processPendingInstall(mArgs, mRet); 10547 } 10548 } 10549 10550 @Override 10551 void handleServiceError() { 10552 mArgs = createInstallArgs(this); 10553 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10554 } 10555 10556 public boolean isForwardLocked() { 10557 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10558 } 10559 } 10560 10561 /** 10562 * Used during creation of InstallArgs 10563 * 10564 * @param installFlags package installation flags 10565 * @return true if should be installed on external storage 10566 */ 10567 private static boolean installOnExternalAsec(int installFlags) { 10568 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10569 return false; 10570 } 10571 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10572 return true; 10573 } 10574 return false; 10575 } 10576 10577 /** 10578 * Used during creation of InstallArgs 10579 * 10580 * @param installFlags package installation flags 10581 * @return true if should be installed as forward locked 10582 */ 10583 private static boolean installForwardLocked(int installFlags) { 10584 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10585 } 10586 10587 private InstallArgs createInstallArgs(InstallParams params) { 10588 if (params.move != null) { 10589 return new MoveInstallArgs(params); 10590 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10591 return new AsecInstallArgs(params); 10592 } else { 10593 return new FileInstallArgs(params); 10594 } 10595 } 10596 10597 /** 10598 * Create args that describe an existing installed package. Typically used 10599 * when cleaning up old installs, or used as a move source. 10600 */ 10601 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10602 String resourcePath, String[] instructionSets) { 10603 final boolean isInAsec; 10604 if (installOnExternalAsec(installFlags)) { 10605 /* Apps on SD card are always in ASEC containers. */ 10606 isInAsec = true; 10607 } else if (installForwardLocked(installFlags) 10608 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10609 /* 10610 * Forward-locked apps are only in ASEC containers if they're the 10611 * new style 10612 */ 10613 isInAsec = true; 10614 } else { 10615 isInAsec = false; 10616 } 10617 10618 if (isInAsec) { 10619 return new AsecInstallArgs(codePath, instructionSets, 10620 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10621 } else { 10622 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10623 } 10624 } 10625 10626 static abstract class InstallArgs { 10627 /** @see InstallParams#origin */ 10628 final OriginInfo origin; 10629 /** @see InstallParams#move */ 10630 final MoveInfo move; 10631 10632 final IPackageInstallObserver2 observer; 10633 // Always refers to PackageManager flags only 10634 final int installFlags; 10635 final String installerPackageName; 10636 final String volumeUuid; 10637 final ManifestDigest manifestDigest; 10638 final UserHandle user; 10639 final String abiOverride; 10640 10641 // The list of instruction sets supported by this app. This is currently 10642 // only used during the rmdex() phase to clean up resources. We can get rid of this 10643 // if we move dex files under the common app path. 10644 /* nullable */ String[] instructionSets; 10645 10646 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10647 int installFlags, String installerPackageName, String volumeUuid, 10648 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10649 String abiOverride) { 10650 this.origin = origin; 10651 this.move = move; 10652 this.installFlags = installFlags; 10653 this.observer = observer; 10654 this.installerPackageName = installerPackageName; 10655 this.volumeUuid = volumeUuid; 10656 this.manifestDigest = manifestDigest; 10657 this.user = user; 10658 this.instructionSets = instructionSets; 10659 this.abiOverride = abiOverride; 10660 } 10661 10662 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10663 abstract int doPreInstall(int status); 10664 10665 /** 10666 * Rename package into final resting place. All paths on the given 10667 * scanned package should be updated to reflect the rename. 10668 */ 10669 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10670 abstract int doPostInstall(int status, int uid); 10671 10672 /** @see PackageSettingBase#codePathString */ 10673 abstract String getCodePath(); 10674 /** @see PackageSettingBase#resourcePathString */ 10675 abstract String getResourcePath(); 10676 10677 // Need installer lock especially for dex file removal. 10678 abstract void cleanUpResourcesLI(); 10679 abstract boolean doPostDeleteLI(boolean delete); 10680 10681 /** 10682 * Called before the source arguments are copied. This is used mostly 10683 * for MoveParams when it needs to read the source file to put it in the 10684 * destination. 10685 */ 10686 int doPreCopy() { 10687 return PackageManager.INSTALL_SUCCEEDED; 10688 } 10689 10690 /** 10691 * Called after the source arguments are copied. This is used mostly for 10692 * MoveParams when it needs to read the source file to put it in the 10693 * destination. 10694 * 10695 * @return 10696 */ 10697 int doPostCopy(int uid) { 10698 return PackageManager.INSTALL_SUCCEEDED; 10699 } 10700 10701 protected boolean isFwdLocked() { 10702 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10703 } 10704 10705 protected boolean isExternalAsec() { 10706 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10707 } 10708 10709 UserHandle getUser() { 10710 return user; 10711 } 10712 } 10713 10714 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10715 if (!allCodePaths.isEmpty()) { 10716 if (instructionSets == null) { 10717 throw new IllegalStateException("instructionSet == null"); 10718 } 10719 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10720 for (String codePath : allCodePaths) { 10721 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10722 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10723 if (retCode < 0) { 10724 Slog.w(TAG, "Couldn't remove dex file for package: " 10725 + " at location " + codePath + ", retcode=" + retCode); 10726 // we don't consider this to be a failure of the core package deletion 10727 } 10728 } 10729 } 10730 } 10731 } 10732 10733 /** 10734 * Logic to handle installation of non-ASEC applications, including copying 10735 * and renaming logic. 10736 */ 10737 class FileInstallArgs extends InstallArgs { 10738 private File codeFile; 10739 private File resourceFile; 10740 10741 // Example topology: 10742 // /data/app/com.example/base.apk 10743 // /data/app/com.example/split_foo.apk 10744 // /data/app/com.example/lib/arm/libfoo.so 10745 // /data/app/com.example/lib/arm64/libfoo.so 10746 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10747 10748 /** New install */ 10749 FileInstallArgs(InstallParams params) { 10750 super(params.origin, params.move, params.observer, params.installFlags, 10751 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10752 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10753 if (isFwdLocked()) { 10754 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10755 } 10756 } 10757 10758 /** Existing install */ 10759 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10760 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10761 null); 10762 this.codeFile = (codePath != null) ? new File(codePath) : null; 10763 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10764 } 10765 10766 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10767 if (origin.staged) { 10768 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10769 codeFile = origin.file; 10770 resourceFile = origin.file; 10771 return PackageManager.INSTALL_SUCCEEDED; 10772 } 10773 10774 try { 10775 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10776 codeFile = tempDir; 10777 resourceFile = tempDir; 10778 } catch (IOException e) { 10779 Slog.w(TAG, "Failed to create copy file: " + e); 10780 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10781 } 10782 10783 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10784 @Override 10785 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10786 if (!FileUtils.isValidExtFilename(name)) { 10787 throw new IllegalArgumentException("Invalid filename: " + name); 10788 } 10789 try { 10790 final File file = new File(codeFile, name); 10791 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10792 O_RDWR | O_CREAT, 0644); 10793 Os.chmod(file.getAbsolutePath(), 0644); 10794 return new ParcelFileDescriptor(fd); 10795 } catch (ErrnoException e) { 10796 throw new RemoteException("Failed to open: " + e.getMessage()); 10797 } 10798 } 10799 }; 10800 10801 int ret = PackageManager.INSTALL_SUCCEEDED; 10802 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10803 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10804 Slog.e(TAG, "Failed to copy package"); 10805 return ret; 10806 } 10807 10808 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10809 NativeLibraryHelper.Handle handle = null; 10810 try { 10811 handle = NativeLibraryHelper.Handle.create(codeFile); 10812 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10813 abiOverride); 10814 } catch (IOException e) { 10815 Slog.e(TAG, "Copying native libraries failed", e); 10816 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10817 } finally { 10818 IoUtils.closeQuietly(handle); 10819 } 10820 10821 return ret; 10822 } 10823 10824 int doPreInstall(int status) { 10825 if (status != PackageManager.INSTALL_SUCCEEDED) { 10826 cleanUp(); 10827 } 10828 return status; 10829 } 10830 10831 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10832 if (status != PackageManager.INSTALL_SUCCEEDED) { 10833 cleanUp(); 10834 return false; 10835 } 10836 10837 final File targetDir = codeFile.getParentFile(); 10838 final File beforeCodeFile = codeFile; 10839 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10840 10841 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10842 try { 10843 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10844 } catch (ErrnoException e) { 10845 Slog.w(TAG, "Failed to rename", e); 10846 return false; 10847 } 10848 10849 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10850 Slog.w(TAG, "Failed to restorecon"); 10851 return false; 10852 } 10853 10854 // Reflect the rename internally 10855 codeFile = afterCodeFile; 10856 resourceFile = afterCodeFile; 10857 10858 // Reflect the rename in scanned details 10859 pkg.codePath = afterCodeFile.getAbsolutePath(); 10860 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10861 pkg.baseCodePath); 10862 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10863 pkg.splitCodePaths); 10864 10865 // Reflect the rename in app info 10866 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10867 pkg.applicationInfo.setCodePath(pkg.codePath); 10868 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10869 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10870 pkg.applicationInfo.setResourcePath(pkg.codePath); 10871 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10872 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10873 10874 return true; 10875 } 10876 10877 int doPostInstall(int status, int uid) { 10878 if (status != PackageManager.INSTALL_SUCCEEDED) { 10879 cleanUp(); 10880 } 10881 return status; 10882 } 10883 10884 @Override 10885 String getCodePath() { 10886 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10887 } 10888 10889 @Override 10890 String getResourcePath() { 10891 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10892 } 10893 10894 private boolean cleanUp() { 10895 if (codeFile == null || !codeFile.exists()) { 10896 return false; 10897 } 10898 10899 if (codeFile.isDirectory()) { 10900 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10901 } else { 10902 codeFile.delete(); 10903 } 10904 10905 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10906 resourceFile.delete(); 10907 } 10908 10909 return true; 10910 } 10911 10912 void cleanUpResourcesLI() { 10913 // Try enumerating all code paths before deleting 10914 List<String> allCodePaths = Collections.EMPTY_LIST; 10915 if (codeFile != null && codeFile.exists()) { 10916 try { 10917 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10918 allCodePaths = pkg.getAllCodePaths(); 10919 } catch (PackageParserException e) { 10920 // Ignored; we tried our best 10921 } 10922 } 10923 10924 cleanUp(); 10925 removeDexFiles(allCodePaths, instructionSets); 10926 } 10927 10928 boolean doPostDeleteLI(boolean delete) { 10929 // XXX err, shouldn't we respect the delete flag? 10930 cleanUpResourcesLI(); 10931 return true; 10932 } 10933 } 10934 10935 private boolean isAsecExternal(String cid) { 10936 final String asecPath = PackageHelper.getSdFilesystem(cid); 10937 return !asecPath.startsWith(mAsecInternalPath); 10938 } 10939 10940 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10941 PackageManagerException { 10942 if (copyRet < 0) { 10943 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10944 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10945 throw new PackageManagerException(copyRet, message); 10946 } 10947 } 10948 } 10949 10950 /** 10951 * Extract the MountService "container ID" from the full code path of an 10952 * .apk. 10953 */ 10954 static String cidFromCodePath(String fullCodePath) { 10955 int eidx = fullCodePath.lastIndexOf("/"); 10956 String subStr1 = fullCodePath.substring(0, eidx); 10957 int sidx = subStr1.lastIndexOf("/"); 10958 return subStr1.substring(sidx+1, eidx); 10959 } 10960 10961 /** 10962 * Logic to handle installation of ASEC applications, including copying and 10963 * renaming logic. 10964 */ 10965 class AsecInstallArgs extends InstallArgs { 10966 static final String RES_FILE_NAME = "pkg.apk"; 10967 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10968 10969 String cid; 10970 String packagePath; 10971 String resourcePath; 10972 10973 /** New install */ 10974 AsecInstallArgs(InstallParams params) { 10975 super(params.origin, params.move, params.observer, params.installFlags, 10976 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10977 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10978 } 10979 10980 /** Existing install */ 10981 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10982 boolean isExternal, boolean isForwardLocked) { 10983 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10984 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10985 instructionSets, null); 10986 // Hackily pretend we're still looking at a full code path 10987 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10988 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10989 } 10990 10991 // Extract cid from fullCodePath 10992 int eidx = fullCodePath.lastIndexOf("/"); 10993 String subStr1 = fullCodePath.substring(0, eidx); 10994 int sidx = subStr1.lastIndexOf("/"); 10995 cid = subStr1.substring(sidx+1, eidx); 10996 setMountPath(subStr1); 10997 } 10998 10999 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11000 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11001 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11002 instructionSets, null); 11003 this.cid = cid; 11004 setMountPath(PackageHelper.getSdDir(cid)); 11005 } 11006 11007 void createCopyFile() { 11008 cid = mInstallerService.allocateExternalStageCidLegacy(); 11009 } 11010 11011 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11012 if (origin.staged) { 11013 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11014 cid = origin.cid; 11015 setMountPath(PackageHelper.getSdDir(cid)); 11016 return PackageManager.INSTALL_SUCCEEDED; 11017 } 11018 11019 if (temp) { 11020 createCopyFile(); 11021 } else { 11022 /* 11023 * Pre-emptively destroy the container since it's destroyed if 11024 * copying fails due to it existing anyway. 11025 */ 11026 PackageHelper.destroySdDir(cid); 11027 } 11028 11029 final String newMountPath = imcs.copyPackageToContainer( 11030 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11031 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11032 11033 if (newMountPath != null) { 11034 setMountPath(newMountPath); 11035 return PackageManager.INSTALL_SUCCEEDED; 11036 } else { 11037 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11038 } 11039 } 11040 11041 @Override 11042 String getCodePath() { 11043 return packagePath; 11044 } 11045 11046 @Override 11047 String getResourcePath() { 11048 return resourcePath; 11049 } 11050 11051 int doPreInstall(int status) { 11052 if (status != PackageManager.INSTALL_SUCCEEDED) { 11053 // Destroy container 11054 PackageHelper.destroySdDir(cid); 11055 } else { 11056 boolean mounted = PackageHelper.isContainerMounted(cid); 11057 if (!mounted) { 11058 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11059 Process.SYSTEM_UID); 11060 if (newMountPath != null) { 11061 setMountPath(newMountPath); 11062 } else { 11063 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11064 } 11065 } 11066 } 11067 return status; 11068 } 11069 11070 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11071 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11072 String newMountPath = null; 11073 if (PackageHelper.isContainerMounted(cid)) { 11074 // Unmount the container 11075 if (!PackageHelper.unMountSdDir(cid)) { 11076 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11077 return false; 11078 } 11079 } 11080 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11081 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11082 " which might be stale. Will try to clean up."); 11083 // Clean up the stale container and proceed to recreate. 11084 if (!PackageHelper.destroySdDir(newCacheId)) { 11085 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11086 return false; 11087 } 11088 // Successfully cleaned up stale container. Try to rename again. 11089 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11090 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11091 + " inspite of cleaning it up."); 11092 return false; 11093 } 11094 } 11095 if (!PackageHelper.isContainerMounted(newCacheId)) { 11096 Slog.w(TAG, "Mounting container " + newCacheId); 11097 newMountPath = PackageHelper.mountSdDir(newCacheId, 11098 getEncryptKey(), Process.SYSTEM_UID); 11099 } else { 11100 newMountPath = PackageHelper.getSdDir(newCacheId); 11101 } 11102 if (newMountPath == null) { 11103 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11104 return false; 11105 } 11106 Log.i(TAG, "Succesfully renamed " + cid + 11107 " to " + newCacheId + 11108 " at new path: " + newMountPath); 11109 cid = newCacheId; 11110 11111 final File beforeCodeFile = new File(packagePath); 11112 setMountPath(newMountPath); 11113 final File afterCodeFile = new File(packagePath); 11114 11115 // Reflect the rename in scanned details 11116 pkg.codePath = afterCodeFile.getAbsolutePath(); 11117 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11118 pkg.baseCodePath); 11119 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11120 pkg.splitCodePaths); 11121 11122 // Reflect the rename in app info 11123 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11124 pkg.applicationInfo.setCodePath(pkg.codePath); 11125 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11126 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11127 pkg.applicationInfo.setResourcePath(pkg.codePath); 11128 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11129 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11130 11131 return true; 11132 } 11133 11134 private void setMountPath(String mountPath) { 11135 final File mountFile = new File(mountPath); 11136 11137 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11138 if (monolithicFile.exists()) { 11139 packagePath = monolithicFile.getAbsolutePath(); 11140 if (isFwdLocked()) { 11141 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11142 } else { 11143 resourcePath = packagePath; 11144 } 11145 } else { 11146 packagePath = mountFile.getAbsolutePath(); 11147 resourcePath = packagePath; 11148 } 11149 } 11150 11151 int doPostInstall(int status, int uid) { 11152 if (status != PackageManager.INSTALL_SUCCEEDED) { 11153 cleanUp(); 11154 } else { 11155 final int groupOwner; 11156 final String protectedFile; 11157 if (isFwdLocked()) { 11158 groupOwner = UserHandle.getSharedAppGid(uid); 11159 protectedFile = RES_FILE_NAME; 11160 } else { 11161 groupOwner = -1; 11162 protectedFile = null; 11163 } 11164 11165 if (uid < Process.FIRST_APPLICATION_UID 11166 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11167 Slog.e(TAG, "Failed to finalize " + cid); 11168 PackageHelper.destroySdDir(cid); 11169 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11170 } 11171 11172 boolean mounted = PackageHelper.isContainerMounted(cid); 11173 if (!mounted) { 11174 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11175 } 11176 } 11177 return status; 11178 } 11179 11180 private void cleanUp() { 11181 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11182 11183 // Destroy secure container 11184 PackageHelper.destroySdDir(cid); 11185 } 11186 11187 private List<String> getAllCodePaths() { 11188 final File codeFile = new File(getCodePath()); 11189 if (codeFile != null && codeFile.exists()) { 11190 try { 11191 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11192 return pkg.getAllCodePaths(); 11193 } catch (PackageParserException e) { 11194 // Ignored; we tried our best 11195 } 11196 } 11197 return Collections.EMPTY_LIST; 11198 } 11199 11200 void cleanUpResourcesLI() { 11201 // Enumerate all code paths before deleting 11202 cleanUpResourcesLI(getAllCodePaths()); 11203 } 11204 11205 private void cleanUpResourcesLI(List<String> allCodePaths) { 11206 cleanUp(); 11207 removeDexFiles(allCodePaths, instructionSets); 11208 } 11209 11210 String getPackageName() { 11211 return getAsecPackageName(cid); 11212 } 11213 11214 boolean doPostDeleteLI(boolean delete) { 11215 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11216 final List<String> allCodePaths = getAllCodePaths(); 11217 boolean mounted = PackageHelper.isContainerMounted(cid); 11218 if (mounted) { 11219 // Unmount first 11220 if (PackageHelper.unMountSdDir(cid)) { 11221 mounted = false; 11222 } 11223 } 11224 if (!mounted && delete) { 11225 cleanUpResourcesLI(allCodePaths); 11226 } 11227 return !mounted; 11228 } 11229 11230 @Override 11231 int doPreCopy() { 11232 if (isFwdLocked()) { 11233 if (!PackageHelper.fixSdPermissions(cid, 11234 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11235 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11236 } 11237 } 11238 11239 return PackageManager.INSTALL_SUCCEEDED; 11240 } 11241 11242 @Override 11243 int doPostCopy(int uid) { 11244 if (isFwdLocked()) { 11245 if (uid < Process.FIRST_APPLICATION_UID 11246 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11247 RES_FILE_NAME)) { 11248 Slog.e(TAG, "Failed to finalize " + cid); 11249 PackageHelper.destroySdDir(cid); 11250 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11251 } 11252 } 11253 11254 return PackageManager.INSTALL_SUCCEEDED; 11255 } 11256 } 11257 11258 /** 11259 * Logic to handle movement of existing installed applications. 11260 */ 11261 class MoveInstallArgs extends InstallArgs { 11262 private File codeFile; 11263 private File resourceFile; 11264 11265 /** New install */ 11266 MoveInstallArgs(InstallParams params) { 11267 super(params.origin, params.move, params.observer, params.installFlags, 11268 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11269 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11270 } 11271 11272 int copyApk(IMediaContainerService imcs, boolean temp) { 11273 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11274 + move.fromUuid + " to " + move.toUuid); 11275 synchronized (mInstaller) { 11276 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11277 move.dataAppName, move.appId, move.seinfo) != 0) { 11278 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11279 } 11280 } 11281 11282 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11283 resourceFile = codeFile; 11284 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11285 11286 return PackageManager.INSTALL_SUCCEEDED; 11287 } 11288 11289 int doPreInstall(int status) { 11290 if (status != PackageManager.INSTALL_SUCCEEDED) { 11291 cleanUp(); 11292 } 11293 return status; 11294 } 11295 11296 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11297 if (status != PackageManager.INSTALL_SUCCEEDED) { 11298 cleanUp(); 11299 return false; 11300 } 11301 11302 // Reflect the move in app info 11303 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11304 pkg.applicationInfo.setCodePath(pkg.codePath); 11305 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11306 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11307 pkg.applicationInfo.setResourcePath(pkg.codePath); 11308 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11309 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11310 11311 return true; 11312 } 11313 11314 int doPostInstall(int status, int uid) { 11315 if (status != PackageManager.INSTALL_SUCCEEDED) { 11316 cleanUp(); 11317 } 11318 return status; 11319 } 11320 11321 @Override 11322 String getCodePath() { 11323 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11324 } 11325 11326 @Override 11327 String getResourcePath() { 11328 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11329 } 11330 11331 private boolean cleanUp() { 11332 if (codeFile == null || !codeFile.exists()) { 11333 return false; 11334 } 11335 11336 if (codeFile.isDirectory()) { 11337 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11338 } else { 11339 codeFile.delete(); 11340 } 11341 11342 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11343 resourceFile.delete(); 11344 } 11345 11346 return true; 11347 } 11348 11349 void cleanUpResourcesLI() { 11350 cleanUp(); 11351 } 11352 11353 boolean doPostDeleteLI(boolean delete) { 11354 // XXX err, shouldn't we respect the delete flag? 11355 cleanUpResourcesLI(); 11356 return true; 11357 } 11358 } 11359 11360 static String getAsecPackageName(String packageCid) { 11361 int idx = packageCid.lastIndexOf("-"); 11362 if (idx == -1) { 11363 return packageCid; 11364 } 11365 return packageCid.substring(0, idx); 11366 } 11367 11368 // Utility method used to create code paths based on package name and available index. 11369 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11370 String idxStr = ""; 11371 int idx = 1; 11372 // Fall back to default value of idx=1 if prefix is not 11373 // part of oldCodePath 11374 if (oldCodePath != null) { 11375 String subStr = oldCodePath; 11376 // Drop the suffix right away 11377 if (suffix != null && subStr.endsWith(suffix)) { 11378 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11379 } 11380 // If oldCodePath already contains prefix find out the 11381 // ending index to either increment or decrement. 11382 int sidx = subStr.lastIndexOf(prefix); 11383 if (sidx != -1) { 11384 subStr = subStr.substring(sidx + prefix.length()); 11385 if (subStr != null) { 11386 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11387 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11388 } 11389 try { 11390 idx = Integer.parseInt(subStr); 11391 if (idx <= 1) { 11392 idx++; 11393 } else { 11394 idx--; 11395 } 11396 } catch(NumberFormatException e) { 11397 } 11398 } 11399 } 11400 } 11401 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11402 return prefix + idxStr; 11403 } 11404 11405 private File getNextCodePath(File targetDir, String packageName) { 11406 int suffix = 1; 11407 File result; 11408 do { 11409 result = new File(targetDir, packageName + "-" + suffix); 11410 suffix++; 11411 } while (result.exists()); 11412 return result; 11413 } 11414 11415 // Utility method that returns the relative package path with respect 11416 // to the installation directory. Like say for /data/data/com.test-1.apk 11417 // string com.test-1 is returned. 11418 static String deriveCodePathName(String codePath) { 11419 if (codePath == null) { 11420 return null; 11421 } 11422 final File codeFile = new File(codePath); 11423 final String name = codeFile.getName(); 11424 if (codeFile.isDirectory()) { 11425 return name; 11426 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11427 final int lastDot = name.lastIndexOf('.'); 11428 return name.substring(0, lastDot); 11429 } else { 11430 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11431 return null; 11432 } 11433 } 11434 11435 class PackageInstalledInfo { 11436 String name; 11437 int uid; 11438 // The set of users that originally had this package installed. 11439 int[] origUsers; 11440 // The set of users that now have this package installed. 11441 int[] newUsers; 11442 PackageParser.Package pkg; 11443 int returnCode; 11444 String returnMsg; 11445 PackageRemovedInfo removedInfo; 11446 11447 public void setError(int code, String msg) { 11448 returnCode = code; 11449 returnMsg = msg; 11450 Slog.w(TAG, msg); 11451 } 11452 11453 public void setError(String msg, PackageParserException e) { 11454 returnCode = e.error; 11455 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11456 Slog.w(TAG, msg, e); 11457 } 11458 11459 public void setError(String msg, PackageManagerException e) { 11460 returnCode = e.error; 11461 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11462 Slog.w(TAG, msg, e); 11463 } 11464 11465 // In some error cases we want to convey more info back to the observer 11466 String origPackage; 11467 String origPermission; 11468 } 11469 11470 /* 11471 * Install a non-existing package. 11472 */ 11473 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11474 UserHandle user, String installerPackageName, String volumeUuid, 11475 PackageInstalledInfo res) { 11476 // Remember this for later, in case we need to rollback this install 11477 String pkgName = pkg.packageName; 11478 11479 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11480 final boolean dataDirExists = Environment 11481 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11482 synchronized(mPackages) { 11483 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11484 // A package with the same name is already installed, though 11485 // it has been renamed to an older name. The package we 11486 // are trying to install should be installed as an update to 11487 // the existing one, but that has not been requested, so bail. 11488 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11489 + " without first uninstalling package running as " 11490 + mSettings.mRenamedPackages.get(pkgName)); 11491 return; 11492 } 11493 if (mPackages.containsKey(pkgName)) { 11494 // Don't allow installation over an existing package with the same name. 11495 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11496 + " without first uninstalling."); 11497 return; 11498 } 11499 } 11500 11501 try { 11502 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11503 System.currentTimeMillis(), user); 11504 11505 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11506 // delete the partially installed application. the data directory will have to be 11507 // restored if it was already existing 11508 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11509 // remove package from internal structures. Note that we want deletePackageX to 11510 // delete the package data and cache directories that it created in 11511 // scanPackageLocked, unless those directories existed before we even tried to 11512 // install. 11513 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11514 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11515 res.removedInfo, true); 11516 } 11517 11518 } catch (PackageManagerException e) { 11519 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11520 } 11521 } 11522 11523 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11524 // Can't rotate keys during boot or if sharedUser. 11525 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11526 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11527 return false; 11528 } 11529 // app is using upgradeKeySets; make sure all are valid 11530 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11531 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11532 for (int i = 0; i < upgradeKeySets.length; i++) { 11533 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11534 Slog.wtf(TAG, "Package " 11535 + (oldPs.name != null ? oldPs.name : "<null>") 11536 + " contains upgrade-key-set reference to unknown key-set: " 11537 + upgradeKeySets[i] 11538 + " reverting to signatures check."); 11539 return false; 11540 } 11541 } 11542 return true; 11543 } 11544 11545 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11546 // Upgrade keysets are being used. Determine if new package has a superset of the 11547 // required keys. 11548 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11549 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11550 for (int i = 0; i < upgradeKeySets.length; i++) { 11551 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11552 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11553 return true; 11554 } 11555 } 11556 return false; 11557 } 11558 11559 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11560 UserHandle user, String installerPackageName, String volumeUuid, 11561 PackageInstalledInfo res) { 11562 final PackageParser.Package oldPackage; 11563 final String pkgName = pkg.packageName; 11564 final int[] allUsers; 11565 final boolean[] perUserInstalled; 11566 final boolean weFroze; 11567 11568 // First find the old package info and check signatures 11569 synchronized(mPackages) { 11570 oldPackage = mPackages.get(pkgName); 11571 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11572 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11573 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11574 if(!checkUpgradeKeySetLP(ps, pkg)) { 11575 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11576 "New package not signed by keys specified by upgrade-keysets: " 11577 + pkgName); 11578 return; 11579 } 11580 } else { 11581 // default to original signature matching 11582 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11583 != PackageManager.SIGNATURE_MATCH) { 11584 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11585 "New package has a different signature: " + pkgName); 11586 return; 11587 } 11588 } 11589 11590 // In case of rollback, remember per-user/profile install state 11591 allUsers = sUserManager.getUserIds(); 11592 perUserInstalled = new boolean[allUsers.length]; 11593 for (int i = 0; i < allUsers.length; i++) { 11594 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11595 } 11596 11597 // Mark the app as frozen to prevent launching during the upgrade 11598 // process, and then kill all running instances 11599 if (!ps.frozen) { 11600 ps.frozen = true; 11601 weFroze = true; 11602 } else { 11603 weFroze = false; 11604 } 11605 } 11606 11607 // Now that we're guarded by frozen state, kill app during upgrade 11608 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11609 11610 try { 11611 boolean sysPkg = (isSystemApp(oldPackage)); 11612 if (sysPkg) { 11613 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11614 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11615 } else { 11616 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11617 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11618 } 11619 } finally { 11620 // Regardless of success or failure of upgrade steps above, always 11621 // unfreeze the package if we froze it 11622 if (weFroze) { 11623 unfreezePackage(pkgName); 11624 } 11625 } 11626 } 11627 11628 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11629 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11630 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11631 String volumeUuid, PackageInstalledInfo res) { 11632 String pkgName = deletedPackage.packageName; 11633 boolean deletedPkg = true; 11634 boolean updatedSettings = false; 11635 11636 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11637 + deletedPackage); 11638 long origUpdateTime; 11639 if (pkg.mExtras != null) { 11640 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11641 } else { 11642 origUpdateTime = 0; 11643 } 11644 11645 // First delete the existing package while retaining the data directory 11646 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11647 res.removedInfo, true)) { 11648 // If the existing package wasn't successfully deleted 11649 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11650 deletedPkg = false; 11651 } else { 11652 // Successfully deleted the old package; proceed with replace. 11653 11654 // If deleted package lived in a container, give users a chance to 11655 // relinquish resources before killing. 11656 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11657 if (DEBUG_INSTALL) { 11658 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11659 } 11660 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11661 final ArrayList<String> pkgList = new ArrayList<String>(1); 11662 pkgList.add(deletedPackage.applicationInfo.packageName); 11663 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11664 } 11665 11666 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11667 try { 11668 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11669 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11670 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11671 perUserInstalled, res, user); 11672 updatedSettings = true; 11673 } catch (PackageManagerException e) { 11674 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11675 } 11676 } 11677 11678 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11679 // remove package from internal structures. Note that we want deletePackageX to 11680 // delete the package data and cache directories that it created in 11681 // scanPackageLocked, unless those directories existed before we even tried to 11682 // install. 11683 if(updatedSettings) { 11684 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11685 deletePackageLI( 11686 pkgName, null, true, allUsers, perUserInstalled, 11687 PackageManager.DELETE_KEEP_DATA, 11688 res.removedInfo, true); 11689 } 11690 // Since we failed to install the new package we need to restore the old 11691 // package that we deleted. 11692 if (deletedPkg) { 11693 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11694 File restoreFile = new File(deletedPackage.codePath); 11695 // Parse old package 11696 boolean oldExternal = isExternal(deletedPackage); 11697 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11698 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11699 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11700 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11701 try { 11702 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11703 } catch (PackageManagerException e) { 11704 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11705 + e.getMessage()); 11706 return; 11707 } 11708 // Restore of old package succeeded. Update permissions. 11709 // writer 11710 synchronized (mPackages) { 11711 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11712 UPDATE_PERMISSIONS_ALL); 11713 // can downgrade to reader 11714 mSettings.writeLPr(); 11715 } 11716 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11717 } 11718 } 11719 } 11720 11721 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11722 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11723 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11724 String volumeUuid, PackageInstalledInfo res) { 11725 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11726 + ", old=" + deletedPackage); 11727 boolean disabledSystem = false; 11728 boolean updatedSettings = false; 11729 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11730 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11731 != 0) { 11732 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11733 } 11734 String packageName = deletedPackage.packageName; 11735 if (packageName == null) { 11736 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11737 "Attempt to delete null packageName."); 11738 return; 11739 } 11740 PackageParser.Package oldPkg; 11741 PackageSetting oldPkgSetting; 11742 // reader 11743 synchronized (mPackages) { 11744 oldPkg = mPackages.get(packageName); 11745 oldPkgSetting = mSettings.mPackages.get(packageName); 11746 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11747 (oldPkgSetting == null)) { 11748 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11749 "Couldn't find package:" + packageName + " information"); 11750 return; 11751 } 11752 } 11753 11754 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11755 res.removedInfo.removedPackage = packageName; 11756 // Remove existing system package 11757 removePackageLI(oldPkgSetting, true); 11758 // writer 11759 synchronized (mPackages) { 11760 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11761 if (!disabledSystem && deletedPackage != null) { 11762 // We didn't need to disable the .apk as a current system package, 11763 // which means we are replacing another update that is already 11764 // installed. We need to make sure to delete the older one's .apk. 11765 res.removedInfo.args = createInstallArgsForExisting(0, 11766 deletedPackage.applicationInfo.getCodePath(), 11767 deletedPackage.applicationInfo.getResourcePath(), 11768 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11769 } else { 11770 res.removedInfo.args = null; 11771 } 11772 } 11773 11774 // Successfully disabled the old package. Now proceed with re-installation 11775 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11776 11777 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11778 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11779 11780 PackageParser.Package newPackage = null; 11781 try { 11782 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11783 if (newPackage.mExtras != null) { 11784 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11785 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11786 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11787 11788 // is the update attempting to change shared user? that isn't going to work... 11789 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11790 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11791 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11792 + " to " + newPkgSetting.sharedUser); 11793 updatedSettings = true; 11794 } 11795 } 11796 11797 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11798 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11799 perUserInstalled, res, user); 11800 updatedSettings = true; 11801 } 11802 11803 } catch (PackageManagerException e) { 11804 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11805 } 11806 11807 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11808 // Re installation failed. Restore old information 11809 // Remove new pkg information 11810 if (newPackage != null) { 11811 removeInstalledPackageLI(newPackage, true); 11812 } 11813 // Add back the old system package 11814 try { 11815 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11816 } catch (PackageManagerException e) { 11817 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11818 } 11819 // Restore the old system information in Settings 11820 synchronized (mPackages) { 11821 if (disabledSystem) { 11822 mSettings.enableSystemPackageLPw(packageName); 11823 } 11824 if (updatedSettings) { 11825 mSettings.setInstallerPackageName(packageName, 11826 oldPkgSetting.installerPackageName); 11827 } 11828 mSettings.writeLPr(); 11829 } 11830 } 11831 } 11832 11833 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11834 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11835 UserHandle user) { 11836 String pkgName = newPackage.packageName; 11837 synchronized (mPackages) { 11838 //write settings. the installStatus will be incomplete at this stage. 11839 //note that the new package setting would have already been 11840 //added to mPackages. It hasn't been persisted yet. 11841 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11842 mSettings.writeLPr(); 11843 } 11844 11845 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11846 11847 synchronized (mPackages) { 11848 updatePermissionsLPw(newPackage.packageName, newPackage, 11849 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11850 ? UPDATE_PERMISSIONS_ALL : 0)); 11851 // For system-bundled packages, we assume that installing an upgraded version 11852 // of the package implies that the user actually wants to run that new code, 11853 // so we enable the package. 11854 PackageSetting ps = mSettings.mPackages.get(pkgName); 11855 if (ps != null) { 11856 if (isSystemApp(newPackage)) { 11857 // NB: implicit assumption that system package upgrades apply to all users 11858 if (DEBUG_INSTALL) { 11859 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11860 } 11861 if (res.origUsers != null) { 11862 for (int userHandle : res.origUsers) { 11863 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11864 userHandle, installerPackageName); 11865 } 11866 } 11867 // Also convey the prior install/uninstall state 11868 if (allUsers != null && perUserInstalled != null) { 11869 for (int i = 0; i < allUsers.length; i++) { 11870 if (DEBUG_INSTALL) { 11871 Slog.d(TAG, " user " + allUsers[i] 11872 + " => " + perUserInstalled[i]); 11873 } 11874 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11875 } 11876 // these install state changes will be persisted in the 11877 // upcoming call to mSettings.writeLPr(). 11878 } 11879 } 11880 // It's implied that when a user requests installation, they want the app to be 11881 // installed and enabled. 11882 int userId = user.getIdentifier(); 11883 if (userId != UserHandle.USER_ALL) { 11884 ps.setInstalled(true, userId); 11885 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11886 } 11887 } 11888 res.name = pkgName; 11889 res.uid = newPackage.applicationInfo.uid; 11890 res.pkg = newPackage; 11891 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11892 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11893 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11894 //to update install status 11895 mSettings.writeLPr(); 11896 } 11897 } 11898 11899 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11900 final int installFlags = args.installFlags; 11901 final String installerPackageName = args.installerPackageName; 11902 final String volumeUuid = args.volumeUuid; 11903 final File tmpPackageFile = new File(args.getCodePath()); 11904 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11905 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11906 || (args.volumeUuid != null)); 11907 boolean replace = false; 11908 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11909 if (args.move != null) { 11910 // moving a complete application; perfom an initial scan on the new install location 11911 scanFlags |= SCAN_INITIAL; 11912 } 11913 // Result object to be returned 11914 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11915 11916 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11917 // Retrieve PackageSettings and parse package 11918 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11919 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11920 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11921 PackageParser pp = new PackageParser(); 11922 pp.setSeparateProcesses(mSeparateProcesses); 11923 pp.setDisplayMetrics(mMetrics); 11924 11925 final PackageParser.Package pkg; 11926 try { 11927 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11928 } catch (PackageParserException e) { 11929 res.setError("Failed parse during installPackageLI", e); 11930 return; 11931 } 11932 11933 // Mark that we have an install time CPU ABI override. 11934 pkg.cpuAbiOverride = args.abiOverride; 11935 11936 String pkgName = res.name = pkg.packageName; 11937 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11938 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11939 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11940 return; 11941 } 11942 } 11943 11944 try { 11945 pp.collectCertificates(pkg, parseFlags); 11946 pp.collectManifestDigest(pkg); 11947 } catch (PackageParserException e) { 11948 res.setError("Failed collect during installPackageLI", e); 11949 return; 11950 } 11951 11952 /* If the installer passed in a manifest digest, compare it now. */ 11953 if (args.manifestDigest != null) { 11954 if (DEBUG_INSTALL) { 11955 final String parsedManifest = pkg.manifestDigest == null ? "null" 11956 : pkg.manifestDigest.toString(); 11957 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11958 + parsedManifest); 11959 } 11960 11961 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11962 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11963 return; 11964 } 11965 } else if (DEBUG_INSTALL) { 11966 final String parsedManifest = pkg.manifestDigest == null 11967 ? "null" : pkg.manifestDigest.toString(); 11968 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11969 } 11970 11971 // Get rid of all references to package scan path via parser. 11972 pp = null; 11973 String oldCodePath = null; 11974 boolean systemApp = false; 11975 synchronized (mPackages) { 11976 // Check if installing already existing package 11977 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11978 String oldName = mSettings.mRenamedPackages.get(pkgName); 11979 if (pkg.mOriginalPackages != null 11980 && pkg.mOriginalPackages.contains(oldName) 11981 && mPackages.containsKey(oldName)) { 11982 // This package is derived from an original package, 11983 // and this device has been updating from that original 11984 // name. We must continue using the original name, so 11985 // rename the new package here. 11986 pkg.setPackageName(oldName); 11987 pkgName = pkg.packageName; 11988 replace = true; 11989 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11990 + oldName + " pkgName=" + pkgName); 11991 } else if (mPackages.containsKey(pkgName)) { 11992 // This package, under its official name, already exists 11993 // on the device; we should replace it. 11994 replace = true; 11995 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11996 } 11997 11998 // Prevent apps opting out from runtime permissions 11999 if (replace) { 12000 PackageParser.Package oldPackage = mPackages.get(pkgName); 12001 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12002 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12003 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12004 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12005 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12006 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12007 + " doesn't support runtime permissions but the old" 12008 + " target SDK " + oldTargetSdk + " does."); 12009 return; 12010 } 12011 } 12012 } 12013 12014 PackageSetting ps = mSettings.mPackages.get(pkgName); 12015 if (ps != null) { 12016 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12017 12018 // Quick sanity check that we're signed correctly if updating; 12019 // we'll check this again later when scanning, but we want to 12020 // bail early here before tripping over redefined permissions. 12021 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12022 if (!checkUpgradeKeySetLP(ps, pkg)) { 12023 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12024 + pkg.packageName + " upgrade keys do not match the " 12025 + "previously installed version"); 12026 return; 12027 } 12028 } else { 12029 try { 12030 verifySignaturesLP(ps, pkg); 12031 } catch (PackageManagerException e) { 12032 res.setError(e.error, e.getMessage()); 12033 return; 12034 } 12035 } 12036 12037 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12038 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12039 systemApp = (ps.pkg.applicationInfo.flags & 12040 ApplicationInfo.FLAG_SYSTEM) != 0; 12041 } 12042 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12043 } 12044 12045 // Check whether the newly-scanned package wants to define an already-defined perm 12046 int N = pkg.permissions.size(); 12047 for (int i = N-1; i >= 0; i--) { 12048 PackageParser.Permission perm = pkg.permissions.get(i); 12049 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12050 if (bp != null) { 12051 // If the defining package is signed with our cert, it's okay. This 12052 // also includes the "updating the same package" case, of course. 12053 // "updating same package" could also involve key-rotation. 12054 final boolean sigsOk; 12055 if (bp.sourcePackage.equals(pkg.packageName) 12056 && (bp.packageSetting instanceof PackageSetting) 12057 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12058 scanFlags))) { 12059 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12060 } else { 12061 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12062 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12063 } 12064 if (!sigsOk) { 12065 // If the owning package is the system itself, we log but allow 12066 // install to proceed; we fail the install on all other permission 12067 // redefinitions. 12068 if (!bp.sourcePackage.equals("android")) { 12069 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12070 + pkg.packageName + " attempting to redeclare permission " 12071 + perm.info.name + " already owned by " + bp.sourcePackage); 12072 res.origPermission = perm.info.name; 12073 res.origPackage = bp.sourcePackage; 12074 return; 12075 } else { 12076 Slog.w(TAG, "Package " + pkg.packageName 12077 + " attempting to redeclare system permission " 12078 + perm.info.name + "; ignoring new declaration"); 12079 pkg.permissions.remove(i); 12080 } 12081 } 12082 } 12083 } 12084 12085 } 12086 12087 if (systemApp && onExternal) { 12088 // Disable updates to system apps on sdcard 12089 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12090 "Cannot install updates to system apps on sdcard"); 12091 return; 12092 } 12093 12094 if (args.move != null) { 12095 // We did an in-place move, so dex is ready to roll 12096 scanFlags |= SCAN_NO_DEX; 12097 scanFlags |= SCAN_MOVE; 12098 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12099 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12100 scanFlags |= SCAN_NO_DEX; 12101 12102 try { 12103 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12104 true /* extract libs */); 12105 } catch (PackageManagerException pme) { 12106 Slog.e(TAG, "Error deriving application ABI", pme); 12107 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12108 return; 12109 } 12110 12111 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12112 int result = mPackageDexOptimizer 12113 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12114 false /* defer */, false /* inclDependencies */); 12115 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12116 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12117 return; 12118 } 12119 } 12120 12121 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12122 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12123 return; 12124 } 12125 12126 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12127 12128 if (replace) { 12129 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12130 installerPackageName, volumeUuid, res); 12131 } else { 12132 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12133 args.user, installerPackageName, volumeUuid, res); 12134 } 12135 synchronized (mPackages) { 12136 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12137 if (ps != null) { 12138 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12139 } 12140 } 12141 } 12142 12143 private void startIntentFilterVerifications(int userId, boolean replacing, 12144 PackageParser.Package pkg) { 12145 if (mIntentFilterVerifierComponent == null) { 12146 Slog.w(TAG, "No IntentFilter verification will not be done as " 12147 + "there is no IntentFilterVerifier available!"); 12148 return; 12149 } 12150 12151 final int verifierUid = getPackageUid( 12152 mIntentFilterVerifierComponent.getPackageName(), 12153 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12154 12155 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12156 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12157 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12158 mHandler.sendMessage(msg); 12159 } 12160 12161 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12162 PackageParser.Package pkg) { 12163 int size = pkg.activities.size(); 12164 if (size == 0) { 12165 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12166 "No activity, so no need to verify any IntentFilter!"); 12167 return; 12168 } 12169 12170 final boolean hasDomainURLs = hasDomainURLs(pkg); 12171 if (!hasDomainURLs) { 12172 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12173 "No domain URLs, so no need to verify any IntentFilter!"); 12174 return; 12175 } 12176 12177 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12178 + " if any IntentFilter from the " + size 12179 + " Activities needs verification ..."); 12180 12181 int count = 0; 12182 final String packageName = pkg.packageName; 12183 12184 synchronized (mPackages) { 12185 // If this is a new install and we see that we've already run verification for this 12186 // package, we have nothing to do: it means the state was restored from backup. 12187 if (!replacing) { 12188 IntentFilterVerificationInfo ivi = 12189 mSettings.getIntentFilterVerificationLPr(packageName); 12190 if (ivi != null) { 12191 if (DEBUG_DOMAIN_VERIFICATION) { 12192 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12193 + ivi.getStatusString()); 12194 } 12195 return; 12196 } 12197 } 12198 12199 // If any filters need to be verified, then all need to be. 12200 boolean needToVerify = false; 12201 for (PackageParser.Activity a : pkg.activities) { 12202 for (ActivityIntentInfo filter : a.intents) { 12203 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12204 if (DEBUG_DOMAIN_VERIFICATION) { 12205 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12206 } 12207 needToVerify = true; 12208 break; 12209 } 12210 } 12211 } 12212 12213 if (needToVerify) { 12214 final int verificationId = mIntentFilterVerificationToken++; 12215 for (PackageParser.Activity a : pkg.activities) { 12216 for (ActivityIntentInfo filter : a.intents) { 12217 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12218 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12219 "Verification needed for IntentFilter:" + filter.toString()); 12220 mIntentFilterVerifier.addOneIntentFilterVerification( 12221 verifierUid, userId, verificationId, filter, packageName); 12222 count++; 12223 } 12224 } 12225 } 12226 } 12227 } 12228 12229 if (count > 0) { 12230 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12231 + " IntentFilter verification" + (count > 1 ? "s" : "") 12232 + " for userId:" + userId); 12233 mIntentFilterVerifier.startVerifications(userId); 12234 } else { 12235 if (DEBUG_DOMAIN_VERIFICATION) { 12236 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12237 } 12238 } 12239 } 12240 12241 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12242 final ComponentName cn = filter.activity.getComponentName(); 12243 final String packageName = cn.getPackageName(); 12244 12245 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12246 packageName); 12247 if (ivi == null) { 12248 return true; 12249 } 12250 int status = ivi.getStatus(); 12251 switch (status) { 12252 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12253 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12254 return true; 12255 12256 default: 12257 // Nothing to do 12258 return false; 12259 } 12260 } 12261 12262 private static boolean isMultiArch(PackageSetting ps) { 12263 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12264 } 12265 12266 private static boolean isMultiArch(ApplicationInfo info) { 12267 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12268 } 12269 12270 private static boolean isExternal(PackageParser.Package pkg) { 12271 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12272 } 12273 12274 private static boolean isExternal(PackageSetting ps) { 12275 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12276 } 12277 12278 private static boolean isExternal(ApplicationInfo info) { 12279 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12280 } 12281 12282 private static boolean isSystemApp(PackageParser.Package pkg) { 12283 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12284 } 12285 12286 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12287 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12288 } 12289 12290 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12291 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12292 } 12293 12294 private static boolean isSystemApp(PackageSetting ps) { 12295 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12296 } 12297 12298 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12299 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12300 } 12301 12302 private int packageFlagsToInstallFlags(PackageSetting ps) { 12303 int installFlags = 0; 12304 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12305 // This existing package was an external ASEC install when we have 12306 // the external flag without a UUID 12307 installFlags |= PackageManager.INSTALL_EXTERNAL; 12308 } 12309 if (ps.isForwardLocked()) { 12310 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12311 } 12312 return installFlags; 12313 } 12314 12315 private void deleteTempPackageFiles() { 12316 final FilenameFilter filter = new FilenameFilter() { 12317 public boolean accept(File dir, String name) { 12318 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12319 } 12320 }; 12321 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12322 file.delete(); 12323 } 12324 } 12325 12326 @Override 12327 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12328 int flags) { 12329 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12330 flags); 12331 } 12332 12333 @Override 12334 public void deletePackage(final String packageName, 12335 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12336 mContext.enforceCallingOrSelfPermission( 12337 android.Manifest.permission.DELETE_PACKAGES, null); 12338 Preconditions.checkNotNull(packageName); 12339 Preconditions.checkNotNull(observer); 12340 final int uid = Binder.getCallingUid(); 12341 if (UserHandle.getUserId(uid) != userId) { 12342 mContext.enforceCallingPermission( 12343 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12344 "deletePackage for user " + userId); 12345 } 12346 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12347 try { 12348 observer.onPackageDeleted(packageName, 12349 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12350 } catch (RemoteException re) { 12351 } 12352 return; 12353 } 12354 12355 boolean uninstallBlocked = false; 12356 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12357 int[] users = sUserManager.getUserIds(); 12358 for (int i = 0; i < users.length; ++i) { 12359 if (getBlockUninstallForUser(packageName, users[i])) { 12360 uninstallBlocked = true; 12361 break; 12362 } 12363 } 12364 } else { 12365 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12366 } 12367 if (uninstallBlocked) { 12368 try { 12369 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12370 null); 12371 } catch (RemoteException re) { 12372 } 12373 return; 12374 } 12375 12376 if (DEBUG_REMOVE) { 12377 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12378 } 12379 // Queue up an async operation since the package deletion may take a little while. 12380 mHandler.post(new Runnable() { 12381 public void run() { 12382 mHandler.removeCallbacks(this); 12383 final int returnCode = deletePackageX(packageName, userId, flags); 12384 if (observer != null) { 12385 try { 12386 observer.onPackageDeleted(packageName, returnCode, null); 12387 } catch (RemoteException e) { 12388 Log.i(TAG, "Observer no longer exists."); 12389 } //end catch 12390 } //end if 12391 } //end run 12392 }); 12393 } 12394 12395 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12396 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12397 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12398 try { 12399 if (dpm != null) { 12400 if (dpm.isDeviceOwner(packageName)) { 12401 return true; 12402 } 12403 int[] users; 12404 if (userId == UserHandle.USER_ALL) { 12405 users = sUserManager.getUserIds(); 12406 } else { 12407 users = new int[]{userId}; 12408 } 12409 for (int i = 0; i < users.length; ++i) { 12410 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12411 return true; 12412 } 12413 } 12414 } 12415 } catch (RemoteException e) { 12416 } 12417 return false; 12418 } 12419 12420 /** 12421 * This method is an internal method that could be get invoked either 12422 * to delete an installed package or to clean up a failed installation. 12423 * After deleting an installed package, a broadcast is sent to notify any 12424 * listeners that the package has been installed. For cleaning up a failed 12425 * installation, the broadcast is not necessary since the package's 12426 * installation wouldn't have sent the initial broadcast either 12427 * The key steps in deleting a package are 12428 * deleting the package information in internal structures like mPackages, 12429 * deleting the packages base directories through installd 12430 * updating mSettings to reflect current status 12431 * persisting settings for later use 12432 * sending a broadcast if necessary 12433 */ 12434 private int deletePackageX(String packageName, int userId, int flags) { 12435 final PackageRemovedInfo info = new PackageRemovedInfo(); 12436 final boolean res; 12437 12438 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12439 ? UserHandle.ALL : new UserHandle(userId); 12440 12441 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12442 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12443 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12444 } 12445 12446 boolean removedForAllUsers = false; 12447 boolean systemUpdate = false; 12448 12449 // for the uninstall-updates case and restricted profiles, remember the per- 12450 // userhandle installed state 12451 int[] allUsers; 12452 boolean[] perUserInstalled; 12453 synchronized (mPackages) { 12454 PackageSetting ps = mSettings.mPackages.get(packageName); 12455 allUsers = sUserManager.getUserIds(); 12456 perUserInstalled = new boolean[allUsers.length]; 12457 for (int i = 0; i < allUsers.length; i++) { 12458 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12459 } 12460 } 12461 12462 synchronized (mInstallLock) { 12463 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12464 res = deletePackageLI(packageName, removeForUser, 12465 true, allUsers, perUserInstalled, 12466 flags | REMOVE_CHATTY, info, true); 12467 systemUpdate = info.isRemovedPackageSystemUpdate; 12468 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12469 removedForAllUsers = true; 12470 } 12471 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12472 + " removedForAllUsers=" + removedForAllUsers); 12473 } 12474 12475 if (res) { 12476 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12477 12478 // If the removed package was a system update, the old system package 12479 // was re-enabled; we need to broadcast this information 12480 if (systemUpdate) { 12481 Bundle extras = new Bundle(1); 12482 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12483 ? info.removedAppId : info.uid); 12484 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12485 12486 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12487 extras, null, null, null); 12488 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12489 extras, null, null, null); 12490 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12491 null, packageName, null, null); 12492 } 12493 } 12494 // Force a gc here. 12495 Runtime.getRuntime().gc(); 12496 // Delete the resources here after sending the broadcast to let 12497 // other processes clean up before deleting resources. 12498 if (info.args != null) { 12499 synchronized (mInstallLock) { 12500 info.args.doPostDeleteLI(true); 12501 } 12502 } 12503 12504 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12505 } 12506 12507 class PackageRemovedInfo { 12508 String removedPackage; 12509 int uid = -1; 12510 int removedAppId = -1; 12511 int[] removedUsers = null; 12512 boolean isRemovedPackageSystemUpdate = false; 12513 // Clean up resources deleted packages. 12514 InstallArgs args = null; 12515 12516 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12517 Bundle extras = new Bundle(1); 12518 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12519 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12520 if (replacing) { 12521 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12522 } 12523 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12524 if (removedPackage != null) { 12525 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12526 extras, null, null, removedUsers); 12527 if (fullRemove && !replacing) { 12528 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12529 extras, null, null, removedUsers); 12530 } 12531 } 12532 if (removedAppId >= 0) { 12533 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12534 removedUsers); 12535 } 12536 } 12537 } 12538 12539 /* 12540 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12541 * flag is not set, the data directory is removed as well. 12542 * make sure this flag is set for partially installed apps. If not its meaningless to 12543 * delete a partially installed application. 12544 */ 12545 private void removePackageDataLI(PackageSetting ps, 12546 int[] allUserHandles, boolean[] perUserInstalled, 12547 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12548 String packageName = ps.name; 12549 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12550 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12551 // Retrieve object to delete permissions for shared user later on 12552 final PackageSetting deletedPs; 12553 // reader 12554 synchronized (mPackages) { 12555 deletedPs = mSettings.mPackages.get(packageName); 12556 if (outInfo != null) { 12557 outInfo.removedPackage = packageName; 12558 outInfo.removedUsers = deletedPs != null 12559 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12560 : null; 12561 } 12562 } 12563 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12564 removeDataDirsLI(ps.volumeUuid, packageName); 12565 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12566 } 12567 // writer 12568 synchronized (mPackages) { 12569 if (deletedPs != null) { 12570 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12571 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12572 clearDefaultBrowserIfNeeded(packageName); 12573 if (outInfo != null) { 12574 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12575 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12576 } 12577 updatePermissionsLPw(deletedPs.name, null, 0); 12578 if (deletedPs.sharedUser != null) { 12579 // Remove permissions associated with package. Since runtime 12580 // permissions are per user we have to kill the removed package 12581 // or packages running under the shared user of the removed 12582 // package if revoking the permissions requested only by the removed 12583 // package is successful and this causes a change in gids. 12584 for (int userId : UserManagerService.getInstance().getUserIds()) { 12585 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12586 userId); 12587 if (userIdToKill == UserHandle.USER_ALL 12588 || userIdToKill >= UserHandle.USER_OWNER) { 12589 // If gids changed for this user, kill all affected packages. 12590 mHandler.post(new Runnable() { 12591 @Override 12592 public void run() { 12593 // This has to happen with no lock held. 12594 killSettingPackagesForUser(deletedPs, userIdToKill, 12595 KILL_APP_REASON_GIDS_CHANGED); 12596 } 12597 }); 12598 break; 12599 } 12600 } 12601 } 12602 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12603 } 12604 // make sure to preserve per-user disabled state if this removal was just 12605 // a downgrade of a system app to the factory package 12606 if (allUserHandles != null && perUserInstalled != null) { 12607 if (DEBUG_REMOVE) { 12608 Slog.d(TAG, "Propagating install state across downgrade"); 12609 } 12610 for (int i = 0; i < allUserHandles.length; i++) { 12611 if (DEBUG_REMOVE) { 12612 Slog.d(TAG, " user " + allUserHandles[i] 12613 + " => " + perUserInstalled[i]); 12614 } 12615 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12616 } 12617 } 12618 } 12619 // can downgrade to reader 12620 if (writeSettings) { 12621 // Save settings now 12622 mSettings.writeLPr(); 12623 } 12624 } 12625 if (outInfo != null) { 12626 // A user ID was deleted here. Go through all users and remove it 12627 // from KeyStore. 12628 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12629 } 12630 } 12631 12632 static boolean locationIsPrivileged(File path) { 12633 try { 12634 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12635 .getCanonicalPath(); 12636 return path.getCanonicalPath().startsWith(privilegedAppDir); 12637 } catch (IOException e) { 12638 Slog.e(TAG, "Unable to access code path " + path); 12639 } 12640 return false; 12641 } 12642 12643 /* 12644 * Tries to delete system package. 12645 */ 12646 private boolean deleteSystemPackageLI(PackageSetting newPs, 12647 int[] allUserHandles, boolean[] perUserInstalled, 12648 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12649 final boolean applyUserRestrictions 12650 = (allUserHandles != null) && (perUserInstalled != null); 12651 PackageSetting disabledPs = null; 12652 // Confirm if the system package has been updated 12653 // An updated system app can be deleted. This will also have to restore 12654 // the system pkg from system partition 12655 // reader 12656 synchronized (mPackages) { 12657 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12658 } 12659 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12660 + " disabledPs=" + disabledPs); 12661 if (disabledPs == null) { 12662 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12663 return false; 12664 } else if (DEBUG_REMOVE) { 12665 Slog.d(TAG, "Deleting system pkg from data partition"); 12666 } 12667 if (DEBUG_REMOVE) { 12668 if (applyUserRestrictions) { 12669 Slog.d(TAG, "Remembering install states:"); 12670 for (int i = 0; i < allUserHandles.length; i++) { 12671 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12672 } 12673 } 12674 } 12675 // Delete the updated package 12676 outInfo.isRemovedPackageSystemUpdate = true; 12677 if (disabledPs.versionCode < newPs.versionCode) { 12678 // Delete data for downgrades 12679 flags &= ~PackageManager.DELETE_KEEP_DATA; 12680 } else { 12681 // Preserve data by setting flag 12682 flags |= PackageManager.DELETE_KEEP_DATA; 12683 } 12684 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12685 allUserHandles, perUserInstalled, outInfo, writeSettings); 12686 if (!ret) { 12687 return false; 12688 } 12689 // writer 12690 synchronized (mPackages) { 12691 // Reinstate the old system package 12692 mSettings.enableSystemPackageLPw(newPs.name); 12693 // Remove any native libraries from the upgraded package. 12694 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12695 } 12696 // Install the system package 12697 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12698 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12699 if (locationIsPrivileged(disabledPs.codePath)) { 12700 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12701 } 12702 12703 final PackageParser.Package newPkg; 12704 try { 12705 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12706 } catch (PackageManagerException e) { 12707 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12708 return false; 12709 } 12710 12711 // writer 12712 synchronized (mPackages) { 12713 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12714 updatePermissionsLPw(newPkg.packageName, newPkg, 12715 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12716 if (applyUserRestrictions) { 12717 if (DEBUG_REMOVE) { 12718 Slog.d(TAG, "Propagating install state across reinstall"); 12719 } 12720 for (int i = 0; i < allUserHandles.length; i++) { 12721 if (DEBUG_REMOVE) { 12722 Slog.d(TAG, " user " + allUserHandles[i] 12723 + " => " + perUserInstalled[i]); 12724 } 12725 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12726 } 12727 // Regardless of writeSettings we need to ensure that this restriction 12728 // state propagation is persisted 12729 mSettings.writeAllUsersPackageRestrictionsLPr(); 12730 } 12731 // can downgrade to reader here 12732 if (writeSettings) { 12733 mSettings.writeLPr(); 12734 } 12735 } 12736 return true; 12737 } 12738 12739 private boolean deleteInstalledPackageLI(PackageSetting ps, 12740 boolean deleteCodeAndResources, int flags, 12741 int[] allUserHandles, boolean[] perUserInstalled, 12742 PackageRemovedInfo outInfo, boolean writeSettings) { 12743 if (outInfo != null) { 12744 outInfo.uid = ps.appId; 12745 } 12746 12747 // Delete package data from internal structures and also remove data if flag is set 12748 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12749 12750 // Delete application code and resources 12751 if (deleteCodeAndResources && (outInfo != null)) { 12752 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12753 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12754 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12755 } 12756 return true; 12757 } 12758 12759 @Override 12760 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12761 int userId) { 12762 mContext.enforceCallingOrSelfPermission( 12763 android.Manifest.permission.DELETE_PACKAGES, null); 12764 synchronized (mPackages) { 12765 PackageSetting ps = mSettings.mPackages.get(packageName); 12766 if (ps == null) { 12767 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12768 return false; 12769 } 12770 if (!ps.getInstalled(userId)) { 12771 // Can't block uninstall for an app that is not installed or enabled. 12772 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12773 return false; 12774 } 12775 ps.setBlockUninstall(blockUninstall, userId); 12776 mSettings.writePackageRestrictionsLPr(userId); 12777 } 12778 return true; 12779 } 12780 12781 @Override 12782 public boolean getBlockUninstallForUser(String packageName, int userId) { 12783 synchronized (mPackages) { 12784 PackageSetting ps = mSettings.mPackages.get(packageName); 12785 if (ps == null) { 12786 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12787 return false; 12788 } 12789 return ps.getBlockUninstall(userId); 12790 } 12791 } 12792 12793 /* 12794 * This method handles package deletion in general 12795 */ 12796 private boolean deletePackageLI(String packageName, UserHandle user, 12797 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12798 int flags, PackageRemovedInfo outInfo, 12799 boolean writeSettings) { 12800 if (packageName == null) { 12801 Slog.w(TAG, "Attempt to delete null packageName."); 12802 return false; 12803 } 12804 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12805 PackageSetting ps; 12806 boolean dataOnly = false; 12807 int removeUser = -1; 12808 int appId = -1; 12809 synchronized (mPackages) { 12810 ps = mSettings.mPackages.get(packageName); 12811 if (ps == null) { 12812 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12813 return false; 12814 } 12815 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12816 && user.getIdentifier() != UserHandle.USER_ALL) { 12817 // The caller is asking that the package only be deleted for a single 12818 // user. To do this, we just mark its uninstalled state and delete 12819 // its data. If this is a system app, we only allow this to happen if 12820 // they have set the special DELETE_SYSTEM_APP which requests different 12821 // semantics than normal for uninstalling system apps. 12822 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12823 ps.setUserState(user.getIdentifier(), 12824 COMPONENT_ENABLED_STATE_DEFAULT, 12825 false, //installed 12826 true, //stopped 12827 true, //notLaunched 12828 false, //hidden 12829 null, null, null, 12830 false, // blockUninstall 12831 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12832 if (!isSystemApp(ps)) { 12833 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12834 // Other user still have this package installed, so all 12835 // we need to do is clear this user's data and save that 12836 // it is uninstalled. 12837 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12838 removeUser = user.getIdentifier(); 12839 appId = ps.appId; 12840 scheduleWritePackageRestrictionsLocked(removeUser); 12841 } else { 12842 // We need to set it back to 'installed' so the uninstall 12843 // broadcasts will be sent correctly. 12844 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12845 ps.setInstalled(true, user.getIdentifier()); 12846 } 12847 } else { 12848 // This is a system app, so we assume that the 12849 // other users still have this package installed, so all 12850 // we need to do is clear this user's data and save that 12851 // it is uninstalled. 12852 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12853 removeUser = user.getIdentifier(); 12854 appId = ps.appId; 12855 scheduleWritePackageRestrictionsLocked(removeUser); 12856 } 12857 } 12858 } 12859 12860 if (removeUser >= 0) { 12861 // From above, we determined that we are deleting this only 12862 // for a single user. Continue the work here. 12863 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12864 if (outInfo != null) { 12865 outInfo.removedPackage = packageName; 12866 outInfo.removedAppId = appId; 12867 outInfo.removedUsers = new int[] {removeUser}; 12868 } 12869 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12870 removeKeystoreDataIfNeeded(removeUser, appId); 12871 schedulePackageCleaning(packageName, removeUser, false); 12872 synchronized (mPackages) { 12873 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12874 scheduleWritePackageRestrictionsLocked(removeUser); 12875 } 12876 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12877 removeUser); 12878 } 12879 return true; 12880 } 12881 12882 if (dataOnly) { 12883 // Delete application data first 12884 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12885 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12886 return true; 12887 } 12888 12889 boolean ret = false; 12890 if (isSystemApp(ps)) { 12891 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12892 // When an updated system application is deleted we delete the existing resources as well and 12893 // fall back to existing code in system partition 12894 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12895 flags, outInfo, writeSettings); 12896 } else { 12897 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12898 // Kill application pre-emptively especially for apps on sd. 12899 killApplication(packageName, ps.appId, "uninstall pkg"); 12900 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12901 allUserHandles, perUserInstalled, 12902 outInfo, writeSettings); 12903 } 12904 12905 return ret; 12906 } 12907 12908 private final class ClearStorageConnection implements ServiceConnection { 12909 IMediaContainerService mContainerService; 12910 12911 @Override 12912 public void onServiceConnected(ComponentName name, IBinder service) { 12913 synchronized (this) { 12914 mContainerService = IMediaContainerService.Stub.asInterface(service); 12915 notifyAll(); 12916 } 12917 } 12918 12919 @Override 12920 public void onServiceDisconnected(ComponentName name) { 12921 } 12922 } 12923 12924 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12925 final boolean mounted; 12926 if (Environment.isExternalStorageEmulated()) { 12927 mounted = true; 12928 } else { 12929 final String status = Environment.getExternalStorageState(); 12930 12931 mounted = status.equals(Environment.MEDIA_MOUNTED) 12932 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12933 } 12934 12935 if (!mounted) { 12936 return; 12937 } 12938 12939 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12940 int[] users; 12941 if (userId == UserHandle.USER_ALL) { 12942 users = sUserManager.getUserIds(); 12943 } else { 12944 users = new int[] { userId }; 12945 } 12946 final ClearStorageConnection conn = new ClearStorageConnection(); 12947 if (mContext.bindServiceAsUser( 12948 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12949 try { 12950 for (int curUser : users) { 12951 long timeout = SystemClock.uptimeMillis() + 5000; 12952 synchronized (conn) { 12953 long now = SystemClock.uptimeMillis(); 12954 while (conn.mContainerService == null && now < timeout) { 12955 try { 12956 conn.wait(timeout - now); 12957 } catch (InterruptedException e) { 12958 } 12959 } 12960 } 12961 if (conn.mContainerService == null) { 12962 return; 12963 } 12964 12965 final UserEnvironment userEnv = new UserEnvironment(curUser); 12966 clearDirectory(conn.mContainerService, 12967 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12968 if (allData) { 12969 clearDirectory(conn.mContainerService, 12970 userEnv.buildExternalStorageAppDataDirs(packageName)); 12971 clearDirectory(conn.mContainerService, 12972 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12973 } 12974 } 12975 } finally { 12976 mContext.unbindService(conn); 12977 } 12978 } 12979 } 12980 12981 @Override 12982 public void clearApplicationUserData(final String packageName, 12983 final IPackageDataObserver observer, final int userId) { 12984 mContext.enforceCallingOrSelfPermission( 12985 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12986 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12987 // Queue up an async operation since the package deletion may take a little while. 12988 mHandler.post(new Runnable() { 12989 public void run() { 12990 mHandler.removeCallbacks(this); 12991 final boolean succeeded; 12992 synchronized (mInstallLock) { 12993 succeeded = clearApplicationUserDataLI(packageName, userId); 12994 } 12995 clearExternalStorageDataSync(packageName, userId, true); 12996 if (succeeded) { 12997 // invoke DeviceStorageMonitor's update method to clear any notifications 12998 DeviceStorageMonitorInternal 12999 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13000 if (dsm != null) { 13001 dsm.checkMemory(); 13002 } 13003 } 13004 if(observer != null) { 13005 try { 13006 observer.onRemoveCompleted(packageName, succeeded); 13007 } catch (RemoteException e) { 13008 Log.i(TAG, "Observer no longer exists."); 13009 } 13010 } //end if observer 13011 } //end run 13012 }); 13013 } 13014 13015 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13016 if (packageName == null) { 13017 Slog.w(TAG, "Attempt to delete null packageName."); 13018 return false; 13019 } 13020 13021 // Try finding details about the requested package 13022 PackageParser.Package pkg; 13023 synchronized (mPackages) { 13024 pkg = mPackages.get(packageName); 13025 if (pkg == null) { 13026 final PackageSetting ps = mSettings.mPackages.get(packageName); 13027 if (ps != null) { 13028 pkg = ps.pkg; 13029 } 13030 } 13031 13032 if (pkg == null) { 13033 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13034 return false; 13035 } 13036 13037 PackageSetting ps = (PackageSetting) pkg.mExtras; 13038 PermissionsState permissionsState = ps.getPermissionsState(); 13039 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 13040 } 13041 13042 // Always delete data directories for package, even if we found no other 13043 // record of app. This helps users recover from UID mismatches without 13044 // resorting to a full data wipe. 13045 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13046 if (retCode < 0) { 13047 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13048 return false; 13049 } 13050 13051 final int appId = pkg.applicationInfo.uid; 13052 removeKeystoreDataIfNeeded(userId, appId); 13053 13054 // Create a native library symlink only if we have native libraries 13055 // and if the native libraries are 32 bit libraries. We do not provide 13056 // this symlink for 64 bit libraries. 13057 if (pkg.applicationInfo.primaryCpuAbi != null && 13058 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13059 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13060 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13061 nativeLibPath, userId) < 0) { 13062 Slog.w(TAG, "Failed linking native library dir"); 13063 return false; 13064 } 13065 } 13066 13067 return true; 13068 } 13069 13070 13071 /** 13072 * Revokes granted runtime permissions and clears resettable flags 13073 * which are flags that can be set by a user interaction. 13074 * 13075 * @param permissionsState The permission state to reset. 13076 * @param userId The device user for which to do a reset. 13077 */ 13078 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 13079 PermissionsState permissionsState, int userId) { 13080 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 13081 | PackageManager.FLAG_PERMISSION_USER_FIXED 13082 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13083 13084 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 13085 } 13086 13087 /** 13088 * Revokes granted runtime permissions and clears all flags. 13089 * 13090 * @param permissionsState The permission state to reset. 13091 * @param userId The device user for which to do a reset. 13092 */ 13093 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 13094 PermissionsState permissionsState, int userId) { 13095 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 13096 PackageManager.MASK_PERMISSION_FLAGS); 13097 } 13098 13099 /** 13100 * Revokes granted runtime permissions and clears certain flags. 13101 * 13102 * @param permissionsState The permission state to reset. 13103 * @param userId The device user for which to do a reset. 13104 * @param flags The flags that is going to be reset. 13105 */ 13106 private void revokeRuntimePermissionsAndClearFlagsLocked( 13107 PermissionsState permissionsState, final int userId, int flags) { 13108 boolean needsWrite = false; 13109 13110 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 13111 BasePermission bp = mSettings.mPermissions.get(state.getName()); 13112 if (bp != null) { 13113 permissionsState.revokeRuntimePermission(bp, userId); 13114 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 13115 needsWrite = true; 13116 } 13117 } 13118 13119 // Ensure default permissions are never cleared. 13120 mHandler.post(new Runnable() { 13121 @Override 13122 public void run() { 13123 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13124 } 13125 }); 13126 13127 if (needsWrite) { 13128 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13129 } 13130 } 13131 13132 /** 13133 * Remove entries from the keystore daemon. Will only remove it if the 13134 * {@code appId} is valid. 13135 */ 13136 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13137 if (appId < 0) { 13138 return; 13139 } 13140 13141 final KeyStore keyStore = KeyStore.getInstance(); 13142 if (keyStore != null) { 13143 if (userId == UserHandle.USER_ALL) { 13144 for (final int individual : sUserManager.getUserIds()) { 13145 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13146 } 13147 } else { 13148 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13149 } 13150 } else { 13151 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13152 } 13153 } 13154 13155 @Override 13156 public void deleteApplicationCacheFiles(final String packageName, 13157 final IPackageDataObserver observer) { 13158 mContext.enforceCallingOrSelfPermission( 13159 android.Manifest.permission.DELETE_CACHE_FILES, null); 13160 // Queue up an async operation since the package deletion may take a little while. 13161 final int userId = UserHandle.getCallingUserId(); 13162 mHandler.post(new Runnable() { 13163 public void run() { 13164 mHandler.removeCallbacks(this); 13165 final boolean succeded; 13166 synchronized (mInstallLock) { 13167 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13168 } 13169 clearExternalStorageDataSync(packageName, userId, false); 13170 if (observer != null) { 13171 try { 13172 observer.onRemoveCompleted(packageName, succeded); 13173 } catch (RemoteException e) { 13174 Log.i(TAG, "Observer no longer exists."); 13175 } 13176 } //end if observer 13177 } //end run 13178 }); 13179 } 13180 13181 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13182 if (packageName == null) { 13183 Slog.w(TAG, "Attempt to delete null packageName."); 13184 return false; 13185 } 13186 PackageParser.Package p; 13187 synchronized (mPackages) { 13188 p = mPackages.get(packageName); 13189 } 13190 if (p == null) { 13191 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13192 return false; 13193 } 13194 final ApplicationInfo applicationInfo = p.applicationInfo; 13195 if (applicationInfo == null) { 13196 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13197 return false; 13198 } 13199 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13200 if (retCode < 0) { 13201 Slog.w(TAG, "Couldn't remove cache files for package: " 13202 + packageName + " u" + userId); 13203 return false; 13204 } 13205 return true; 13206 } 13207 13208 @Override 13209 public void getPackageSizeInfo(final String packageName, int userHandle, 13210 final IPackageStatsObserver observer) { 13211 mContext.enforceCallingOrSelfPermission( 13212 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13213 if (packageName == null) { 13214 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13215 } 13216 13217 PackageStats stats = new PackageStats(packageName, userHandle); 13218 13219 /* 13220 * Queue up an async operation since the package measurement may take a 13221 * little while. 13222 */ 13223 Message msg = mHandler.obtainMessage(INIT_COPY); 13224 msg.obj = new MeasureParams(stats, observer); 13225 mHandler.sendMessage(msg); 13226 } 13227 13228 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13229 PackageStats pStats) { 13230 if (packageName == null) { 13231 Slog.w(TAG, "Attempt to get size of null packageName."); 13232 return false; 13233 } 13234 PackageParser.Package p; 13235 boolean dataOnly = false; 13236 String libDirRoot = null; 13237 String asecPath = null; 13238 PackageSetting ps = null; 13239 synchronized (mPackages) { 13240 p = mPackages.get(packageName); 13241 ps = mSettings.mPackages.get(packageName); 13242 if(p == null) { 13243 dataOnly = true; 13244 if((ps == null) || (ps.pkg == null)) { 13245 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13246 return false; 13247 } 13248 p = ps.pkg; 13249 } 13250 if (ps != null) { 13251 libDirRoot = ps.legacyNativeLibraryPathString; 13252 } 13253 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13254 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13255 if (secureContainerId != null) { 13256 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13257 } 13258 } 13259 } 13260 String publicSrcDir = null; 13261 if(!dataOnly) { 13262 final ApplicationInfo applicationInfo = p.applicationInfo; 13263 if (applicationInfo == null) { 13264 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13265 return false; 13266 } 13267 if (p.isForwardLocked()) { 13268 publicSrcDir = applicationInfo.getBaseResourcePath(); 13269 } 13270 } 13271 // TODO: extend to measure size of split APKs 13272 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13273 // not just the first level. 13274 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13275 // just the primary. 13276 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13277 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13278 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13279 if (res < 0) { 13280 return false; 13281 } 13282 13283 // Fix-up for forward-locked applications in ASEC containers. 13284 if (!isExternal(p)) { 13285 pStats.codeSize += pStats.externalCodeSize; 13286 pStats.externalCodeSize = 0L; 13287 } 13288 13289 return true; 13290 } 13291 13292 13293 @Override 13294 public void addPackageToPreferred(String packageName) { 13295 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13296 } 13297 13298 @Override 13299 public void removePackageFromPreferred(String packageName) { 13300 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13301 } 13302 13303 @Override 13304 public List<PackageInfo> getPreferredPackages(int flags) { 13305 return new ArrayList<PackageInfo>(); 13306 } 13307 13308 private int getUidTargetSdkVersionLockedLPr(int uid) { 13309 Object obj = mSettings.getUserIdLPr(uid); 13310 if (obj instanceof SharedUserSetting) { 13311 final SharedUserSetting sus = (SharedUserSetting) obj; 13312 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13313 final Iterator<PackageSetting> it = sus.packages.iterator(); 13314 while (it.hasNext()) { 13315 final PackageSetting ps = it.next(); 13316 if (ps.pkg != null) { 13317 int v = ps.pkg.applicationInfo.targetSdkVersion; 13318 if (v < vers) vers = v; 13319 } 13320 } 13321 return vers; 13322 } else if (obj instanceof PackageSetting) { 13323 final PackageSetting ps = (PackageSetting) obj; 13324 if (ps.pkg != null) { 13325 return ps.pkg.applicationInfo.targetSdkVersion; 13326 } 13327 } 13328 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13329 } 13330 13331 @Override 13332 public void addPreferredActivity(IntentFilter filter, int match, 13333 ComponentName[] set, ComponentName activity, int userId) { 13334 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13335 "Adding preferred"); 13336 } 13337 13338 private void addPreferredActivityInternal(IntentFilter filter, int match, 13339 ComponentName[] set, ComponentName activity, boolean always, int userId, 13340 String opname) { 13341 // writer 13342 int callingUid = Binder.getCallingUid(); 13343 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13344 if (filter.countActions() == 0) { 13345 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13346 return; 13347 } 13348 synchronized (mPackages) { 13349 if (mContext.checkCallingOrSelfPermission( 13350 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13351 != PackageManager.PERMISSION_GRANTED) { 13352 if (getUidTargetSdkVersionLockedLPr(callingUid) 13353 < Build.VERSION_CODES.FROYO) { 13354 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13355 + callingUid); 13356 return; 13357 } 13358 mContext.enforceCallingOrSelfPermission( 13359 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13360 } 13361 13362 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13363 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13364 + userId + ":"); 13365 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13366 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13367 scheduleWritePackageRestrictionsLocked(userId); 13368 } 13369 } 13370 13371 @Override 13372 public void replacePreferredActivity(IntentFilter filter, int match, 13373 ComponentName[] set, ComponentName activity, int userId) { 13374 if (filter.countActions() != 1) { 13375 throw new IllegalArgumentException( 13376 "replacePreferredActivity expects filter to have only 1 action."); 13377 } 13378 if (filter.countDataAuthorities() != 0 13379 || filter.countDataPaths() != 0 13380 || filter.countDataSchemes() > 1 13381 || filter.countDataTypes() != 0) { 13382 throw new IllegalArgumentException( 13383 "replacePreferredActivity expects filter to have no data authorities, " + 13384 "paths, or types; and at most one scheme."); 13385 } 13386 13387 final int callingUid = Binder.getCallingUid(); 13388 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13389 synchronized (mPackages) { 13390 if (mContext.checkCallingOrSelfPermission( 13391 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13392 != PackageManager.PERMISSION_GRANTED) { 13393 if (getUidTargetSdkVersionLockedLPr(callingUid) 13394 < Build.VERSION_CODES.FROYO) { 13395 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13396 + Binder.getCallingUid()); 13397 return; 13398 } 13399 mContext.enforceCallingOrSelfPermission( 13400 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13401 } 13402 13403 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13404 if (pir != null) { 13405 // Get all of the existing entries that exactly match this filter. 13406 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13407 if (existing != null && existing.size() == 1) { 13408 PreferredActivity cur = existing.get(0); 13409 if (DEBUG_PREFERRED) { 13410 Slog.i(TAG, "Checking replace of preferred:"); 13411 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13412 if (!cur.mPref.mAlways) { 13413 Slog.i(TAG, " -- CUR; not mAlways!"); 13414 } else { 13415 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13416 Slog.i(TAG, " -- CUR: mSet=" 13417 + Arrays.toString(cur.mPref.mSetComponents)); 13418 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13419 Slog.i(TAG, " -- NEW: mMatch=" 13420 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13421 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13422 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13423 } 13424 } 13425 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13426 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13427 && cur.mPref.sameSet(set)) { 13428 // Setting the preferred activity to what it happens to be already 13429 if (DEBUG_PREFERRED) { 13430 Slog.i(TAG, "Replacing with same preferred activity " 13431 + cur.mPref.mShortComponent + " for user " 13432 + userId + ":"); 13433 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13434 } 13435 return; 13436 } 13437 } 13438 13439 if (existing != null) { 13440 if (DEBUG_PREFERRED) { 13441 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13442 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13443 } 13444 for (int i = 0; i < existing.size(); i++) { 13445 PreferredActivity pa = existing.get(i); 13446 if (DEBUG_PREFERRED) { 13447 Slog.i(TAG, "Removing existing preferred activity " 13448 + pa.mPref.mComponent + ":"); 13449 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13450 } 13451 pir.removeFilter(pa); 13452 } 13453 } 13454 } 13455 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13456 "Replacing preferred"); 13457 } 13458 } 13459 13460 @Override 13461 public void clearPackagePreferredActivities(String packageName) { 13462 final int uid = Binder.getCallingUid(); 13463 // writer 13464 synchronized (mPackages) { 13465 PackageParser.Package pkg = mPackages.get(packageName); 13466 if (pkg == null || pkg.applicationInfo.uid != uid) { 13467 if (mContext.checkCallingOrSelfPermission( 13468 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13469 != PackageManager.PERMISSION_GRANTED) { 13470 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13471 < Build.VERSION_CODES.FROYO) { 13472 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13473 + Binder.getCallingUid()); 13474 return; 13475 } 13476 mContext.enforceCallingOrSelfPermission( 13477 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13478 } 13479 } 13480 13481 int user = UserHandle.getCallingUserId(); 13482 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13483 scheduleWritePackageRestrictionsLocked(user); 13484 } 13485 } 13486 } 13487 13488 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13489 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13490 ArrayList<PreferredActivity> removed = null; 13491 boolean changed = false; 13492 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13493 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13494 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13495 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13496 continue; 13497 } 13498 Iterator<PreferredActivity> it = pir.filterIterator(); 13499 while (it.hasNext()) { 13500 PreferredActivity pa = it.next(); 13501 // Mark entry for removal only if it matches the package name 13502 // and the entry is of type "always". 13503 if (packageName == null || 13504 (pa.mPref.mComponent.getPackageName().equals(packageName) 13505 && pa.mPref.mAlways)) { 13506 if (removed == null) { 13507 removed = new ArrayList<PreferredActivity>(); 13508 } 13509 removed.add(pa); 13510 } 13511 } 13512 if (removed != null) { 13513 for (int j=0; j<removed.size(); j++) { 13514 PreferredActivity pa = removed.get(j); 13515 pir.removeFilter(pa); 13516 } 13517 changed = true; 13518 } 13519 } 13520 return changed; 13521 } 13522 13523 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13524 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13525 if (userId == UserHandle.USER_ALL) { 13526 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13527 sUserManager.getUserIds())) { 13528 for (int oneUserId : sUserManager.getUserIds()) { 13529 scheduleWritePackageRestrictionsLocked(oneUserId); 13530 } 13531 } 13532 } else { 13533 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13534 scheduleWritePackageRestrictionsLocked(userId); 13535 } 13536 } 13537 } 13538 13539 13540 void clearDefaultBrowserIfNeeded(String packageName) { 13541 for (int oneUserId : sUserManager.getUserIds()) { 13542 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13543 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13544 if (packageName.equals(defaultBrowserPackageName)) { 13545 setDefaultBrowserPackageName(null, oneUserId); 13546 } 13547 } 13548 } 13549 13550 @Override 13551 public void resetPreferredActivities(int userId) { 13552 mContext.enforceCallingOrSelfPermission( 13553 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13554 // writer 13555 synchronized (mPackages) { 13556 clearPackagePreferredActivitiesLPw(null, userId); 13557 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13558 applyFactoryDefaultBrowserLPw(userId); 13559 13560 scheduleWritePackageRestrictionsLocked(userId); 13561 } 13562 } 13563 13564 @Override 13565 public int getPreferredActivities(List<IntentFilter> outFilters, 13566 List<ComponentName> outActivities, String packageName) { 13567 13568 int num = 0; 13569 final int userId = UserHandle.getCallingUserId(); 13570 // reader 13571 synchronized (mPackages) { 13572 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13573 if (pir != null) { 13574 final Iterator<PreferredActivity> it = pir.filterIterator(); 13575 while (it.hasNext()) { 13576 final PreferredActivity pa = it.next(); 13577 if (packageName == null 13578 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13579 && pa.mPref.mAlways)) { 13580 if (outFilters != null) { 13581 outFilters.add(new IntentFilter(pa)); 13582 } 13583 if (outActivities != null) { 13584 outActivities.add(pa.mPref.mComponent); 13585 } 13586 } 13587 } 13588 } 13589 } 13590 13591 return num; 13592 } 13593 13594 @Override 13595 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13596 int userId) { 13597 int callingUid = Binder.getCallingUid(); 13598 if (callingUid != Process.SYSTEM_UID) { 13599 throw new SecurityException( 13600 "addPersistentPreferredActivity can only be run by the system"); 13601 } 13602 if (filter.countActions() == 0) { 13603 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13604 return; 13605 } 13606 synchronized (mPackages) { 13607 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13608 " :"); 13609 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13610 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13611 new PersistentPreferredActivity(filter, activity)); 13612 scheduleWritePackageRestrictionsLocked(userId); 13613 } 13614 } 13615 13616 @Override 13617 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13618 int callingUid = Binder.getCallingUid(); 13619 if (callingUid != Process.SYSTEM_UID) { 13620 throw new SecurityException( 13621 "clearPackagePersistentPreferredActivities can only be run by the system"); 13622 } 13623 ArrayList<PersistentPreferredActivity> removed = null; 13624 boolean changed = false; 13625 synchronized (mPackages) { 13626 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13627 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13628 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13629 .valueAt(i); 13630 if (userId != thisUserId) { 13631 continue; 13632 } 13633 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13634 while (it.hasNext()) { 13635 PersistentPreferredActivity ppa = it.next(); 13636 // Mark entry for removal only if it matches the package name. 13637 if (ppa.mComponent.getPackageName().equals(packageName)) { 13638 if (removed == null) { 13639 removed = new ArrayList<PersistentPreferredActivity>(); 13640 } 13641 removed.add(ppa); 13642 } 13643 } 13644 if (removed != null) { 13645 for (int j=0; j<removed.size(); j++) { 13646 PersistentPreferredActivity ppa = removed.get(j); 13647 ppir.removeFilter(ppa); 13648 } 13649 changed = true; 13650 } 13651 } 13652 13653 if (changed) { 13654 scheduleWritePackageRestrictionsLocked(userId); 13655 } 13656 } 13657 } 13658 13659 /** 13660 * Common machinery for picking apart a restored XML blob and passing 13661 * it to a caller-supplied functor to be applied to the running system. 13662 */ 13663 private void restoreFromXml(XmlPullParser parser, int userId, 13664 String expectedStartTag, BlobXmlRestorer functor) 13665 throws IOException, XmlPullParserException { 13666 int type; 13667 while ((type = parser.next()) != XmlPullParser.START_TAG 13668 && type != XmlPullParser.END_DOCUMENT) { 13669 } 13670 if (type != XmlPullParser.START_TAG) { 13671 // oops didn't find a start tag?! 13672 if (DEBUG_BACKUP) { 13673 Slog.e(TAG, "Didn't find start tag during restore"); 13674 } 13675 return; 13676 } 13677 13678 // this is supposed to be TAG_PREFERRED_BACKUP 13679 if (!expectedStartTag.equals(parser.getName())) { 13680 if (DEBUG_BACKUP) { 13681 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13682 } 13683 return; 13684 } 13685 13686 // skip interfering stuff, then we're aligned with the backing implementation 13687 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13688 functor.apply(parser, userId); 13689 } 13690 13691 private interface BlobXmlRestorer { 13692 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13693 } 13694 13695 /** 13696 * Non-Binder method, support for the backup/restore mechanism: write the 13697 * full set of preferred activities in its canonical XML format. Returns the 13698 * XML output as a byte array, or null if there is none. 13699 */ 13700 @Override 13701 public byte[] getPreferredActivityBackup(int userId) { 13702 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13703 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13704 } 13705 13706 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13707 try { 13708 final XmlSerializer serializer = new FastXmlSerializer(); 13709 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13710 serializer.startDocument(null, true); 13711 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13712 13713 synchronized (mPackages) { 13714 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13715 } 13716 13717 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13718 serializer.endDocument(); 13719 serializer.flush(); 13720 } catch (Exception e) { 13721 if (DEBUG_BACKUP) { 13722 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13723 } 13724 return null; 13725 } 13726 13727 return dataStream.toByteArray(); 13728 } 13729 13730 @Override 13731 public void restorePreferredActivities(byte[] backup, int userId) { 13732 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13733 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13734 } 13735 13736 try { 13737 final XmlPullParser parser = Xml.newPullParser(); 13738 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13739 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13740 new BlobXmlRestorer() { 13741 @Override 13742 public void apply(XmlPullParser parser, int userId) 13743 throws XmlPullParserException, IOException { 13744 synchronized (mPackages) { 13745 mSettings.readPreferredActivitiesLPw(parser, userId); 13746 } 13747 } 13748 } ); 13749 } catch (Exception e) { 13750 if (DEBUG_BACKUP) { 13751 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13752 } 13753 } 13754 } 13755 13756 /** 13757 * Non-Binder method, support for the backup/restore mechanism: write the 13758 * default browser (etc) settings in its canonical XML format. Returns the default 13759 * browser XML representation as a byte array, or null if there is none. 13760 */ 13761 @Override 13762 public byte[] getDefaultAppsBackup(int userId) { 13763 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13764 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13765 } 13766 13767 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13768 try { 13769 final XmlSerializer serializer = new FastXmlSerializer(); 13770 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13771 serializer.startDocument(null, true); 13772 serializer.startTag(null, TAG_DEFAULT_APPS); 13773 13774 synchronized (mPackages) { 13775 mSettings.writeDefaultAppsLPr(serializer, userId); 13776 } 13777 13778 serializer.endTag(null, TAG_DEFAULT_APPS); 13779 serializer.endDocument(); 13780 serializer.flush(); 13781 } catch (Exception e) { 13782 if (DEBUG_BACKUP) { 13783 Slog.e(TAG, "Unable to write default apps for backup", e); 13784 } 13785 return null; 13786 } 13787 13788 return dataStream.toByteArray(); 13789 } 13790 13791 @Override 13792 public void restoreDefaultApps(byte[] backup, int userId) { 13793 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13794 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13795 } 13796 13797 try { 13798 final XmlPullParser parser = Xml.newPullParser(); 13799 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13800 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13801 new BlobXmlRestorer() { 13802 @Override 13803 public void apply(XmlPullParser parser, int userId) 13804 throws XmlPullParserException, IOException { 13805 synchronized (mPackages) { 13806 mSettings.readDefaultAppsLPw(parser, userId); 13807 } 13808 } 13809 } ); 13810 } catch (Exception e) { 13811 if (DEBUG_BACKUP) { 13812 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13813 } 13814 } 13815 } 13816 13817 @Override 13818 public byte[] getIntentFilterVerificationBackup(int userId) { 13819 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13820 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13821 } 13822 13823 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13824 try { 13825 final XmlSerializer serializer = new FastXmlSerializer(); 13826 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13827 serializer.startDocument(null, true); 13828 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13829 13830 synchronized (mPackages) { 13831 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13832 } 13833 13834 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13835 serializer.endDocument(); 13836 serializer.flush(); 13837 } catch (Exception e) { 13838 if (DEBUG_BACKUP) { 13839 Slog.e(TAG, "Unable to write default apps for backup", e); 13840 } 13841 return null; 13842 } 13843 13844 return dataStream.toByteArray(); 13845 } 13846 13847 @Override 13848 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13849 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13850 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13851 } 13852 13853 try { 13854 final XmlPullParser parser = Xml.newPullParser(); 13855 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13856 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13857 new BlobXmlRestorer() { 13858 @Override 13859 public void apply(XmlPullParser parser, int userId) 13860 throws XmlPullParserException, IOException { 13861 synchronized (mPackages) { 13862 mSettings.readAllDomainVerificationsLPr(parser, userId); 13863 mSettings.writeLPr(); 13864 } 13865 } 13866 } ); 13867 } catch (Exception e) { 13868 if (DEBUG_BACKUP) { 13869 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13870 } 13871 } 13872 } 13873 13874 @Override 13875 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13876 int sourceUserId, int targetUserId, int flags) { 13877 mContext.enforceCallingOrSelfPermission( 13878 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13879 int callingUid = Binder.getCallingUid(); 13880 enforceOwnerRights(ownerPackage, callingUid); 13881 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13882 if (intentFilter.countActions() == 0) { 13883 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13884 return; 13885 } 13886 synchronized (mPackages) { 13887 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13888 ownerPackage, targetUserId, flags); 13889 CrossProfileIntentResolver resolver = 13890 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13891 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13892 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13893 if (existing != null) { 13894 int size = existing.size(); 13895 for (int i = 0; i < size; i++) { 13896 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13897 return; 13898 } 13899 } 13900 } 13901 resolver.addFilter(newFilter); 13902 scheduleWritePackageRestrictionsLocked(sourceUserId); 13903 } 13904 } 13905 13906 @Override 13907 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13908 mContext.enforceCallingOrSelfPermission( 13909 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13910 int callingUid = Binder.getCallingUid(); 13911 enforceOwnerRights(ownerPackage, callingUid); 13912 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13913 synchronized (mPackages) { 13914 CrossProfileIntentResolver resolver = 13915 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13916 ArraySet<CrossProfileIntentFilter> set = 13917 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13918 for (CrossProfileIntentFilter filter : set) { 13919 if (filter.getOwnerPackage().equals(ownerPackage)) { 13920 resolver.removeFilter(filter); 13921 } 13922 } 13923 scheduleWritePackageRestrictionsLocked(sourceUserId); 13924 } 13925 } 13926 13927 // Enforcing that callingUid is owning pkg on userId 13928 private void enforceOwnerRights(String pkg, int callingUid) { 13929 // The system owns everything. 13930 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13931 return; 13932 } 13933 int callingUserId = UserHandle.getUserId(callingUid); 13934 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13935 if (pi == null) { 13936 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13937 + callingUserId); 13938 } 13939 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13940 throw new SecurityException("Calling uid " + callingUid 13941 + " does not own package " + pkg); 13942 } 13943 } 13944 13945 @Override 13946 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13947 Intent intent = new Intent(Intent.ACTION_MAIN); 13948 intent.addCategory(Intent.CATEGORY_HOME); 13949 13950 final int callingUserId = UserHandle.getCallingUserId(); 13951 List<ResolveInfo> list = queryIntentActivities(intent, null, 13952 PackageManager.GET_META_DATA, callingUserId); 13953 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13954 true, false, false, callingUserId); 13955 13956 allHomeCandidates.clear(); 13957 if (list != null) { 13958 for (ResolveInfo ri : list) { 13959 allHomeCandidates.add(ri); 13960 } 13961 } 13962 return (preferred == null || preferred.activityInfo == null) 13963 ? null 13964 : new ComponentName(preferred.activityInfo.packageName, 13965 preferred.activityInfo.name); 13966 } 13967 13968 @Override 13969 public void setApplicationEnabledSetting(String appPackageName, 13970 int newState, int flags, int userId, String callingPackage) { 13971 if (!sUserManager.exists(userId)) return; 13972 if (callingPackage == null) { 13973 callingPackage = Integer.toString(Binder.getCallingUid()); 13974 } 13975 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13976 } 13977 13978 @Override 13979 public void setComponentEnabledSetting(ComponentName componentName, 13980 int newState, int flags, int userId) { 13981 if (!sUserManager.exists(userId)) return; 13982 setEnabledSetting(componentName.getPackageName(), 13983 componentName.getClassName(), newState, flags, userId, null); 13984 } 13985 13986 private void setEnabledSetting(final String packageName, String className, int newState, 13987 final int flags, int userId, String callingPackage) { 13988 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13989 || newState == COMPONENT_ENABLED_STATE_ENABLED 13990 || newState == COMPONENT_ENABLED_STATE_DISABLED 13991 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13992 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13993 throw new IllegalArgumentException("Invalid new component state: " 13994 + newState); 13995 } 13996 PackageSetting pkgSetting; 13997 final int uid = Binder.getCallingUid(); 13998 final int permission = mContext.checkCallingOrSelfPermission( 13999 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14000 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14001 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14002 boolean sendNow = false; 14003 boolean isApp = (className == null); 14004 String componentName = isApp ? packageName : className; 14005 int packageUid = -1; 14006 ArrayList<String> components; 14007 14008 // writer 14009 synchronized (mPackages) { 14010 pkgSetting = mSettings.mPackages.get(packageName); 14011 if (pkgSetting == null) { 14012 if (className == null) { 14013 throw new IllegalArgumentException( 14014 "Unknown package: " + packageName); 14015 } 14016 throw new IllegalArgumentException( 14017 "Unknown component: " + packageName 14018 + "/" + className); 14019 } 14020 // Allow root and verify that userId is not being specified by a different user 14021 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14022 throw new SecurityException( 14023 "Permission Denial: attempt to change component state from pid=" 14024 + Binder.getCallingPid() 14025 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14026 } 14027 if (className == null) { 14028 // We're dealing with an application/package level state change 14029 if (pkgSetting.getEnabled(userId) == newState) { 14030 // Nothing to do 14031 return; 14032 } 14033 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14034 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14035 // Don't care about who enables an app. 14036 callingPackage = null; 14037 } 14038 pkgSetting.setEnabled(newState, userId, callingPackage); 14039 // pkgSetting.pkg.mSetEnabled = newState; 14040 } else { 14041 // We're dealing with a component level state change 14042 // First, verify that this is a valid class name. 14043 PackageParser.Package pkg = pkgSetting.pkg; 14044 if (pkg == null || !pkg.hasComponentClassName(className)) { 14045 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14046 throw new IllegalArgumentException("Component class " + className 14047 + " does not exist in " + packageName); 14048 } else { 14049 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14050 + className + " does not exist in " + packageName); 14051 } 14052 } 14053 switch (newState) { 14054 case COMPONENT_ENABLED_STATE_ENABLED: 14055 if (!pkgSetting.enableComponentLPw(className, userId)) { 14056 return; 14057 } 14058 break; 14059 case COMPONENT_ENABLED_STATE_DISABLED: 14060 if (!pkgSetting.disableComponentLPw(className, userId)) { 14061 return; 14062 } 14063 break; 14064 case COMPONENT_ENABLED_STATE_DEFAULT: 14065 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14066 return; 14067 } 14068 break; 14069 default: 14070 Slog.e(TAG, "Invalid new component state: " + newState); 14071 return; 14072 } 14073 } 14074 scheduleWritePackageRestrictionsLocked(userId); 14075 components = mPendingBroadcasts.get(userId, packageName); 14076 final boolean newPackage = components == null; 14077 if (newPackage) { 14078 components = new ArrayList<String>(); 14079 } 14080 if (!components.contains(componentName)) { 14081 components.add(componentName); 14082 } 14083 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14084 sendNow = true; 14085 // Purge entry from pending broadcast list if another one exists already 14086 // since we are sending one right away. 14087 mPendingBroadcasts.remove(userId, packageName); 14088 } else { 14089 if (newPackage) { 14090 mPendingBroadcasts.put(userId, packageName, components); 14091 } 14092 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14093 // Schedule a message 14094 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14095 } 14096 } 14097 } 14098 14099 long callingId = Binder.clearCallingIdentity(); 14100 try { 14101 if (sendNow) { 14102 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14103 sendPackageChangedBroadcast(packageName, 14104 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14105 } 14106 } finally { 14107 Binder.restoreCallingIdentity(callingId); 14108 } 14109 } 14110 14111 private void sendPackageChangedBroadcast(String packageName, 14112 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14113 if (DEBUG_INSTALL) 14114 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14115 + componentNames); 14116 Bundle extras = new Bundle(4); 14117 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14118 String nameList[] = new String[componentNames.size()]; 14119 componentNames.toArray(nameList); 14120 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14121 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14122 extras.putInt(Intent.EXTRA_UID, packageUid); 14123 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14124 new int[] {UserHandle.getUserId(packageUid)}); 14125 } 14126 14127 @Override 14128 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14129 if (!sUserManager.exists(userId)) return; 14130 final int uid = Binder.getCallingUid(); 14131 final int permission = mContext.checkCallingOrSelfPermission( 14132 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14133 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14134 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14135 // writer 14136 synchronized (mPackages) { 14137 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14138 allowedByPermission, uid, userId)) { 14139 scheduleWritePackageRestrictionsLocked(userId); 14140 } 14141 } 14142 } 14143 14144 @Override 14145 public String getInstallerPackageName(String packageName) { 14146 // reader 14147 synchronized (mPackages) { 14148 return mSettings.getInstallerPackageNameLPr(packageName); 14149 } 14150 } 14151 14152 @Override 14153 public int getApplicationEnabledSetting(String packageName, int userId) { 14154 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14155 int uid = Binder.getCallingUid(); 14156 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14157 // reader 14158 synchronized (mPackages) { 14159 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14160 } 14161 } 14162 14163 @Override 14164 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14165 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14166 int uid = Binder.getCallingUid(); 14167 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14168 // reader 14169 synchronized (mPackages) { 14170 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14171 } 14172 } 14173 14174 @Override 14175 public void enterSafeMode() { 14176 enforceSystemOrRoot("Only the system can request entering safe mode"); 14177 14178 if (!mSystemReady) { 14179 mSafeMode = true; 14180 } 14181 } 14182 14183 @Override 14184 public void systemReady() { 14185 mSystemReady = true; 14186 14187 // Read the compatibilty setting when the system is ready. 14188 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14189 mContext.getContentResolver(), 14190 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14191 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14192 if (DEBUG_SETTINGS) { 14193 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14194 } 14195 14196 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14197 14198 synchronized (mPackages) { 14199 // Verify that all of the preferred activity components actually 14200 // exist. It is possible for applications to be updated and at 14201 // that point remove a previously declared activity component that 14202 // had been set as a preferred activity. We try to clean this up 14203 // the next time we encounter that preferred activity, but it is 14204 // possible for the user flow to never be able to return to that 14205 // situation so here we do a sanity check to make sure we haven't 14206 // left any junk around. 14207 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14208 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14209 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14210 removed.clear(); 14211 for (PreferredActivity pa : pir.filterSet()) { 14212 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14213 removed.add(pa); 14214 } 14215 } 14216 if (removed.size() > 0) { 14217 for (int r=0; r<removed.size(); r++) { 14218 PreferredActivity pa = removed.get(r); 14219 Slog.w(TAG, "Removing dangling preferred activity: " 14220 + pa.mPref.mComponent); 14221 pir.removeFilter(pa); 14222 } 14223 mSettings.writePackageRestrictionsLPr( 14224 mSettings.mPreferredActivities.keyAt(i)); 14225 } 14226 } 14227 14228 for (int userId : UserManagerService.getInstance().getUserIds()) { 14229 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14230 grantPermissionsUserIds = ArrayUtils.appendInt( 14231 grantPermissionsUserIds, userId); 14232 } 14233 } 14234 } 14235 sUserManager.systemReady(); 14236 14237 // If we upgraded grant all default permissions before kicking off. 14238 for (int userId : grantPermissionsUserIds) { 14239 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14240 } 14241 14242 // Kick off any messages waiting for system ready 14243 if (mPostSystemReadyMessages != null) { 14244 for (Message msg : mPostSystemReadyMessages) { 14245 msg.sendToTarget(); 14246 } 14247 mPostSystemReadyMessages = null; 14248 } 14249 14250 // Watch for external volumes that come and go over time 14251 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14252 storage.registerListener(mStorageListener); 14253 14254 mInstallerService.systemReady(); 14255 mPackageDexOptimizer.systemReady(); 14256 } 14257 14258 @Override 14259 public boolean isSafeMode() { 14260 return mSafeMode; 14261 } 14262 14263 @Override 14264 public boolean hasSystemUidErrors() { 14265 return mHasSystemUidErrors; 14266 } 14267 14268 static String arrayToString(int[] array) { 14269 StringBuffer buf = new StringBuffer(128); 14270 buf.append('['); 14271 if (array != null) { 14272 for (int i=0; i<array.length; i++) { 14273 if (i > 0) buf.append(", "); 14274 buf.append(array[i]); 14275 } 14276 } 14277 buf.append(']'); 14278 return buf.toString(); 14279 } 14280 14281 static class DumpState { 14282 public static final int DUMP_LIBS = 1 << 0; 14283 public static final int DUMP_FEATURES = 1 << 1; 14284 public static final int DUMP_RESOLVERS = 1 << 2; 14285 public static final int DUMP_PERMISSIONS = 1 << 3; 14286 public static final int DUMP_PACKAGES = 1 << 4; 14287 public static final int DUMP_SHARED_USERS = 1 << 5; 14288 public static final int DUMP_MESSAGES = 1 << 6; 14289 public static final int DUMP_PROVIDERS = 1 << 7; 14290 public static final int DUMP_VERIFIERS = 1 << 8; 14291 public static final int DUMP_PREFERRED = 1 << 9; 14292 public static final int DUMP_PREFERRED_XML = 1 << 10; 14293 public static final int DUMP_KEYSETS = 1 << 11; 14294 public static final int DUMP_VERSION = 1 << 12; 14295 public static final int DUMP_INSTALLS = 1 << 13; 14296 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14297 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14298 14299 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14300 14301 private int mTypes; 14302 14303 private int mOptions; 14304 14305 private boolean mTitlePrinted; 14306 14307 private SharedUserSetting mSharedUser; 14308 14309 public boolean isDumping(int type) { 14310 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14311 return true; 14312 } 14313 14314 return (mTypes & type) != 0; 14315 } 14316 14317 public void setDump(int type) { 14318 mTypes |= type; 14319 } 14320 14321 public boolean isOptionEnabled(int option) { 14322 return (mOptions & option) != 0; 14323 } 14324 14325 public void setOptionEnabled(int option) { 14326 mOptions |= option; 14327 } 14328 14329 public boolean onTitlePrinted() { 14330 final boolean printed = mTitlePrinted; 14331 mTitlePrinted = true; 14332 return printed; 14333 } 14334 14335 public boolean getTitlePrinted() { 14336 return mTitlePrinted; 14337 } 14338 14339 public void setTitlePrinted(boolean enabled) { 14340 mTitlePrinted = enabled; 14341 } 14342 14343 public SharedUserSetting getSharedUser() { 14344 return mSharedUser; 14345 } 14346 14347 public void setSharedUser(SharedUserSetting user) { 14348 mSharedUser = user; 14349 } 14350 } 14351 14352 @Override 14353 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14354 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14355 != PackageManager.PERMISSION_GRANTED) { 14356 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14357 + Binder.getCallingPid() 14358 + ", uid=" + Binder.getCallingUid() 14359 + " without permission " 14360 + android.Manifest.permission.DUMP); 14361 return; 14362 } 14363 14364 DumpState dumpState = new DumpState(); 14365 boolean fullPreferred = false; 14366 boolean checkin = false; 14367 14368 String packageName = null; 14369 ArraySet<String> permissionNames = null; 14370 14371 int opti = 0; 14372 while (opti < args.length) { 14373 String opt = args[opti]; 14374 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14375 break; 14376 } 14377 opti++; 14378 14379 if ("-a".equals(opt)) { 14380 // Right now we only know how to print all. 14381 } else if ("-h".equals(opt)) { 14382 pw.println("Package manager dump options:"); 14383 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14384 pw.println(" --checkin: dump for a checkin"); 14385 pw.println(" -f: print details of intent filters"); 14386 pw.println(" -h: print this help"); 14387 pw.println(" cmd may be one of:"); 14388 pw.println(" l[ibraries]: list known shared libraries"); 14389 pw.println(" f[ibraries]: list device features"); 14390 pw.println(" k[eysets]: print known keysets"); 14391 pw.println(" r[esolvers]: dump intent resolvers"); 14392 pw.println(" perm[issions]: dump permissions"); 14393 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14394 pw.println(" pref[erred]: print preferred package settings"); 14395 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14396 pw.println(" prov[iders]: dump content providers"); 14397 pw.println(" p[ackages]: dump installed packages"); 14398 pw.println(" s[hared-users]: dump shared user IDs"); 14399 pw.println(" m[essages]: print collected runtime messages"); 14400 pw.println(" v[erifiers]: print package verifier info"); 14401 pw.println(" version: print database version info"); 14402 pw.println(" write: write current settings now"); 14403 pw.println(" <package.name>: info about given package"); 14404 pw.println(" installs: details about install sessions"); 14405 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14406 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14407 return; 14408 } else if ("--checkin".equals(opt)) { 14409 checkin = true; 14410 } else if ("-f".equals(opt)) { 14411 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14412 } else { 14413 pw.println("Unknown argument: " + opt + "; use -h for help"); 14414 } 14415 } 14416 14417 // Is the caller requesting to dump a particular piece of data? 14418 if (opti < args.length) { 14419 String cmd = args[opti]; 14420 opti++; 14421 // Is this a package name? 14422 if ("android".equals(cmd) || cmd.contains(".")) { 14423 packageName = cmd; 14424 // When dumping a single package, we always dump all of its 14425 // filter information since the amount of data will be reasonable. 14426 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14427 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14428 dumpState.setDump(DumpState.DUMP_LIBS); 14429 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14430 dumpState.setDump(DumpState.DUMP_FEATURES); 14431 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14432 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14433 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14434 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14435 } else if ("permission".equals(cmd)) { 14436 if (opti >= args.length) { 14437 pw.println("Error: permission requires permission name"); 14438 return; 14439 } 14440 permissionNames = new ArraySet<>(); 14441 while (opti < args.length) { 14442 permissionNames.add(args[opti]); 14443 opti++; 14444 } 14445 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14446 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14447 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14448 dumpState.setDump(DumpState.DUMP_PREFERRED); 14449 } else if ("preferred-xml".equals(cmd)) { 14450 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14451 if (opti < args.length && "--full".equals(args[opti])) { 14452 fullPreferred = true; 14453 opti++; 14454 } 14455 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14456 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14457 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14458 dumpState.setDump(DumpState.DUMP_PACKAGES); 14459 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14460 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14461 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14462 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14463 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14464 dumpState.setDump(DumpState.DUMP_MESSAGES); 14465 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14466 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14467 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14468 || "intent-filter-verifiers".equals(cmd)) { 14469 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14470 } else if ("version".equals(cmd)) { 14471 dumpState.setDump(DumpState.DUMP_VERSION); 14472 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14473 dumpState.setDump(DumpState.DUMP_KEYSETS); 14474 } else if ("installs".equals(cmd)) { 14475 dumpState.setDump(DumpState.DUMP_INSTALLS); 14476 } else if ("write".equals(cmd)) { 14477 synchronized (mPackages) { 14478 mSettings.writeLPr(); 14479 pw.println("Settings written."); 14480 return; 14481 } 14482 } 14483 } 14484 14485 if (checkin) { 14486 pw.println("vers,1"); 14487 } 14488 14489 // reader 14490 synchronized (mPackages) { 14491 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14492 if (!checkin) { 14493 if (dumpState.onTitlePrinted()) 14494 pw.println(); 14495 pw.println("Database versions:"); 14496 pw.print(" SDK Version:"); 14497 pw.print(" internal="); 14498 pw.print(mSettings.mInternalSdkPlatform); 14499 pw.print(" external="); 14500 pw.println(mSettings.mExternalSdkPlatform); 14501 pw.print(" DB Version:"); 14502 pw.print(" internal="); 14503 pw.print(mSettings.mInternalDatabaseVersion); 14504 pw.print(" external="); 14505 pw.println(mSettings.mExternalDatabaseVersion); 14506 } 14507 } 14508 14509 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14510 if (!checkin) { 14511 if (dumpState.onTitlePrinted()) 14512 pw.println(); 14513 pw.println("Verifiers:"); 14514 pw.print(" Required: "); 14515 pw.print(mRequiredVerifierPackage); 14516 pw.print(" (uid="); 14517 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14518 pw.println(")"); 14519 } else if (mRequiredVerifierPackage != null) { 14520 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14521 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14522 } 14523 } 14524 14525 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14526 packageName == null) { 14527 if (mIntentFilterVerifierComponent != null) { 14528 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14529 if (!checkin) { 14530 if (dumpState.onTitlePrinted()) 14531 pw.println(); 14532 pw.println("Intent Filter Verifier:"); 14533 pw.print(" Using: "); 14534 pw.print(verifierPackageName); 14535 pw.print(" (uid="); 14536 pw.print(getPackageUid(verifierPackageName, 0)); 14537 pw.println(")"); 14538 } else if (verifierPackageName != null) { 14539 pw.print("ifv,"); pw.print(verifierPackageName); 14540 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14541 } 14542 } else { 14543 pw.println(); 14544 pw.println("No Intent Filter Verifier available!"); 14545 } 14546 } 14547 14548 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14549 boolean printedHeader = false; 14550 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14551 while (it.hasNext()) { 14552 String name = it.next(); 14553 SharedLibraryEntry ent = mSharedLibraries.get(name); 14554 if (!checkin) { 14555 if (!printedHeader) { 14556 if (dumpState.onTitlePrinted()) 14557 pw.println(); 14558 pw.println("Libraries:"); 14559 printedHeader = true; 14560 } 14561 pw.print(" "); 14562 } else { 14563 pw.print("lib,"); 14564 } 14565 pw.print(name); 14566 if (!checkin) { 14567 pw.print(" -> "); 14568 } 14569 if (ent.path != null) { 14570 if (!checkin) { 14571 pw.print("(jar) "); 14572 pw.print(ent.path); 14573 } else { 14574 pw.print(",jar,"); 14575 pw.print(ent.path); 14576 } 14577 } else { 14578 if (!checkin) { 14579 pw.print("(apk) "); 14580 pw.print(ent.apk); 14581 } else { 14582 pw.print(",apk,"); 14583 pw.print(ent.apk); 14584 } 14585 } 14586 pw.println(); 14587 } 14588 } 14589 14590 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14591 if (dumpState.onTitlePrinted()) 14592 pw.println(); 14593 if (!checkin) { 14594 pw.println("Features:"); 14595 } 14596 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14597 while (it.hasNext()) { 14598 String name = it.next(); 14599 if (!checkin) { 14600 pw.print(" "); 14601 } else { 14602 pw.print("feat,"); 14603 } 14604 pw.println(name); 14605 } 14606 } 14607 14608 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14609 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14610 : "Activity Resolver Table:", " ", packageName, 14611 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14612 dumpState.setTitlePrinted(true); 14613 } 14614 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14615 : "Receiver Resolver Table:", " ", packageName, 14616 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14617 dumpState.setTitlePrinted(true); 14618 } 14619 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14620 : "Service Resolver Table:", " ", packageName, 14621 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14622 dumpState.setTitlePrinted(true); 14623 } 14624 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14625 : "Provider Resolver Table:", " ", packageName, 14626 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14627 dumpState.setTitlePrinted(true); 14628 } 14629 } 14630 14631 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14632 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14633 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14634 int user = mSettings.mPreferredActivities.keyAt(i); 14635 if (pir.dump(pw, 14636 dumpState.getTitlePrinted() 14637 ? "\nPreferred Activities User " + user + ":" 14638 : "Preferred Activities User " + user + ":", " ", 14639 packageName, true, false)) { 14640 dumpState.setTitlePrinted(true); 14641 } 14642 } 14643 } 14644 14645 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14646 pw.flush(); 14647 FileOutputStream fout = new FileOutputStream(fd); 14648 BufferedOutputStream str = new BufferedOutputStream(fout); 14649 XmlSerializer serializer = new FastXmlSerializer(); 14650 try { 14651 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14652 serializer.startDocument(null, true); 14653 serializer.setFeature( 14654 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14655 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14656 serializer.endDocument(); 14657 serializer.flush(); 14658 } catch (IllegalArgumentException e) { 14659 pw.println("Failed writing: " + e); 14660 } catch (IllegalStateException e) { 14661 pw.println("Failed writing: " + e); 14662 } catch (IOException e) { 14663 pw.println("Failed writing: " + e); 14664 } 14665 } 14666 14667 if (!checkin 14668 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14669 && packageName == null) { 14670 pw.println(); 14671 int count = mSettings.mPackages.size(); 14672 if (count == 0) { 14673 pw.println("No domain preferred apps!"); 14674 pw.println(); 14675 } else { 14676 final String prefix = " "; 14677 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14678 if (allPackageSettings.size() == 0) { 14679 pw.println("No domain preferred apps!"); 14680 pw.println(); 14681 } else { 14682 pw.println("Domain preferred apps status:"); 14683 pw.println(); 14684 count = 0; 14685 for (PackageSetting ps : allPackageSettings) { 14686 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14687 if (ivi == null || ivi.getPackageName() == null) continue; 14688 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14689 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14690 pw.println(prefix + "Status: " + ivi.getStatusString()); 14691 pw.println(); 14692 count++; 14693 } 14694 if (count == 0) { 14695 pw.println(prefix + "No domain preferred app status!"); 14696 pw.println(); 14697 } 14698 for (int userId : sUserManager.getUserIds()) { 14699 pw.println("Domain preferred apps for User " + userId + ":"); 14700 pw.println(); 14701 count = 0; 14702 for (PackageSetting ps : allPackageSettings) { 14703 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14704 if (ivi == null || ivi.getPackageName() == null) { 14705 continue; 14706 } 14707 final int status = ps.getDomainVerificationStatusForUser(userId); 14708 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14709 continue; 14710 } 14711 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14712 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14713 String statusStr = IntentFilterVerificationInfo. 14714 getStatusStringFromValue(status); 14715 pw.println(prefix + "Status: " + statusStr); 14716 pw.println(); 14717 count++; 14718 } 14719 if (count == 0) { 14720 pw.println(prefix + "No domain preferred apps!"); 14721 pw.println(); 14722 } 14723 } 14724 } 14725 } 14726 } 14727 14728 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14729 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14730 if (packageName == null && permissionNames == null) { 14731 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14732 if (iperm == 0) { 14733 if (dumpState.onTitlePrinted()) 14734 pw.println(); 14735 pw.println("AppOp Permissions:"); 14736 } 14737 pw.print(" AppOp Permission "); 14738 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14739 pw.println(":"); 14740 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14741 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14742 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14743 } 14744 } 14745 } 14746 } 14747 14748 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14749 boolean printedSomething = false; 14750 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14751 if (packageName != null && !packageName.equals(p.info.packageName)) { 14752 continue; 14753 } 14754 if (!printedSomething) { 14755 if (dumpState.onTitlePrinted()) 14756 pw.println(); 14757 pw.println("Registered ContentProviders:"); 14758 printedSomething = true; 14759 } 14760 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14761 pw.print(" "); pw.println(p.toString()); 14762 } 14763 printedSomething = false; 14764 for (Map.Entry<String, PackageParser.Provider> entry : 14765 mProvidersByAuthority.entrySet()) { 14766 PackageParser.Provider p = entry.getValue(); 14767 if (packageName != null && !packageName.equals(p.info.packageName)) { 14768 continue; 14769 } 14770 if (!printedSomething) { 14771 if (dumpState.onTitlePrinted()) 14772 pw.println(); 14773 pw.println("ContentProvider Authorities:"); 14774 printedSomething = true; 14775 } 14776 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14777 pw.print(" "); pw.println(p.toString()); 14778 if (p.info != null && p.info.applicationInfo != null) { 14779 final String appInfo = p.info.applicationInfo.toString(); 14780 pw.print(" applicationInfo="); pw.println(appInfo); 14781 } 14782 } 14783 } 14784 14785 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14786 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14787 } 14788 14789 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14790 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14791 } 14792 14793 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14794 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14795 } 14796 14797 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14798 // XXX should handle packageName != null by dumping only install data that 14799 // the given package is involved with. 14800 if (dumpState.onTitlePrinted()) pw.println(); 14801 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14802 } 14803 14804 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14805 if (dumpState.onTitlePrinted()) pw.println(); 14806 mSettings.dumpReadMessagesLPr(pw, dumpState); 14807 14808 pw.println(); 14809 pw.println("Package warning messages:"); 14810 BufferedReader in = null; 14811 String line = null; 14812 try { 14813 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14814 while ((line = in.readLine()) != null) { 14815 if (line.contains("ignored: updated version")) continue; 14816 pw.println(line); 14817 } 14818 } catch (IOException ignored) { 14819 } finally { 14820 IoUtils.closeQuietly(in); 14821 } 14822 } 14823 14824 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14825 BufferedReader in = null; 14826 String line = null; 14827 try { 14828 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14829 while ((line = in.readLine()) != null) { 14830 if (line.contains("ignored: updated version")) continue; 14831 pw.print("msg,"); 14832 pw.println(line); 14833 } 14834 } catch (IOException ignored) { 14835 } finally { 14836 IoUtils.closeQuietly(in); 14837 } 14838 } 14839 } 14840 } 14841 14842 // ------- apps on sdcard specific code ------- 14843 static final boolean DEBUG_SD_INSTALL = false; 14844 14845 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14846 14847 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14848 14849 private boolean mMediaMounted = false; 14850 14851 static String getEncryptKey() { 14852 try { 14853 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14854 SD_ENCRYPTION_KEYSTORE_NAME); 14855 if (sdEncKey == null) { 14856 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14857 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14858 if (sdEncKey == null) { 14859 Slog.e(TAG, "Failed to create encryption keys"); 14860 return null; 14861 } 14862 } 14863 return sdEncKey; 14864 } catch (NoSuchAlgorithmException nsae) { 14865 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14866 return null; 14867 } catch (IOException ioe) { 14868 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14869 return null; 14870 } 14871 } 14872 14873 /* 14874 * Update media status on PackageManager. 14875 */ 14876 @Override 14877 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14878 int callingUid = Binder.getCallingUid(); 14879 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14880 throw new SecurityException("Media status can only be updated by the system"); 14881 } 14882 // reader; this apparently protects mMediaMounted, but should probably 14883 // be a different lock in that case. 14884 synchronized (mPackages) { 14885 Log.i(TAG, "Updating external media status from " 14886 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14887 + (mediaStatus ? "mounted" : "unmounted")); 14888 if (DEBUG_SD_INSTALL) 14889 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14890 + ", mMediaMounted=" + mMediaMounted); 14891 if (mediaStatus == mMediaMounted) { 14892 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14893 : 0, -1); 14894 mHandler.sendMessage(msg); 14895 return; 14896 } 14897 mMediaMounted = mediaStatus; 14898 } 14899 // Queue up an async operation since the package installation may take a 14900 // little while. 14901 mHandler.post(new Runnable() { 14902 public void run() { 14903 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14904 } 14905 }); 14906 } 14907 14908 /** 14909 * Called by MountService when the initial ASECs to scan are available. 14910 * Should block until all the ASEC containers are finished being scanned. 14911 */ 14912 public void scanAvailableAsecs() { 14913 updateExternalMediaStatusInner(true, false, false); 14914 if (mShouldRestoreconData) { 14915 SELinuxMMAC.setRestoreconDone(); 14916 mShouldRestoreconData = false; 14917 } 14918 } 14919 14920 /* 14921 * Collect information of applications on external media, map them against 14922 * existing containers and update information based on current mount status. 14923 * Please note that we always have to report status if reportStatus has been 14924 * set to true especially when unloading packages. 14925 */ 14926 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14927 boolean externalStorage) { 14928 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14929 int[] uidArr = EmptyArray.INT; 14930 14931 final String[] list = PackageHelper.getSecureContainerList(); 14932 if (ArrayUtils.isEmpty(list)) { 14933 Log.i(TAG, "No secure containers found"); 14934 } else { 14935 // Process list of secure containers and categorize them 14936 // as active or stale based on their package internal state. 14937 14938 // reader 14939 synchronized (mPackages) { 14940 for (String cid : list) { 14941 // Leave stages untouched for now; installer service owns them 14942 if (PackageInstallerService.isStageName(cid)) continue; 14943 14944 if (DEBUG_SD_INSTALL) 14945 Log.i(TAG, "Processing container " + cid); 14946 String pkgName = getAsecPackageName(cid); 14947 if (pkgName == null) { 14948 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14949 continue; 14950 } 14951 if (DEBUG_SD_INSTALL) 14952 Log.i(TAG, "Looking for pkg : " + pkgName); 14953 14954 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14955 if (ps == null) { 14956 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14957 continue; 14958 } 14959 14960 /* 14961 * Skip packages that are not external if we're unmounting 14962 * external storage. 14963 */ 14964 if (externalStorage && !isMounted && !isExternal(ps)) { 14965 continue; 14966 } 14967 14968 final AsecInstallArgs args = new AsecInstallArgs(cid, 14969 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14970 // The package status is changed only if the code path 14971 // matches between settings and the container id. 14972 if (ps.codePathString != null 14973 && ps.codePathString.startsWith(args.getCodePath())) { 14974 if (DEBUG_SD_INSTALL) { 14975 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14976 + " at code path: " + ps.codePathString); 14977 } 14978 14979 // We do have a valid package installed on sdcard 14980 processCids.put(args, ps.codePathString); 14981 final int uid = ps.appId; 14982 if (uid != -1) { 14983 uidArr = ArrayUtils.appendInt(uidArr, uid); 14984 } 14985 } else { 14986 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14987 + ps.codePathString); 14988 } 14989 } 14990 } 14991 14992 Arrays.sort(uidArr); 14993 } 14994 14995 // Process packages with valid entries. 14996 if (isMounted) { 14997 if (DEBUG_SD_INSTALL) 14998 Log.i(TAG, "Loading packages"); 14999 loadMediaPackages(processCids, uidArr); 15000 startCleaningPackages(); 15001 mInstallerService.onSecureContainersAvailable(); 15002 } else { 15003 if (DEBUG_SD_INSTALL) 15004 Log.i(TAG, "Unloading packages"); 15005 unloadMediaPackages(processCids, uidArr, reportStatus); 15006 } 15007 } 15008 15009 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15010 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15011 final int size = infos.size(); 15012 final String[] packageNames = new String[size]; 15013 final int[] packageUids = new int[size]; 15014 for (int i = 0; i < size; i++) { 15015 final ApplicationInfo info = infos.get(i); 15016 packageNames[i] = info.packageName; 15017 packageUids[i] = info.uid; 15018 } 15019 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15020 finishedReceiver); 15021 } 15022 15023 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15024 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15025 sendResourcesChangedBroadcast(mediaStatus, replacing, 15026 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15027 } 15028 15029 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15030 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15031 int size = pkgList.length; 15032 if (size > 0) { 15033 // Send broadcasts here 15034 Bundle extras = new Bundle(); 15035 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15036 if (uidArr != null) { 15037 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15038 } 15039 if (replacing) { 15040 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15041 } 15042 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15043 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15044 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15045 } 15046 } 15047 15048 /* 15049 * Look at potentially valid container ids from processCids If package 15050 * information doesn't match the one on record or package scanning fails, 15051 * the cid is added to list of removeCids. We currently don't delete stale 15052 * containers. 15053 */ 15054 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15055 ArrayList<String> pkgList = new ArrayList<String>(); 15056 Set<AsecInstallArgs> keys = processCids.keySet(); 15057 15058 for (AsecInstallArgs args : keys) { 15059 String codePath = processCids.get(args); 15060 if (DEBUG_SD_INSTALL) 15061 Log.i(TAG, "Loading container : " + args.cid); 15062 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15063 try { 15064 // Make sure there are no container errors first. 15065 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15066 Slog.e(TAG, "Failed to mount cid : " + args.cid 15067 + " when installing from sdcard"); 15068 continue; 15069 } 15070 // Check code path here. 15071 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15072 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15073 + " does not match one in settings " + codePath); 15074 continue; 15075 } 15076 // Parse package 15077 int parseFlags = mDefParseFlags; 15078 if (args.isExternalAsec()) { 15079 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15080 } 15081 if (args.isFwdLocked()) { 15082 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15083 } 15084 15085 synchronized (mInstallLock) { 15086 PackageParser.Package pkg = null; 15087 try { 15088 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15089 } catch (PackageManagerException e) { 15090 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15091 } 15092 // Scan the package 15093 if (pkg != null) { 15094 /* 15095 * TODO why is the lock being held? doPostInstall is 15096 * called in other places without the lock. This needs 15097 * to be straightened out. 15098 */ 15099 // writer 15100 synchronized (mPackages) { 15101 retCode = PackageManager.INSTALL_SUCCEEDED; 15102 pkgList.add(pkg.packageName); 15103 // Post process args 15104 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15105 pkg.applicationInfo.uid); 15106 } 15107 } else { 15108 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15109 } 15110 } 15111 15112 } finally { 15113 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15114 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15115 } 15116 } 15117 } 15118 // writer 15119 synchronized (mPackages) { 15120 // If the platform SDK has changed since the last time we booted, 15121 // we need to re-grant app permission to catch any new ones that 15122 // appear. This is really a hack, and means that apps can in some 15123 // cases get permissions that the user didn't initially explicitly 15124 // allow... it would be nice to have some better way to handle 15125 // this situation. 15126 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15127 if (regrantPermissions) 15128 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15129 + mSdkVersion + "; regranting permissions for external storage"); 15130 mSettings.mExternalSdkPlatform = mSdkVersion; 15131 15132 // Make sure group IDs have been assigned, and any permission 15133 // changes in other apps are accounted for 15134 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15135 | (regrantPermissions 15136 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15137 : 0)); 15138 15139 mSettings.updateExternalDatabaseVersion(); 15140 15141 // can downgrade to reader 15142 // Persist settings 15143 mSettings.writeLPr(); 15144 } 15145 // Send a broadcast to let everyone know we are done processing 15146 if (pkgList.size() > 0) { 15147 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15148 } 15149 } 15150 15151 /* 15152 * Utility method to unload a list of specified containers 15153 */ 15154 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15155 // Just unmount all valid containers. 15156 for (AsecInstallArgs arg : cidArgs) { 15157 synchronized (mInstallLock) { 15158 arg.doPostDeleteLI(false); 15159 } 15160 } 15161 } 15162 15163 /* 15164 * Unload packages mounted on external media. This involves deleting package 15165 * data from internal structures, sending broadcasts about diabled packages, 15166 * gc'ing to free up references, unmounting all secure containers 15167 * corresponding to packages on external media, and posting a 15168 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15169 * that we always have to post this message if status has been requested no 15170 * matter what. 15171 */ 15172 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15173 final boolean reportStatus) { 15174 if (DEBUG_SD_INSTALL) 15175 Log.i(TAG, "unloading media packages"); 15176 ArrayList<String> pkgList = new ArrayList<String>(); 15177 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15178 final Set<AsecInstallArgs> keys = processCids.keySet(); 15179 for (AsecInstallArgs args : keys) { 15180 String pkgName = args.getPackageName(); 15181 if (DEBUG_SD_INSTALL) 15182 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15183 // Delete package internally 15184 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15185 synchronized (mInstallLock) { 15186 boolean res = deletePackageLI(pkgName, null, false, null, null, 15187 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15188 if (res) { 15189 pkgList.add(pkgName); 15190 } else { 15191 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15192 failedList.add(args); 15193 } 15194 } 15195 } 15196 15197 // reader 15198 synchronized (mPackages) { 15199 // We didn't update the settings after removing each package; 15200 // write them now for all packages. 15201 mSettings.writeLPr(); 15202 } 15203 15204 // We have to absolutely send UPDATED_MEDIA_STATUS only 15205 // after confirming that all the receivers processed the ordered 15206 // broadcast when packages get disabled, force a gc to clean things up. 15207 // and unload all the containers. 15208 if (pkgList.size() > 0) { 15209 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15210 new IIntentReceiver.Stub() { 15211 public void performReceive(Intent intent, int resultCode, String data, 15212 Bundle extras, boolean ordered, boolean sticky, 15213 int sendingUser) throws RemoteException { 15214 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15215 reportStatus ? 1 : 0, 1, keys); 15216 mHandler.sendMessage(msg); 15217 } 15218 }); 15219 } else { 15220 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15221 keys); 15222 mHandler.sendMessage(msg); 15223 } 15224 } 15225 15226 private void loadPrivatePackages(VolumeInfo vol) { 15227 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15228 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15229 synchronized (mInstallLock) { 15230 synchronized (mPackages) { 15231 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15232 for (PackageSetting ps : packages) { 15233 final PackageParser.Package pkg; 15234 try { 15235 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15236 loaded.add(pkg.applicationInfo); 15237 } catch (PackageManagerException e) { 15238 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15239 } 15240 } 15241 15242 // TODO: regrant any permissions that changed based since original install 15243 15244 mSettings.writeLPr(); 15245 } 15246 } 15247 15248 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15249 sendResourcesChangedBroadcast(true, false, loaded, null); 15250 } 15251 15252 private void unloadPrivatePackages(VolumeInfo vol) { 15253 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15254 synchronized (mInstallLock) { 15255 synchronized (mPackages) { 15256 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15257 for (PackageSetting ps : packages) { 15258 if (ps.pkg == null) continue; 15259 15260 final ApplicationInfo info = ps.pkg.applicationInfo; 15261 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15262 if (deletePackageLI(ps.name, null, false, null, null, 15263 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15264 unloaded.add(info); 15265 } else { 15266 Slog.w(TAG, "Failed to unload " + ps.codePath); 15267 } 15268 } 15269 15270 mSettings.writeLPr(); 15271 } 15272 } 15273 15274 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15275 sendResourcesChangedBroadcast(false, false, unloaded, null); 15276 } 15277 15278 /** 15279 * Examine all users present on given mounted volume, and destroy data 15280 * belonging to users that are no longer valid, or whose user ID has been 15281 * recycled. 15282 */ 15283 private void reconcileUsers(String volumeUuid) { 15284 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15285 if (ArrayUtils.isEmpty(files)) { 15286 Slog.d(TAG, "No users found on " + volumeUuid); 15287 return; 15288 } 15289 15290 for (File file : files) { 15291 if (!file.isDirectory()) continue; 15292 15293 final int userId; 15294 final UserInfo info; 15295 try { 15296 userId = Integer.parseInt(file.getName()); 15297 info = sUserManager.getUserInfo(userId); 15298 } catch (NumberFormatException e) { 15299 Slog.w(TAG, "Invalid user directory " + file); 15300 continue; 15301 } 15302 15303 boolean destroyUser = false; 15304 if (info == null) { 15305 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15306 + " because no matching user was found"); 15307 destroyUser = true; 15308 } else { 15309 try { 15310 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15311 } catch (IOException e) { 15312 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15313 + " because we failed to enforce serial number: " + e); 15314 destroyUser = true; 15315 } 15316 } 15317 15318 if (destroyUser) { 15319 synchronized (mInstallLock) { 15320 mInstaller.removeUserDataDirs(volumeUuid, userId); 15321 } 15322 } 15323 } 15324 15325 final UserManager um = mContext.getSystemService(UserManager.class); 15326 for (UserInfo user : um.getUsers()) { 15327 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15328 if (userDir.exists()) continue; 15329 15330 try { 15331 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15332 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15333 } catch (IOException e) { 15334 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15335 } 15336 } 15337 } 15338 15339 /** 15340 * Examine all apps present on given mounted volume, and destroy apps that 15341 * aren't expected, either due to uninstallation or reinstallation on 15342 * another volume. 15343 */ 15344 private void reconcileApps(String volumeUuid) { 15345 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15346 if (ArrayUtils.isEmpty(files)) { 15347 Slog.d(TAG, "No apps found on " + volumeUuid); 15348 return; 15349 } 15350 15351 for (File file : files) { 15352 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15353 && !PackageInstallerService.isStageName(file.getName()); 15354 if (!isPackage) { 15355 // Ignore entries which are not packages 15356 continue; 15357 } 15358 15359 boolean destroyApp = false; 15360 String packageName = null; 15361 try { 15362 final PackageLite pkg = PackageParser.parsePackageLite(file, 15363 PackageParser.PARSE_MUST_BE_APK); 15364 packageName = pkg.packageName; 15365 15366 synchronized (mPackages) { 15367 final PackageSetting ps = mSettings.mPackages.get(packageName); 15368 if (ps == null) { 15369 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15370 + volumeUuid + " because we found no install record"); 15371 destroyApp = true; 15372 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15373 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15374 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15375 destroyApp = true; 15376 } 15377 } 15378 15379 } catch (PackageParserException e) { 15380 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15381 destroyApp = true; 15382 } 15383 15384 if (destroyApp) { 15385 synchronized (mInstallLock) { 15386 if (packageName != null) { 15387 removeDataDirsLI(volumeUuid, packageName); 15388 } 15389 if (file.isDirectory()) { 15390 mInstaller.rmPackageDir(file.getAbsolutePath()); 15391 } else { 15392 file.delete(); 15393 } 15394 } 15395 } 15396 } 15397 } 15398 15399 private void unfreezePackage(String packageName) { 15400 synchronized (mPackages) { 15401 final PackageSetting ps = mSettings.mPackages.get(packageName); 15402 if (ps != null) { 15403 ps.frozen = false; 15404 } 15405 } 15406 } 15407 15408 @Override 15409 public int movePackage(final String packageName, final String volumeUuid) { 15410 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15411 15412 final int moveId = mNextMoveId.getAndIncrement(); 15413 try { 15414 movePackageInternal(packageName, volumeUuid, moveId); 15415 } catch (PackageManagerException e) { 15416 Slog.w(TAG, "Failed to move " + packageName, e); 15417 mMoveCallbacks.notifyStatusChanged(moveId, 15418 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15419 } 15420 return moveId; 15421 } 15422 15423 private void movePackageInternal(final String packageName, final String volumeUuid, 15424 final int moveId) throws PackageManagerException { 15425 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15426 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15427 final PackageManager pm = mContext.getPackageManager(); 15428 15429 final boolean currentAsec; 15430 final String currentVolumeUuid; 15431 final File codeFile; 15432 final String installerPackageName; 15433 final String packageAbiOverride; 15434 final int appId; 15435 final String seinfo; 15436 final String label; 15437 15438 // reader 15439 synchronized (mPackages) { 15440 final PackageParser.Package pkg = mPackages.get(packageName); 15441 final PackageSetting ps = mSettings.mPackages.get(packageName); 15442 if (pkg == null || ps == null) { 15443 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15444 } 15445 15446 if (pkg.applicationInfo.isSystemApp()) { 15447 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15448 "Cannot move system application"); 15449 } 15450 15451 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15452 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15453 "Package already moved to " + volumeUuid); 15454 } 15455 15456 final File probe = new File(pkg.codePath); 15457 final File probeOat = new File(probe, "oat"); 15458 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15459 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15460 "Move only supported for modern cluster style installs"); 15461 } 15462 15463 if (ps.frozen) { 15464 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15465 "Failed to move already frozen package"); 15466 } 15467 ps.frozen = true; 15468 15469 currentAsec = pkg.applicationInfo.isForwardLocked() 15470 || pkg.applicationInfo.isExternalAsec(); 15471 currentVolumeUuid = ps.volumeUuid; 15472 codeFile = new File(pkg.codePath); 15473 installerPackageName = ps.installerPackageName; 15474 packageAbiOverride = ps.cpuAbiOverrideString; 15475 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15476 seinfo = pkg.applicationInfo.seinfo; 15477 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15478 } 15479 15480 // Now that we're guarded by frozen state, kill app during move 15481 killApplication(packageName, appId, "move pkg"); 15482 15483 final Bundle extras = new Bundle(); 15484 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15485 extras.putString(Intent.EXTRA_TITLE, label); 15486 mMoveCallbacks.notifyCreated(moveId, extras); 15487 15488 int installFlags; 15489 final boolean moveCompleteApp; 15490 final File measurePath; 15491 15492 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15493 installFlags = INSTALL_INTERNAL; 15494 moveCompleteApp = !currentAsec; 15495 measurePath = Environment.getDataAppDirectory(volumeUuid); 15496 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15497 installFlags = INSTALL_EXTERNAL; 15498 moveCompleteApp = false; 15499 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15500 } else { 15501 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15502 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15503 || !volume.isMountedWritable()) { 15504 unfreezePackage(packageName); 15505 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15506 "Move location not mounted private volume"); 15507 } 15508 15509 Preconditions.checkState(!currentAsec); 15510 15511 installFlags = INSTALL_INTERNAL; 15512 moveCompleteApp = true; 15513 measurePath = Environment.getDataAppDirectory(volumeUuid); 15514 } 15515 15516 final PackageStats stats = new PackageStats(null, -1); 15517 synchronized (mInstaller) { 15518 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15519 unfreezePackage(packageName); 15520 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15521 "Failed to measure package size"); 15522 } 15523 } 15524 15525 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15526 + stats.dataSize); 15527 15528 final long startFreeBytes = measurePath.getFreeSpace(); 15529 final long sizeBytes; 15530 if (moveCompleteApp) { 15531 sizeBytes = stats.codeSize + stats.dataSize; 15532 } else { 15533 sizeBytes = stats.codeSize; 15534 } 15535 15536 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15537 unfreezePackage(packageName); 15538 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15539 "Not enough free space to move"); 15540 } 15541 15542 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15543 15544 final CountDownLatch installedLatch = new CountDownLatch(1); 15545 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15546 @Override 15547 public void onUserActionRequired(Intent intent) throws RemoteException { 15548 throw new IllegalStateException(); 15549 } 15550 15551 @Override 15552 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15553 Bundle extras) throws RemoteException { 15554 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15555 + PackageManager.installStatusToString(returnCode, msg)); 15556 15557 installedLatch.countDown(); 15558 15559 // Regardless of success or failure of the move operation, 15560 // always unfreeze the package 15561 unfreezePackage(packageName); 15562 15563 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15564 switch (status) { 15565 case PackageInstaller.STATUS_SUCCESS: 15566 mMoveCallbacks.notifyStatusChanged(moveId, 15567 PackageManager.MOVE_SUCCEEDED); 15568 break; 15569 case PackageInstaller.STATUS_FAILURE_STORAGE: 15570 mMoveCallbacks.notifyStatusChanged(moveId, 15571 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15572 break; 15573 default: 15574 mMoveCallbacks.notifyStatusChanged(moveId, 15575 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15576 break; 15577 } 15578 } 15579 }; 15580 15581 final MoveInfo move; 15582 if (moveCompleteApp) { 15583 // Kick off a thread to report progress estimates 15584 new Thread() { 15585 @Override 15586 public void run() { 15587 while (true) { 15588 try { 15589 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15590 break; 15591 } 15592 } catch (InterruptedException ignored) { 15593 } 15594 15595 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15596 final int progress = 10 + (int) MathUtils.constrain( 15597 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15598 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15599 } 15600 } 15601 }.start(); 15602 15603 final String dataAppName = codeFile.getName(); 15604 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15605 dataAppName, appId, seinfo); 15606 } else { 15607 move = null; 15608 } 15609 15610 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15611 15612 final Message msg = mHandler.obtainMessage(INIT_COPY); 15613 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15614 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15615 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15616 mHandler.sendMessage(msg); 15617 } 15618 15619 @Override 15620 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15621 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15622 15623 final int realMoveId = mNextMoveId.getAndIncrement(); 15624 final Bundle extras = new Bundle(); 15625 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15626 mMoveCallbacks.notifyCreated(realMoveId, extras); 15627 15628 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15629 @Override 15630 public void onCreated(int moveId, Bundle extras) { 15631 // Ignored 15632 } 15633 15634 @Override 15635 public void onStatusChanged(int moveId, int status, long estMillis) { 15636 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15637 } 15638 }; 15639 15640 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15641 storage.setPrimaryStorageUuid(volumeUuid, callback); 15642 return realMoveId; 15643 } 15644 15645 @Override 15646 public int getMoveStatus(int moveId) { 15647 mContext.enforceCallingOrSelfPermission( 15648 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15649 return mMoveCallbacks.mLastStatus.get(moveId); 15650 } 15651 15652 @Override 15653 public void registerMoveCallback(IPackageMoveObserver callback) { 15654 mContext.enforceCallingOrSelfPermission( 15655 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15656 mMoveCallbacks.register(callback); 15657 } 15658 15659 @Override 15660 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15661 mContext.enforceCallingOrSelfPermission( 15662 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15663 mMoveCallbacks.unregister(callback); 15664 } 15665 15666 @Override 15667 public boolean setInstallLocation(int loc) { 15668 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15669 null); 15670 if (getInstallLocation() == loc) { 15671 return true; 15672 } 15673 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15674 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15675 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15676 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15677 return true; 15678 } 15679 return false; 15680 } 15681 15682 @Override 15683 public int getInstallLocation() { 15684 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15685 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15686 PackageHelper.APP_INSTALL_AUTO); 15687 } 15688 15689 /** Called by UserManagerService */ 15690 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15691 mDirtyUsers.remove(userHandle); 15692 mSettings.removeUserLPw(userHandle); 15693 mPendingBroadcasts.remove(userHandle); 15694 if (mInstaller != null) { 15695 // Technically, we shouldn't be doing this with the package lock 15696 // held. However, this is very rare, and there is already so much 15697 // other disk I/O going on, that we'll let it slide for now. 15698 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15699 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15700 final String volumeUuid = vol.getFsUuid(); 15701 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15702 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15703 } 15704 } 15705 mUserNeedsBadging.delete(userHandle); 15706 removeUnusedPackagesLILPw(userManager, userHandle); 15707 } 15708 15709 /** 15710 * We're removing userHandle and would like to remove any downloaded packages 15711 * that are no longer in use by any other user. 15712 * @param userHandle the user being removed 15713 */ 15714 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15715 final boolean DEBUG_CLEAN_APKS = false; 15716 int [] users = userManager.getUserIdsLPr(); 15717 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15718 while (psit.hasNext()) { 15719 PackageSetting ps = psit.next(); 15720 if (ps.pkg == null) { 15721 continue; 15722 } 15723 final String packageName = ps.pkg.packageName; 15724 // Skip over if system app 15725 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15726 continue; 15727 } 15728 if (DEBUG_CLEAN_APKS) { 15729 Slog.i(TAG, "Checking package " + packageName); 15730 } 15731 boolean keep = false; 15732 for (int i = 0; i < users.length; i++) { 15733 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15734 keep = true; 15735 if (DEBUG_CLEAN_APKS) { 15736 Slog.i(TAG, " Keeping package " + packageName + " for user " 15737 + users[i]); 15738 } 15739 break; 15740 } 15741 } 15742 if (!keep) { 15743 if (DEBUG_CLEAN_APKS) { 15744 Slog.i(TAG, " Removing package " + packageName); 15745 } 15746 mHandler.post(new Runnable() { 15747 public void run() { 15748 deletePackageX(packageName, userHandle, 0); 15749 } //end run 15750 }); 15751 } 15752 } 15753 } 15754 15755 /** Called by UserManagerService */ 15756 void createNewUserLILPw(int userHandle) { 15757 if (mInstaller != null) { 15758 mInstaller.createUserConfig(userHandle); 15759 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15760 applyFactoryDefaultBrowserLPw(userHandle); 15761 } 15762 } 15763 15764 void newUserCreatedLILPw(final int userHandle) { 15765 // We cannot grant the default permissions with a lock held as 15766 // we query providers from other components for default handlers 15767 // such as enabled IMEs, etc. 15768 mHandler.post(new Runnable() { 15769 @Override 15770 public void run() { 15771 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15772 } 15773 }); 15774 } 15775 15776 @Override 15777 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15778 mContext.enforceCallingOrSelfPermission( 15779 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15780 "Only package verification agents can read the verifier device identity"); 15781 15782 synchronized (mPackages) { 15783 return mSettings.getVerifierDeviceIdentityLPw(); 15784 } 15785 } 15786 15787 @Override 15788 public void setPermissionEnforced(String permission, boolean enforced) { 15789 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15790 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15791 synchronized (mPackages) { 15792 if (mSettings.mReadExternalStorageEnforced == null 15793 || mSettings.mReadExternalStorageEnforced != enforced) { 15794 mSettings.mReadExternalStorageEnforced = enforced; 15795 mSettings.writeLPr(); 15796 } 15797 } 15798 // kill any non-foreground processes so we restart them and 15799 // grant/revoke the GID. 15800 final IActivityManager am = ActivityManagerNative.getDefault(); 15801 if (am != null) { 15802 final long token = Binder.clearCallingIdentity(); 15803 try { 15804 am.killProcessesBelowForeground("setPermissionEnforcement"); 15805 } catch (RemoteException e) { 15806 } finally { 15807 Binder.restoreCallingIdentity(token); 15808 } 15809 } 15810 } else { 15811 throw new IllegalArgumentException("No selective enforcement for " + permission); 15812 } 15813 } 15814 15815 @Override 15816 @Deprecated 15817 public boolean isPermissionEnforced(String permission) { 15818 return true; 15819 } 15820 15821 @Override 15822 public boolean isStorageLow() { 15823 final long token = Binder.clearCallingIdentity(); 15824 try { 15825 final DeviceStorageMonitorInternal 15826 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15827 if (dsm != null) { 15828 return dsm.isMemoryLow(); 15829 } else { 15830 return false; 15831 } 15832 } finally { 15833 Binder.restoreCallingIdentity(token); 15834 } 15835 } 15836 15837 @Override 15838 public IPackageInstaller getPackageInstaller() { 15839 return mInstallerService; 15840 } 15841 15842 private boolean userNeedsBadging(int userId) { 15843 int index = mUserNeedsBadging.indexOfKey(userId); 15844 if (index < 0) { 15845 final UserInfo userInfo; 15846 final long token = Binder.clearCallingIdentity(); 15847 try { 15848 userInfo = sUserManager.getUserInfo(userId); 15849 } finally { 15850 Binder.restoreCallingIdentity(token); 15851 } 15852 final boolean b; 15853 if (userInfo != null && userInfo.isManagedProfile()) { 15854 b = true; 15855 } else { 15856 b = false; 15857 } 15858 mUserNeedsBadging.put(userId, b); 15859 return b; 15860 } 15861 return mUserNeedsBadging.valueAt(index); 15862 } 15863 15864 @Override 15865 public KeySet getKeySetByAlias(String packageName, String alias) { 15866 if (packageName == null || alias == null) { 15867 return null; 15868 } 15869 synchronized(mPackages) { 15870 final PackageParser.Package pkg = mPackages.get(packageName); 15871 if (pkg == null) { 15872 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15873 throw new IllegalArgumentException("Unknown package: " + packageName); 15874 } 15875 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15876 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15877 } 15878 } 15879 15880 @Override 15881 public KeySet getSigningKeySet(String packageName) { 15882 if (packageName == null) { 15883 return null; 15884 } 15885 synchronized(mPackages) { 15886 final PackageParser.Package pkg = mPackages.get(packageName); 15887 if (pkg == null) { 15888 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15889 throw new IllegalArgumentException("Unknown package: " + packageName); 15890 } 15891 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15892 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15893 throw new SecurityException("May not access signing KeySet of other apps."); 15894 } 15895 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15896 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15897 } 15898 } 15899 15900 @Override 15901 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15902 if (packageName == null || ks == null) { 15903 return false; 15904 } 15905 synchronized(mPackages) { 15906 final PackageParser.Package pkg = mPackages.get(packageName); 15907 if (pkg == null) { 15908 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15909 throw new IllegalArgumentException("Unknown package: " + packageName); 15910 } 15911 IBinder ksh = ks.getToken(); 15912 if (ksh instanceof KeySetHandle) { 15913 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15914 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15915 } 15916 return false; 15917 } 15918 } 15919 15920 @Override 15921 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15922 if (packageName == null || ks == null) { 15923 return false; 15924 } 15925 synchronized(mPackages) { 15926 final PackageParser.Package pkg = mPackages.get(packageName); 15927 if (pkg == null) { 15928 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15929 throw new IllegalArgumentException("Unknown package: " + packageName); 15930 } 15931 IBinder ksh = ks.getToken(); 15932 if (ksh instanceof KeySetHandle) { 15933 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15934 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15935 } 15936 return false; 15937 } 15938 } 15939 15940 public void getUsageStatsIfNoPackageUsageInfo() { 15941 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15942 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15943 if (usm == null) { 15944 throw new IllegalStateException("UsageStatsManager must be initialized"); 15945 } 15946 long now = System.currentTimeMillis(); 15947 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15948 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15949 String packageName = entry.getKey(); 15950 PackageParser.Package pkg = mPackages.get(packageName); 15951 if (pkg == null) { 15952 continue; 15953 } 15954 UsageStats usage = entry.getValue(); 15955 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15956 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15957 } 15958 } 15959 } 15960 15961 /** 15962 * Check and throw if the given before/after packages would be considered a 15963 * downgrade. 15964 */ 15965 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15966 throws PackageManagerException { 15967 if (after.versionCode < before.mVersionCode) { 15968 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15969 "Update version code " + after.versionCode + " is older than current " 15970 + before.mVersionCode); 15971 } else if (after.versionCode == before.mVersionCode) { 15972 if (after.baseRevisionCode < before.baseRevisionCode) { 15973 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15974 "Update base revision code " + after.baseRevisionCode 15975 + " is older than current " + before.baseRevisionCode); 15976 } 15977 15978 if (!ArrayUtils.isEmpty(after.splitNames)) { 15979 for (int i = 0; i < after.splitNames.length; i++) { 15980 final String splitName = after.splitNames[i]; 15981 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15982 if (j != -1) { 15983 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15984 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15985 "Update split " + splitName + " revision code " 15986 + after.splitRevisionCodes[i] + " is older than current " 15987 + before.splitRevisionCodes[j]); 15988 } 15989 } 15990 } 15991 } 15992 } 15993 } 15994 15995 private static class MoveCallbacks extends Handler { 15996 private static final int MSG_CREATED = 1; 15997 private static final int MSG_STATUS_CHANGED = 2; 15998 15999 private final RemoteCallbackList<IPackageMoveObserver> 16000 mCallbacks = new RemoteCallbackList<>(); 16001 16002 private final SparseIntArray mLastStatus = new SparseIntArray(); 16003 16004 public MoveCallbacks(Looper looper) { 16005 super(looper); 16006 } 16007 16008 public void register(IPackageMoveObserver callback) { 16009 mCallbacks.register(callback); 16010 } 16011 16012 public void unregister(IPackageMoveObserver callback) { 16013 mCallbacks.unregister(callback); 16014 } 16015 16016 @Override 16017 public void handleMessage(Message msg) { 16018 final SomeArgs args = (SomeArgs) msg.obj; 16019 final int n = mCallbacks.beginBroadcast(); 16020 for (int i = 0; i < n; i++) { 16021 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16022 try { 16023 invokeCallback(callback, msg.what, args); 16024 } catch (RemoteException ignored) { 16025 } 16026 } 16027 mCallbacks.finishBroadcast(); 16028 args.recycle(); 16029 } 16030 16031 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16032 throws RemoteException { 16033 switch (what) { 16034 case MSG_CREATED: { 16035 callback.onCreated(args.argi1, (Bundle) args.arg2); 16036 break; 16037 } 16038 case MSG_STATUS_CHANGED: { 16039 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16040 break; 16041 } 16042 } 16043 } 16044 16045 private void notifyCreated(int moveId, Bundle extras) { 16046 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16047 16048 final SomeArgs args = SomeArgs.obtain(); 16049 args.argi1 = moveId; 16050 args.arg2 = extras; 16051 obtainMessage(MSG_CREATED, args).sendToTarget(); 16052 } 16053 16054 private void notifyStatusChanged(int moveId, int status) { 16055 notifyStatusChanged(moveId, status, -1); 16056 } 16057 16058 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16059 Slog.v(TAG, "Move " + moveId + " status " + status); 16060 16061 final SomeArgs args = SomeArgs.obtain(); 16062 args.argi1 = moveId; 16063 args.argi2 = status; 16064 args.arg3 = estMillis; 16065 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16066 16067 synchronized (mLastStatus) { 16068 mLastStatus.put(moveId, status); 16069 } 16070 } 16071 } 16072 16073 private final class OnPermissionChangeListeners extends Handler { 16074 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16075 16076 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16077 new RemoteCallbackList<>(); 16078 16079 public OnPermissionChangeListeners(Looper looper) { 16080 super(looper); 16081 } 16082 16083 @Override 16084 public void handleMessage(Message msg) { 16085 switch (msg.what) { 16086 case MSG_ON_PERMISSIONS_CHANGED: { 16087 final int uid = msg.arg1; 16088 handleOnPermissionsChanged(uid); 16089 } break; 16090 } 16091 } 16092 16093 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16094 mPermissionListeners.register(listener); 16095 16096 } 16097 16098 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16099 mPermissionListeners.unregister(listener); 16100 } 16101 16102 public void onPermissionsChanged(int uid) { 16103 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16104 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16105 } 16106 } 16107 16108 private void handleOnPermissionsChanged(int uid) { 16109 final int count = mPermissionListeners.beginBroadcast(); 16110 try { 16111 for (int i = 0; i < count; i++) { 16112 IOnPermissionsChangeListener callback = mPermissionListeners 16113 .getBroadcastItem(i); 16114 try { 16115 callback.onPermissionsChanged(uid); 16116 } catch (RemoteException e) { 16117 Log.e(TAG, "Permission listener is dead", e); 16118 } 16119 } 16120 } finally { 16121 mPermissionListeners.finishBroadcast(); 16122 } 16123 } 16124 } 16125 16126 private class PackageManagerInternalImpl extends PackageManagerInternal { 16127 @Override 16128 public void setLocationPackagesProvider(PackagesProvider provider) { 16129 synchronized (mPackages) { 16130 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16131 } 16132 } 16133 16134 @Override 16135 public void setImePackagesProvider(PackagesProvider provider) { 16136 synchronized (mPackages) { 16137 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16138 } 16139 } 16140 16141 @Override 16142 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16143 synchronized (mPackages) { 16144 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16145 } 16146 } 16147 16148 @Override 16149 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16150 synchronized (mPackages) { 16151 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16152 } 16153 } 16154 16155 @Override 16156 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16157 synchronized (mPackages) { 16158 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16159 } 16160 } 16161 16162 @Override 16163 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16164 synchronized (mPackages) { 16165 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16166 } 16167 } 16168 16169 @Override 16170 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16171 synchronized (mPackages) { 16172 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16173 packageName, userId); 16174 } 16175 } 16176 16177 @Override 16178 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16179 synchronized (mPackages) { 16180 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16181 packageName, userId); 16182 } 16183 } 16184 } 16185 16186 @Override 16187 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16188 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16189 synchronized (mPackages) { 16190 final long identity = Binder.clearCallingIdentity(); 16191 try { 16192 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16193 packageNames, userId); 16194 } finally { 16195 Binder.restoreCallingIdentity(identity); 16196 } 16197 } 16198 } 16199 16200 private static void enforceSystemOrPhoneCaller(String tag) { 16201 int callingUid = Binder.getCallingUid(); 16202 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16203 throw new SecurityException( 16204 "Cannot call " + tag + " from UID " + callingUid); 16205 } 16206 } 16207} 16208