PackageManagerService.java revision 2f37bd39217177fc2d49b07a9d1b2821d3177e80
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.IPackagesProvider; 106import android.content.pm.InstrumentationInfo; 107import android.content.pm.IntentFilterVerificationInfo; 108import android.content.pm.KeySet; 109import android.content.pm.ManifestDigest; 110import android.content.pm.PackageCleanItem; 111import android.content.pm.PackageInfo; 112import android.content.pm.PackageInfoLite; 113import android.content.pm.PackageInstaller; 114import android.content.pm.PackageManager; 115import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 116import android.content.pm.PackageManagerInternal; 117import android.content.pm.PackageParser; 118import android.content.pm.PackageParser.ActivityIntentInfo; 119import android.content.pm.PackageParser.PackageLite; 120import android.content.pm.PackageParser.PackageParserException; 121import android.content.pm.PackageStats; 122import android.content.pm.PackageUserState; 123import android.content.pm.ParceledListSlice; 124import android.content.pm.PermissionGroupInfo; 125import android.content.pm.PermissionInfo; 126import android.content.pm.ProviderInfo; 127import android.content.pm.ResolveInfo; 128import android.content.pm.ServiceInfo; 129import android.content.pm.Signature; 130import android.content.pm.UserInfo; 131import android.content.pm.VerificationParams; 132import android.content.pm.VerifierDeviceIdentity; 133import android.content.pm.VerifierInfo; 134import android.content.res.Resources; 135import android.hardware.display.DisplayManager; 136import android.net.Uri; 137import android.os.Binder; 138import android.os.Build; 139import android.os.Bundle; 140import android.os.Debug; 141import android.os.Environment; 142import android.os.Environment.UserEnvironment; 143import android.os.FileUtils; 144import android.os.Handler; 145import android.os.IBinder; 146import android.os.Looper; 147import android.os.Message; 148import android.os.Parcel; 149import android.os.ParcelFileDescriptor; 150import android.os.Process; 151import android.os.RemoteCallbackList; 152import android.os.RemoteException; 153import android.os.SELinux; 154import android.os.ServiceManager; 155import android.os.SystemClock; 156import android.os.SystemProperties; 157import android.os.UserHandle; 158import android.os.UserManager; 159import android.os.storage.IMountService; 160import android.os.storage.StorageEventListener; 161import android.os.storage.StorageManager; 162import android.os.storage.VolumeInfo; 163import android.os.storage.VolumeRecord; 164import android.security.KeyStore; 165import android.security.SystemKeyStore; 166import android.system.ErrnoException; 167import android.system.Os; 168import android.system.StructStat; 169import android.text.TextUtils; 170import android.text.format.DateUtils; 171import android.util.ArrayMap; 172import android.util.ArraySet; 173import android.util.AtomicFile; 174import android.util.DisplayMetrics; 175import android.util.EventLog; 176import android.util.ExceptionUtils; 177import android.util.Log; 178import android.util.LogPrinter; 179import android.util.MathUtils; 180import android.util.PrintStreamPrinter; 181import android.util.Slog; 182import android.util.SparseArray; 183import android.util.SparseBooleanArray; 184import android.util.SparseIntArray; 185import android.util.Xml; 186import android.view.Display; 187 188import dalvik.system.DexFile; 189import dalvik.system.VMRuntime; 190 191import libcore.io.IoUtils; 192import libcore.util.EmptyArray; 193 194import com.android.internal.R; 195import com.android.internal.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 final ServiceThread mHandlerThread; 391 392 final PackageHandler mHandler; 393 394 /** 395 * Messages for {@link #mHandler} that need to wait for system ready before 396 * being dispatched. 397 */ 398 private ArrayList<Message> mPostSystemReadyMessages; 399 400 final int mSdkVersion = Build.VERSION.SDK_INT; 401 402 final Context mContext; 403 final boolean mFactoryTest; 404 final boolean mOnlyCore; 405 final boolean mLazyDexOpt; 406 final long mDexOptLRUThresholdInMills; 407 final DisplayMetrics mMetrics; 408 final int mDefParseFlags; 409 final String[] mSeparateProcesses; 410 final boolean mIsUpgrade; 411 412 // This is where all application persistent data goes. 413 final File mAppDataDir; 414 415 // This is where all application persistent data goes for secondary users. 416 final File mUserAppDataDir; 417 418 /** The location for ASEC container files on internal storage. */ 419 final String mAsecInternalPath; 420 421 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 422 // LOCK HELD. Can be called with mInstallLock held. 423 final Installer mInstaller; 424 425 /** Directory where installed third-party apps stored */ 426 final File mAppInstallDir; 427 428 /** 429 * Directory to which applications installed internally have their 430 * 32 bit native libraries copied. 431 */ 432 private File mAppLib32InstallDir; 433 434 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 435 // apps. 436 final File mDrmAppPrivateInstallDir; 437 438 // ---------------------------------------------------------------- 439 440 // Lock for state used when installing and doing other long running 441 // operations. Methods that must be called with this lock held have 442 // the suffix "LI". 443 final Object mInstallLock = new Object(); 444 445 // ---------------------------------------------------------------- 446 447 // Keys are String (package name), values are Package. This also serves 448 // as the lock for the global state. Methods that must be called with 449 // this lock held have the prefix "LP". 450 final ArrayMap<String, PackageParser.Package> mPackages = 451 new ArrayMap<String, PackageParser.Package>(); 452 453 // Tracks available target package names -> overlay package paths. 454 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 455 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 456 457 final Settings mSettings; 458 boolean mRestoredSettings; 459 460 // System configuration read by SystemConfig. 461 final int[] mGlobalGids; 462 final SparseArray<ArraySet<String>> mSystemPermissions; 463 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 464 465 // If mac_permissions.xml was found for seinfo labeling. 466 boolean mFoundPolicyFile; 467 468 // If a recursive restorecon of /data/data/<pkg> is needed. 469 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 470 471 public static final class SharedLibraryEntry { 472 public final String path; 473 public final String apk; 474 475 SharedLibraryEntry(String _path, String _apk) { 476 path = _path; 477 apk = _apk; 478 } 479 } 480 481 // Currently known shared libraries. 482 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 483 new ArrayMap<String, SharedLibraryEntry>(); 484 485 // All available activities, for your resolving pleasure. 486 final ActivityIntentResolver mActivities = 487 new ActivityIntentResolver(); 488 489 // All available receivers, for your resolving pleasure. 490 final ActivityIntentResolver mReceivers = 491 new ActivityIntentResolver(); 492 493 // All available services, for your resolving pleasure. 494 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 495 496 // All available providers, for your resolving pleasure. 497 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 498 499 // Mapping from provider base names (first directory in content URI codePath) 500 // to the provider information. 501 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 502 new ArrayMap<String, PackageParser.Provider>(); 503 504 // Mapping from instrumentation class names to info about them. 505 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 506 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 507 508 // Mapping from permission names to info about them. 509 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 510 new ArrayMap<String, PackageParser.PermissionGroup>(); 511 512 // Packages whose data we have transfered into another package, thus 513 // should no longer exist. 514 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 515 516 // Broadcast actions that are only available to the system. 517 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 518 519 /** List of packages waiting for verification. */ 520 final SparseArray<PackageVerificationState> mPendingVerification 521 = new SparseArray<PackageVerificationState>(); 522 523 /** Set of packages associated with each app op permission. */ 524 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 525 526 final PackageInstallerService mInstallerService; 527 528 private final PackageDexOptimizer mPackageDexOptimizer; 529 530 private AtomicInteger mNextMoveId = new AtomicInteger(); 531 private final MoveCallbacks mMoveCallbacks; 532 533 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 534 535 // Cache of users who need badging. 536 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 537 538 /** Token for keys in mPendingVerification. */ 539 private int mPendingVerificationToken = 0; 540 541 volatile boolean mSystemReady; 542 volatile boolean mSafeMode; 543 volatile boolean mHasSystemUidErrors; 544 545 ApplicationInfo mAndroidApplication; 546 final ActivityInfo mResolveActivity = new ActivityInfo(); 547 final ResolveInfo mResolveInfo = new ResolveInfo(); 548 ComponentName mResolveComponentName; 549 PackageParser.Package mPlatformPackage; 550 ComponentName mCustomResolverComponentName; 551 552 boolean mResolverReplaced = false; 553 554 private final ComponentName mIntentFilterVerifierComponent; 555 private int mIntentFilterVerificationToken = 0; 556 557 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 558 = new SparseArray<IntentFilterVerificationState>(); 559 560 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 561 new DefaultPermissionGrantPolicy(this); 562 563 private static class IFVerificationParams { 564 PackageParser.Package pkg; 565 boolean replacing; 566 int userId; 567 int verifierUid; 568 569 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 570 int _userId, int _verifierUid) { 571 pkg = _pkg; 572 replacing = _replacing; 573 userId = _userId; 574 replacing = _replacing; 575 verifierUid = _verifierUid; 576 } 577 } 578 579 private interface IntentFilterVerifier<T extends IntentFilter> { 580 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 581 T filter, String packageName); 582 void startVerifications(int userId); 583 void receiveVerificationResponse(int verificationId); 584 } 585 586 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 587 private Context mContext; 588 private ComponentName mIntentFilterVerifierComponent; 589 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 590 591 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 592 mContext = context; 593 mIntentFilterVerifierComponent = verifierComponent; 594 } 595 596 private String getDefaultScheme() { 597 return IntentFilter.SCHEME_HTTPS; 598 } 599 600 @Override 601 public void startVerifications(int userId) { 602 // Launch verifications requests 603 int count = mCurrentIntentFilterVerifications.size(); 604 for (int n=0; n<count; n++) { 605 int verificationId = mCurrentIntentFilterVerifications.get(n); 606 final IntentFilterVerificationState ivs = 607 mIntentFilterVerificationStates.get(verificationId); 608 609 String packageName = ivs.getPackageName(); 610 611 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 612 final int filterCount = filters.size(); 613 ArraySet<String> domainsSet = new ArraySet<>(); 614 for (int m=0; m<filterCount; m++) { 615 PackageParser.ActivityIntentInfo filter = filters.get(m); 616 domainsSet.addAll(filter.getHostsList()); 617 } 618 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 619 synchronized (mPackages) { 620 if (mSettings.createIntentFilterVerificationIfNeededLPw( 621 packageName, domainsList) != null) { 622 scheduleWriteSettingsLocked(); 623 } 624 } 625 sendVerificationRequest(userId, verificationId, ivs); 626 } 627 mCurrentIntentFilterVerifications.clear(); 628 } 629 630 private void sendVerificationRequest(int userId, int verificationId, 631 IntentFilterVerificationState ivs) { 632 633 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 634 verificationIntent.putExtra( 635 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 636 verificationId); 637 verificationIntent.putExtra( 638 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 639 getDefaultScheme()); 640 verificationIntent.putExtra( 641 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 642 ivs.getHostsString()); 643 verificationIntent.putExtra( 644 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 645 ivs.getPackageName()); 646 verificationIntent.setComponent(mIntentFilterVerifierComponent); 647 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 648 649 UserHandle user = new UserHandle(userId); 650 mContext.sendBroadcastAsUser(verificationIntent, user); 651 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 652 "Sending IntentFilter verification broadcast"); 653 } 654 655 public void receiveVerificationResponse(int verificationId) { 656 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 657 658 final boolean verified = ivs.isVerified(); 659 660 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 661 final int count = filters.size(); 662 if (DEBUG_DOMAIN_VERIFICATION) { 663 Slog.i(TAG, "Received verification response " + verificationId 664 + " for " + count + " filters, verified=" + verified); 665 } 666 for (int n=0; n<count; n++) { 667 PackageParser.ActivityIntentInfo filter = filters.get(n); 668 filter.setVerified(verified); 669 670 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 671 + " verified with result:" + verified + " and hosts:" 672 + ivs.getHostsString()); 673 } 674 675 mIntentFilterVerificationStates.remove(verificationId); 676 677 final String packageName = ivs.getPackageName(); 678 IntentFilterVerificationInfo ivi = null; 679 680 synchronized (mPackages) { 681 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 682 } 683 if (ivi == null) { 684 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 685 + verificationId + " packageName:" + packageName); 686 return; 687 } 688 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 689 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 690 691 synchronized (mPackages) { 692 if (verified) { 693 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 694 } else { 695 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 696 } 697 scheduleWriteSettingsLocked(); 698 699 final int userId = ivs.getUserId(); 700 if (userId != UserHandle.USER_ALL) { 701 final int userStatus = 702 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 703 704 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 705 boolean needUpdate = false; 706 707 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 708 // already been set by the User thru the Disambiguation dialog 709 switch (userStatus) { 710 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 711 if (verified) { 712 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 713 } else { 714 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 715 } 716 needUpdate = true; 717 break; 718 719 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 720 if (verified) { 721 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 722 needUpdate = true; 723 } 724 break; 725 726 default: 727 // Nothing to do 728 } 729 730 if (needUpdate) { 731 mSettings.updateIntentFilterVerificationStatusLPw( 732 packageName, updatedStatus, userId); 733 scheduleWritePackageRestrictionsLocked(userId); 734 } 735 } 736 } 737 } 738 739 @Override 740 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 741 ActivityIntentInfo filter, String packageName) { 742 if (!hasValidDomains(filter)) { 743 return false; 744 } 745 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 746 if (ivs == null) { 747 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 748 packageName); 749 } 750 if (DEBUG_DOMAIN_VERIFICATION) { 751 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 752 } 753 ivs.addFilter(filter); 754 return true; 755 } 756 757 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 758 int userId, int verificationId, String packageName) { 759 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 760 verifierUid, userId, packageName); 761 ivs.setPendingState(); 762 synchronized (mPackages) { 763 mIntentFilterVerificationStates.append(verificationId, ivs); 764 mCurrentIntentFilterVerifications.add(verificationId); 765 } 766 return ivs; 767 } 768 } 769 770 private static boolean hasValidDomains(ActivityIntentInfo filter) { 771 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 772 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 773 if (!hasHTTPorHTTPS) { 774 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 775 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 776 return false; 777 } 778 return true; 779 } 780 781 private IntentFilterVerifier mIntentFilterVerifier; 782 783 // Set of pending broadcasts for aggregating enable/disable of components. 784 static class PendingPackageBroadcasts { 785 // for each user id, a map of <package name -> components within that package> 786 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 787 788 public PendingPackageBroadcasts() { 789 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 790 } 791 792 public ArrayList<String> get(int userId, String packageName) { 793 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 794 return packages.get(packageName); 795 } 796 797 public void put(int userId, String packageName, ArrayList<String> components) { 798 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 799 packages.put(packageName, components); 800 } 801 802 public void remove(int userId, String packageName) { 803 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 804 if (packages != null) { 805 packages.remove(packageName); 806 } 807 } 808 809 public void remove(int userId) { 810 mUidMap.remove(userId); 811 } 812 813 public int userIdCount() { 814 return mUidMap.size(); 815 } 816 817 public int userIdAt(int n) { 818 return mUidMap.keyAt(n); 819 } 820 821 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 822 return mUidMap.get(userId); 823 } 824 825 public int size() { 826 // total number of pending broadcast entries across all userIds 827 int num = 0; 828 for (int i = 0; i< mUidMap.size(); i++) { 829 num += mUidMap.valueAt(i).size(); 830 } 831 return num; 832 } 833 834 public void clear() { 835 mUidMap.clear(); 836 } 837 838 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 839 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 840 if (map == null) { 841 map = new ArrayMap<String, ArrayList<String>>(); 842 mUidMap.put(userId, map); 843 } 844 return map; 845 } 846 } 847 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 848 849 // Service Connection to remote media container service to copy 850 // package uri's from external media onto secure containers 851 // or internal storage. 852 private IMediaContainerService mContainerService = null; 853 854 static final int SEND_PENDING_BROADCAST = 1; 855 static final int MCS_BOUND = 3; 856 static final int END_COPY = 4; 857 static final int INIT_COPY = 5; 858 static final int MCS_UNBIND = 6; 859 static final int START_CLEANING_PACKAGE = 7; 860 static final int FIND_INSTALL_LOC = 8; 861 static final int POST_INSTALL = 9; 862 static final int MCS_RECONNECT = 10; 863 static final int MCS_GIVE_UP = 11; 864 static final int UPDATED_MEDIA_STATUS = 12; 865 static final int WRITE_SETTINGS = 13; 866 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 867 static final int PACKAGE_VERIFIED = 15; 868 static final int CHECK_PENDING_VERIFICATION = 16; 869 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 870 static final int INTENT_FILTER_VERIFIED = 18; 871 872 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 873 874 // Delay time in millisecs 875 static final int BROADCAST_DELAY = 10 * 1000; 876 877 static UserManagerService sUserManager; 878 879 // Stores a list of users whose package restrictions file needs to be updated 880 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 881 882 final private DefaultContainerConnection mDefContainerConn = 883 new DefaultContainerConnection(); 884 class DefaultContainerConnection implements ServiceConnection { 885 public void onServiceConnected(ComponentName name, IBinder service) { 886 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 887 IMediaContainerService imcs = 888 IMediaContainerService.Stub.asInterface(service); 889 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 890 } 891 892 public void onServiceDisconnected(ComponentName name) { 893 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 894 } 895 } 896 897 // Recordkeeping of restore-after-install operations that are currently in flight 898 // between the Package Manager and the Backup Manager 899 class PostInstallData { 900 public InstallArgs args; 901 public PackageInstalledInfo res; 902 903 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 904 args = _a; 905 res = _r; 906 } 907 } 908 909 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 910 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 911 912 // XML tags for backup/restore of various bits of state 913 private static final String TAG_PREFERRED_BACKUP = "pa"; 914 private static final String TAG_DEFAULT_APPS = "da"; 915 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 916 917 private final String mRequiredVerifierPackage; 918 919 private final PackageUsage mPackageUsage = new PackageUsage(); 920 921 private class PackageUsage { 922 private static final int WRITE_INTERVAL 923 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 924 925 private final Object mFileLock = new Object(); 926 private final AtomicLong mLastWritten = new AtomicLong(0); 927 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 928 929 private boolean mIsHistoricalPackageUsageAvailable = true; 930 931 boolean isHistoricalPackageUsageAvailable() { 932 return mIsHistoricalPackageUsageAvailable; 933 } 934 935 void write(boolean force) { 936 if (force) { 937 writeInternal(); 938 return; 939 } 940 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 941 && !DEBUG_DEXOPT) { 942 return; 943 } 944 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 945 new Thread("PackageUsage_DiskWriter") { 946 @Override 947 public void run() { 948 try { 949 writeInternal(); 950 } finally { 951 mBackgroundWriteRunning.set(false); 952 } 953 } 954 }.start(); 955 } 956 } 957 958 private void writeInternal() { 959 synchronized (mPackages) { 960 synchronized (mFileLock) { 961 AtomicFile file = getFile(); 962 FileOutputStream f = null; 963 try { 964 f = file.startWrite(); 965 BufferedOutputStream out = new BufferedOutputStream(f); 966 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 967 StringBuilder sb = new StringBuilder(); 968 for (PackageParser.Package pkg : mPackages.values()) { 969 if (pkg.mLastPackageUsageTimeInMills == 0) { 970 continue; 971 } 972 sb.setLength(0); 973 sb.append(pkg.packageName); 974 sb.append(' '); 975 sb.append((long)pkg.mLastPackageUsageTimeInMills); 976 sb.append('\n'); 977 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 978 } 979 out.flush(); 980 file.finishWrite(f); 981 } catch (IOException e) { 982 if (f != null) { 983 file.failWrite(f); 984 } 985 Log.e(TAG, "Failed to write package usage times", e); 986 } 987 } 988 } 989 mLastWritten.set(SystemClock.elapsedRealtime()); 990 } 991 992 void readLP() { 993 synchronized (mFileLock) { 994 AtomicFile file = getFile(); 995 BufferedInputStream in = null; 996 try { 997 in = new BufferedInputStream(file.openRead()); 998 StringBuffer sb = new StringBuffer(); 999 while (true) { 1000 String packageName = readToken(in, sb, ' '); 1001 if (packageName == null) { 1002 break; 1003 } 1004 String timeInMillisString = readToken(in, sb, '\n'); 1005 if (timeInMillisString == null) { 1006 throw new IOException("Failed to find last usage time for package " 1007 + packageName); 1008 } 1009 PackageParser.Package pkg = mPackages.get(packageName); 1010 if (pkg == null) { 1011 continue; 1012 } 1013 long timeInMillis; 1014 try { 1015 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1016 } catch (NumberFormatException e) { 1017 throw new IOException("Failed to parse " + timeInMillisString 1018 + " as a long.", e); 1019 } 1020 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1021 } 1022 } catch (FileNotFoundException expected) { 1023 mIsHistoricalPackageUsageAvailable = false; 1024 } catch (IOException e) { 1025 Log.w(TAG, "Failed to read package usage times", e); 1026 } finally { 1027 IoUtils.closeQuietly(in); 1028 } 1029 } 1030 mLastWritten.set(SystemClock.elapsedRealtime()); 1031 } 1032 1033 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1034 throws IOException { 1035 sb.setLength(0); 1036 while (true) { 1037 int ch = in.read(); 1038 if (ch == -1) { 1039 if (sb.length() == 0) { 1040 return null; 1041 } 1042 throw new IOException("Unexpected EOF"); 1043 } 1044 if (ch == endOfToken) { 1045 return sb.toString(); 1046 } 1047 sb.append((char)ch); 1048 } 1049 } 1050 1051 private AtomicFile getFile() { 1052 File dataDir = Environment.getDataDirectory(); 1053 File systemDir = new File(dataDir, "system"); 1054 File fname = new File(systemDir, "package-usage.list"); 1055 return new AtomicFile(fname); 1056 } 1057 } 1058 1059 class PackageHandler extends Handler { 1060 private boolean mBound = false; 1061 final ArrayList<HandlerParams> mPendingInstalls = 1062 new ArrayList<HandlerParams>(); 1063 1064 private boolean connectToService() { 1065 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1066 " DefaultContainerService"); 1067 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1068 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1069 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1070 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1071 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1072 mBound = true; 1073 return true; 1074 } 1075 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1076 return false; 1077 } 1078 1079 private void disconnectService() { 1080 mContainerService = null; 1081 mBound = false; 1082 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1083 mContext.unbindService(mDefContainerConn); 1084 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1085 } 1086 1087 PackageHandler(Looper looper) { 1088 super(looper); 1089 } 1090 1091 public void handleMessage(Message msg) { 1092 try { 1093 doHandleMessage(msg); 1094 } finally { 1095 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1096 } 1097 } 1098 1099 void doHandleMessage(Message msg) { 1100 switch (msg.what) { 1101 case INIT_COPY: { 1102 HandlerParams params = (HandlerParams) msg.obj; 1103 int idx = mPendingInstalls.size(); 1104 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1105 // If a bind was already initiated we dont really 1106 // need to do anything. The pending install 1107 // will be processed later on. 1108 if (!mBound) { 1109 // If this is the only one pending we might 1110 // have to bind to the service again. 1111 if (!connectToService()) { 1112 Slog.e(TAG, "Failed to bind to media container service"); 1113 params.serviceError(); 1114 return; 1115 } else { 1116 // Once we bind to the service, the first 1117 // pending request will be processed. 1118 mPendingInstalls.add(idx, params); 1119 } 1120 } else { 1121 mPendingInstalls.add(idx, params); 1122 // Already bound to the service. Just make 1123 // sure we trigger off processing the first request. 1124 if (idx == 0) { 1125 mHandler.sendEmptyMessage(MCS_BOUND); 1126 } 1127 } 1128 break; 1129 } 1130 case MCS_BOUND: { 1131 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1132 if (msg.obj != null) { 1133 mContainerService = (IMediaContainerService) msg.obj; 1134 } 1135 if (mContainerService == null) { 1136 if (!mBound) { 1137 // Something seriously wrong since we are not bound and we are not 1138 // waiting for connection. Bail out. 1139 Slog.e(TAG, "Cannot bind to media container service"); 1140 for (HandlerParams params : mPendingInstalls) { 1141 // Indicate service bind error 1142 params.serviceError(); 1143 } 1144 mPendingInstalls.clear(); 1145 } else { 1146 Slog.w(TAG, "Waiting to connect to media container service"); 1147 } 1148 } else if (mPendingInstalls.size() > 0) { 1149 HandlerParams params = mPendingInstalls.get(0); 1150 if (params != null) { 1151 if (params.startCopy()) { 1152 // We are done... look for more work or to 1153 // go idle. 1154 if (DEBUG_SD_INSTALL) Log.i(TAG, 1155 "Checking for more work or unbind..."); 1156 // Delete pending install 1157 if (mPendingInstalls.size() > 0) { 1158 mPendingInstalls.remove(0); 1159 } 1160 if (mPendingInstalls.size() == 0) { 1161 if (mBound) { 1162 if (DEBUG_SD_INSTALL) Log.i(TAG, 1163 "Posting delayed MCS_UNBIND"); 1164 removeMessages(MCS_UNBIND); 1165 Message ubmsg = obtainMessage(MCS_UNBIND); 1166 // Unbind after a little delay, to avoid 1167 // continual thrashing. 1168 sendMessageDelayed(ubmsg, 10000); 1169 } 1170 } else { 1171 // There are more pending requests in queue. 1172 // Just post MCS_BOUND message to trigger processing 1173 // of next pending install. 1174 if (DEBUG_SD_INSTALL) Log.i(TAG, 1175 "Posting MCS_BOUND for next work"); 1176 mHandler.sendEmptyMessage(MCS_BOUND); 1177 } 1178 } 1179 } 1180 } else { 1181 // Should never happen ideally. 1182 Slog.w(TAG, "Empty queue"); 1183 } 1184 break; 1185 } 1186 case MCS_RECONNECT: { 1187 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1188 if (mPendingInstalls.size() > 0) { 1189 if (mBound) { 1190 disconnectService(); 1191 } 1192 if (!connectToService()) { 1193 Slog.e(TAG, "Failed to bind to media container service"); 1194 for (HandlerParams params : mPendingInstalls) { 1195 // Indicate service bind error 1196 params.serviceError(); 1197 } 1198 mPendingInstalls.clear(); 1199 } 1200 } 1201 break; 1202 } 1203 case MCS_UNBIND: { 1204 // If there is no actual work left, then time to unbind. 1205 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1206 1207 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1208 if (mBound) { 1209 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1210 1211 disconnectService(); 1212 } 1213 } else if (mPendingInstalls.size() > 0) { 1214 // There are more pending requests in queue. 1215 // Just post MCS_BOUND message to trigger processing 1216 // of next pending install. 1217 mHandler.sendEmptyMessage(MCS_BOUND); 1218 } 1219 1220 break; 1221 } 1222 case MCS_GIVE_UP: { 1223 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1224 mPendingInstalls.remove(0); 1225 break; 1226 } 1227 case SEND_PENDING_BROADCAST: { 1228 String packages[]; 1229 ArrayList<String> components[]; 1230 int size = 0; 1231 int uids[]; 1232 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1233 synchronized (mPackages) { 1234 if (mPendingBroadcasts == null) { 1235 return; 1236 } 1237 size = mPendingBroadcasts.size(); 1238 if (size <= 0) { 1239 // Nothing to be done. Just return 1240 return; 1241 } 1242 packages = new String[size]; 1243 components = new ArrayList[size]; 1244 uids = new int[size]; 1245 int i = 0; // filling out the above arrays 1246 1247 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1248 int packageUserId = mPendingBroadcasts.userIdAt(n); 1249 Iterator<Map.Entry<String, ArrayList<String>>> it 1250 = mPendingBroadcasts.packagesForUserId(packageUserId) 1251 .entrySet().iterator(); 1252 while (it.hasNext() && i < size) { 1253 Map.Entry<String, ArrayList<String>> ent = it.next(); 1254 packages[i] = ent.getKey(); 1255 components[i] = ent.getValue(); 1256 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1257 uids[i] = (ps != null) 1258 ? UserHandle.getUid(packageUserId, ps.appId) 1259 : -1; 1260 i++; 1261 } 1262 } 1263 size = i; 1264 mPendingBroadcasts.clear(); 1265 } 1266 // Send broadcasts 1267 for (int i = 0; i < size; i++) { 1268 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1269 } 1270 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1271 break; 1272 } 1273 case START_CLEANING_PACKAGE: { 1274 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1275 final String packageName = (String)msg.obj; 1276 final int userId = msg.arg1; 1277 final boolean andCode = msg.arg2 != 0; 1278 synchronized (mPackages) { 1279 if (userId == UserHandle.USER_ALL) { 1280 int[] users = sUserManager.getUserIds(); 1281 for (int user : users) { 1282 mSettings.addPackageToCleanLPw( 1283 new PackageCleanItem(user, packageName, andCode)); 1284 } 1285 } else { 1286 mSettings.addPackageToCleanLPw( 1287 new PackageCleanItem(userId, packageName, andCode)); 1288 } 1289 } 1290 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1291 startCleaningPackages(); 1292 } break; 1293 case POST_INSTALL: { 1294 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1295 PostInstallData data = mRunningInstalls.get(msg.arg1); 1296 mRunningInstalls.delete(msg.arg1); 1297 boolean deleteOld = false; 1298 1299 if (data != null) { 1300 InstallArgs args = data.args; 1301 PackageInstalledInfo res = data.res; 1302 1303 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1304 res.removedInfo.sendBroadcast(false, true, false); 1305 Bundle extras = new Bundle(1); 1306 extras.putInt(Intent.EXTRA_UID, res.uid); 1307 1308 // Now that we successfully installed the package, grant runtime 1309 // permissions if requested before broadcasting the install. 1310 if ((args.installFlags 1311 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1312 grantRequestedRuntimePermissions(res.pkg, 1313 args.user.getIdentifier()); 1314 } 1315 1316 // Determine the set of users who are adding this 1317 // package for the first time vs. those who are seeing 1318 // an update. 1319 int[] firstUsers; 1320 int[] updateUsers = new int[0]; 1321 if (res.origUsers == null || res.origUsers.length == 0) { 1322 firstUsers = res.newUsers; 1323 } else { 1324 firstUsers = new int[0]; 1325 for (int i=0; i<res.newUsers.length; i++) { 1326 int user = res.newUsers[i]; 1327 boolean isNew = true; 1328 for (int j=0; j<res.origUsers.length; j++) { 1329 if (res.origUsers[j] == user) { 1330 isNew = false; 1331 break; 1332 } 1333 } 1334 if (isNew) { 1335 int[] newFirst = new int[firstUsers.length+1]; 1336 System.arraycopy(firstUsers, 0, newFirst, 0, 1337 firstUsers.length); 1338 newFirst[firstUsers.length] = user; 1339 firstUsers = newFirst; 1340 } else { 1341 int[] newUpdate = new int[updateUsers.length+1]; 1342 System.arraycopy(updateUsers, 0, newUpdate, 0, 1343 updateUsers.length); 1344 newUpdate[updateUsers.length] = user; 1345 updateUsers = newUpdate; 1346 } 1347 } 1348 } 1349 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1350 res.pkg.applicationInfo.packageName, 1351 extras, null, null, firstUsers); 1352 final boolean update = res.removedInfo.removedPackage != null; 1353 if (update) { 1354 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1355 } 1356 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1357 res.pkg.applicationInfo.packageName, 1358 extras, null, null, updateUsers); 1359 if (update) { 1360 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1361 res.pkg.applicationInfo.packageName, 1362 extras, null, null, updateUsers); 1363 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1364 null, null, 1365 res.pkg.applicationInfo.packageName, null, updateUsers); 1366 1367 // treat asec-hosted packages like removable media on upgrade 1368 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1369 if (DEBUG_INSTALL) { 1370 Slog.i(TAG, "upgrading pkg " + res.pkg 1371 + " is ASEC-hosted -> AVAILABLE"); 1372 } 1373 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1374 ArrayList<String> pkgList = new ArrayList<String>(1); 1375 pkgList.add(res.pkg.applicationInfo.packageName); 1376 sendResourcesChangedBroadcast(true, true, 1377 pkgList,uidArray, null); 1378 } 1379 } 1380 if (res.removedInfo.args != null) { 1381 // Remove the replaced package's older resources safely now 1382 deleteOld = true; 1383 } 1384 1385 // Log current value of "unknown sources" setting 1386 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1387 getUnknownSourcesSettings()); 1388 } 1389 // Force a gc to clear up things 1390 Runtime.getRuntime().gc(); 1391 // We delete after a gc for applications on sdcard. 1392 if (deleteOld) { 1393 synchronized (mInstallLock) { 1394 res.removedInfo.args.doPostDeleteLI(true); 1395 } 1396 } 1397 if (args.observer != null) { 1398 try { 1399 Bundle extras = extrasForInstallResult(res); 1400 args.observer.onPackageInstalled(res.name, res.returnCode, 1401 res.returnMsg, extras); 1402 } catch (RemoteException e) { 1403 Slog.i(TAG, "Observer no longer exists."); 1404 } 1405 } 1406 } else { 1407 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1408 } 1409 } break; 1410 case UPDATED_MEDIA_STATUS: { 1411 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1412 boolean reportStatus = msg.arg1 == 1; 1413 boolean doGc = msg.arg2 == 1; 1414 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1415 if (doGc) { 1416 // Force a gc to clear up stale containers. 1417 Runtime.getRuntime().gc(); 1418 } 1419 if (msg.obj != null) { 1420 @SuppressWarnings("unchecked") 1421 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1422 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1423 // Unload containers 1424 unloadAllContainers(args); 1425 } 1426 if (reportStatus) { 1427 try { 1428 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1429 PackageHelper.getMountService().finishMediaUpdate(); 1430 } catch (RemoteException e) { 1431 Log.e(TAG, "MountService not running?"); 1432 } 1433 } 1434 } break; 1435 case WRITE_SETTINGS: { 1436 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1437 synchronized (mPackages) { 1438 removeMessages(WRITE_SETTINGS); 1439 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1440 mSettings.writeLPr(); 1441 mDirtyUsers.clear(); 1442 } 1443 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1444 } break; 1445 case WRITE_PACKAGE_RESTRICTIONS: { 1446 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1447 synchronized (mPackages) { 1448 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1449 for (int userId : mDirtyUsers) { 1450 mSettings.writePackageRestrictionsLPr(userId); 1451 } 1452 mDirtyUsers.clear(); 1453 } 1454 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1455 } break; 1456 case CHECK_PENDING_VERIFICATION: { 1457 final int verificationId = msg.arg1; 1458 final PackageVerificationState state = mPendingVerification.get(verificationId); 1459 1460 if ((state != null) && !state.timeoutExtended()) { 1461 final InstallArgs args = state.getInstallArgs(); 1462 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1463 1464 Slog.i(TAG, "Verification timed out for " + originUri); 1465 mPendingVerification.remove(verificationId); 1466 1467 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1468 1469 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1470 Slog.i(TAG, "Continuing with installation of " + originUri); 1471 state.setVerifierResponse(Binder.getCallingUid(), 1472 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1473 broadcastPackageVerified(verificationId, originUri, 1474 PackageManager.VERIFICATION_ALLOW, 1475 state.getInstallArgs().getUser()); 1476 try { 1477 ret = args.copyApk(mContainerService, true); 1478 } catch (RemoteException e) { 1479 Slog.e(TAG, "Could not contact the ContainerService"); 1480 } 1481 } else { 1482 broadcastPackageVerified(verificationId, originUri, 1483 PackageManager.VERIFICATION_REJECT, 1484 state.getInstallArgs().getUser()); 1485 } 1486 1487 processPendingInstall(args, ret); 1488 mHandler.sendEmptyMessage(MCS_UNBIND); 1489 } 1490 break; 1491 } 1492 case PACKAGE_VERIFIED: { 1493 final int verificationId = msg.arg1; 1494 1495 final PackageVerificationState state = mPendingVerification.get(verificationId); 1496 if (state == null) { 1497 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1498 break; 1499 } 1500 1501 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1502 1503 state.setVerifierResponse(response.callerUid, response.code); 1504 1505 if (state.isVerificationComplete()) { 1506 mPendingVerification.remove(verificationId); 1507 1508 final InstallArgs args = state.getInstallArgs(); 1509 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1510 1511 int ret; 1512 if (state.isInstallAllowed()) { 1513 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1514 broadcastPackageVerified(verificationId, originUri, 1515 response.code, state.getInstallArgs().getUser()); 1516 try { 1517 ret = args.copyApk(mContainerService, true); 1518 } catch (RemoteException e) { 1519 Slog.e(TAG, "Could not contact the ContainerService"); 1520 } 1521 } else { 1522 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1523 } 1524 1525 processPendingInstall(args, ret); 1526 1527 mHandler.sendEmptyMessage(MCS_UNBIND); 1528 } 1529 1530 break; 1531 } 1532 case START_INTENT_FILTER_VERIFICATIONS: { 1533 IFVerificationParams params = (IFVerificationParams) msg.obj; 1534 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1535 params.replacing, params.pkg); 1536 break; 1537 } 1538 case INTENT_FILTER_VERIFIED: { 1539 final int verificationId = msg.arg1; 1540 1541 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1542 verificationId); 1543 if (state == null) { 1544 Slog.w(TAG, "Invalid IntentFilter verification token " 1545 + verificationId + " received"); 1546 break; 1547 } 1548 1549 final int userId = state.getUserId(); 1550 1551 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1552 "Processing IntentFilter verification with token:" 1553 + verificationId + " and userId:" + userId); 1554 1555 final IntentFilterVerificationResponse response = 1556 (IntentFilterVerificationResponse) msg.obj; 1557 1558 state.setVerifierResponse(response.callerUid, response.code); 1559 1560 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1561 "IntentFilter verification with token:" + verificationId 1562 + " and userId:" + userId 1563 + " is settings verifier response with response code:" 1564 + response.code); 1565 1566 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1567 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1568 + response.getFailedDomainsString()); 1569 } 1570 1571 if (state.isVerificationComplete()) { 1572 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1573 } else { 1574 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1575 "IntentFilter verification with token:" + verificationId 1576 + " was not said to be complete"); 1577 } 1578 1579 break; 1580 } 1581 } 1582 } 1583 } 1584 1585 private StorageEventListener mStorageListener = new StorageEventListener() { 1586 @Override 1587 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1588 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1589 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1590 // TODO: ensure that private directories exist for all active users 1591 // TODO: remove user data whose serial number doesn't match 1592 loadPrivatePackages(vol); 1593 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1594 unloadPrivatePackages(vol); 1595 } 1596 } 1597 1598 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1599 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1600 updateExternalMediaStatus(true, false); 1601 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1602 updateExternalMediaStatus(false, false); 1603 } 1604 } 1605 } 1606 1607 @Override 1608 public void onVolumeForgotten(String fsUuid) { 1609 // TODO: remove all packages hosted on this uuid 1610 } 1611 }; 1612 1613 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1614 if (userId >= UserHandle.USER_OWNER) { 1615 grantRequestedRuntimePermissionsForUser(pkg, userId); 1616 } else if (userId == UserHandle.USER_ALL) { 1617 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1618 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1619 } 1620 } 1621 1622 // We could have touched GID membership, so flush out packages.list 1623 synchronized (mPackages) { 1624 mSettings.writePackageListLPr(); 1625 } 1626 } 1627 1628 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1629 SettingBase sb = (SettingBase) pkg.mExtras; 1630 if (sb == null) { 1631 return; 1632 } 1633 1634 PermissionsState permissionsState = sb.getPermissionsState(); 1635 1636 for (String permission : pkg.requestedPermissions) { 1637 BasePermission bp = mSettings.mPermissions.get(permission); 1638 if (bp != null && bp.isRuntime()) { 1639 permissionsState.grantRuntimePermission(bp, userId); 1640 } 1641 } 1642 } 1643 1644 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1645 Bundle extras = null; 1646 switch (res.returnCode) { 1647 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1648 extras = new Bundle(); 1649 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1650 res.origPermission); 1651 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1652 res.origPackage); 1653 break; 1654 } 1655 case PackageManager.INSTALL_SUCCEEDED: { 1656 extras = new Bundle(); 1657 extras.putBoolean(Intent.EXTRA_REPLACING, 1658 res.removedInfo != null && res.removedInfo.removedPackage != null); 1659 break; 1660 } 1661 } 1662 return extras; 1663 } 1664 1665 void scheduleWriteSettingsLocked() { 1666 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1667 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1668 } 1669 } 1670 1671 void scheduleWritePackageRestrictionsLocked(int userId) { 1672 if (!sUserManager.exists(userId)) return; 1673 mDirtyUsers.add(userId); 1674 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1675 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1676 } 1677 } 1678 1679 public static PackageManagerService main(Context context, Installer installer, 1680 boolean factoryTest, boolean onlyCore) { 1681 PackageManagerService m = new PackageManagerService(context, installer, 1682 factoryTest, onlyCore); 1683 ServiceManager.addService("package", m); 1684 return m; 1685 } 1686 1687 static String[] splitString(String str, char sep) { 1688 int count = 1; 1689 int i = 0; 1690 while ((i=str.indexOf(sep, i)) >= 0) { 1691 count++; 1692 i++; 1693 } 1694 1695 String[] res = new String[count]; 1696 i=0; 1697 count = 0; 1698 int lastI=0; 1699 while ((i=str.indexOf(sep, i)) >= 0) { 1700 res[count] = str.substring(lastI, i); 1701 count++; 1702 i++; 1703 lastI = i; 1704 } 1705 res[count] = str.substring(lastI, str.length()); 1706 return res; 1707 } 1708 1709 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1710 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1711 Context.DISPLAY_SERVICE); 1712 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1713 } 1714 1715 public PackageManagerService(Context context, Installer installer, 1716 boolean factoryTest, boolean onlyCore) { 1717 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1718 SystemClock.uptimeMillis()); 1719 1720 if (mSdkVersion <= 0) { 1721 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1722 } 1723 1724 mContext = context; 1725 mFactoryTest = factoryTest; 1726 mOnlyCore = onlyCore; 1727 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1728 mMetrics = new DisplayMetrics(); 1729 mSettings = new Settings(mPackages); 1730 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1731 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1732 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1733 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1734 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1735 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1736 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1737 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1738 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1739 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1740 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1741 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1742 1743 // TODO: add a property to control this? 1744 long dexOptLRUThresholdInMinutes; 1745 if (mLazyDexOpt) { 1746 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1747 } else { 1748 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1749 } 1750 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1751 1752 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1753 if (separateProcesses != null && separateProcesses.length() > 0) { 1754 if ("*".equals(separateProcesses)) { 1755 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1756 mSeparateProcesses = null; 1757 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1758 } else { 1759 mDefParseFlags = 0; 1760 mSeparateProcesses = separateProcesses.split(","); 1761 Slog.w(TAG, "Running with debug.separate_processes: " 1762 + separateProcesses); 1763 } 1764 } else { 1765 mDefParseFlags = 0; 1766 mSeparateProcesses = null; 1767 } 1768 1769 mInstaller = installer; 1770 mPackageDexOptimizer = new PackageDexOptimizer(this); 1771 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1772 1773 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1774 FgThread.get().getLooper()); 1775 1776 getDefaultDisplayMetrics(context, mMetrics); 1777 1778 SystemConfig systemConfig = SystemConfig.getInstance(); 1779 mGlobalGids = systemConfig.getGlobalGids(); 1780 mSystemPermissions = systemConfig.getSystemPermissions(); 1781 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1782 1783 synchronized (mInstallLock) { 1784 // writer 1785 synchronized (mPackages) { 1786 mHandlerThread = new ServiceThread(TAG, 1787 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1788 mHandlerThread.start(); 1789 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1790 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1791 1792 File dataDir = Environment.getDataDirectory(); 1793 mAppDataDir = new File(dataDir, "data"); 1794 mAppInstallDir = new File(dataDir, "app"); 1795 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1796 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1797 mUserAppDataDir = new File(dataDir, "user"); 1798 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1799 1800 sUserManager = new UserManagerService(context, this, 1801 mInstallLock, mPackages); 1802 1803 // Propagate permission configuration in to package manager. 1804 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1805 = systemConfig.getPermissions(); 1806 for (int i=0; i<permConfig.size(); i++) { 1807 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1808 BasePermission bp = mSettings.mPermissions.get(perm.name); 1809 if (bp == null) { 1810 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1811 mSettings.mPermissions.put(perm.name, bp); 1812 } 1813 if (perm.gids != null) { 1814 bp.setGids(perm.gids, perm.perUser); 1815 } 1816 } 1817 1818 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1819 for (int i=0; i<libConfig.size(); i++) { 1820 mSharedLibraries.put(libConfig.keyAt(i), 1821 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1822 } 1823 1824 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1825 1826 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1827 mSdkVersion, mOnlyCore); 1828 1829 String customResolverActivity = Resources.getSystem().getString( 1830 R.string.config_customResolverActivity); 1831 if (TextUtils.isEmpty(customResolverActivity)) { 1832 customResolverActivity = null; 1833 } else { 1834 mCustomResolverComponentName = ComponentName.unflattenFromString( 1835 customResolverActivity); 1836 } 1837 1838 long startTime = SystemClock.uptimeMillis(); 1839 1840 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1841 startTime); 1842 1843 // Set flag to monitor and not change apk file paths when 1844 // scanning install directories. 1845 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1846 1847 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1848 1849 /** 1850 * Add everything in the in the boot class path to the 1851 * list of process files because dexopt will have been run 1852 * if necessary during zygote startup. 1853 */ 1854 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1855 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1856 1857 if (bootClassPath != null) { 1858 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1859 for (String element : bootClassPathElements) { 1860 alreadyDexOpted.add(element); 1861 } 1862 } else { 1863 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1864 } 1865 1866 if (systemServerClassPath != null) { 1867 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1868 for (String element : systemServerClassPathElements) { 1869 alreadyDexOpted.add(element); 1870 } 1871 } else { 1872 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1873 } 1874 1875 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1876 final String[] dexCodeInstructionSets = 1877 getDexCodeInstructionSets( 1878 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1879 1880 /** 1881 * Ensure all external libraries have had dexopt run on them. 1882 */ 1883 if (mSharedLibraries.size() > 0) { 1884 // NOTE: For now, we're compiling these system "shared libraries" 1885 // (and framework jars) into all available architectures. It's possible 1886 // to compile them only when we come across an app that uses them (there's 1887 // already logic for that in scanPackageLI) but that adds some complexity. 1888 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1889 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1890 final String lib = libEntry.path; 1891 if (lib == null) { 1892 continue; 1893 } 1894 1895 try { 1896 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1897 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1898 alreadyDexOpted.add(lib); 1899 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1900 } 1901 } catch (FileNotFoundException e) { 1902 Slog.w(TAG, "Library not found: " + lib); 1903 } catch (IOException e) { 1904 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1905 + e.getMessage()); 1906 } 1907 } 1908 } 1909 } 1910 1911 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1912 1913 // Gross hack for now: we know this file doesn't contain any 1914 // code, so don't dexopt it to avoid the resulting log spew. 1915 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1916 1917 // Gross hack for now: we know this file is only part of 1918 // the boot class path for art, so don't dexopt it to 1919 // avoid the resulting log spew. 1920 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1921 1922 /** 1923 * There are a number of commands implemented in Java, which 1924 * we currently need to do the dexopt on so that they can be 1925 * run from a non-root shell. 1926 */ 1927 String[] frameworkFiles = frameworkDir.list(); 1928 if (frameworkFiles != null) { 1929 // TODO: We could compile these only for the most preferred ABI. We should 1930 // first double check that the dex files for these commands are not referenced 1931 // by other system apps. 1932 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1933 for (int i=0; i<frameworkFiles.length; i++) { 1934 File libPath = new File(frameworkDir, frameworkFiles[i]); 1935 String path = libPath.getPath(); 1936 // Skip the file if we already did it. 1937 if (alreadyDexOpted.contains(path)) { 1938 continue; 1939 } 1940 // Skip the file if it is not a type we want to dexopt. 1941 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1942 continue; 1943 } 1944 try { 1945 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1946 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1947 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1948 } 1949 } catch (FileNotFoundException e) { 1950 Slog.w(TAG, "Jar not found: " + path); 1951 } catch (IOException e) { 1952 Slog.w(TAG, "Exception reading jar: " + path, e); 1953 } 1954 } 1955 } 1956 } 1957 1958 // Collect vendor overlay packages. 1959 // (Do this before scanning any apps.) 1960 // For security and version matching reason, only consider 1961 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1962 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1963 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1964 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1965 1966 // Find base frameworks (resource packages without code). 1967 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1968 | PackageParser.PARSE_IS_SYSTEM_DIR 1969 | PackageParser.PARSE_IS_PRIVILEGED, 1970 scanFlags | SCAN_NO_DEX, 0); 1971 1972 // Collected privileged system packages. 1973 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1974 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1975 | PackageParser.PARSE_IS_SYSTEM_DIR 1976 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1977 1978 // Collect ordinary system packages. 1979 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1980 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1981 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1982 1983 // Collect all vendor packages. 1984 File vendorAppDir = new File("/vendor/app"); 1985 try { 1986 vendorAppDir = vendorAppDir.getCanonicalFile(); 1987 } catch (IOException e) { 1988 // failed to look up canonical path, continue with original one 1989 } 1990 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1991 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1992 1993 // Collect all OEM packages. 1994 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1995 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1996 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1997 1998 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1999 mInstaller.moveFiles(); 2000 2001 // Prune any system packages that no longer exist. 2002 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2003 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2004 if (!mOnlyCore) { 2005 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2006 while (psit.hasNext()) { 2007 PackageSetting ps = psit.next(); 2008 2009 /* 2010 * If this is not a system app, it can't be a 2011 * disable system app. 2012 */ 2013 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2014 continue; 2015 } 2016 2017 /* 2018 * If the package is scanned, it's not erased. 2019 */ 2020 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2021 if (scannedPkg != null) { 2022 /* 2023 * If the system app is both scanned and in the 2024 * disabled packages list, then it must have been 2025 * added via OTA. Remove it from the currently 2026 * scanned package so the previously user-installed 2027 * application can be scanned. 2028 */ 2029 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2030 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2031 + ps.name + "; removing system app. Last known codePath=" 2032 + ps.codePathString + ", installStatus=" + ps.installStatus 2033 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2034 + scannedPkg.mVersionCode); 2035 removePackageLI(ps, true); 2036 expectingBetter.put(ps.name, ps.codePath); 2037 } 2038 2039 continue; 2040 } 2041 2042 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2043 psit.remove(); 2044 logCriticalInfo(Log.WARN, "System package " + ps.name 2045 + " no longer exists; wiping its data"); 2046 removeDataDirsLI(null, ps.name); 2047 } else { 2048 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2049 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2050 possiblyDeletedUpdatedSystemApps.add(ps.name); 2051 } 2052 } 2053 } 2054 } 2055 2056 //look for any incomplete package installations 2057 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2058 //clean up list 2059 for(int i = 0; i < deletePkgsList.size(); i++) { 2060 //clean up here 2061 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2062 } 2063 //delete tmp files 2064 deleteTempPackageFiles(); 2065 2066 // Remove any shared userIDs that have no associated packages 2067 mSettings.pruneSharedUsersLPw(); 2068 2069 if (!mOnlyCore) { 2070 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2071 SystemClock.uptimeMillis()); 2072 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2073 2074 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2075 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2076 2077 /** 2078 * Remove disable package settings for any updated system 2079 * apps that were removed via an OTA. If they're not a 2080 * previously-updated app, remove them completely. 2081 * Otherwise, just revoke their system-level permissions. 2082 */ 2083 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2084 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2085 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2086 2087 String msg; 2088 if (deletedPkg == null) { 2089 msg = "Updated system package " + deletedAppName 2090 + " no longer exists; wiping its data"; 2091 removeDataDirsLI(null, deletedAppName); 2092 } else { 2093 msg = "Updated system app + " + deletedAppName 2094 + " no longer present; removing system privileges for " 2095 + deletedAppName; 2096 2097 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2098 2099 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2100 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2101 } 2102 logCriticalInfo(Log.WARN, msg); 2103 } 2104 2105 /** 2106 * Make sure all system apps that we expected to appear on 2107 * the userdata partition actually showed up. If they never 2108 * appeared, crawl back and revive the system version. 2109 */ 2110 for (int i = 0; i < expectingBetter.size(); i++) { 2111 final String packageName = expectingBetter.keyAt(i); 2112 if (!mPackages.containsKey(packageName)) { 2113 final File scanFile = expectingBetter.valueAt(i); 2114 2115 logCriticalInfo(Log.WARN, "Expected better " + packageName 2116 + " but never showed up; reverting to system"); 2117 2118 final int reparseFlags; 2119 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2120 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2121 | PackageParser.PARSE_IS_SYSTEM_DIR 2122 | PackageParser.PARSE_IS_PRIVILEGED; 2123 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2124 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2125 | PackageParser.PARSE_IS_SYSTEM_DIR; 2126 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2127 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2128 | PackageParser.PARSE_IS_SYSTEM_DIR; 2129 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2130 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2131 | PackageParser.PARSE_IS_SYSTEM_DIR; 2132 } else { 2133 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2134 continue; 2135 } 2136 2137 mSettings.enableSystemPackageLPw(packageName); 2138 2139 try { 2140 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2141 } catch (PackageManagerException e) { 2142 Slog.e(TAG, "Failed to parse original system package: " 2143 + e.getMessage()); 2144 } 2145 } 2146 } 2147 } 2148 2149 // Now that we know all of the shared libraries, update all clients to have 2150 // the correct library paths. 2151 updateAllSharedLibrariesLPw(); 2152 2153 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2154 // NOTE: We ignore potential failures here during a system scan (like 2155 // the rest of the commands above) because there's precious little we 2156 // can do about it. A settings error is reported, though. 2157 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2158 false /* force dexopt */, false /* defer dexopt */); 2159 } 2160 2161 // Now that we know all the packages we are keeping, 2162 // read and update their last usage times. 2163 mPackageUsage.readLP(); 2164 2165 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2166 SystemClock.uptimeMillis()); 2167 Slog.i(TAG, "Time to scan packages: " 2168 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2169 + " seconds"); 2170 2171 // If the platform SDK has changed since the last time we booted, 2172 // we need to re-grant app permission to catch any new ones that 2173 // appear. This is really a hack, and means that apps can in some 2174 // cases get permissions that the user didn't initially explicitly 2175 // allow... it would be nice to have some better way to handle 2176 // this situation. 2177 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2178 != mSdkVersion; 2179 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2180 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2181 + "; regranting permissions for internal storage"); 2182 mSettings.mInternalSdkPlatform = mSdkVersion; 2183 2184 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2185 | (regrantPermissions 2186 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2187 : 0)); 2188 2189 // If this is the first boot, and it is a normal boot, then 2190 // we need to initialize the default preferred apps. 2191 if (!mRestoredSettings && !onlyCore) { 2192 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2193 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2194 } 2195 2196 // If this is first boot after an OTA, and a normal boot, then 2197 // we need to clear code cache directories. 2198 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2199 if (mIsUpgrade && !onlyCore) { 2200 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2201 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2202 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2203 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2204 } 2205 mSettings.mFingerprint = Build.FINGERPRINT; 2206 } 2207 2208 primeDomainVerificationsLPw(); 2209 checkDefaultBrowser(); 2210 2211 // All the changes are done during package scanning. 2212 mSettings.updateInternalDatabaseVersion(); 2213 2214 // can downgrade to reader 2215 mSettings.writeLPr(); 2216 2217 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2218 SystemClock.uptimeMillis()); 2219 2220 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2221 2222 mInstallerService = new PackageInstallerService(context, this); 2223 2224 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2225 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2226 mIntentFilterVerifierComponent); 2227 2228 } // synchronized (mPackages) 2229 } // synchronized (mInstallLock) 2230 2231 // Now after opening every single application zip, make sure they 2232 // are all flushed. Not really needed, but keeps things nice and 2233 // tidy. 2234 Runtime.getRuntime().gc(); 2235 2236 // Expose private service for system components to use. 2237 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2238 } 2239 2240 @Override 2241 public boolean isFirstBoot() { 2242 return !mRestoredSettings; 2243 } 2244 2245 @Override 2246 public boolean isOnlyCoreApps() { 2247 return mOnlyCore; 2248 } 2249 2250 @Override 2251 public boolean isUpgrade() { 2252 return mIsUpgrade; 2253 } 2254 2255 private String getRequiredVerifierLPr() { 2256 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2257 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2258 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2259 2260 String requiredVerifier = null; 2261 2262 final int N = receivers.size(); 2263 for (int i = 0; i < N; i++) { 2264 final ResolveInfo info = receivers.get(i); 2265 2266 if (info.activityInfo == null) { 2267 continue; 2268 } 2269 2270 final String packageName = info.activityInfo.packageName; 2271 2272 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2273 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2274 continue; 2275 } 2276 2277 if (requiredVerifier != null) { 2278 throw new RuntimeException("There can be only one required verifier"); 2279 } 2280 2281 requiredVerifier = packageName; 2282 } 2283 2284 return requiredVerifier; 2285 } 2286 2287 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2288 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2289 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2290 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2291 2292 ComponentName verifierComponentName = null; 2293 2294 int priority = -1000; 2295 final int N = receivers.size(); 2296 for (int i = 0; i < N; i++) { 2297 final ResolveInfo info = receivers.get(i); 2298 2299 if (info.activityInfo == null) { 2300 continue; 2301 } 2302 2303 final String packageName = info.activityInfo.packageName; 2304 2305 final PackageSetting ps = mSettings.mPackages.get(packageName); 2306 if (ps == null) { 2307 continue; 2308 } 2309 2310 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2311 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2312 continue; 2313 } 2314 2315 // Select the IntentFilterVerifier with the highest priority 2316 if (priority < info.priority) { 2317 priority = info.priority; 2318 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2319 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2320 + verifierComponentName + " with priority: " + info.priority); 2321 } 2322 } 2323 2324 return verifierComponentName; 2325 } 2326 2327 private void primeDomainVerificationsLPw() { 2328 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2329 boolean updated = false; 2330 ArraySet<String> allHostsSet = new ArraySet<>(); 2331 for (PackageParser.Package pkg : mPackages.values()) { 2332 final String packageName = pkg.packageName; 2333 if (!hasDomainURLs(pkg)) { 2334 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2335 "package with no domain URLs: " + packageName); 2336 continue; 2337 } 2338 if (!pkg.isSystemApp()) { 2339 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2340 "No priming domain verifications for a non system package : " + 2341 packageName); 2342 continue; 2343 } 2344 for (PackageParser.Activity a : pkg.activities) { 2345 for (ActivityIntentInfo filter : a.intents) { 2346 if (hasValidDomains(filter)) { 2347 allHostsSet.addAll(filter.getHostsList()); 2348 } 2349 } 2350 } 2351 if (allHostsSet.size() == 0) { 2352 allHostsSet.add("*"); 2353 } 2354 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2355 IntentFilterVerificationInfo ivi = 2356 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2357 if (ivi != null) { 2358 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2359 "Priming domain verifications for package: " + packageName + 2360 " with hosts:" + ivi.getDomainsString()); 2361 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2362 updated = true; 2363 } 2364 else { 2365 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2366 "No priming domain verifications for package: " + packageName); 2367 } 2368 allHostsSet.clear(); 2369 } 2370 if (updated) { 2371 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2372 "Will need to write primed domain verifications"); 2373 } 2374 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2375 } 2376 2377 private void applyFactoryDefaultBrowserLPw(int userId) { 2378 // The default browser app's package name is stored in a string resource, 2379 // with a product-specific overlay used for vendor customization. 2380 String browserPkg = mContext.getResources().getString( 2381 com.android.internal.R.string.default_browser); 2382 if (browserPkg != null) { 2383 // non-empty string => required to be a known package 2384 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2385 if (ps == null) { 2386 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2387 browserPkg = null; 2388 } else { 2389 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2390 } 2391 } 2392 2393 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2394 // default. If there's more than one, just leave everything alone. 2395 if (browserPkg == null) { 2396 calculateDefaultBrowserLPw(userId); 2397 } 2398 } 2399 2400 private void calculateDefaultBrowserLPw(int userId) { 2401 List<String> allBrowsers = resolveAllBrowserApps(userId); 2402 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2403 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2404 } 2405 2406 private List<String> resolveAllBrowserApps(int userId) { 2407 // Match all generic http: browser apps 2408 Intent intent = new Intent(); 2409 intent.setAction(Intent.ACTION_VIEW); 2410 intent.addCategory(Intent.CATEGORY_BROWSABLE); 2411 intent.setData(Uri.parse("http:")); 2412 2413 // Resolve that intent and check that the handleAllWebDataURI boolean is set 2414 List<ResolveInfo> list = queryIntentActivities(intent, null, 0, userId); 2415 2416 final int count = list.size(); 2417 List<String> result = new ArrayList<String>(count); 2418 for (int i=0; i<count; i++) { 2419 ResolveInfo info = list.get(i); 2420 if (info.activityInfo == null 2421 || !info.handleAllWebDataURI 2422 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2423 || result.contains(info.activityInfo.packageName)) { 2424 continue; 2425 } 2426 result.add(info.activityInfo.packageName); 2427 } 2428 2429 return result; 2430 } 2431 2432 private void checkDefaultBrowser() { 2433 final int myUserId = UserHandle.myUserId(); 2434 final String packageName = getDefaultBrowserPackageName(myUserId); 2435 if (packageName != null) { 2436 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2437 if (info == null) { 2438 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2439 synchronized (mPackages) { 2440 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2441 } 2442 } 2443 } 2444 } 2445 2446 @Override 2447 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2448 throws RemoteException { 2449 try { 2450 return super.onTransact(code, data, reply, flags); 2451 } catch (RuntimeException e) { 2452 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2453 Slog.wtf(TAG, "Package Manager Crash", e); 2454 } 2455 throw e; 2456 } 2457 } 2458 2459 void cleanupInstallFailedPackage(PackageSetting ps) { 2460 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2461 2462 removeDataDirsLI(ps.volumeUuid, ps.name); 2463 if (ps.codePath != null) { 2464 if (ps.codePath.isDirectory()) { 2465 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2466 } else { 2467 ps.codePath.delete(); 2468 } 2469 } 2470 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2471 if (ps.resourcePath.isDirectory()) { 2472 FileUtils.deleteContents(ps.resourcePath); 2473 } 2474 ps.resourcePath.delete(); 2475 } 2476 mSettings.removePackageLPw(ps.name); 2477 } 2478 2479 static int[] appendInts(int[] cur, int[] add) { 2480 if (add == null) return cur; 2481 if (cur == null) return add; 2482 final int N = add.length; 2483 for (int i=0; i<N; i++) { 2484 cur = appendInt(cur, add[i]); 2485 } 2486 return cur; 2487 } 2488 2489 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2490 if (!sUserManager.exists(userId)) return null; 2491 final PackageSetting ps = (PackageSetting) p.mExtras; 2492 if (ps == null) { 2493 return null; 2494 } 2495 2496 final PermissionsState permissionsState = ps.getPermissionsState(); 2497 2498 final int[] gids = permissionsState.computeGids(userId); 2499 final Set<String> permissions = permissionsState.getPermissions(userId); 2500 final PackageUserState state = ps.readUserState(userId); 2501 2502 return PackageParser.generatePackageInfo(p, gids, flags, 2503 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2504 } 2505 2506 @Override 2507 public boolean isPackageFrozen(String packageName) { 2508 synchronized (mPackages) { 2509 final PackageSetting ps = mSettings.mPackages.get(packageName); 2510 if (ps != null) { 2511 return ps.frozen; 2512 } 2513 } 2514 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2515 return true; 2516 } 2517 2518 @Override 2519 public boolean isPackageAvailable(String packageName, int userId) { 2520 if (!sUserManager.exists(userId)) return false; 2521 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2522 synchronized (mPackages) { 2523 PackageParser.Package p = mPackages.get(packageName); 2524 if (p != null) { 2525 final PackageSetting ps = (PackageSetting) p.mExtras; 2526 if (ps != null) { 2527 final PackageUserState state = ps.readUserState(userId); 2528 if (state != null) { 2529 return PackageParser.isAvailable(state); 2530 } 2531 } 2532 } 2533 } 2534 return false; 2535 } 2536 2537 @Override 2538 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2539 if (!sUserManager.exists(userId)) return null; 2540 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2541 // reader 2542 synchronized (mPackages) { 2543 PackageParser.Package p = mPackages.get(packageName); 2544 if (DEBUG_PACKAGE_INFO) 2545 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2546 if (p != null) { 2547 return generatePackageInfo(p, flags, userId); 2548 } 2549 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2550 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2551 } 2552 } 2553 return null; 2554 } 2555 2556 @Override 2557 public String[] currentToCanonicalPackageNames(String[] names) { 2558 String[] out = new String[names.length]; 2559 // reader 2560 synchronized (mPackages) { 2561 for (int i=names.length-1; i>=0; i--) { 2562 PackageSetting ps = mSettings.mPackages.get(names[i]); 2563 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2564 } 2565 } 2566 return out; 2567 } 2568 2569 @Override 2570 public String[] canonicalToCurrentPackageNames(String[] names) { 2571 String[] out = new String[names.length]; 2572 // reader 2573 synchronized (mPackages) { 2574 for (int i=names.length-1; i>=0; i--) { 2575 String cur = mSettings.mRenamedPackages.get(names[i]); 2576 out[i] = cur != null ? cur : names[i]; 2577 } 2578 } 2579 return out; 2580 } 2581 2582 @Override 2583 public int getPackageUid(String packageName, int userId) { 2584 if (!sUserManager.exists(userId)) return -1; 2585 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2586 2587 // reader 2588 synchronized (mPackages) { 2589 PackageParser.Package p = mPackages.get(packageName); 2590 if(p != null) { 2591 return UserHandle.getUid(userId, p.applicationInfo.uid); 2592 } 2593 PackageSetting ps = mSettings.mPackages.get(packageName); 2594 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2595 return -1; 2596 } 2597 p = ps.pkg; 2598 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2599 } 2600 } 2601 2602 @Override 2603 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2604 if (!sUserManager.exists(userId)) { 2605 return null; 2606 } 2607 2608 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2609 "getPackageGids"); 2610 2611 // reader 2612 synchronized (mPackages) { 2613 PackageParser.Package p = mPackages.get(packageName); 2614 if (DEBUG_PACKAGE_INFO) { 2615 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2616 } 2617 if (p != null) { 2618 PackageSetting ps = (PackageSetting) p.mExtras; 2619 return ps.getPermissionsState().computeGids(userId); 2620 } 2621 } 2622 2623 return null; 2624 } 2625 2626 @Override 2627 public int getMountExternalMode(int uid) { 2628 if (Process.isIsolated(uid)) { 2629 return Zygote.MOUNT_EXTERNAL_NONE; 2630 } else { 2631 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2632 return Zygote.MOUNT_EXTERNAL_WRITE; 2633 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2634 return Zygote.MOUNT_EXTERNAL_READ; 2635 } else { 2636 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2637 } 2638 } 2639 } 2640 2641 static PermissionInfo generatePermissionInfo( 2642 BasePermission bp, int flags) { 2643 if (bp.perm != null) { 2644 return PackageParser.generatePermissionInfo(bp.perm, flags); 2645 } 2646 PermissionInfo pi = new PermissionInfo(); 2647 pi.name = bp.name; 2648 pi.packageName = bp.sourcePackage; 2649 pi.nonLocalizedLabel = bp.name; 2650 pi.protectionLevel = bp.protectionLevel; 2651 return pi; 2652 } 2653 2654 @Override 2655 public PermissionInfo getPermissionInfo(String name, int flags) { 2656 // reader 2657 synchronized (mPackages) { 2658 final BasePermission p = mSettings.mPermissions.get(name); 2659 if (p != null) { 2660 return generatePermissionInfo(p, flags); 2661 } 2662 return null; 2663 } 2664 } 2665 2666 @Override 2667 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2668 // reader 2669 synchronized (mPackages) { 2670 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2671 for (BasePermission p : mSettings.mPermissions.values()) { 2672 if (group == null) { 2673 if (p.perm == null || p.perm.info.group == null) { 2674 out.add(generatePermissionInfo(p, flags)); 2675 } 2676 } else { 2677 if (p.perm != null && group.equals(p.perm.info.group)) { 2678 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2679 } 2680 } 2681 } 2682 2683 if (out.size() > 0) { 2684 return out; 2685 } 2686 return mPermissionGroups.containsKey(group) ? out : null; 2687 } 2688 } 2689 2690 @Override 2691 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2692 // reader 2693 synchronized (mPackages) { 2694 return PackageParser.generatePermissionGroupInfo( 2695 mPermissionGroups.get(name), flags); 2696 } 2697 } 2698 2699 @Override 2700 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2701 // reader 2702 synchronized (mPackages) { 2703 final int N = mPermissionGroups.size(); 2704 ArrayList<PermissionGroupInfo> out 2705 = new ArrayList<PermissionGroupInfo>(N); 2706 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2707 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2708 } 2709 return out; 2710 } 2711 } 2712 2713 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2714 int userId) { 2715 if (!sUserManager.exists(userId)) return null; 2716 PackageSetting ps = mSettings.mPackages.get(packageName); 2717 if (ps != null) { 2718 if (ps.pkg == null) { 2719 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2720 flags, userId); 2721 if (pInfo != null) { 2722 return pInfo.applicationInfo; 2723 } 2724 return null; 2725 } 2726 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2727 ps.readUserState(userId), userId); 2728 } 2729 return null; 2730 } 2731 2732 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2733 int userId) { 2734 if (!sUserManager.exists(userId)) return null; 2735 PackageSetting ps = mSettings.mPackages.get(packageName); 2736 if (ps != null) { 2737 PackageParser.Package pkg = ps.pkg; 2738 if (pkg == null) { 2739 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2740 return null; 2741 } 2742 // Only data remains, so we aren't worried about code paths 2743 pkg = new PackageParser.Package(packageName); 2744 pkg.applicationInfo.packageName = packageName; 2745 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2746 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2747 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2748 packageName, userId).getAbsolutePath(); 2749 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2750 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2751 } 2752 return generatePackageInfo(pkg, flags, userId); 2753 } 2754 return null; 2755 } 2756 2757 @Override 2758 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2759 if (!sUserManager.exists(userId)) return null; 2760 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2761 // writer 2762 synchronized (mPackages) { 2763 PackageParser.Package p = mPackages.get(packageName); 2764 if (DEBUG_PACKAGE_INFO) Log.v( 2765 TAG, "getApplicationInfo " + packageName 2766 + ": " + p); 2767 if (p != null) { 2768 PackageSetting ps = mSettings.mPackages.get(packageName); 2769 if (ps == null) return null; 2770 // Note: isEnabledLP() does not apply here - always return info 2771 return PackageParser.generateApplicationInfo( 2772 p, flags, ps.readUserState(userId), userId); 2773 } 2774 if ("android".equals(packageName)||"system".equals(packageName)) { 2775 return mAndroidApplication; 2776 } 2777 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2778 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2779 } 2780 } 2781 return null; 2782 } 2783 2784 @Override 2785 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2786 final IPackageDataObserver observer) { 2787 mContext.enforceCallingOrSelfPermission( 2788 android.Manifest.permission.CLEAR_APP_CACHE, null); 2789 // Queue up an async operation since clearing cache may take a little while. 2790 mHandler.post(new Runnable() { 2791 public void run() { 2792 mHandler.removeCallbacks(this); 2793 int retCode = -1; 2794 synchronized (mInstallLock) { 2795 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2796 if (retCode < 0) { 2797 Slog.w(TAG, "Couldn't clear application caches"); 2798 } 2799 } 2800 if (observer != null) { 2801 try { 2802 observer.onRemoveCompleted(null, (retCode >= 0)); 2803 } catch (RemoteException e) { 2804 Slog.w(TAG, "RemoveException when invoking call back"); 2805 } 2806 } 2807 } 2808 }); 2809 } 2810 2811 @Override 2812 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2813 final IntentSender pi) { 2814 mContext.enforceCallingOrSelfPermission( 2815 android.Manifest.permission.CLEAR_APP_CACHE, null); 2816 // Queue up an async operation since clearing cache may take a little while. 2817 mHandler.post(new Runnable() { 2818 public void run() { 2819 mHandler.removeCallbacks(this); 2820 int retCode = -1; 2821 synchronized (mInstallLock) { 2822 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2823 if (retCode < 0) { 2824 Slog.w(TAG, "Couldn't clear application caches"); 2825 } 2826 } 2827 if(pi != null) { 2828 try { 2829 // Callback via pending intent 2830 int code = (retCode >= 0) ? 1 : 0; 2831 pi.sendIntent(null, code, null, 2832 null, null); 2833 } catch (SendIntentException e1) { 2834 Slog.i(TAG, "Failed to send pending intent"); 2835 } 2836 } 2837 } 2838 }); 2839 } 2840 2841 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2842 synchronized (mInstallLock) { 2843 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2844 throw new IOException("Failed to free enough space"); 2845 } 2846 } 2847 } 2848 2849 @Override 2850 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2851 if (!sUserManager.exists(userId)) return null; 2852 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2853 synchronized (mPackages) { 2854 PackageParser.Activity a = mActivities.mActivities.get(component); 2855 2856 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2857 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2858 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2859 if (ps == null) return null; 2860 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2861 userId); 2862 } 2863 if (mResolveComponentName.equals(component)) { 2864 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2865 new PackageUserState(), userId); 2866 } 2867 } 2868 return null; 2869 } 2870 2871 @Override 2872 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2873 String resolvedType) { 2874 synchronized (mPackages) { 2875 PackageParser.Activity a = mActivities.mActivities.get(component); 2876 if (a == null) { 2877 return false; 2878 } 2879 for (int i=0; i<a.intents.size(); i++) { 2880 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2881 intent.getData(), intent.getCategories(), TAG) >= 0) { 2882 return true; 2883 } 2884 } 2885 return false; 2886 } 2887 } 2888 2889 @Override 2890 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2891 if (!sUserManager.exists(userId)) return null; 2892 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2893 synchronized (mPackages) { 2894 PackageParser.Activity a = mReceivers.mActivities.get(component); 2895 if (DEBUG_PACKAGE_INFO) Log.v( 2896 TAG, "getReceiverInfo " + component + ": " + a); 2897 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2898 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2899 if (ps == null) return null; 2900 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2901 userId); 2902 } 2903 } 2904 return null; 2905 } 2906 2907 @Override 2908 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2911 synchronized (mPackages) { 2912 PackageParser.Service s = mServices.mServices.get(component); 2913 if (DEBUG_PACKAGE_INFO) Log.v( 2914 TAG, "getServiceInfo " + component + ": " + s); 2915 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2916 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2917 if (ps == null) return null; 2918 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2919 userId); 2920 } 2921 } 2922 return null; 2923 } 2924 2925 @Override 2926 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2927 if (!sUserManager.exists(userId)) return null; 2928 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2929 synchronized (mPackages) { 2930 PackageParser.Provider p = mProviders.mProviders.get(component); 2931 if (DEBUG_PACKAGE_INFO) Log.v( 2932 TAG, "getProviderInfo " + component + ": " + p); 2933 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2934 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2935 if (ps == null) return null; 2936 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2937 userId); 2938 } 2939 } 2940 return null; 2941 } 2942 2943 @Override 2944 public String[] getSystemSharedLibraryNames() { 2945 Set<String> libSet; 2946 synchronized (mPackages) { 2947 libSet = mSharedLibraries.keySet(); 2948 int size = libSet.size(); 2949 if (size > 0) { 2950 String[] libs = new String[size]; 2951 libSet.toArray(libs); 2952 return libs; 2953 } 2954 } 2955 return null; 2956 } 2957 2958 /** 2959 * @hide 2960 */ 2961 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2962 synchronized (mPackages) { 2963 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2964 if (lib != null && lib.apk != null) { 2965 return mPackages.get(lib.apk); 2966 } 2967 } 2968 return null; 2969 } 2970 2971 @Override 2972 public FeatureInfo[] getSystemAvailableFeatures() { 2973 Collection<FeatureInfo> featSet; 2974 synchronized (mPackages) { 2975 featSet = mAvailableFeatures.values(); 2976 int size = featSet.size(); 2977 if (size > 0) { 2978 FeatureInfo[] features = new FeatureInfo[size+1]; 2979 featSet.toArray(features); 2980 FeatureInfo fi = new FeatureInfo(); 2981 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2982 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2983 features[size] = fi; 2984 return features; 2985 } 2986 } 2987 return null; 2988 } 2989 2990 @Override 2991 public boolean hasSystemFeature(String name) { 2992 synchronized (mPackages) { 2993 return mAvailableFeatures.containsKey(name); 2994 } 2995 } 2996 2997 private void checkValidCaller(int uid, int userId) { 2998 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2999 return; 3000 3001 throw new SecurityException("Caller uid=" + uid 3002 + " is not privileged to communicate with user=" + userId); 3003 } 3004 3005 @Override 3006 public int checkPermission(String permName, String pkgName, int userId) { 3007 if (!sUserManager.exists(userId)) { 3008 return PackageManager.PERMISSION_DENIED; 3009 } 3010 3011 synchronized (mPackages) { 3012 final PackageParser.Package p = mPackages.get(pkgName); 3013 if (p != null && p.mExtras != null) { 3014 final PackageSetting ps = (PackageSetting) p.mExtras; 3015 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3016 return PackageManager.PERMISSION_GRANTED; 3017 } 3018 } 3019 } 3020 3021 return PackageManager.PERMISSION_DENIED; 3022 } 3023 3024 @Override 3025 public int checkUidPermission(String permName, int uid) { 3026 final int userId = UserHandle.getUserId(uid); 3027 3028 if (!sUserManager.exists(userId)) { 3029 return PackageManager.PERMISSION_DENIED; 3030 } 3031 3032 synchronized (mPackages) { 3033 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3034 if (obj != null) { 3035 final SettingBase ps = (SettingBase) obj; 3036 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3037 return PackageManager.PERMISSION_GRANTED; 3038 } 3039 } else { 3040 ArraySet<String> perms = mSystemPermissions.get(uid); 3041 if (perms != null && perms.contains(permName)) { 3042 return PackageManager.PERMISSION_GRANTED; 3043 } 3044 } 3045 } 3046 3047 return PackageManager.PERMISSION_DENIED; 3048 } 3049 3050 /** 3051 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3052 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3053 * @param checkShell TODO(yamasani): 3054 * @param message the message to log on security exception 3055 */ 3056 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3057 boolean checkShell, String message) { 3058 if (userId < 0) { 3059 throw new IllegalArgumentException("Invalid userId " + userId); 3060 } 3061 if (checkShell) { 3062 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3063 } 3064 if (userId == UserHandle.getUserId(callingUid)) return; 3065 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3066 if (requireFullPermission) { 3067 mContext.enforceCallingOrSelfPermission( 3068 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3069 } else { 3070 try { 3071 mContext.enforceCallingOrSelfPermission( 3072 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3073 } catch (SecurityException se) { 3074 mContext.enforceCallingOrSelfPermission( 3075 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3076 } 3077 } 3078 } 3079 } 3080 3081 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3082 if (callingUid == Process.SHELL_UID) { 3083 if (userHandle >= 0 3084 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3085 throw new SecurityException("Shell does not have permission to access user " 3086 + userHandle); 3087 } else if (userHandle < 0) { 3088 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3089 + Debug.getCallers(3)); 3090 } 3091 } 3092 } 3093 3094 private BasePermission findPermissionTreeLP(String permName) { 3095 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3096 if (permName.startsWith(bp.name) && 3097 permName.length() > bp.name.length() && 3098 permName.charAt(bp.name.length()) == '.') { 3099 return bp; 3100 } 3101 } 3102 return null; 3103 } 3104 3105 private BasePermission checkPermissionTreeLP(String permName) { 3106 if (permName != null) { 3107 BasePermission bp = findPermissionTreeLP(permName); 3108 if (bp != null) { 3109 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3110 return bp; 3111 } 3112 throw new SecurityException("Calling uid " 3113 + Binder.getCallingUid() 3114 + " is not allowed to add to permission tree " 3115 + bp.name + " owned by uid " + bp.uid); 3116 } 3117 } 3118 throw new SecurityException("No permission tree found for " + permName); 3119 } 3120 3121 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3122 if (s1 == null) { 3123 return s2 == null; 3124 } 3125 if (s2 == null) { 3126 return false; 3127 } 3128 if (s1.getClass() != s2.getClass()) { 3129 return false; 3130 } 3131 return s1.equals(s2); 3132 } 3133 3134 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3135 if (pi1.icon != pi2.icon) return false; 3136 if (pi1.logo != pi2.logo) return false; 3137 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3138 if (!compareStrings(pi1.name, pi2.name)) return false; 3139 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3140 // We'll take care of setting this one. 3141 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3142 // These are not currently stored in settings. 3143 //if (!compareStrings(pi1.group, pi2.group)) return false; 3144 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3145 //if (pi1.labelRes != pi2.labelRes) return false; 3146 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3147 return true; 3148 } 3149 3150 int permissionInfoFootprint(PermissionInfo info) { 3151 int size = info.name.length(); 3152 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3153 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3154 return size; 3155 } 3156 3157 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3158 int size = 0; 3159 for (BasePermission perm : mSettings.mPermissions.values()) { 3160 if (perm.uid == tree.uid) { 3161 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3162 } 3163 } 3164 return size; 3165 } 3166 3167 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3168 // We calculate the max size of permissions defined by this uid and throw 3169 // if that plus the size of 'info' would exceed our stated maximum. 3170 if (tree.uid != Process.SYSTEM_UID) { 3171 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3172 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3173 throw new SecurityException("Permission tree size cap exceeded"); 3174 } 3175 } 3176 } 3177 3178 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3179 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3180 throw new SecurityException("Label must be specified in permission"); 3181 } 3182 BasePermission tree = checkPermissionTreeLP(info.name); 3183 BasePermission bp = mSettings.mPermissions.get(info.name); 3184 boolean added = bp == null; 3185 boolean changed = true; 3186 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3187 if (added) { 3188 enforcePermissionCapLocked(info, tree); 3189 bp = new BasePermission(info.name, tree.sourcePackage, 3190 BasePermission.TYPE_DYNAMIC); 3191 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3192 throw new SecurityException( 3193 "Not allowed to modify non-dynamic permission " 3194 + info.name); 3195 } else { 3196 if (bp.protectionLevel == fixedLevel 3197 && bp.perm.owner.equals(tree.perm.owner) 3198 && bp.uid == tree.uid 3199 && comparePermissionInfos(bp.perm.info, info)) { 3200 changed = false; 3201 } 3202 } 3203 bp.protectionLevel = fixedLevel; 3204 info = new PermissionInfo(info); 3205 info.protectionLevel = fixedLevel; 3206 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3207 bp.perm.info.packageName = tree.perm.info.packageName; 3208 bp.uid = tree.uid; 3209 if (added) { 3210 mSettings.mPermissions.put(info.name, bp); 3211 } 3212 if (changed) { 3213 if (!async) { 3214 mSettings.writeLPr(); 3215 } else { 3216 scheduleWriteSettingsLocked(); 3217 } 3218 } 3219 return added; 3220 } 3221 3222 @Override 3223 public boolean addPermission(PermissionInfo info) { 3224 synchronized (mPackages) { 3225 return addPermissionLocked(info, false); 3226 } 3227 } 3228 3229 @Override 3230 public boolean addPermissionAsync(PermissionInfo info) { 3231 synchronized (mPackages) { 3232 return addPermissionLocked(info, true); 3233 } 3234 } 3235 3236 @Override 3237 public void removePermission(String name) { 3238 synchronized (mPackages) { 3239 checkPermissionTreeLP(name); 3240 BasePermission bp = mSettings.mPermissions.get(name); 3241 if (bp != null) { 3242 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3243 throw new SecurityException( 3244 "Not allowed to modify non-dynamic permission " 3245 + name); 3246 } 3247 mSettings.mPermissions.remove(name); 3248 mSettings.writeLPr(); 3249 } 3250 } 3251 } 3252 3253 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3254 BasePermission bp) { 3255 int index = pkg.requestedPermissions.indexOf(bp.name); 3256 if (index == -1) { 3257 throw new SecurityException("Package " + pkg.packageName 3258 + " has not requested permission " + bp.name); 3259 } 3260 if (!bp.isRuntime()) { 3261 throw new SecurityException("Permission " + bp.name 3262 + " is not a changeable permission type"); 3263 } 3264 } 3265 3266 @Override 3267 public void grantRuntimePermission(String packageName, String name, final int userId) { 3268 if (!sUserManager.exists(userId)) { 3269 Log.e(TAG, "No such user:" + userId); 3270 return; 3271 } 3272 3273 mContext.enforceCallingOrSelfPermission( 3274 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3275 "grantRuntimePermission"); 3276 3277 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3278 "grantRuntimePermission"); 3279 3280 final int uid; 3281 final SettingBase sb; 3282 3283 synchronized (mPackages) { 3284 final PackageParser.Package pkg = mPackages.get(packageName); 3285 if (pkg == null) { 3286 throw new IllegalArgumentException("Unknown package: " + packageName); 3287 } 3288 3289 final BasePermission bp = mSettings.mPermissions.get(name); 3290 if (bp == null) { 3291 throw new IllegalArgumentException("Unknown permission: " + name); 3292 } 3293 3294 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3295 3296 uid = pkg.applicationInfo.uid; 3297 sb = (SettingBase) pkg.mExtras; 3298 if (sb == null) { 3299 throw new IllegalArgumentException("Unknown package: " + packageName); 3300 } 3301 3302 final PermissionsState permissionsState = sb.getPermissionsState(); 3303 3304 final int flags = permissionsState.getPermissionFlags(name, userId); 3305 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3306 throw new SecurityException("Cannot grant system fixed permission: " 3307 + name + " for package: " + packageName); 3308 } 3309 3310 final int result = permissionsState.grantRuntimePermission(bp, userId); 3311 switch (result) { 3312 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3313 return; 3314 } 3315 3316 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3317 mHandler.post(new Runnable() { 3318 @Override 3319 public void run() { 3320 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3321 } 3322 }); 3323 } break; 3324 } 3325 3326 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3327 3328 // Not critical if that is lost - app has to request again. 3329 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3330 } 3331 3332 if (READ_EXTERNAL_STORAGE.equals(name) 3333 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3334 final long token = Binder.clearCallingIdentity(); 3335 try { 3336 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3337 storage.remountUid(uid); 3338 } finally { 3339 Binder.restoreCallingIdentity(token); 3340 } 3341 } 3342 } 3343 3344 @Override 3345 public void revokeRuntimePermission(String packageName, String name, int userId) { 3346 if (!sUserManager.exists(userId)) { 3347 Log.e(TAG, "No such user:" + userId); 3348 return; 3349 } 3350 3351 mContext.enforceCallingOrSelfPermission( 3352 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3353 "revokeRuntimePermission"); 3354 3355 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3356 "revokeRuntimePermission"); 3357 3358 final SettingBase sb; 3359 3360 synchronized (mPackages) { 3361 final PackageParser.Package pkg = mPackages.get(packageName); 3362 if (pkg == null) { 3363 throw new IllegalArgumentException("Unknown package: " + packageName); 3364 } 3365 3366 final BasePermission bp = mSettings.mPermissions.get(name); 3367 if (bp == null) { 3368 throw new IllegalArgumentException("Unknown permission: " + name); 3369 } 3370 3371 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3372 3373 sb = (SettingBase) pkg.mExtras; 3374 if (sb == null) { 3375 throw new IllegalArgumentException("Unknown package: " + packageName); 3376 } 3377 3378 final PermissionsState permissionsState = sb.getPermissionsState(); 3379 3380 final int flags = permissionsState.getPermissionFlags(name, userId); 3381 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3382 throw new SecurityException("Cannot revoke system fixed permission: " 3383 + name + " for package: " + packageName); 3384 } 3385 3386 if (permissionsState.revokeRuntimePermission(bp, userId) == 3387 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3388 return; 3389 } 3390 3391 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3392 3393 // Critical, after this call app should never have the permission. 3394 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3395 } 3396 3397 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3398 } 3399 3400 @Override 3401 public void resetRuntimePermissions() { 3402 mContext.enforceCallingOrSelfPermission( 3403 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3404 "revokeRuntimePermission"); 3405 3406 int callingUid = Binder.getCallingUid(); 3407 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3408 mContext.enforceCallingOrSelfPermission( 3409 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3410 "resetRuntimePermissions"); 3411 } 3412 3413 synchronized (mPackages) { 3414 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3415 for (int userId : UserManagerService.getInstance().getUserIds()) { 3416 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3417 } 3418 } 3419 } 3420 3421 @Override 3422 public int getPermissionFlags(String name, String packageName, int userId) { 3423 if (!sUserManager.exists(userId)) { 3424 return 0; 3425 } 3426 3427 mContext.enforceCallingOrSelfPermission( 3428 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3429 "getPermissionFlags"); 3430 3431 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3432 "getPermissionFlags"); 3433 3434 synchronized (mPackages) { 3435 final PackageParser.Package pkg = mPackages.get(packageName); 3436 if (pkg == null) { 3437 throw new IllegalArgumentException("Unknown package: " + packageName); 3438 } 3439 3440 final BasePermission bp = mSettings.mPermissions.get(name); 3441 if (bp == null) { 3442 throw new IllegalArgumentException("Unknown permission: " + name); 3443 } 3444 3445 SettingBase sb = (SettingBase) pkg.mExtras; 3446 if (sb == null) { 3447 throw new IllegalArgumentException("Unknown package: " + packageName); 3448 } 3449 3450 PermissionsState permissionsState = sb.getPermissionsState(); 3451 return permissionsState.getPermissionFlags(name, userId); 3452 } 3453 } 3454 3455 @Override 3456 public void updatePermissionFlags(String name, String packageName, int flagMask, 3457 int flagValues, int userId) { 3458 if (!sUserManager.exists(userId)) { 3459 return; 3460 } 3461 3462 mContext.enforceCallingOrSelfPermission( 3463 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3464 "updatePermissionFlags"); 3465 3466 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3467 "updatePermissionFlags"); 3468 3469 // Only the system can change system fixed flags. 3470 if (getCallingUid() != Process.SYSTEM_UID) { 3471 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3472 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3473 } 3474 3475 synchronized (mPackages) { 3476 final PackageParser.Package pkg = mPackages.get(packageName); 3477 if (pkg == null) { 3478 throw new IllegalArgumentException("Unknown package: " + packageName); 3479 } 3480 3481 final BasePermission bp = mSettings.mPermissions.get(name); 3482 if (bp == null) { 3483 throw new IllegalArgumentException("Unknown permission: " + name); 3484 } 3485 3486 SettingBase sb = (SettingBase) pkg.mExtras; 3487 if (sb == null) { 3488 throw new IllegalArgumentException("Unknown package: " + packageName); 3489 } 3490 3491 PermissionsState permissionsState = sb.getPermissionsState(); 3492 3493 // Only the package manager can change flags for system component permissions. 3494 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3495 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3496 return; 3497 } 3498 3499 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3500 3501 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3502 // Install and runtime permissions are stored in different places, 3503 // so figure out what permission changed and persist the change. 3504 if (permissionsState.getInstallPermissionState(name) != null) { 3505 scheduleWriteSettingsLocked(); 3506 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3507 || hadState) { 3508 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3509 } 3510 } 3511 } 3512 } 3513 3514 /** 3515 * Update the permission flags for all packages and runtime permissions of a user in order 3516 * to allow device or profile owner to remove POLICY_FIXED. 3517 */ 3518 @Override 3519 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3520 if (!sUserManager.exists(userId)) { 3521 return; 3522 } 3523 3524 mContext.enforceCallingOrSelfPermission( 3525 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3526 "updatePermissionFlagsForAllApps"); 3527 3528 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3529 "updatePermissionFlagsForAllApps"); 3530 3531 // Only the system can change system fixed flags. 3532 if (getCallingUid() != Process.SYSTEM_UID) { 3533 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3534 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3535 } 3536 3537 synchronized (mPackages) { 3538 boolean changed = false; 3539 final int packageCount = mPackages.size(); 3540 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3541 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3542 SettingBase sb = (SettingBase) pkg.mExtras; 3543 if (sb == null) { 3544 continue; 3545 } 3546 PermissionsState permissionsState = sb.getPermissionsState(); 3547 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3548 userId, flagMask, flagValues); 3549 } 3550 if (changed) { 3551 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3552 } 3553 } 3554 } 3555 3556 @Override 3557 public boolean shouldShowRequestPermissionRationale(String permissionName, 3558 String packageName, int userId) { 3559 if (UserHandle.getCallingUserId() != userId) { 3560 mContext.enforceCallingPermission( 3561 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3562 "canShowRequestPermissionRationale for user " + userId); 3563 } 3564 3565 final int uid = getPackageUid(packageName, userId); 3566 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3567 return false; 3568 } 3569 3570 if (checkPermission(permissionName, packageName, userId) 3571 == PackageManager.PERMISSION_GRANTED) { 3572 return false; 3573 } 3574 3575 final int flags; 3576 3577 final long identity = Binder.clearCallingIdentity(); 3578 try { 3579 flags = getPermissionFlags(permissionName, 3580 packageName, userId); 3581 } finally { 3582 Binder.restoreCallingIdentity(identity); 3583 } 3584 3585 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3586 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3587 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3588 3589 if ((flags & fixedFlags) != 0) { 3590 return false; 3591 } 3592 3593 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3594 } 3595 3596 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3597 BasePermission bp = mSettings.mPermissions.get(permission); 3598 if (bp == null) { 3599 throw new SecurityException("Missing " + permission + " permission"); 3600 } 3601 3602 SettingBase sb = (SettingBase) pkg.mExtras; 3603 PermissionsState permissionsState = sb.getPermissionsState(); 3604 3605 if (permissionsState.grantInstallPermission(bp) != 3606 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3607 scheduleWriteSettingsLocked(); 3608 } 3609 } 3610 3611 @Override 3612 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3613 mContext.enforceCallingOrSelfPermission( 3614 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3615 "addOnPermissionsChangeListener"); 3616 3617 synchronized (mPackages) { 3618 mOnPermissionChangeListeners.addListenerLocked(listener); 3619 } 3620 } 3621 3622 @Override 3623 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3624 synchronized (mPackages) { 3625 mOnPermissionChangeListeners.removeListenerLocked(listener); 3626 } 3627 } 3628 3629 @Override 3630 public boolean isProtectedBroadcast(String actionName) { 3631 synchronized (mPackages) { 3632 return mProtectedBroadcasts.contains(actionName); 3633 } 3634 } 3635 3636 @Override 3637 public int checkSignatures(String pkg1, String pkg2) { 3638 synchronized (mPackages) { 3639 final PackageParser.Package p1 = mPackages.get(pkg1); 3640 final PackageParser.Package p2 = mPackages.get(pkg2); 3641 if (p1 == null || p1.mExtras == null 3642 || p2 == null || p2.mExtras == null) { 3643 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3644 } 3645 return compareSignatures(p1.mSignatures, p2.mSignatures); 3646 } 3647 } 3648 3649 @Override 3650 public int checkUidSignatures(int uid1, int uid2) { 3651 // Map to base uids. 3652 uid1 = UserHandle.getAppId(uid1); 3653 uid2 = UserHandle.getAppId(uid2); 3654 // reader 3655 synchronized (mPackages) { 3656 Signature[] s1; 3657 Signature[] s2; 3658 Object obj = mSettings.getUserIdLPr(uid1); 3659 if (obj != null) { 3660 if (obj instanceof SharedUserSetting) { 3661 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3662 } else if (obj instanceof PackageSetting) { 3663 s1 = ((PackageSetting)obj).signatures.mSignatures; 3664 } else { 3665 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3666 } 3667 } else { 3668 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3669 } 3670 obj = mSettings.getUserIdLPr(uid2); 3671 if (obj != null) { 3672 if (obj instanceof SharedUserSetting) { 3673 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3674 } else if (obj instanceof PackageSetting) { 3675 s2 = ((PackageSetting)obj).signatures.mSignatures; 3676 } else { 3677 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3678 } 3679 } else { 3680 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3681 } 3682 return compareSignatures(s1, s2); 3683 } 3684 } 3685 3686 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3687 final long identity = Binder.clearCallingIdentity(); 3688 try { 3689 if (sb instanceof SharedUserSetting) { 3690 SharedUserSetting sus = (SharedUserSetting) sb; 3691 final int packageCount = sus.packages.size(); 3692 for (int i = 0; i < packageCount; i++) { 3693 PackageSetting susPs = sus.packages.valueAt(i); 3694 if (userId == UserHandle.USER_ALL) { 3695 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3696 } else { 3697 final int uid = UserHandle.getUid(userId, susPs.appId); 3698 killUid(uid, reason); 3699 } 3700 } 3701 } else if (sb instanceof PackageSetting) { 3702 PackageSetting ps = (PackageSetting) sb; 3703 if (userId == UserHandle.USER_ALL) { 3704 killApplication(ps.pkg.packageName, ps.appId, reason); 3705 } else { 3706 final int uid = UserHandle.getUid(userId, ps.appId); 3707 killUid(uid, reason); 3708 } 3709 } 3710 } finally { 3711 Binder.restoreCallingIdentity(identity); 3712 } 3713 } 3714 3715 private static void killUid(int uid, String reason) { 3716 IActivityManager am = ActivityManagerNative.getDefault(); 3717 if (am != null) { 3718 try { 3719 am.killUid(uid, reason); 3720 } catch (RemoteException e) { 3721 /* ignore - same process */ 3722 } 3723 } 3724 } 3725 3726 /** 3727 * Compares two sets of signatures. Returns: 3728 * <br /> 3729 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3730 * <br /> 3731 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3732 * <br /> 3733 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3734 * <br /> 3735 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3736 * <br /> 3737 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3738 */ 3739 static int compareSignatures(Signature[] s1, Signature[] s2) { 3740 if (s1 == null) { 3741 return s2 == null 3742 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3743 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3744 } 3745 3746 if (s2 == null) { 3747 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3748 } 3749 3750 if (s1.length != s2.length) { 3751 return PackageManager.SIGNATURE_NO_MATCH; 3752 } 3753 3754 // Since both signature sets are of size 1, we can compare without HashSets. 3755 if (s1.length == 1) { 3756 return s1[0].equals(s2[0]) ? 3757 PackageManager.SIGNATURE_MATCH : 3758 PackageManager.SIGNATURE_NO_MATCH; 3759 } 3760 3761 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3762 for (Signature sig : s1) { 3763 set1.add(sig); 3764 } 3765 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3766 for (Signature sig : s2) { 3767 set2.add(sig); 3768 } 3769 // Make sure s2 contains all signatures in s1. 3770 if (set1.equals(set2)) { 3771 return PackageManager.SIGNATURE_MATCH; 3772 } 3773 return PackageManager.SIGNATURE_NO_MATCH; 3774 } 3775 3776 /** 3777 * If the database version for this type of package (internal storage or 3778 * external storage) is less than the version where package signatures 3779 * were updated, return true. 3780 */ 3781 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3782 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3783 DatabaseVersion.SIGNATURE_END_ENTITY)) 3784 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3785 DatabaseVersion.SIGNATURE_END_ENTITY)); 3786 } 3787 3788 /** 3789 * Used for backward compatibility to make sure any packages with 3790 * certificate chains get upgraded to the new style. {@code existingSigs} 3791 * will be in the old format (since they were stored on disk from before the 3792 * system upgrade) and {@code scannedSigs} will be in the newer format. 3793 */ 3794 private int compareSignaturesCompat(PackageSignatures existingSigs, 3795 PackageParser.Package scannedPkg) { 3796 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3797 return PackageManager.SIGNATURE_NO_MATCH; 3798 } 3799 3800 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3801 for (Signature sig : existingSigs.mSignatures) { 3802 existingSet.add(sig); 3803 } 3804 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3805 for (Signature sig : scannedPkg.mSignatures) { 3806 try { 3807 Signature[] chainSignatures = sig.getChainSignatures(); 3808 for (Signature chainSig : chainSignatures) { 3809 scannedCompatSet.add(chainSig); 3810 } 3811 } catch (CertificateEncodingException e) { 3812 scannedCompatSet.add(sig); 3813 } 3814 } 3815 /* 3816 * Make sure the expanded scanned set contains all signatures in the 3817 * existing one. 3818 */ 3819 if (scannedCompatSet.equals(existingSet)) { 3820 // Migrate the old signatures to the new scheme. 3821 existingSigs.assignSignatures(scannedPkg.mSignatures); 3822 // The new KeySets will be re-added later in the scanning process. 3823 synchronized (mPackages) { 3824 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3825 } 3826 return PackageManager.SIGNATURE_MATCH; 3827 } 3828 return PackageManager.SIGNATURE_NO_MATCH; 3829 } 3830 3831 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3832 if (isExternal(scannedPkg)) { 3833 return mSettings.isExternalDatabaseVersionOlderThan( 3834 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3835 } else { 3836 return mSettings.isInternalDatabaseVersionOlderThan( 3837 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3838 } 3839 } 3840 3841 private int compareSignaturesRecover(PackageSignatures existingSigs, 3842 PackageParser.Package scannedPkg) { 3843 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3844 return PackageManager.SIGNATURE_NO_MATCH; 3845 } 3846 3847 String msg = null; 3848 try { 3849 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3850 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3851 + scannedPkg.packageName); 3852 return PackageManager.SIGNATURE_MATCH; 3853 } 3854 } catch (CertificateException e) { 3855 msg = e.getMessage(); 3856 } 3857 3858 logCriticalInfo(Log.INFO, 3859 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3860 return PackageManager.SIGNATURE_NO_MATCH; 3861 } 3862 3863 @Override 3864 public String[] getPackagesForUid(int uid) { 3865 uid = UserHandle.getAppId(uid); 3866 // reader 3867 synchronized (mPackages) { 3868 Object obj = mSettings.getUserIdLPr(uid); 3869 if (obj instanceof SharedUserSetting) { 3870 final SharedUserSetting sus = (SharedUserSetting) obj; 3871 final int N = sus.packages.size(); 3872 final String[] res = new String[N]; 3873 final Iterator<PackageSetting> it = sus.packages.iterator(); 3874 int i = 0; 3875 while (it.hasNext()) { 3876 res[i++] = it.next().name; 3877 } 3878 return res; 3879 } else if (obj instanceof PackageSetting) { 3880 final PackageSetting ps = (PackageSetting) obj; 3881 return new String[] { ps.name }; 3882 } 3883 } 3884 return null; 3885 } 3886 3887 @Override 3888 public String getNameForUid(int uid) { 3889 // reader 3890 synchronized (mPackages) { 3891 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3892 if (obj instanceof SharedUserSetting) { 3893 final SharedUserSetting sus = (SharedUserSetting) obj; 3894 return sus.name + ":" + sus.userId; 3895 } else if (obj instanceof PackageSetting) { 3896 final PackageSetting ps = (PackageSetting) obj; 3897 return ps.name; 3898 } 3899 } 3900 return null; 3901 } 3902 3903 @Override 3904 public int getUidForSharedUser(String sharedUserName) { 3905 if(sharedUserName == null) { 3906 return -1; 3907 } 3908 // reader 3909 synchronized (mPackages) { 3910 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3911 if (suid == null) { 3912 return -1; 3913 } 3914 return suid.userId; 3915 } 3916 } 3917 3918 @Override 3919 public int getFlagsForUid(int uid) { 3920 synchronized (mPackages) { 3921 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3922 if (obj instanceof SharedUserSetting) { 3923 final SharedUserSetting sus = (SharedUserSetting) obj; 3924 return sus.pkgFlags; 3925 } else if (obj instanceof PackageSetting) { 3926 final PackageSetting ps = (PackageSetting) obj; 3927 return ps.pkgFlags; 3928 } 3929 } 3930 return 0; 3931 } 3932 3933 @Override 3934 public int getPrivateFlagsForUid(int uid) { 3935 synchronized (mPackages) { 3936 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3937 if (obj instanceof SharedUserSetting) { 3938 final SharedUserSetting sus = (SharedUserSetting) obj; 3939 return sus.pkgPrivateFlags; 3940 } else if (obj instanceof PackageSetting) { 3941 final PackageSetting ps = (PackageSetting) obj; 3942 return ps.pkgPrivateFlags; 3943 } 3944 } 3945 return 0; 3946 } 3947 3948 @Override 3949 public boolean isUidPrivileged(int uid) { 3950 uid = UserHandle.getAppId(uid); 3951 // reader 3952 synchronized (mPackages) { 3953 Object obj = mSettings.getUserIdLPr(uid); 3954 if (obj instanceof SharedUserSetting) { 3955 final SharedUserSetting sus = (SharedUserSetting) obj; 3956 final Iterator<PackageSetting> it = sus.packages.iterator(); 3957 while (it.hasNext()) { 3958 if (it.next().isPrivileged()) { 3959 return true; 3960 } 3961 } 3962 } else if (obj instanceof PackageSetting) { 3963 final PackageSetting ps = (PackageSetting) obj; 3964 return ps.isPrivileged(); 3965 } 3966 } 3967 return false; 3968 } 3969 3970 @Override 3971 public String[] getAppOpPermissionPackages(String permissionName) { 3972 synchronized (mPackages) { 3973 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3974 if (pkgs == null) { 3975 return null; 3976 } 3977 return pkgs.toArray(new String[pkgs.size()]); 3978 } 3979 } 3980 3981 @Override 3982 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3983 int flags, int userId) { 3984 if (!sUserManager.exists(userId)) return null; 3985 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3986 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3987 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3988 } 3989 3990 @Override 3991 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3992 IntentFilter filter, int match, ComponentName activity) { 3993 final int userId = UserHandle.getCallingUserId(); 3994 if (DEBUG_PREFERRED) { 3995 Log.v(TAG, "setLastChosenActivity intent=" + intent 3996 + " resolvedType=" + resolvedType 3997 + " flags=" + flags 3998 + " filter=" + filter 3999 + " match=" + match 4000 + " activity=" + activity); 4001 filter.dump(new PrintStreamPrinter(System.out), " "); 4002 } 4003 intent.setComponent(null); 4004 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4005 // Find any earlier preferred or last chosen entries and nuke them 4006 findPreferredActivity(intent, resolvedType, 4007 flags, query, 0, false, true, false, userId); 4008 // Add the new activity as the last chosen for this filter 4009 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4010 "Setting last chosen"); 4011 } 4012 4013 @Override 4014 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4015 final int userId = UserHandle.getCallingUserId(); 4016 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4017 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4018 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4019 false, false, false, userId); 4020 } 4021 4022 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4023 int flags, List<ResolveInfo> query, int userId) { 4024 if (query != null) { 4025 final int N = query.size(); 4026 if (N == 1) { 4027 return query.get(0); 4028 } else if (N > 1) { 4029 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4030 // If there is more than one activity with the same priority, 4031 // then let the user decide between them. 4032 ResolveInfo r0 = query.get(0); 4033 ResolveInfo r1 = query.get(1); 4034 if (DEBUG_INTENT_MATCHING || debug) { 4035 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4036 + r1.activityInfo.name + "=" + r1.priority); 4037 } 4038 // If the first activity has a higher priority, or a different 4039 // default, then it is always desireable to pick it. 4040 if (r0.priority != r1.priority 4041 || r0.preferredOrder != r1.preferredOrder 4042 || r0.isDefault != r1.isDefault) { 4043 return query.get(0); 4044 } 4045 // If we have saved a preference for a preferred activity for 4046 // this Intent, use that. 4047 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4048 flags, query, r0.priority, true, false, debug, userId); 4049 if (ri != null) { 4050 return ri; 4051 } 4052 if (userId != 0) { 4053 ri = new ResolveInfo(mResolveInfo); 4054 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4055 ri.activityInfo.applicationInfo = new ApplicationInfo( 4056 ri.activityInfo.applicationInfo); 4057 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4058 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4059 return ri; 4060 } 4061 return mResolveInfo; 4062 } 4063 } 4064 return null; 4065 } 4066 4067 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4068 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4069 final int N = query.size(); 4070 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4071 .get(userId); 4072 // Get the list of persistent preferred activities that handle the intent 4073 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4074 List<PersistentPreferredActivity> pprefs = ppir != null 4075 ? ppir.queryIntent(intent, resolvedType, 4076 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4077 : null; 4078 if (pprefs != null && pprefs.size() > 0) { 4079 final int M = pprefs.size(); 4080 for (int i=0; i<M; i++) { 4081 final PersistentPreferredActivity ppa = pprefs.get(i); 4082 if (DEBUG_PREFERRED || debug) { 4083 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4084 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4085 + "\n component=" + ppa.mComponent); 4086 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4087 } 4088 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4089 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4090 if (DEBUG_PREFERRED || debug) { 4091 Slog.v(TAG, "Found persistent preferred activity:"); 4092 if (ai != null) { 4093 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4094 } else { 4095 Slog.v(TAG, " null"); 4096 } 4097 } 4098 if (ai == null) { 4099 // This previously registered persistent preferred activity 4100 // component is no longer known. Ignore it and do NOT remove it. 4101 continue; 4102 } 4103 for (int j=0; j<N; j++) { 4104 final ResolveInfo ri = query.get(j); 4105 if (!ri.activityInfo.applicationInfo.packageName 4106 .equals(ai.applicationInfo.packageName)) { 4107 continue; 4108 } 4109 if (!ri.activityInfo.name.equals(ai.name)) { 4110 continue; 4111 } 4112 // Found a persistent preference that can handle the intent. 4113 if (DEBUG_PREFERRED || debug) { 4114 Slog.v(TAG, "Returning persistent preferred activity: " + 4115 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4116 } 4117 return ri; 4118 } 4119 } 4120 } 4121 return null; 4122 } 4123 4124 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4125 List<ResolveInfo> query, int priority, boolean always, 4126 boolean removeMatches, boolean debug, int userId) { 4127 if (!sUserManager.exists(userId)) return null; 4128 // writer 4129 synchronized (mPackages) { 4130 if (intent.getSelector() != null) { 4131 intent = intent.getSelector(); 4132 } 4133 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4134 4135 // Try to find a matching persistent preferred activity. 4136 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4137 debug, userId); 4138 4139 // If a persistent preferred activity matched, use it. 4140 if (pri != null) { 4141 return pri; 4142 } 4143 4144 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4145 // Get the list of preferred activities that handle the intent 4146 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4147 List<PreferredActivity> prefs = pir != null 4148 ? pir.queryIntent(intent, resolvedType, 4149 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4150 : null; 4151 if (prefs != null && prefs.size() > 0) { 4152 boolean changed = false; 4153 try { 4154 // First figure out how good the original match set is. 4155 // We will only allow preferred activities that came 4156 // from the same match quality. 4157 int match = 0; 4158 4159 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4160 4161 final int N = query.size(); 4162 for (int j=0; j<N; j++) { 4163 final ResolveInfo ri = query.get(j); 4164 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4165 + ": 0x" + Integer.toHexString(match)); 4166 if (ri.match > match) { 4167 match = ri.match; 4168 } 4169 } 4170 4171 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4172 + Integer.toHexString(match)); 4173 4174 match &= IntentFilter.MATCH_CATEGORY_MASK; 4175 final int M = prefs.size(); 4176 for (int i=0; i<M; i++) { 4177 final PreferredActivity pa = prefs.get(i); 4178 if (DEBUG_PREFERRED || debug) { 4179 Slog.v(TAG, "Checking PreferredActivity ds=" 4180 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4181 + "\n component=" + pa.mPref.mComponent); 4182 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4183 } 4184 if (pa.mPref.mMatch != match) { 4185 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4186 + Integer.toHexString(pa.mPref.mMatch)); 4187 continue; 4188 } 4189 // If it's not an "always" type preferred activity and that's what we're 4190 // looking for, skip it. 4191 if (always && !pa.mPref.mAlways) { 4192 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4193 continue; 4194 } 4195 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4196 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4197 if (DEBUG_PREFERRED || debug) { 4198 Slog.v(TAG, "Found preferred activity:"); 4199 if (ai != null) { 4200 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4201 } else { 4202 Slog.v(TAG, " null"); 4203 } 4204 } 4205 if (ai == null) { 4206 // This previously registered preferred activity 4207 // component is no longer known. Most likely an update 4208 // to the app was installed and in the new version this 4209 // component no longer exists. Clean it up by removing 4210 // it from the preferred activities list, and skip it. 4211 Slog.w(TAG, "Removing dangling preferred activity: " 4212 + pa.mPref.mComponent); 4213 pir.removeFilter(pa); 4214 changed = true; 4215 continue; 4216 } 4217 for (int j=0; j<N; j++) { 4218 final ResolveInfo ri = query.get(j); 4219 if (!ri.activityInfo.applicationInfo.packageName 4220 .equals(ai.applicationInfo.packageName)) { 4221 continue; 4222 } 4223 if (!ri.activityInfo.name.equals(ai.name)) { 4224 continue; 4225 } 4226 4227 if (removeMatches) { 4228 pir.removeFilter(pa); 4229 changed = true; 4230 if (DEBUG_PREFERRED) { 4231 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4232 } 4233 break; 4234 } 4235 4236 // Okay we found a previously set preferred or last chosen app. 4237 // If the result set is different from when this 4238 // was created, we need to clear it and re-ask the 4239 // user their preference, if we're looking for an "always" type entry. 4240 if (always && !pa.mPref.sameSet(query)) { 4241 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4242 + intent + " type " + resolvedType); 4243 if (DEBUG_PREFERRED) { 4244 Slog.v(TAG, "Removing preferred activity since set changed " 4245 + pa.mPref.mComponent); 4246 } 4247 pir.removeFilter(pa); 4248 // Re-add the filter as a "last chosen" entry (!always) 4249 PreferredActivity lastChosen = new PreferredActivity( 4250 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4251 pir.addFilter(lastChosen); 4252 changed = true; 4253 return null; 4254 } 4255 4256 // Yay! Either the set matched or we're looking for the last chosen 4257 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4258 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4259 return ri; 4260 } 4261 } 4262 } finally { 4263 if (changed) { 4264 if (DEBUG_PREFERRED) { 4265 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4266 } 4267 scheduleWritePackageRestrictionsLocked(userId); 4268 } 4269 } 4270 } 4271 } 4272 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4273 return null; 4274 } 4275 4276 /* 4277 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4278 */ 4279 @Override 4280 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4281 int targetUserId) { 4282 mContext.enforceCallingOrSelfPermission( 4283 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4284 List<CrossProfileIntentFilter> matches = 4285 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4286 if (matches != null) { 4287 int size = matches.size(); 4288 for (int i = 0; i < size; i++) { 4289 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4290 } 4291 } 4292 if (hasWebURI(intent)) { 4293 // cross-profile app linking works only towards the parent. 4294 final UserInfo parent = getProfileParent(sourceUserId); 4295 synchronized(mPackages) { 4296 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4297 parent.id) != null; 4298 } 4299 } 4300 return false; 4301 } 4302 4303 private UserInfo getProfileParent(int userId) { 4304 final long identity = Binder.clearCallingIdentity(); 4305 try { 4306 return sUserManager.getProfileParent(userId); 4307 } finally { 4308 Binder.restoreCallingIdentity(identity); 4309 } 4310 } 4311 4312 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4313 String resolvedType, int userId) { 4314 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4315 if (resolver != null) { 4316 return resolver.queryIntent(intent, resolvedType, false, userId); 4317 } 4318 return null; 4319 } 4320 4321 @Override 4322 public List<ResolveInfo> queryIntentActivities(Intent intent, 4323 String resolvedType, int flags, int userId) { 4324 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4325 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4326 ComponentName comp = intent.getComponent(); 4327 if (comp == null) { 4328 if (intent.getSelector() != null) { 4329 intent = intent.getSelector(); 4330 comp = intent.getComponent(); 4331 } 4332 } 4333 4334 if (comp != null) { 4335 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4336 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4337 if (ai != null) { 4338 final ResolveInfo ri = new ResolveInfo(); 4339 ri.activityInfo = ai; 4340 list.add(ri); 4341 } 4342 return list; 4343 } 4344 4345 // reader 4346 synchronized (mPackages) { 4347 final String pkgName = intent.getPackage(); 4348 if (pkgName == null) { 4349 List<CrossProfileIntentFilter> matchingFilters = 4350 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4351 // Check for results that need to skip the current profile. 4352 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4353 resolvedType, flags, userId); 4354 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4355 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4356 result.add(xpResolveInfo); 4357 return filterIfNotPrimaryUser(result, userId); 4358 } 4359 4360 // Check for results in the current profile. 4361 List<ResolveInfo> result = mActivities.queryIntent( 4362 intent, resolvedType, flags, userId); 4363 4364 // Check for cross profile results. 4365 xpResolveInfo = queryCrossProfileIntents( 4366 matchingFilters, intent, resolvedType, flags, userId); 4367 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4368 result.add(xpResolveInfo); 4369 Collections.sort(result, mResolvePrioritySorter); 4370 } 4371 result = filterIfNotPrimaryUser(result, userId); 4372 if (hasWebURI(intent)) { 4373 CrossProfileDomainInfo xpDomainInfo = null; 4374 final UserInfo parent = getProfileParent(userId); 4375 if (parent != null) { 4376 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4377 flags, userId, parent.id); 4378 } 4379 if (xpDomainInfo != null) { 4380 if (xpResolveInfo != null) { 4381 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4382 // in the result. 4383 result.remove(xpResolveInfo); 4384 } 4385 if (result.size() == 0) { 4386 result.add(xpDomainInfo.resolveInfo); 4387 return result; 4388 } 4389 } else if (result.size() <= 1) { 4390 return result; 4391 } 4392 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4393 xpDomainInfo); 4394 Collections.sort(result, mResolvePrioritySorter); 4395 } 4396 return result; 4397 } 4398 final PackageParser.Package pkg = mPackages.get(pkgName); 4399 if (pkg != null) { 4400 return filterIfNotPrimaryUser( 4401 mActivities.queryIntentForPackage( 4402 intent, resolvedType, flags, pkg.activities, userId), 4403 userId); 4404 } 4405 return new ArrayList<ResolveInfo>(); 4406 } 4407 } 4408 4409 private static class CrossProfileDomainInfo { 4410 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4411 ResolveInfo resolveInfo; 4412 /* Best domain verification status of the activities found in the other profile */ 4413 int bestDomainVerificationStatus; 4414 } 4415 4416 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4417 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4418 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4419 sourceUserId)) { 4420 return null; 4421 } 4422 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4423 resolvedType, flags, parentUserId); 4424 4425 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4426 return null; 4427 } 4428 CrossProfileDomainInfo result = null; 4429 int size = resultTargetUser.size(); 4430 for (int i = 0; i < size; i++) { 4431 ResolveInfo riTargetUser = resultTargetUser.get(i); 4432 // Intent filter verification is only for filters that specify a host. So don't return 4433 // those that handle all web uris. 4434 if (riTargetUser.handleAllWebDataURI) { 4435 continue; 4436 } 4437 String packageName = riTargetUser.activityInfo.packageName; 4438 PackageSetting ps = mSettings.mPackages.get(packageName); 4439 if (ps == null) { 4440 continue; 4441 } 4442 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4443 if (result == null) { 4444 result = new CrossProfileDomainInfo(); 4445 result.resolveInfo = 4446 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4447 result.bestDomainVerificationStatus = status; 4448 } else { 4449 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4450 result.bestDomainVerificationStatus); 4451 } 4452 } 4453 return result; 4454 } 4455 4456 /** 4457 * Verification statuses are ordered from the worse to the best, except for 4458 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4459 */ 4460 private int bestDomainVerificationStatus(int status1, int status2) { 4461 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4462 return status2; 4463 } 4464 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4465 return status1; 4466 } 4467 return (int) MathUtils.max(status1, status2); 4468 } 4469 4470 private boolean isUserEnabled(int userId) { 4471 long callingId = Binder.clearCallingIdentity(); 4472 try { 4473 UserInfo userInfo = sUserManager.getUserInfo(userId); 4474 return userInfo != null && userInfo.isEnabled(); 4475 } finally { 4476 Binder.restoreCallingIdentity(callingId); 4477 } 4478 } 4479 4480 /** 4481 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4482 * 4483 * @return filtered list 4484 */ 4485 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4486 if (userId == UserHandle.USER_OWNER) { 4487 return resolveInfos; 4488 } 4489 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4490 ResolveInfo info = resolveInfos.get(i); 4491 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4492 resolveInfos.remove(i); 4493 } 4494 } 4495 return resolveInfos; 4496 } 4497 4498 private static boolean hasWebURI(Intent intent) { 4499 if (intent.getData() == null) { 4500 return false; 4501 } 4502 final String scheme = intent.getScheme(); 4503 if (TextUtils.isEmpty(scheme)) { 4504 return false; 4505 } 4506 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4507 } 4508 4509 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4510 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4511 if (DEBUG_PREFERRED) { 4512 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4513 candidates.size()); 4514 } 4515 4516 final int userId = UserHandle.getCallingUserId(); 4517 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4518 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4519 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4520 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4521 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4522 4523 synchronized (mPackages) { 4524 final int count = candidates.size(); 4525 // First, try to use the domain preferred app. Partition the candidates into four lists: 4526 // one for the final results, one for the "do not use ever", one for "undefined status" 4527 // and finally one for "Browser App type". 4528 for (int n=0; n<count; n++) { 4529 ResolveInfo info = candidates.get(n); 4530 String packageName = info.activityInfo.packageName; 4531 PackageSetting ps = mSettings.mPackages.get(packageName); 4532 if (ps != null) { 4533 // Add to the special match all list (Browser use case) 4534 if (info.handleAllWebDataURI) { 4535 matchAllList.add(info); 4536 continue; 4537 } 4538 // Try to get the status from User settings first 4539 int status = getDomainVerificationStatusLPr(ps, userId); 4540 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4541 alwaysList.add(info); 4542 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4543 neverList.add(info); 4544 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4545 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4546 undefinedList.add(info); 4547 } 4548 } 4549 } 4550 // First try to add the "always" resolution for the current user if there is any 4551 if (alwaysList.size() > 0) { 4552 result.addAll(alwaysList); 4553 // if there is an "always" for the parent user, add it. 4554 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4555 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4556 result.add(xpDomainInfo.resolveInfo); 4557 } else { 4558 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4559 result.addAll(undefinedList); 4560 if (xpDomainInfo != null && ( 4561 xpDomainInfo.bestDomainVerificationStatus 4562 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4563 || xpDomainInfo.bestDomainVerificationStatus 4564 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4565 result.add(xpDomainInfo.resolveInfo); 4566 } 4567 // Also add Browsers (all of them or only the default one) 4568 if ((flags & MATCH_ALL) != 0) { 4569 result.addAll(matchAllList); 4570 } else { 4571 // Try to add the Default Browser if we can 4572 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4573 UserHandle.myUserId()); 4574 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4575 boolean defaultBrowserFound = false; 4576 final int browserCount = matchAllList.size(); 4577 for (int n=0; n<browserCount; n++) { 4578 ResolveInfo browser = matchAllList.get(n); 4579 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4580 result.add(browser); 4581 defaultBrowserFound = true; 4582 break; 4583 } 4584 } 4585 if (!defaultBrowserFound) { 4586 result.addAll(matchAllList); 4587 } 4588 } else { 4589 result.addAll(matchAllList); 4590 } 4591 } 4592 4593 // If there is nothing selected, add all candidates and remove the ones that the User 4594 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4595 if (result.size() == 0) { 4596 result.addAll(candidates); 4597 result.removeAll(neverList); 4598 } 4599 } 4600 } 4601 if (DEBUG_PREFERRED) { 4602 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4603 result.size()); 4604 } 4605 return result; 4606 } 4607 4608 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4609 int status = ps.getDomainVerificationStatusForUser(userId); 4610 // if none available, get the master status 4611 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4612 if (ps.getIntentFilterVerificationInfo() != null) { 4613 status = ps.getIntentFilterVerificationInfo().getStatus(); 4614 } 4615 } 4616 return status; 4617 } 4618 4619 private ResolveInfo querySkipCurrentProfileIntents( 4620 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4621 int flags, int sourceUserId) { 4622 if (matchingFilters != null) { 4623 int size = matchingFilters.size(); 4624 for (int i = 0; i < size; i ++) { 4625 CrossProfileIntentFilter filter = matchingFilters.get(i); 4626 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4627 // Checking if there are activities in the target user that can handle the 4628 // intent. 4629 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4630 flags, sourceUserId); 4631 if (resolveInfo != null) { 4632 return resolveInfo; 4633 } 4634 } 4635 } 4636 } 4637 return null; 4638 } 4639 4640 // Return matching ResolveInfo if any for skip current profile intent filters. 4641 private ResolveInfo queryCrossProfileIntents( 4642 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4643 int flags, int sourceUserId) { 4644 if (matchingFilters != null) { 4645 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4646 // match the same intent. For performance reasons, it is better not to 4647 // run queryIntent twice for the same userId 4648 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4649 int size = matchingFilters.size(); 4650 for (int i = 0; i < size; i++) { 4651 CrossProfileIntentFilter filter = matchingFilters.get(i); 4652 int targetUserId = filter.getTargetUserId(); 4653 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4654 && !alreadyTriedUserIds.get(targetUserId)) { 4655 // Checking if there are activities in the target user that can handle the 4656 // intent. 4657 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4658 flags, sourceUserId); 4659 if (resolveInfo != null) return resolveInfo; 4660 alreadyTriedUserIds.put(targetUserId, true); 4661 } 4662 } 4663 } 4664 return null; 4665 } 4666 4667 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4668 String resolvedType, int flags, int sourceUserId) { 4669 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4670 resolvedType, flags, filter.getTargetUserId()); 4671 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4672 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4673 } 4674 return null; 4675 } 4676 4677 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4678 int sourceUserId, int targetUserId) { 4679 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4680 String className; 4681 if (targetUserId == UserHandle.USER_OWNER) { 4682 className = FORWARD_INTENT_TO_USER_OWNER; 4683 } else { 4684 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4685 } 4686 ComponentName forwardingActivityComponentName = new ComponentName( 4687 mAndroidApplication.packageName, className); 4688 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4689 sourceUserId); 4690 if (targetUserId == UserHandle.USER_OWNER) { 4691 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4692 forwardingResolveInfo.noResourceId = true; 4693 } 4694 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4695 forwardingResolveInfo.priority = 0; 4696 forwardingResolveInfo.preferredOrder = 0; 4697 forwardingResolveInfo.match = 0; 4698 forwardingResolveInfo.isDefault = true; 4699 forwardingResolveInfo.filter = filter; 4700 forwardingResolveInfo.targetUserId = targetUserId; 4701 return forwardingResolveInfo; 4702 } 4703 4704 @Override 4705 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4706 Intent[] specifics, String[] specificTypes, Intent intent, 4707 String resolvedType, int flags, int userId) { 4708 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4709 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4710 false, "query intent activity options"); 4711 final String resultsAction = intent.getAction(); 4712 4713 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4714 | PackageManager.GET_RESOLVED_FILTER, userId); 4715 4716 if (DEBUG_INTENT_MATCHING) { 4717 Log.v(TAG, "Query " + intent + ": " + results); 4718 } 4719 4720 int specificsPos = 0; 4721 int N; 4722 4723 // todo: note that the algorithm used here is O(N^2). This 4724 // isn't a problem in our current environment, but if we start running 4725 // into situations where we have more than 5 or 10 matches then this 4726 // should probably be changed to something smarter... 4727 4728 // First we go through and resolve each of the specific items 4729 // that were supplied, taking care of removing any corresponding 4730 // duplicate items in the generic resolve list. 4731 if (specifics != null) { 4732 for (int i=0; i<specifics.length; i++) { 4733 final Intent sintent = specifics[i]; 4734 if (sintent == null) { 4735 continue; 4736 } 4737 4738 if (DEBUG_INTENT_MATCHING) { 4739 Log.v(TAG, "Specific #" + i + ": " + sintent); 4740 } 4741 4742 String action = sintent.getAction(); 4743 if (resultsAction != null && resultsAction.equals(action)) { 4744 // If this action was explicitly requested, then don't 4745 // remove things that have it. 4746 action = null; 4747 } 4748 4749 ResolveInfo ri = null; 4750 ActivityInfo ai = null; 4751 4752 ComponentName comp = sintent.getComponent(); 4753 if (comp == null) { 4754 ri = resolveIntent( 4755 sintent, 4756 specificTypes != null ? specificTypes[i] : null, 4757 flags, userId); 4758 if (ri == null) { 4759 continue; 4760 } 4761 if (ri == mResolveInfo) { 4762 // ACK! Must do something better with this. 4763 } 4764 ai = ri.activityInfo; 4765 comp = new ComponentName(ai.applicationInfo.packageName, 4766 ai.name); 4767 } else { 4768 ai = getActivityInfo(comp, flags, userId); 4769 if (ai == null) { 4770 continue; 4771 } 4772 } 4773 4774 // Look for any generic query activities that are duplicates 4775 // of this specific one, and remove them from the results. 4776 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4777 N = results.size(); 4778 int j; 4779 for (j=specificsPos; j<N; j++) { 4780 ResolveInfo sri = results.get(j); 4781 if ((sri.activityInfo.name.equals(comp.getClassName()) 4782 && sri.activityInfo.applicationInfo.packageName.equals( 4783 comp.getPackageName())) 4784 || (action != null && sri.filter.matchAction(action))) { 4785 results.remove(j); 4786 if (DEBUG_INTENT_MATCHING) Log.v( 4787 TAG, "Removing duplicate item from " + j 4788 + " due to specific " + specificsPos); 4789 if (ri == null) { 4790 ri = sri; 4791 } 4792 j--; 4793 N--; 4794 } 4795 } 4796 4797 // Add this specific item to its proper place. 4798 if (ri == null) { 4799 ri = new ResolveInfo(); 4800 ri.activityInfo = ai; 4801 } 4802 results.add(specificsPos, ri); 4803 ri.specificIndex = i; 4804 specificsPos++; 4805 } 4806 } 4807 4808 // Now we go through the remaining generic results and remove any 4809 // duplicate actions that are found here. 4810 N = results.size(); 4811 for (int i=specificsPos; i<N-1; i++) { 4812 final ResolveInfo rii = results.get(i); 4813 if (rii.filter == null) { 4814 continue; 4815 } 4816 4817 // Iterate over all of the actions of this result's intent 4818 // filter... typically this should be just one. 4819 final Iterator<String> it = rii.filter.actionsIterator(); 4820 if (it == null) { 4821 continue; 4822 } 4823 while (it.hasNext()) { 4824 final String action = it.next(); 4825 if (resultsAction != null && resultsAction.equals(action)) { 4826 // If this action was explicitly requested, then don't 4827 // remove things that have it. 4828 continue; 4829 } 4830 for (int j=i+1; j<N; j++) { 4831 final ResolveInfo rij = results.get(j); 4832 if (rij.filter != null && rij.filter.hasAction(action)) { 4833 results.remove(j); 4834 if (DEBUG_INTENT_MATCHING) Log.v( 4835 TAG, "Removing duplicate item from " + j 4836 + " due to action " + action + " at " + i); 4837 j--; 4838 N--; 4839 } 4840 } 4841 } 4842 4843 // If the caller didn't request filter information, drop it now 4844 // so we don't have to marshall/unmarshall it. 4845 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4846 rii.filter = null; 4847 } 4848 } 4849 4850 // Filter out the caller activity if so requested. 4851 if (caller != null) { 4852 N = results.size(); 4853 for (int i=0; i<N; i++) { 4854 ActivityInfo ainfo = results.get(i).activityInfo; 4855 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4856 && caller.getClassName().equals(ainfo.name)) { 4857 results.remove(i); 4858 break; 4859 } 4860 } 4861 } 4862 4863 // If the caller didn't request filter information, 4864 // drop them now so we don't have to 4865 // marshall/unmarshall it. 4866 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4867 N = results.size(); 4868 for (int i=0; i<N; i++) { 4869 results.get(i).filter = null; 4870 } 4871 } 4872 4873 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4874 return results; 4875 } 4876 4877 @Override 4878 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4879 int userId) { 4880 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4881 ComponentName comp = intent.getComponent(); 4882 if (comp == null) { 4883 if (intent.getSelector() != null) { 4884 intent = intent.getSelector(); 4885 comp = intent.getComponent(); 4886 } 4887 } 4888 if (comp != null) { 4889 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4890 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4891 if (ai != null) { 4892 ResolveInfo ri = new ResolveInfo(); 4893 ri.activityInfo = ai; 4894 list.add(ri); 4895 } 4896 return list; 4897 } 4898 4899 // reader 4900 synchronized (mPackages) { 4901 String pkgName = intent.getPackage(); 4902 if (pkgName == null) { 4903 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4904 } 4905 final PackageParser.Package pkg = mPackages.get(pkgName); 4906 if (pkg != null) { 4907 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4908 userId); 4909 } 4910 return null; 4911 } 4912 } 4913 4914 @Override 4915 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4916 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4917 if (!sUserManager.exists(userId)) return null; 4918 if (query != null) { 4919 if (query.size() >= 1) { 4920 // If there is more than one service with the same priority, 4921 // just arbitrarily pick the first one. 4922 return query.get(0); 4923 } 4924 } 4925 return null; 4926 } 4927 4928 @Override 4929 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4930 int userId) { 4931 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4932 ComponentName comp = intent.getComponent(); 4933 if (comp == null) { 4934 if (intent.getSelector() != null) { 4935 intent = intent.getSelector(); 4936 comp = intent.getComponent(); 4937 } 4938 } 4939 if (comp != null) { 4940 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4941 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4942 if (si != null) { 4943 final ResolveInfo ri = new ResolveInfo(); 4944 ri.serviceInfo = si; 4945 list.add(ri); 4946 } 4947 return list; 4948 } 4949 4950 // reader 4951 synchronized (mPackages) { 4952 String pkgName = intent.getPackage(); 4953 if (pkgName == null) { 4954 return mServices.queryIntent(intent, resolvedType, flags, userId); 4955 } 4956 final PackageParser.Package pkg = mPackages.get(pkgName); 4957 if (pkg != null) { 4958 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4959 userId); 4960 } 4961 return null; 4962 } 4963 } 4964 4965 @Override 4966 public List<ResolveInfo> queryIntentContentProviders( 4967 Intent intent, String resolvedType, int flags, int userId) { 4968 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4969 ComponentName comp = intent.getComponent(); 4970 if (comp == null) { 4971 if (intent.getSelector() != null) { 4972 intent = intent.getSelector(); 4973 comp = intent.getComponent(); 4974 } 4975 } 4976 if (comp != null) { 4977 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4978 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4979 if (pi != null) { 4980 final ResolveInfo ri = new ResolveInfo(); 4981 ri.providerInfo = pi; 4982 list.add(ri); 4983 } 4984 return list; 4985 } 4986 4987 // reader 4988 synchronized (mPackages) { 4989 String pkgName = intent.getPackage(); 4990 if (pkgName == null) { 4991 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4992 } 4993 final PackageParser.Package pkg = mPackages.get(pkgName); 4994 if (pkg != null) { 4995 return mProviders.queryIntentForPackage( 4996 intent, resolvedType, flags, pkg.providers, userId); 4997 } 4998 return null; 4999 } 5000 } 5001 5002 @Override 5003 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5004 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5005 5006 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5007 5008 // writer 5009 synchronized (mPackages) { 5010 ArrayList<PackageInfo> list; 5011 if (listUninstalled) { 5012 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5013 for (PackageSetting ps : mSettings.mPackages.values()) { 5014 PackageInfo pi; 5015 if (ps.pkg != null) { 5016 pi = generatePackageInfo(ps.pkg, flags, userId); 5017 } else { 5018 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5019 } 5020 if (pi != null) { 5021 list.add(pi); 5022 } 5023 } 5024 } else { 5025 list = new ArrayList<PackageInfo>(mPackages.size()); 5026 for (PackageParser.Package p : mPackages.values()) { 5027 PackageInfo pi = generatePackageInfo(p, flags, userId); 5028 if (pi != null) { 5029 list.add(pi); 5030 } 5031 } 5032 } 5033 5034 return new ParceledListSlice<PackageInfo>(list); 5035 } 5036 } 5037 5038 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5039 String[] permissions, boolean[] tmp, int flags, int userId) { 5040 int numMatch = 0; 5041 final PermissionsState permissionsState = ps.getPermissionsState(); 5042 for (int i=0; i<permissions.length; i++) { 5043 final String permission = permissions[i]; 5044 if (permissionsState.hasPermission(permission, userId)) { 5045 tmp[i] = true; 5046 numMatch++; 5047 } else { 5048 tmp[i] = false; 5049 } 5050 } 5051 if (numMatch == 0) { 5052 return; 5053 } 5054 PackageInfo pi; 5055 if (ps.pkg != null) { 5056 pi = generatePackageInfo(ps.pkg, flags, userId); 5057 } else { 5058 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5059 } 5060 // The above might return null in cases of uninstalled apps or install-state 5061 // skew across users/profiles. 5062 if (pi != null) { 5063 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5064 if (numMatch == permissions.length) { 5065 pi.requestedPermissions = permissions; 5066 } else { 5067 pi.requestedPermissions = new String[numMatch]; 5068 numMatch = 0; 5069 for (int i=0; i<permissions.length; i++) { 5070 if (tmp[i]) { 5071 pi.requestedPermissions[numMatch] = permissions[i]; 5072 numMatch++; 5073 } 5074 } 5075 } 5076 } 5077 list.add(pi); 5078 } 5079 } 5080 5081 @Override 5082 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5083 String[] permissions, int flags, int userId) { 5084 if (!sUserManager.exists(userId)) return null; 5085 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5086 5087 // writer 5088 synchronized (mPackages) { 5089 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5090 boolean[] tmpBools = new boolean[permissions.length]; 5091 if (listUninstalled) { 5092 for (PackageSetting ps : mSettings.mPackages.values()) { 5093 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5094 } 5095 } else { 5096 for (PackageParser.Package pkg : mPackages.values()) { 5097 PackageSetting ps = (PackageSetting)pkg.mExtras; 5098 if (ps != null) { 5099 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5100 userId); 5101 } 5102 } 5103 } 5104 5105 return new ParceledListSlice<PackageInfo>(list); 5106 } 5107 } 5108 5109 @Override 5110 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5111 if (!sUserManager.exists(userId)) return null; 5112 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5113 5114 // writer 5115 synchronized (mPackages) { 5116 ArrayList<ApplicationInfo> list; 5117 if (listUninstalled) { 5118 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5119 for (PackageSetting ps : mSettings.mPackages.values()) { 5120 ApplicationInfo ai; 5121 if (ps.pkg != null) { 5122 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5123 ps.readUserState(userId), userId); 5124 } else { 5125 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5126 } 5127 if (ai != null) { 5128 list.add(ai); 5129 } 5130 } 5131 } else { 5132 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5133 for (PackageParser.Package p : mPackages.values()) { 5134 if (p.mExtras != null) { 5135 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5136 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5137 if (ai != null) { 5138 list.add(ai); 5139 } 5140 } 5141 } 5142 } 5143 5144 return new ParceledListSlice<ApplicationInfo>(list); 5145 } 5146 } 5147 5148 public List<ApplicationInfo> getPersistentApplications(int flags) { 5149 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5150 5151 // reader 5152 synchronized (mPackages) { 5153 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5154 final int userId = UserHandle.getCallingUserId(); 5155 while (i.hasNext()) { 5156 final PackageParser.Package p = i.next(); 5157 if (p.applicationInfo != null 5158 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5159 && (!mSafeMode || isSystemApp(p))) { 5160 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5161 if (ps != null) { 5162 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5163 ps.readUserState(userId), userId); 5164 if (ai != null) { 5165 finalList.add(ai); 5166 } 5167 } 5168 } 5169 } 5170 } 5171 5172 return finalList; 5173 } 5174 5175 @Override 5176 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5177 if (!sUserManager.exists(userId)) return null; 5178 // reader 5179 synchronized (mPackages) { 5180 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5181 PackageSetting ps = provider != null 5182 ? mSettings.mPackages.get(provider.owner.packageName) 5183 : null; 5184 return ps != null 5185 && mSettings.isEnabledLPr(provider.info, flags, userId) 5186 && (!mSafeMode || (provider.info.applicationInfo.flags 5187 &ApplicationInfo.FLAG_SYSTEM) != 0) 5188 ? PackageParser.generateProviderInfo(provider, flags, 5189 ps.readUserState(userId), userId) 5190 : null; 5191 } 5192 } 5193 5194 /** 5195 * @deprecated 5196 */ 5197 @Deprecated 5198 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5199 // reader 5200 synchronized (mPackages) { 5201 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5202 .entrySet().iterator(); 5203 final int userId = UserHandle.getCallingUserId(); 5204 while (i.hasNext()) { 5205 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5206 PackageParser.Provider p = entry.getValue(); 5207 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5208 5209 if (ps != null && p.syncable 5210 && (!mSafeMode || (p.info.applicationInfo.flags 5211 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5212 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5213 ps.readUserState(userId), userId); 5214 if (info != null) { 5215 outNames.add(entry.getKey()); 5216 outInfo.add(info); 5217 } 5218 } 5219 } 5220 } 5221 } 5222 5223 @Override 5224 public List<ProviderInfo> queryContentProviders(String processName, 5225 int uid, int flags) { 5226 ArrayList<ProviderInfo> finalList = null; 5227 // reader 5228 synchronized (mPackages) { 5229 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5230 final int userId = processName != null ? 5231 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5232 while (i.hasNext()) { 5233 final PackageParser.Provider p = i.next(); 5234 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5235 if (ps != null && p.info.authority != null 5236 && (processName == null 5237 || (p.info.processName.equals(processName) 5238 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5239 && mSettings.isEnabledLPr(p.info, flags, userId) 5240 && (!mSafeMode 5241 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5242 if (finalList == null) { 5243 finalList = new ArrayList<ProviderInfo>(3); 5244 } 5245 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5246 ps.readUserState(userId), userId); 5247 if (info != null) { 5248 finalList.add(info); 5249 } 5250 } 5251 } 5252 } 5253 5254 if (finalList != null) { 5255 Collections.sort(finalList, mProviderInitOrderSorter); 5256 } 5257 5258 return finalList; 5259 } 5260 5261 @Override 5262 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5263 int flags) { 5264 // reader 5265 synchronized (mPackages) { 5266 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5267 return PackageParser.generateInstrumentationInfo(i, flags); 5268 } 5269 } 5270 5271 @Override 5272 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5273 int flags) { 5274 ArrayList<InstrumentationInfo> finalList = 5275 new ArrayList<InstrumentationInfo>(); 5276 5277 // reader 5278 synchronized (mPackages) { 5279 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5280 while (i.hasNext()) { 5281 final PackageParser.Instrumentation p = i.next(); 5282 if (targetPackage == null 5283 || targetPackage.equals(p.info.targetPackage)) { 5284 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5285 flags); 5286 if (ii != null) { 5287 finalList.add(ii); 5288 } 5289 } 5290 } 5291 } 5292 5293 return finalList; 5294 } 5295 5296 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5297 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5298 if (overlays == null) { 5299 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5300 return; 5301 } 5302 for (PackageParser.Package opkg : overlays.values()) { 5303 // Not much to do if idmap fails: we already logged the error 5304 // and we certainly don't want to abort installation of pkg simply 5305 // because an overlay didn't fit properly. For these reasons, 5306 // ignore the return value of createIdmapForPackagePairLI. 5307 createIdmapForPackagePairLI(pkg, opkg); 5308 } 5309 } 5310 5311 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5312 PackageParser.Package opkg) { 5313 if (!opkg.mTrustedOverlay) { 5314 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5315 opkg.baseCodePath + ": overlay not trusted"); 5316 return false; 5317 } 5318 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5319 if (overlaySet == null) { 5320 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5321 opkg.baseCodePath + " but target package has no known overlays"); 5322 return false; 5323 } 5324 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5325 // TODO: generate idmap for split APKs 5326 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5327 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5328 + opkg.baseCodePath); 5329 return false; 5330 } 5331 PackageParser.Package[] overlayArray = 5332 overlaySet.values().toArray(new PackageParser.Package[0]); 5333 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5334 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5335 return p1.mOverlayPriority - p2.mOverlayPriority; 5336 } 5337 }; 5338 Arrays.sort(overlayArray, cmp); 5339 5340 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5341 int i = 0; 5342 for (PackageParser.Package p : overlayArray) { 5343 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5344 } 5345 return true; 5346 } 5347 5348 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5349 final File[] files = dir.listFiles(); 5350 if (ArrayUtils.isEmpty(files)) { 5351 Log.d(TAG, "No files in app dir " + dir); 5352 return; 5353 } 5354 5355 if (DEBUG_PACKAGE_SCANNING) { 5356 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5357 + " flags=0x" + Integer.toHexString(parseFlags)); 5358 } 5359 5360 for (File file : files) { 5361 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5362 && !PackageInstallerService.isStageName(file.getName()); 5363 if (!isPackage) { 5364 // Ignore entries which are not packages 5365 continue; 5366 } 5367 try { 5368 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5369 scanFlags, currentTime, null); 5370 } catch (PackageManagerException e) { 5371 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5372 5373 // Delete invalid userdata apps 5374 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5375 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5376 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5377 if (file.isDirectory()) { 5378 mInstaller.rmPackageDir(file.getAbsolutePath()); 5379 } else { 5380 file.delete(); 5381 } 5382 } 5383 } 5384 } 5385 } 5386 5387 private static File getSettingsProblemFile() { 5388 File dataDir = Environment.getDataDirectory(); 5389 File systemDir = new File(dataDir, "system"); 5390 File fname = new File(systemDir, "uiderrors.txt"); 5391 return fname; 5392 } 5393 5394 static void reportSettingsProblem(int priority, String msg) { 5395 logCriticalInfo(priority, msg); 5396 } 5397 5398 static void logCriticalInfo(int priority, String msg) { 5399 Slog.println(priority, TAG, msg); 5400 EventLogTags.writePmCriticalInfo(msg); 5401 try { 5402 File fname = getSettingsProblemFile(); 5403 FileOutputStream out = new FileOutputStream(fname, true); 5404 PrintWriter pw = new FastPrintWriter(out); 5405 SimpleDateFormat formatter = new SimpleDateFormat(); 5406 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5407 pw.println(dateString + ": " + msg); 5408 pw.close(); 5409 FileUtils.setPermissions( 5410 fname.toString(), 5411 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5412 -1, -1); 5413 } catch (java.io.IOException e) { 5414 } 5415 } 5416 5417 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5418 PackageParser.Package pkg, File srcFile, int parseFlags) 5419 throws PackageManagerException { 5420 if (ps != null 5421 && ps.codePath.equals(srcFile) 5422 && ps.timeStamp == srcFile.lastModified() 5423 && !isCompatSignatureUpdateNeeded(pkg) 5424 && !isRecoverSignatureUpdateNeeded(pkg)) { 5425 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5426 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5427 ArraySet<PublicKey> signingKs; 5428 synchronized (mPackages) { 5429 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5430 } 5431 if (ps.signatures.mSignatures != null 5432 && ps.signatures.mSignatures.length != 0 5433 && signingKs != null) { 5434 // Optimization: reuse the existing cached certificates 5435 // if the package appears to be unchanged. 5436 pkg.mSignatures = ps.signatures.mSignatures; 5437 pkg.mSigningKeys = signingKs; 5438 return; 5439 } 5440 5441 Slog.w(TAG, "PackageSetting for " + ps.name 5442 + " is missing signatures. Collecting certs again to recover them."); 5443 } else { 5444 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5445 } 5446 5447 try { 5448 pp.collectCertificates(pkg, parseFlags); 5449 pp.collectManifestDigest(pkg); 5450 } catch (PackageParserException e) { 5451 throw PackageManagerException.from(e); 5452 } 5453 } 5454 5455 /* 5456 * Scan a package and return the newly parsed package. 5457 * Returns null in case of errors and the error code is stored in mLastScanError 5458 */ 5459 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5460 long currentTime, UserHandle user) throws PackageManagerException { 5461 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5462 parseFlags |= mDefParseFlags; 5463 PackageParser pp = new PackageParser(); 5464 pp.setSeparateProcesses(mSeparateProcesses); 5465 pp.setOnlyCoreApps(mOnlyCore); 5466 pp.setDisplayMetrics(mMetrics); 5467 5468 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5469 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5470 } 5471 5472 final PackageParser.Package pkg; 5473 try { 5474 pkg = pp.parsePackage(scanFile, parseFlags); 5475 } catch (PackageParserException e) { 5476 throw PackageManagerException.from(e); 5477 } 5478 5479 PackageSetting ps = null; 5480 PackageSetting updatedPkg; 5481 // reader 5482 synchronized (mPackages) { 5483 // Look to see if we already know about this package. 5484 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5485 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5486 // This package has been renamed to its original name. Let's 5487 // use that. 5488 ps = mSettings.peekPackageLPr(oldName); 5489 } 5490 // If there was no original package, see one for the real package name. 5491 if (ps == null) { 5492 ps = mSettings.peekPackageLPr(pkg.packageName); 5493 } 5494 // Check to see if this package could be hiding/updating a system 5495 // package. Must look for it either under the original or real 5496 // package name depending on our state. 5497 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5498 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5499 } 5500 boolean updatedPkgBetter = false; 5501 // First check if this is a system package that may involve an update 5502 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5503 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5504 // it needs to drop FLAG_PRIVILEGED. 5505 if (locationIsPrivileged(scanFile)) { 5506 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5507 } else { 5508 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5509 } 5510 5511 if (ps != null && !ps.codePath.equals(scanFile)) { 5512 // The path has changed from what was last scanned... check the 5513 // version of the new path against what we have stored to determine 5514 // what to do. 5515 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5516 if (pkg.mVersionCode <= ps.versionCode) { 5517 // The system package has been updated and the code path does not match 5518 // Ignore entry. Skip it. 5519 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5520 + " ignored: updated version " + ps.versionCode 5521 + " better than this " + pkg.mVersionCode); 5522 if (!updatedPkg.codePath.equals(scanFile)) { 5523 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5524 + ps.name + " changing from " + updatedPkg.codePathString 5525 + " to " + scanFile); 5526 updatedPkg.codePath = scanFile; 5527 updatedPkg.codePathString = scanFile.toString(); 5528 updatedPkg.resourcePath = scanFile; 5529 updatedPkg.resourcePathString = scanFile.toString(); 5530 } 5531 updatedPkg.pkg = pkg; 5532 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5533 } else { 5534 // The current app on the system partition is better than 5535 // what we have updated to on the data partition; switch 5536 // back to the system partition version. 5537 // At this point, its safely assumed that package installation for 5538 // apps in system partition will go through. If not there won't be a working 5539 // version of the app 5540 // writer 5541 synchronized (mPackages) { 5542 // Just remove the loaded entries from package lists. 5543 mPackages.remove(ps.name); 5544 } 5545 5546 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5547 + " reverting from " + ps.codePathString 5548 + ": new version " + pkg.mVersionCode 5549 + " better than installed " + ps.versionCode); 5550 5551 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5552 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5553 synchronized (mInstallLock) { 5554 args.cleanUpResourcesLI(); 5555 } 5556 synchronized (mPackages) { 5557 mSettings.enableSystemPackageLPw(ps.name); 5558 } 5559 updatedPkgBetter = true; 5560 } 5561 } 5562 } 5563 5564 if (updatedPkg != null) { 5565 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5566 // initially 5567 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5568 5569 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5570 // flag set initially 5571 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5572 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5573 } 5574 } 5575 5576 // Verify certificates against what was last scanned 5577 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5578 5579 /* 5580 * A new system app appeared, but we already had a non-system one of the 5581 * same name installed earlier. 5582 */ 5583 boolean shouldHideSystemApp = false; 5584 if (updatedPkg == null && ps != null 5585 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5586 /* 5587 * Check to make sure the signatures match first. If they don't, 5588 * wipe the installed application and its data. 5589 */ 5590 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5591 != PackageManager.SIGNATURE_MATCH) { 5592 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5593 + " signatures don't match existing userdata copy; removing"); 5594 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5595 ps = null; 5596 } else { 5597 /* 5598 * If the newly-added system app is an older version than the 5599 * already installed version, hide it. It will be scanned later 5600 * and re-added like an update. 5601 */ 5602 if (pkg.mVersionCode <= ps.versionCode) { 5603 shouldHideSystemApp = true; 5604 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5605 + " but new version " + pkg.mVersionCode + " better than installed " 5606 + ps.versionCode + "; hiding system"); 5607 } else { 5608 /* 5609 * The newly found system app is a newer version that the 5610 * one previously installed. Simply remove the 5611 * already-installed application and replace it with our own 5612 * while keeping the application data. 5613 */ 5614 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5615 + " reverting from " + ps.codePathString + ": new version " 5616 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5617 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5618 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5619 synchronized (mInstallLock) { 5620 args.cleanUpResourcesLI(); 5621 } 5622 } 5623 } 5624 } 5625 5626 // The apk is forward locked (not public) if its code and resources 5627 // are kept in different files. (except for app in either system or 5628 // vendor path). 5629 // TODO grab this value from PackageSettings 5630 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5631 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5632 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5633 } 5634 } 5635 5636 // TODO: extend to support forward-locked splits 5637 String resourcePath = null; 5638 String baseResourcePath = null; 5639 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5640 if (ps != null && ps.resourcePathString != null) { 5641 resourcePath = ps.resourcePathString; 5642 baseResourcePath = ps.resourcePathString; 5643 } else { 5644 // Should not happen at all. Just log an error. 5645 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5646 } 5647 } else { 5648 resourcePath = pkg.codePath; 5649 baseResourcePath = pkg.baseCodePath; 5650 } 5651 5652 // Set application objects path explicitly. 5653 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5654 pkg.applicationInfo.setCodePath(pkg.codePath); 5655 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5656 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5657 pkg.applicationInfo.setResourcePath(resourcePath); 5658 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5659 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5660 5661 // Note that we invoke the following method only if we are about to unpack an application 5662 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5663 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5664 5665 /* 5666 * If the system app should be overridden by a previously installed 5667 * data, hide the system app now and let the /data/app scan pick it up 5668 * again. 5669 */ 5670 if (shouldHideSystemApp) { 5671 synchronized (mPackages) { 5672 /* 5673 * We have to grant systems permissions before we hide, because 5674 * grantPermissions will assume the package update is trying to 5675 * expand its permissions. 5676 */ 5677 grantPermissionsLPw(pkg, true, pkg.packageName); 5678 mSettings.disableSystemPackageLPw(pkg.packageName); 5679 } 5680 } 5681 5682 return scannedPkg; 5683 } 5684 5685 private static String fixProcessName(String defProcessName, 5686 String processName, int uid) { 5687 if (processName == null) { 5688 return defProcessName; 5689 } 5690 return processName; 5691 } 5692 5693 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5694 throws PackageManagerException { 5695 if (pkgSetting.signatures.mSignatures != null) { 5696 // Already existing package. Make sure signatures match 5697 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5698 == PackageManager.SIGNATURE_MATCH; 5699 if (!match) { 5700 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5701 == PackageManager.SIGNATURE_MATCH; 5702 } 5703 if (!match) { 5704 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5705 == PackageManager.SIGNATURE_MATCH; 5706 } 5707 if (!match) { 5708 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5709 + pkg.packageName + " signatures do not match the " 5710 + "previously installed version; ignoring!"); 5711 } 5712 } 5713 5714 // Check for shared user signatures 5715 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5716 // Already existing package. Make sure signatures match 5717 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5718 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5719 if (!match) { 5720 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5721 == PackageManager.SIGNATURE_MATCH; 5722 } 5723 if (!match) { 5724 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5725 == PackageManager.SIGNATURE_MATCH; 5726 } 5727 if (!match) { 5728 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5729 "Package " + pkg.packageName 5730 + " has no signatures that match those in shared user " 5731 + pkgSetting.sharedUser.name + "; ignoring!"); 5732 } 5733 } 5734 } 5735 5736 /** 5737 * Enforces that only the system UID or root's UID can call a method exposed 5738 * via Binder. 5739 * 5740 * @param message used as message if SecurityException is thrown 5741 * @throws SecurityException if the caller is not system or root 5742 */ 5743 private static final void enforceSystemOrRoot(String message) { 5744 final int uid = Binder.getCallingUid(); 5745 if (uid != Process.SYSTEM_UID && uid != 0) { 5746 throw new SecurityException(message); 5747 } 5748 } 5749 5750 @Override 5751 public void performBootDexOpt() { 5752 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5753 5754 // Before everything else, see whether we need to fstrim. 5755 try { 5756 IMountService ms = PackageHelper.getMountService(); 5757 if (ms != null) { 5758 final boolean isUpgrade = isUpgrade(); 5759 boolean doTrim = isUpgrade; 5760 if (doTrim) { 5761 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5762 } else { 5763 final long interval = android.provider.Settings.Global.getLong( 5764 mContext.getContentResolver(), 5765 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5766 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5767 if (interval > 0) { 5768 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5769 if (timeSinceLast > interval) { 5770 doTrim = true; 5771 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5772 + "; running immediately"); 5773 } 5774 } 5775 } 5776 if (doTrim) { 5777 if (!isFirstBoot()) { 5778 try { 5779 ActivityManagerNative.getDefault().showBootMessage( 5780 mContext.getResources().getString( 5781 R.string.android_upgrading_fstrim), true); 5782 } catch (RemoteException e) { 5783 } 5784 } 5785 ms.runMaintenance(); 5786 } 5787 } else { 5788 Slog.e(TAG, "Mount service unavailable!"); 5789 } 5790 } catch (RemoteException e) { 5791 // Can't happen; MountService is local 5792 } 5793 5794 final ArraySet<PackageParser.Package> pkgs; 5795 synchronized (mPackages) { 5796 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5797 } 5798 5799 if (pkgs != null) { 5800 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5801 // in case the device runs out of space. 5802 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5803 // Give priority to core apps. 5804 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5805 PackageParser.Package pkg = it.next(); 5806 if (pkg.coreApp) { 5807 if (DEBUG_DEXOPT) { 5808 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5809 } 5810 sortedPkgs.add(pkg); 5811 it.remove(); 5812 } 5813 } 5814 // Give priority to system apps that listen for pre boot complete. 5815 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5816 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5817 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5818 PackageParser.Package pkg = it.next(); 5819 if (pkgNames.contains(pkg.packageName)) { 5820 if (DEBUG_DEXOPT) { 5821 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5822 } 5823 sortedPkgs.add(pkg); 5824 it.remove(); 5825 } 5826 } 5827 // Give priority to system apps. 5828 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5829 PackageParser.Package pkg = it.next(); 5830 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5831 if (DEBUG_DEXOPT) { 5832 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5833 } 5834 sortedPkgs.add(pkg); 5835 it.remove(); 5836 } 5837 } 5838 // Give priority to updated system apps. 5839 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5840 PackageParser.Package pkg = it.next(); 5841 if (pkg.isUpdatedSystemApp()) { 5842 if (DEBUG_DEXOPT) { 5843 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5844 } 5845 sortedPkgs.add(pkg); 5846 it.remove(); 5847 } 5848 } 5849 // Give priority to apps that listen for boot complete. 5850 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5851 pkgNames = getPackageNamesForIntent(intent); 5852 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5853 PackageParser.Package pkg = it.next(); 5854 if (pkgNames.contains(pkg.packageName)) { 5855 if (DEBUG_DEXOPT) { 5856 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5857 } 5858 sortedPkgs.add(pkg); 5859 it.remove(); 5860 } 5861 } 5862 // Filter out packages that aren't recently used. 5863 filterRecentlyUsedApps(pkgs); 5864 // Add all remaining apps. 5865 for (PackageParser.Package pkg : pkgs) { 5866 if (DEBUG_DEXOPT) { 5867 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5868 } 5869 sortedPkgs.add(pkg); 5870 } 5871 5872 // If we want to be lazy, filter everything that wasn't recently used. 5873 if (mLazyDexOpt) { 5874 filterRecentlyUsedApps(sortedPkgs); 5875 } 5876 5877 int i = 0; 5878 int total = sortedPkgs.size(); 5879 File dataDir = Environment.getDataDirectory(); 5880 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5881 if (lowThreshold == 0) { 5882 throw new IllegalStateException("Invalid low memory threshold"); 5883 } 5884 for (PackageParser.Package pkg : sortedPkgs) { 5885 long usableSpace = dataDir.getUsableSpace(); 5886 if (usableSpace < lowThreshold) { 5887 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5888 break; 5889 } 5890 performBootDexOpt(pkg, ++i, total); 5891 } 5892 } 5893 } 5894 5895 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5896 // Filter out packages that aren't recently used. 5897 // 5898 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5899 // should do a full dexopt. 5900 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5901 int total = pkgs.size(); 5902 int skipped = 0; 5903 long now = System.currentTimeMillis(); 5904 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5905 PackageParser.Package pkg = i.next(); 5906 long then = pkg.mLastPackageUsageTimeInMills; 5907 if (then + mDexOptLRUThresholdInMills < now) { 5908 if (DEBUG_DEXOPT) { 5909 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5910 ((then == 0) ? "never" : new Date(then))); 5911 } 5912 i.remove(); 5913 skipped++; 5914 } 5915 } 5916 if (DEBUG_DEXOPT) { 5917 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5918 } 5919 } 5920 } 5921 5922 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5923 List<ResolveInfo> ris = null; 5924 try { 5925 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5926 intent, null, 0, UserHandle.USER_OWNER); 5927 } catch (RemoteException e) { 5928 } 5929 ArraySet<String> pkgNames = new ArraySet<String>(); 5930 if (ris != null) { 5931 for (ResolveInfo ri : ris) { 5932 pkgNames.add(ri.activityInfo.packageName); 5933 } 5934 } 5935 return pkgNames; 5936 } 5937 5938 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5939 if (DEBUG_DEXOPT) { 5940 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5941 } 5942 if (!isFirstBoot()) { 5943 try { 5944 ActivityManagerNative.getDefault().showBootMessage( 5945 mContext.getResources().getString(R.string.android_upgrading_apk, 5946 curr, total), true); 5947 } catch (RemoteException e) { 5948 } 5949 } 5950 PackageParser.Package p = pkg; 5951 synchronized (mInstallLock) { 5952 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5953 false /* force dex */, false /* defer */, true /* include dependencies */); 5954 } 5955 } 5956 5957 @Override 5958 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5959 return performDexOpt(packageName, instructionSet, false); 5960 } 5961 5962 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5963 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5964 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5965 if (!dexopt && !updateUsage) { 5966 // We aren't going to dexopt or update usage, so bail early. 5967 return false; 5968 } 5969 PackageParser.Package p; 5970 final String targetInstructionSet; 5971 synchronized (mPackages) { 5972 p = mPackages.get(packageName); 5973 if (p == null) { 5974 return false; 5975 } 5976 if (updateUsage) { 5977 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5978 } 5979 mPackageUsage.write(false); 5980 if (!dexopt) { 5981 // We aren't going to dexopt, so bail early. 5982 return false; 5983 } 5984 5985 targetInstructionSet = instructionSet != null ? instructionSet : 5986 getPrimaryInstructionSet(p.applicationInfo); 5987 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5988 return false; 5989 } 5990 } 5991 5992 synchronized (mInstallLock) { 5993 final String[] instructionSets = new String[] { targetInstructionSet }; 5994 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5995 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5996 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5997 } 5998 } 5999 6000 public ArraySet<String> getPackagesThatNeedDexOpt() { 6001 ArraySet<String> pkgs = null; 6002 synchronized (mPackages) { 6003 for (PackageParser.Package p : mPackages.values()) { 6004 if (DEBUG_DEXOPT) { 6005 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6006 } 6007 if (!p.mDexOptPerformed.isEmpty()) { 6008 continue; 6009 } 6010 if (pkgs == null) { 6011 pkgs = new ArraySet<String>(); 6012 } 6013 pkgs.add(p.packageName); 6014 } 6015 } 6016 return pkgs; 6017 } 6018 6019 public void shutdown() { 6020 mPackageUsage.write(true); 6021 } 6022 6023 @Override 6024 public void forceDexOpt(String packageName) { 6025 enforceSystemOrRoot("forceDexOpt"); 6026 6027 PackageParser.Package pkg; 6028 synchronized (mPackages) { 6029 pkg = mPackages.get(packageName); 6030 if (pkg == null) { 6031 throw new IllegalArgumentException("Missing package: " + packageName); 6032 } 6033 } 6034 6035 synchronized (mInstallLock) { 6036 final String[] instructionSets = new String[] { 6037 getPrimaryInstructionSet(pkg.applicationInfo) }; 6038 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6039 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6040 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6041 throw new IllegalStateException("Failed to dexopt: " + res); 6042 } 6043 } 6044 } 6045 6046 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6047 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6048 Slog.w(TAG, "Unable to update from " + oldPkg.name 6049 + " to " + newPkg.packageName 6050 + ": old package not in system partition"); 6051 return false; 6052 } else if (mPackages.get(oldPkg.name) != null) { 6053 Slog.w(TAG, "Unable to update from " + oldPkg.name 6054 + " to " + newPkg.packageName 6055 + ": old package still exists"); 6056 return false; 6057 } 6058 return true; 6059 } 6060 6061 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6062 int[] users = sUserManager.getUserIds(); 6063 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6064 if (res < 0) { 6065 return res; 6066 } 6067 for (int user : users) { 6068 if (user != 0) { 6069 res = mInstaller.createUserData(volumeUuid, packageName, 6070 UserHandle.getUid(user, uid), user, seinfo); 6071 if (res < 0) { 6072 return res; 6073 } 6074 } 6075 } 6076 return res; 6077 } 6078 6079 private int removeDataDirsLI(String volumeUuid, String packageName) { 6080 int[] users = sUserManager.getUserIds(); 6081 int res = 0; 6082 for (int user : users) { 6083 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6084 if (resInner < 0) { 6085 res = resInner; 6086 } 6087 } 6088 6089 return res; 6090 } 6091 6092 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6093 int[] users = sUserManager.getUserIds(); 6094 int res = 0; 6095 for (int user : users) { 6096 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6097 if (resInner < 0) { 6098 res = resInner; 6099 } 6100 } 6101 return res; 6102 } 6103 6104 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6105 PackageParser.Package changingLib) { 6106 if (file.path != null) { 6107 usesLibraryFiles.add(file.path); 6108 return; 6109 } 6110 PackageParser.Package p = mPackages.get(file.apk); 6111 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6112 // If we are doing this while in the middle of updating a library apk, 6113 // then we need to make sure to use that new apk for determining the 6114 // dependencies here. (We haven't yet finished committing the new apk 6115 // to the package manager state.) 6116 if (p == null || p.packageName.equals(changingLib.packageName)) { 6117 p = changingLib; 6118 } 6119 } 6120 if (p != null) { 6121 usesLibraryFiles.addAll(p.getAllCodePaths()); 6122 } 6123 } 6124 6125 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6126 PackageParser.Package changingLib) throws PackageManagerException { 6127 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6128 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6129 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6130 for (int i=0; i<N; i++) { 6131 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6132 if (file == null) { 6133 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6134 "Package " + pkg.packageName + " requires unavailable shared library " 6135 + pkg.usesLibraries.get(i) + "; failing!"); 6136 } 6137 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6138 } 6139 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6140 for (int i=0; i<N; i++) { 6141 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6142 if (file == null) { 6143 Slog.w(TAG, "Package " + pkg.packageName 6144 + " desires unavailable shared library " 6145 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6146 } else { 6147 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6148 } 6149 } 6150 N = usesLibraryFiles.size(); 6151 if (N > 0) { 6152 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6153 } else { 6154 pkg.usesLibraryFiles = null; 6155 } 6156 } 6157 } 6158 6159 private static boolean hasString(List<String> list, List<String> which) { 6160 if (list == null) { 6161 return false; 6162 } 6163 for (int i=list.size()-1; i>=0; i--) { 6164 for (int j=which.size()-1; j>=0; j--) { 6165 if (which.get(j).equals(list.get(i))) { 6166 return true; 6167 } 6168 } 6169 } 6170 return false; 6171 } 6172 6173 private void updateAllSharedLibrariesLPw() { 6174 for (PackageParser.Package pkg : mPackages.values()) { 6175 try { 6176 updateSharedLibrariesLPw(pkg, null); 6177 } catch (PackageManagerException e) { 6178 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6179 } 6180 } 6181 } 6182 6183 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6184 PackageParser.Package changingPkg) { 6185 ArrayList<PackageParser.Package> res = null; 6186 for (PackageParser.Package pkg : mPackages.values()) { 6187 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6188 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6189 if (res == null) { 6190 res = new ArrayList<PackageParser.Package>(); 6191 } 6192 res.add(pkg); 6193 try { 6194 updateSharedLibrariesLPw(pkg, changingPkg); 6195 } catch (PackageManagerException e) { 6196 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6197 } 6198 } 6199 } 6200 return res; 6201 } 6202 6203 /** 6204 * Derive the value of the {@code cpuAbiOverride} based on the provided 6205 * value and an optional stored value from the package settings. 6206 */ 6207 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6208 String cpuAbiOverride = null; 6209 6210 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6211 cpuAbiOverride = null; 6212 } else if (abiOverride != null) { 6213 cpuAbiOverride = abiOverride; 6214 } else if (settings != null) { 6215 cpuAbiOverride = settings.cpuAbiOverrideString; 6216 } 6217 6218 return cpuAbiOverride; 6219 } 6220 6221 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6222 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6223 boolean success = false; 6224 try { 6225 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6226 currentTime, user); 6227 success = true; 6228 return res; 6229 } finally { 6230 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6231 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6232 } 6233 } 6234 } 6235 6236 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6237 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6238 final File scanFile = new File(pkg.codePath); 6239 if (pkg.applicationInfo.getCodePath() == null || 6240 pkg.applicationInfo.getResourcePath() == null) { 6241 // Bail out. The resource and code paths haven't been set. 6242 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6243 "Code and resource paths haven't been set correctly"); 6244 } 6245 6246 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6247 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6248 } else { 6249 // Only allow system apps to be flagged as core apps. 6250 pkg.coreApp = false; 6251 } 6252 6253 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6254 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6255 } 6256 6257 if (mCustomResolverComponentName != null && 6258 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6259 setUpCustomResolverActivity(pkg); 6260 } 6261 6262 if (pkg.packageName.equals("android")) { 6263 synchronized (mPackages) { 6264 if (mAndroidApplication != null) { 6265 Slog.w(TAG, "*************************************************"); 6266 Slog.w(TAG, "Core android package being redefined. Skipping."); 6267 Slog.w(TAG, " file=" + scanFile); 6268 Slog.w(TAG, "*************************************************"); 6269 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6270 "Core android package being redefined. Skipping."); 6271 } 6272 6273 // Set up information for our fall-back user intent resolution activity. 6274 mPlatformPackage = pkg; 6275 pkg.mVersionCode = mSdkVersion; 6276 mAndroidApplication = pkg.applicationInfo; 6277 6278 if (!mResolverReplaced) { 6279 mResolveActivity.applicationInfo = mAndroidApplication; 6280 mResolveActivity.name = ResolverActivity.class.getName(); 6281 mResolveActivity.packageName = mAndroidApplication.packageName; 6282 mResolveActivity.processName = "system:ui"; 6283 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6284 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6285 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6286 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6287 mResolveActivity.exported = true; 6288 mResolveActivity.enabled = true; 6289 mResolveInfo.activityInfo = mResolveActivity; 6290 mResolveInfo.priority = 0; 6291 mResolveInfo.preferredOrder = 0; 6292 mResolveInfo.match = 0; 6293 mResolveComponentName = new ComponentName( 6294 mAndroidApplication.packageName, mResolveActivity.name); 6295 } 6296 } 6297 } 6298 6299 if (DEBUG_PACKAGE_SCANNING) { 6300 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6301 Log.d(TAG, "Scanning package " + pkg.packageName); 6302 } 6303 6304 if (mPackages.containsKey(pkg.packageName) 6305 || mSharedLibraries.containsKey(pkg.packageName)) { 6306 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6307 "Application package " + pkg.packageName 6308 + " already installed. Skipping duplicate."); 6309 } 6310 6311 // If we're only installing presumed-existing packages, require that the 6312 // scanned APK is both already known and at the path previously established 6313 // for it. Previously unknown packages we pick up normally, but if we have an 6314 // a priori expectation about this package's install presence, enforce it. 6315 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6316 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6317 if (known != null) { 6318 if (DEBUG_PACKAGE_SCANNING) { 6319 Log.d(TAG, "Examining " + pkg.codePath 6320 + " and requiring known paths " + known.codePathString 6321 + " & " + known.resourcePathString); 6322 } 6323 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6324 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6325 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6326 "Application package " + pkg.packageName 6327 + " found at " + pkg.applicationInfo.getCodePath() 6328 + " but expected at " + known.codePathString + "; ignoring."); 6329 } 6330 } 6331 } 6332 6333 // Initialize package source and resource directories 6334 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6335 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6336 6337 SharedUserSetting suid = null; 6338 PackageSetting pkgSetting = null; 6339 6340 if (!isSystemApp(pkg)) { 6341 // Only system apps can use these features. 6342 pkg.mOriginalPackages = null; 6343 pkg.mRealPackage = null; 6344 pkg.mAdoptPermissions = null; 6345 } 6346 6347 // writer 6348 synchronized (mPackages) { 6349 if (pkg.mSharedUserId != null) { 6350 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6351 if (suid == null) { 6352 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6353 "Creating application package " + pkg.packageName 6354 + " for shared user failed"); 6355 } 6356 if (DEBUG_PACKAGE_SCANNING) { 6357 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6358 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6359 + "): packages=" + suid.packages); 6360 } 6361 } 6362 6363 // Check if we are renaming from an original package name. 6364 PackageSetting origPackage = null; 6365 String realName = null; 6366 if (pkg.mOriginalPackages != null) { 6367 // This package may need to be renamed to a previously 6368 // installed name. Let's check on that... 6369 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6370 if (pkg.mOriginalPackages.contains(renamed)) { 6371 // This package had originally been installed as the 6372 // original name, and we have already taken care of 6373 // transitioning to the new one. Just update the new 6374 // one to continue using the old name. 6375 realName = pkg.mRealPackage; 6376 if (!pkg.packageName.equals(renamed)) { 6377 // Callers into this function may have already taken 6378 // care of renaming the package; only do it here if 6379 // it is not already done. 6380 pkg.setPackageName(renamed); 6381 } 6382 6383 } else { 6384 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6385 if ((origPackage = mSettings.peekPackageLPr( 6386 pkg.mOriginalPackages.get(i))) != null) { 6387 // We do have the package already installed under its 6388 // original name... should we use it? 6389 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6390 // New package is not compatible with original. 6391 origPackage = null; 6392 continue; 6393 } else if (origPackage.sharedUser != null) { 6394 // Make sure uid is compatible between packages. 6395 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6396 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6397 + " to " + pkg.packageName + ": old uid " 6398 + origPackage.sharedUser.name 6399 + " differs from " + pkg.mSharedUserId); 6400 origPackage = null; 6401 continue; 6402 } 6403 } else { 6404 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6405 + pkg.packageName + " to old name " + origPackage.name); 6406 } 6407 break; 6408 } 6409 } 6410 } 6411 } 6412 6413 if (mTransferedPackages.contains(pkg.packageName)) { 6414 Slog.w(TAG, "Package " + pkg.packageName 6415 + " was transferred to another, but its .apk remains"); 6416 } 6417 6418 // Just create the setting, don't add it yet. For already existing packages 6419 // the PkgSetting exists already and doesn't have to be created. 6420 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6421 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6422 pkg.applicationInfo.primaryCpuAbi, 6423 pkg.applicationInfo.secondaryCpuAbi, 6424 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6425 user, false); 6426 if (pkgSetting == null) { 6427 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6428 "Creating application package " + pkg.packageName + " failed"); 6429 } 6430 6431 if (pkgSetting.origPackage != null) { 6432 // If we are first transitioning from an original package, 6433 // fix up the new package's name now. We need to do this after 6434 // looking up the package under its new name, so getPackageLP 6435 // can take care of fiddling things correctly. 6436 pkg.setPackageName(origPackage.name); 6437 6438 // File a report about this. 6439 String msg = "New package " + pkgSetting.realName 6440 + " renamed to replace old package " + pkgSetting.name; 6441 reportSettingsProblem(Log.WARN, msg); 6442 6443 // Make a note of it. 6444 mTransferedPackages.add(origPackage.name); 6445 6446 // No longer need to retain this. 6447 pkgSetting.origPackage = null; 6448 } 6449 6450 if (realName != null) { 6451 // Make a note of it. 6452 mTransferedPackages.add(pkg.packageName); 6453 } 6454 6455 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6456 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6457 } 6458 6459 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6460 // Check all shared libraries and map to their actual file path. 6461 // We only do this here for apps not on a system dir, because those 6462 // are the only ones that can fail an install due to this. We 6463 // will take care of the system apps by updating all of their 6464 // library paths after the scan is done. 6465 updateSharedLibrariesLPw(pkg, null); 6466 } 6467 6468 if (mFoundPolicyFile) { 6469 SELinuxMMAC.assignSeinfoValue(pkg); 6470 } 6471 6472 pkg.applicationInfo.uid = pkgSetting.appId; 6473 pkg.mExtras = pkgSetting; 6474 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6475 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6476 // We just determined the app is signed correctly, so bring 6477 // over the latest parsed certs. 6478 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6479 } else { 6480 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6481 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6482 "Package " + pkg.packageName + " upgrade keys do not match the " 6483 + "previously installed version"); 6484 } else { 6485 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6486 String msg = "System package " + pkg.packageName 6487 + " signature changed; retaining data."; 6488 reportSettingsProblem(Log.WARN, msg); 6489 } 6490 } 6491 } else { 6492 try { 6493 verifySignaturesLP(pkgSetting, pkg); 6494 // We just determined the app is signed correctly, so bring 6495 // over the latest parsed certs. 6496 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6497 } catch (PackageManagerException e) { 6498 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6499 throw e; 6500 } 6501 // The signature has changed, but this package is in the system 6502 // image... let's recover! 6503 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6504 // However... if this package is part of a shared user, but it 6505 // doesn't match the signature of the shared user, let's fail. 6506 // What this means is that you can't change the signatures 6507 // associated with an overall shared user, which doesn't seem all 6508 // that unreasonable. 6509 if (pkgSetting.sharedUser != null) { 6510 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6511 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6512 throw new PackageManagerException( 6513 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6514 "Signature mismatch for shared user : " 6515 + pkgSetting.sharedUser); 6516 } 6517 } 6518 // File a report about this. 6519 String msg = "System package " + pkg.packageName 6520 + " signature changed; retaining data."; 6521 reportSettingsProblem(Log.WARN, msg); 6522 } 6523 } 6524 // Verify that this new package doesn't have any content providers 6525 // that conflict with existing packages. Only do this if the 6526 // package isn't already installed, since we don't want to break 6527 // things that are installed. 6528 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6529 final int N = pkg.providers.size(); 6530 int i; 6531 for (i=0; i<N; i++) { 6532 PackageParser.Provider p = pkg.providers.get(i); 6533 if (p.info.authority != null) { 6534 String names[] = p.info.authority.split(";"); 6535 for (int j = 0; j < names.length; j++) { 6536 if (mProvidersByAuthority.containsKey(names[j])) { 6537 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6538 final String otherPackageName = 6539 ((other != null && other.getComponentName() != null) ? 6540 other.getComponentName().getPackageName() : "?"); 6541 throw new PackageManagerException( 6542 INSTALL_FAILED_CONFLICTING_PROVIDER, 6543 "Can't install because provider name " + names[j] 6544 + " (in package " + pkg.applicationInfo.packageName 6545 + ") is already used by " + otherPackageName); 6546 } 6547 } 6548 } 6549 } 6550 } 6551 6552 if (pkg.mAdoptPermissions != null) { 6553 // This package wants to adopt ownership of permissions from 6554 // another package. 6555 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6556 final String origName = pkg.mAdoptPermissions.get(i); 6557 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6558 if (orig != null) { 6559 if (verifyPackageUpdateLPr(orig, pkg)) { 6560 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6561 + pkg.packageName); 6562 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6563 } 6564 } 6565 } 6566 } 6567 } 6568 6569 final String pkgName = pkg.packageName; 6570 6571 final long scanFileTime = scanFile.lastModified(); 6572 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6573 pkg.applicationInfo.processName = fixProcessName( 6574 pkg.applicationInfo.packageName, 6575 pkg.applicationInfo.processName, 6576 pkg.applicationInfo.uid); 6577 6578 File dataPath; 6579 if (mPlatformPackage == pkg) { 6580 // The system package is special. 6581 dataPath = new File(Environment.getDataDirectory(), "system"); 6582 6583 pkg.applicationInfo.dataDir = dataPath.getPath(); 6584 6585 } else { 6586 // This is a normal package, need to make its data directory. 6587 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6588 UserHandle.USER_OWNER); 6589 6590 boolean uidError = false; 6591 if (dataPath.exists()) { 6592 int currentUid = 0; 6593 try { 6594 StructStat stat = Os.stat(dataPath.getPath()); 6595 currentUid = stat.st_uid; 6596 } catch (ErrnoException e) { 6597 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6598 } 6599 6600 // If we have mismatched owners for the data path, we have a problem. 6601 if (currentUid != pkg.applicationInfo.uid) { 6602 boolean recovered = false; 6603 if (currentUid == 0) { 6604 // The directory somehow became owned by root. Wow. 6605 // This is probably because the system was stopped while 6606 // installd was in the middle of messing with its libs 6607 // directory. Ask installd to fix that. 6608 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6609 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6610 if (ret >= 0) { 6611 recovered = true; 6612 String msg = "Package " + pkg.packageName 6613 + " unexpectedly changed to uid 0; recovered to " + 6614 + pkg.applicationInfo.uid; 6615 reportSettingsProblem(Log.WARN, msg); 6616 } 6617 } 6618 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6619 || (scanFlags&SCAN_BOOTING) != 0)) { 6620 // If this is a system app, we can at least delete its 6621 // current data so the application will still work. 6622 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6623 if (ret >= 0) { 6624 // TODO: Kill the processes first 6625 // Old data gone! 6626 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6627 ? "System package " : "Third party package "; 6628 String msg = prefix + pkg.packageName 6629 + " has changed from uid: " 6630 + currentUid + " to " 6631 + pkg.applicationInfo.uid + "; old data erased"; 6632 reportSettingsProblem(Log.WARN, msg); 6633 recovered = true; 6634 6635 // And now re-install the app. 6636 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6637 pkg.applicationInfo.seinfo); 6638 if (ret == -1) { 6639 // Ack should not happen! 6640 msg = prefix + pkg.packageName 6641 + " could not have data directory re-created after delete."; 6642 reportSettingsProblem(Log.WARN, msg); 6643 throw new PackageManagerException( 6644 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6645 } 6646 } 6647 if (!recovered) { 6648 mHasSystemUidErrors = true; 6649 } 6650 } else if (!recovered) { 6651 // If we allow this install to proceed, we will be broken. 6652 // Abort, abort! 6653 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6654 "scanPackageLI"); 6655 } 6656 if (!recovered) { 6657 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6658 + pkg.applicationInfo.uid + "/fs_" 6659 + currentUid; 6660 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6661 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6662 String msg = "Package " + pkg.packageName 6663 + " has mismatched uid: " 6664 + currentUid + " on disk, " 6665 + pkg.applicationInfo.uid + " in settings"; 6666 // writer 6667 synchronized (mPackages) { 6668 mSettings.mReadMessages.append(msg); 6669 mSettings.mReadMessages.append('\n'); 6670 uidError = true; 6671 if (!pkgSetting.uidError) { 6672 reportSettingsProblem(Log.ERROR, msg); 6673 } 6674 } 6675 } 6676 } 6677 pkg.applicationInfo.dataDir = dataPath.getPath(); 6678 if (mShouldRestoreconData) { 6679 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6680 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6681 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6682 } 6683 } else { 6684 if (DEBUG_PACKAGE_SCANNING) { 6685 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6686 Log.v(TAG, "Want this data dir: " + dataPath); 6687 } 6688 //invoke installer to do the actual installation 6689 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6690 pkg.applicationInfo.seinfo); 6691 if (ret < 0) { 6692 // Error from installer 6693 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6694 "Unable to create data dirs [errorCode=" + ret + "]"); 6695 } 6696 6697 if (dataPath.exists()) { 6698 pkg.applicationInfo.dataDir = dataPath.getPath(); 6699 } else { 6700 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6701 pkg.applicationInfo.dataDir = null; 6702 } 6703 } 6704 6705 pkgSetting.uidError = uidError; 6706 } 6707 6708 final String path = scanFile.getPath(); 6709 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6710 6711 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6712 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6713 6714 // Some system apps still use directory structure for native libraries 6715 // in which case we might end up not detecting abi solely based on apk 6716 // structure. Try to detect abi based on directory structure. 6717 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6718 pkg.applicationInfo.primaryCpuAbi == null) { 6719 setBundledAppAbisAndRoots(pkg, pkgSetting); 6720 setNativeLibraryPaths(pkg); 6721 } 6722 6723 } else { 6724 if ((scanFlags & SCAN_MOVE) != 0) { 6725 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6726 // but we already have this packages package info in the PackageSetting. We just 6727 // use that and derive the native library path based on the new codepath. 6728 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6729 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6730 } 6731 6732 // Set native library paths again. For moves, the path will be updated based on the 6733 // ABIs we've determined above. For non-moves, the path will be updated based on the 6734 // ABIs we determined during compilation, but the path will depend on the final 6735 // package path (after the rename away from the stage path). 6736 setNativeLibraryPaths(pkg); 6737 } 6738 6739 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6740 final int[] userIds = sUserManager.getUserIds(); 6741 synchronized (mInstallLock) { 6742 // Create a native library symlink only if we have native libraries 6743 // and if the native libraries are 32 bit libraries. We do not provide 6744 // this symlink for 64 bit libraries. 6745 if (pkg.applicationInfo.primaryCpuAbi != null && 6746 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6747 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6748 for (int userId : userIds) { 6749 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6750 nativeLibPath, userId) < 0) { 6751 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6752 "Failed linking native library dir (user=" + userId + ")"); 6753 } 6754 } 6755 } 6756 } 6757 6758 // This is a special case for the "system" package, where the ABI is 6759 // dictated by the zygote configuration (and init.rc). We should keep track 6760 // of this ABI so that we can deal with "normal" applications that run under 6761 // the same UID correctly. 6762 if (mPlatformPackage == pkg) { 6763 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6764 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6765 } 6766 6767 // If there's a mismatch between the abi-override in the package setting 6768 // and the abiOverride specified for the install. Warn about this because we 6769 // would've already compiled the app without taking the package setting into 6770 // account. 6771 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6772 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6773 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6774 " for package: " + pkg.packageName); 6775 } 6776 } 6777 6778 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6779 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6780 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6781 6782 // Copy the derived override back to the parsed package, so that we can 6783 // update the package settings accordingly. 6784 pkg.cpuAbiOverride = cpuAbiOverride; 6785 6786 if (DEBUG_ABI_SELECTION) { 6787 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6788 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6789 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6790 } 6791 6792 // Push the derived path down into PackageSettings so we know what to 6793 // clean up at uninstall time. 6794 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6795 6796 if (DEBUG_ABI_SELECTION) { 6797 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6798 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6799 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6800 } 6801 6802 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6803 // We don't do this here during boot because we can do it all 6804 // at once after scanning all existing packages. 6805 // 6806 // We also do this *before* we perform dexopt on this package, so that 6807 // we can avoid redundant dexopts, and also to make sure we've got the 6808 // code and package path correct. 6809 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6810 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6811 } 6812 6813 if ((scanFlags & SCAN_NO_DEX) == 0) { 6814 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6815 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6816 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6817 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6818 } 6819 } 6820 if (mFactoryTest && pkg.requestedPermissions.contains( 6821 android.Manifest.permission.FACTORY_TEST)) { 6822 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6823 } 6824 6825 ArrayList<PackageParser.Package> clientLibPkgs = null; 6826 6827 // writer 6828 synchronized (mPackages) { 6829 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6830 // Only system apps can add new shared libraries. 6831 if (pkg.libraryNames != null) { 6832 for (int i=0; i<pkg.libraryNames.size(); i++) { 6833 String name = pkg.libraryNames.get(i); 6834 boolean allowed = false; 6835 if (pkg.isUpdatedSystemApp()) { 6836 // New library entries can only be added through the 6837 // system image. This is important to get rid of a lot 6838 // of nasty edge cases: for example if we allowed a non- 6839 // system update of the app to add a library, then uninstalling 6840 // the update would make the library go away, and assumptions 6841 // we made such as through app install filtering would now 6842 // have allowed apps on the device which aren't compatible 6843 // with it. Better to just have the restriction here, be 6844 // conservative, and create many fewer cases that can negatively 6845 // impact the user experience. 6846 final PackageSetting sysPs = mSettings 6847 .getDisabledSystemPkgLPr(pkg.packageName); 6848 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6849 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6850 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6851 allowed = true; 6852 allowed = true; 6853 break; 6854 } 6855 } 6856 } 6857 } else { 6858 allowed = true; 6859 } 6860 if (allowed) { 6861 if (!mSharedLibraries.containsKey(name)) { 6862 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6863 } else if (!name.equals(pkg.packageName)) { 6864 Slog.w(TAG, "Package " + pkg.packageName + " library " 6865 + name + " already exists; skipping"); 6866 } 6867 } else { 6868 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6869 + name + " that is not declared on system image; skipping"); 6870 } 6871 } 6872 if ((scanFlags&SCAN_BOOTING) == 0) { 6873 // If we are not booting, we need to update any applications 6874 // that are clients of our shared library. If we are booting, 6875 // this will all be done once the scan is complete. 6876 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6877 } 6878 } 6879 } 6880 } 6881 6882 // We also need to dexopt any apps that are dependent on this library. Note that 6883 // if these fail, we should abort the install since installing the library will 6884 // result in some apps being broken. 6885 if (clientLibPkgs != null) { 6886 if ((scanFlags & SCAN_NO_DEX) == 0) { 6887 for (int i = 0; i < clientLibPkgs.size(); i++) { 6888 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6889 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6890 null /* instruction sets */, forceDex, 6891 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6892 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6893 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6894 "scanPackageLI failed to dexopt clientLibPkgs"); 6895 } 6896 } 6897 } 6898 } 6899 6900 // Also need to kill any apps that are dependent on the library. 6901 if (clientLibPkgs != null) { 6902 for (int i=0; i<clientLibPkgs.size(); i++) { 6903 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6904 killApplication(clientPkg.applicationInfo.packageName, 6905 clientPkg.applicationInfo.uid, "update lib"); 6906 } 6907 } 6908 6909 // Make sure we're not adding any bogus keyset info 6910 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6911 ksms.assertScannedPackageValid(pkg); 6912 6913 // writer 6914 synchronized (mPackages) { 6915 // We don't expect installation to fail beyond this point 6916 6917 // Add the new setting to mSettings 6918 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6919 // Add the new setting to mPackages 6920 mPackages.put(pkg.applicationInfo.packageName, pkg); 6921 // Make sure we don't accidentally delete its data. 6922 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6923 while (iter.hasNext()) { 6924 PackageCleanItem item = iter.next(); 6925 if (pkgName.equals(item.packageName)) { 6926 iter.remove(); 6927 } 6928 } 6929 6930 // Take care of first install / last update times. 6931 if (currentTime != 0) { 6932 if (pkgSetting.firstInstallTime == 0) { 6933 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6934 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6935 pkgSetting.lastUpdateTime = currentTime; 6936 } 6937 } else if (pkgSetting.firstInstallTime == 0) { 6938 // We need *something*. Take time time stamp of the file. 6939 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6940 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6941 if (scanFileTime != pkgSetting.timeStamp) { 6942 // A package on the system image has changed; consider this 6943 // to be an update. 6944 pkgSetting.lastUpdateTime = scanFileTime; 6945 } 6946 } 6947 6948 // Add the package's KeySets to the global KeySetManagerService 6949 ksms.addScannedPackageLPw(pkg); 6950 6951 int N = pkg.providers.size(); 6952 StringBuilder r = null; 6953 int i; 6954 for (i=0; i<N; i++) { 6955 PackageParser.Provider p = pkg.providers.get(i); 6956 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6957 p.info.processName, pkg.applicationInfo.uid); 6958 mProviders.addProvider(p); 6959 p.syncable = p.info.isSyncable; 6960 if (p.info.authority != null) { 6961 String names[] = p.info.authority.split(";"); 6962 p.info.authority = null; 6963 for (int j = 0; j < names.length; j++) { 6964 if (j == 1 && p.syncable) { 6965 // We only want the first authority for a provider to possibly be 6966 // syncable, so if we already added this provider using a different 6967 // authority clear the syncable flag. We copy the provider before 6968 // changing it because the mProviders object contains a reference 6969 // to a provider that we don't want to change. 6970 // Only do this for the second authority since the resulting provider 6971 // object can be the same for all future authorities for this provider. 6972 p = new PackageParser.Provider(p); 6973 p.syncable = false; 6974 } 6975 if (!mProvidersByAuthority.containsKey(names[j])) { 6976 mProvidersByAuthority.put(names[j], p); 6977 if (p.info.authority == null) { 6978 p.info.authority = names[j]; 6979 } else { 6980 p.info.authority = p.info.authority + ";" + names[j]; 6981 } 6982 if (DEBUG_PACKAGE_SCANNING) { 6983 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6984 Log.d(TAG, "Registered content provider: " + names[j] 6985 + ", className = " + p.info.name + ", isSyncable = " 6986 + p.info.isSyncable); 6987 } 6988 } else { 6989 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6990 Slog.w(TAG, "Skipping provider name " + names[j] + 6991 " (in package " + pkg.applicationInfo.packageName + 6992 "): name already used by " 6993 + ((other != null && other.getComponentName() != null) 6994 ? other.getComponentName().getPackageName() : "?")); 6995 } 6996 } 6997 } 6998 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6999 if (r == null) { 7000 r = new StringBuilder(256); 7001 } else { 7002 r.append(' '); 7003 } 7004 r.append(p.info.name); 7005 } 7006 } 7007 if (r != null) { 7008 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7009 } 7010 7011 N = pkg.services.size(); 7012 r = null; 7013 for (i=0; i<N; i++) { 7014 PackageParser.Service s = pkg.services.get(i); 7015 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7016 s.info.processName, pkg.applicationInfo.uid); 7017 mServices.addService(s); 7018 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7019 if (r == null) { 7020 r = new StringBuilder(256); 7021 } else { 7022 r.append(' '); 7023 } 7024 r.append(s.info.name); 7025 } 7026 } 7027 if (r != null) { 7028 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7029 } 7030 7031 N = pkg.receivers.size(); 7032 r = null; 7033 for (i=0; i<N; i++) { 7034 PackageParser.Activity a = pkg.receivers.get(i); 7035 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7036 a.info.processName, pkg.applicationInfo.uid); 7037 mReceivers.addActivity(a, "receiver"); 7038 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7039 if (r == null) { 7040 r = new StringBuilder(256); 7041 } else { 7042 r.append(' '); 7043 } 7044 r.append(a.info.name); 7045 } 7046 } 7047 if (r != null) { 7048 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7049 } 7050 7051 N = pkg.activities.size(); 7052 r = null; 7053 for (i=0; i<N; i++) { 7054 PackageParser.Activity a = pkg.activities.get(i); 7055 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7056 a.info.processName, pkg.applicationInfo.uid); 7057 mActivities.addActivity(a, "activity"); 7058 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7059 if (r == null) { 7060 r = new StringBuilder(256); 7061 } else { 7062 r.append(' '); 7063 } 7064 r.append(a.info.name); 7065 } 7066 } 7067 if (r != null) { 7068 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7069 } 7070 7071 N = pkg.permissionGroups.size(); 7072 r = null; 7073 for (i=0; i<N; i++) { 7074 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7075 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7076 if (cur == null) { 7077 mPermissionGroups.put(pg.info.name, pg); 7078 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7079 if (r == null) { 7080 r = new StringBuilder(256); 7081 } else { 7082 r.append(' '); 7083 } 7084 r.append(pg.info.name); 7085 } 7086 } else { 7087 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7088 + pg.info.packageName + " ignored: original from " 7089 + cur.info.packageName); 7090 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7091 if (r == null) { 7092 r = new StringBuilder(256); 7093 } else { 7094 r.append(' '); 7095 } 7096 r.append("DUP:"); 7097 r.append(pg.info.name); 7098 } 7099 } 7100 } 7101 if (r != null) { 7102 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7103 } 7104 7105 N = pkg.permissions.size(); 7106 r = null; 7107 for (i=0; i<N; i++) { 7108 PackageParser.Permission p = pkg.permissions.get(i); 7109 7110 // Now that permission groups have a special meaning, we ignore permission 7111 // groups for legacy apps to prevent unexpected behavior. In particular, 7112 // permissions for one app being granted to someone just becuase they happen 7113 // to be in a group defined by another app (before this had no implications). 7114 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7115 p.group = mPermissionGroups.get(p.info.group); 7116 // Warn for a permission in an unknown group. 7117 if (p.info.group != null && p.group == null) { 7118 Slog.w(TAG, "Permission " + p.info.name + " from package " 7119 + p.info.packageName + " in an unknown group " + p.info.group); 7120 } 7121 } 7122 7123 ArrayMap<String, BasePermission> permissionMap = 7124 p.tree ? mSettings.mPermissionTrees 7125 : mSettings.mPermissions; 7126 BasePermission bp = permissionMap.get(p.info.name); 7127 7128 // Allow system apps to redefine non-system permissions 7129 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7130 final boolean currentOwnerIsSystem = (bp.perm != null 7131 && isSystemApp(bp.perm.owner)); 7132 if (isSystemApp(p.owner)) { 7133 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7134 // It's a built-in permission and no owner, take ownership now 7135 bp.packageSetting = pkgSetting; 7136 bp.perm = p; 7137 bp.uid = pkg.applicationInfo.uid; 7138 bp.sourcePackage = p.info.packageName; 7139 } else if (!currentOwnerIsSystem) { 7140 String msg = "New decl " + p.owner + " of permission " 7141 + p.info.name + " is system; overriding " + bp.sourcePackage; 7142 reportSettingsProblem(Log.WARN, msg); 7143 bp = null; 7144 } 7145 } 7146 } 7147 7148 if (bp == null) { 7149 bp = new BasePermission(p.info.name, p.info.packageName, 7150 BasePermission.TYPE_NORMAL); 7151 permissionMap.put(p.info.name, bp); 7152 } 7153 7154 if (bp.perm == null) { 7155 if (bp.sourcePackage == null 7156 || bp.sourcePackage.equals(p.info.packageName)) { 7157 BasePermission tree = findPermissionTreeLP(p.info.name); 7158 if (tree == null 7159 || tree.sourcePackage.equals(p.info.packageName)) { 7160 bp.packageSetting = pkgSetting; 7161 bp.perm = p; 7162 bp.uid = pkg.applicationInfo.uid; 7163 bp.sourcePackage = p.info.packageName; 7164 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7165 if (r == null) { 7166 r = new StringBuilder(256); 7167 } else { 7168 r.append(' '); 7169 } 7170 r.append(p.info.name); 7171 } 7172 } else { 7173 Slog.w(TAG, "Permission " + p.info.name + " from package " 7174 + p.info.packageName + " ignored: base tree " 7175 + tree.name + " is from package " 7176 + tree.sourcePackage); 7177 } 7178 } else { 7179 Slog.w(TAG, "Permission " + p.info.name + " from package " 7180 + p.info.packageName + " ignored: original from " 7181 + bp.sourcePackage); 7182 } 7183 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7184 if (r == null) { 7185 r = new StringBuilder(256); 7186 } else { 7187 r.append(' '); 7188 } 7189 r.append("DUP:"); 7190 r.append(p.info.name); 7191 } 7192 if (bp.perm == p) { 7193 bp.protectionLevel = p.info.protectionLevel; 7194 } 7195 } 7196 7197 if (r != null) { 7198 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7199 } 7200 7201 N = pkg.instrumentation.size(); 7202 r = null; 7203 for (i=0; i<N; i++) { 7204 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7205 a.info.packageName = pkg.applicationInfo.packageName; 7206 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7207 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7208 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7209 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7210 a.info.dataDir = pkg.applicationInfo.dataDir; 7211 7212 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7213 // need other information about the application, like the ABI and what not ? 7214 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7215 mInstrumentation.put(a.getComponentName(), a); 7216 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7217 if (r == null) { 7218 r = new StringBuilder(256); 7219 } else { 7220 r.append(' '); 7221 } 7222 r.append(a.info.name); 7223 } 7224 } 7225 if (r != null) { 7226 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7227 } 7228 7229 if (pkg.protectedBroadcasts != null) { 7230 N = pkg.protectedBroadcasts.size(); 7231 for (i=0; i<N; i++) { 7232 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7233 } 7234 } 7235 7236 pkgSetting.setTimeStamp(scanFileTime); 7237 7238 // Create idmap files for pairs of (packages, overlay packages). 7239 // Note: "android", ie framework-res.apk, is handled by native layers. 7240 if (pkg.mOverlayTarget != null) { 7241 // This is an overlay package. 7242 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7243 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7244 mOverlays.put(pkg.mOverlayTarget, 7245 new ArrayMap<String, PackageParser.Package>()); 7246 } 7247 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7248 map.put(pkg.packageName, pkg); 7249 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7250 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7251 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7252 "scanPackageLI failed to createIdmap"); 7253 } 7254 } 7255 } else if (mOverlays.containsKey(pkg.packageName) && 7256 !pkg.packageName.equals("android")) { 7257 // This is a regular package, with one or more known overlay packages. 7258 createIdmapsForPackageLI(pkg); 7259 } 7260 } 7261 7262 return pkg; 7263 } 7264 7265 /** 7266 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7267 * is derived purely on the basis of the contents of {@code scanFile} and 7268 * {@code cpuAbiOverride}. 7269 * 7270 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7271 */ 7272 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7273 String cpuAbiOverride, boolean extractLibs) 7274 throws PackageManagerException { 7275 // TODO: We can probably be smarter about this stuff. For installed apps, 7276 // we can calculate this information at install time once and for all. For 7277 // system apps, we can probably assume that this information doesn't change 7278 // after the first boot scan. As things stand, we do lots of unnecessary work. 7279 7280 // Give ourselves some initial paths; we'll come back for another 7281 // pass once we've determined ABI below. 7282 setNativeLibraryPaths(pkg); 7283 7284 // We would never need to extract libs for forward-locked and external packages, 7285 // since the container service will do it for us. We shouldn't attempt to 7286 // extract libs from system app when it was not updated. 7287 if (pkg.isForwardLocked() || isExternal(pkg) || 7288 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7289 extractLibs = false; 7290 } 7291 7292 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7293 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7294 7295 NativeLibraryHelper.Handle handle = null; 7296 try { 7297 handle = NativeLibraryHelper.Handle.create(pkg); 7298 // TODO(multiArch): This can be null for apps that didn't go through the 7299 // usual installation process. We can calculate it again, like we 7300 // do during install time. 7301 // 7302 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7303 // unnecessary. 7304 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7305 7306 // Null out the abis so that they can be recalculated. 7307 pkg.applicationInfo.primaryCpuAbi = null; 7308 pkg.applicationInfo.secondaryCpuAbi = null; 7309 if (isMultiArch(pkg.applicationInfo)) { 7310 // Warn if we've set an abiOverride for multi-lib packages.. 7311 // By definition, we need to copy both 32 and 64 bit libraries for 7312 // such packages. 7313 if (pkg.cpuAbiOverride != null 7314 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7315 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7316 } 7317 7318 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7319 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7320 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7321 if (extractLibs) { 7322 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7323 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7324 useIsaSpecificSubdirs); 7325 } else { 7326 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7327 } 7328 } 7329 7330 maybeThrowExceptionForMultiArchCopy( 7331 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7332 7333 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7334 if (extractLibs) { 7335 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7336 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7337 useIsaSpecificSubdirs); 7338 } else { 7339 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7340 } 7341 } 7342 7343 maybeThrowExceptionForMultiArchCopy( 7344 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7345 7346 if (abi64 >= 0) { 7347 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7348 } 7349 7350 if (abi32 >= 0) { 7351 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7352 if (abi64 >= 0) { 7353 pkg.applicationInfo.secondaryCpuAbi = abi; 7354 } else { 7355 pkg.applicationInfo.primaryCpuAbi = abi; 7356 } 7357 } 7358 } else { 7359 String[] abiList = (cpuAbiOverride != null) ? 7360 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7361 7362 // Enable gross and lame hacks for apps that are built with old 7363 // SDK tools. We must scan their APKs for renderscript bitcode and 7364 // not launch them if it's present. Don't bother checking on devices 7365 // that don't have 64 bit support. 7366 boolean needsRenderScriptOverride = false; 7367 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7368 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7369 abiList = Build.SUPPORTED_32_BIT_ABIS; 7370 needsRenderScriptOverride = true; 7371 } 7372 7373 final int copyRet; 7374 if (extractLibs) { 7375 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7376 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7377 } else { 7378 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7379 } 7380 7381 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7382 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7383 "Error unpackaging native libs for app, errorCode=" + copyRet); 7384 } 7385 7386 if (copyRet >= 0) { 7387 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7388 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7389 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7390 } else if (needsRenderScriptOverride) { 7391 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7392 } 7393 } 7394 } catch (IOException ioe) { 7395 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7396 } finally { 7397 IoUtils.closeQuietly(handle); 7398 } 7399 7400 // Now that we've calculated the ABIs and determined if it's an internal app, 7401 // we will go ahead and populate the nativeLibraryPath. 7402 setNativeLibraryPaths(pkg); 7403 } 7404 7405 /** 7406 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7407 * i.e, so that all packages can be run inside a single process if required. 7408 * 7409 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7410 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7411 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7412 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7413 * updating a package that belongs to a shared user. 7414 * 7415 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7416 * adds unnecessary complexity. 7417 */ 7418 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7419 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7420 String requiredInstructionSet = null; 7421 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7422 requiredInstructionSet = VMRuntime.getInstructionSet( 7423 scannedPackage.applicationInfo.primaryCpuAbi); 7424 } 7425 7426 PackageSetting requirer = null; 7427 for (PackageSetting ps : packagesForUser) { 7428 // If packagesForUser contains scannedPackage, we skip it. This will happen 7429 // when scannedPackage is an update of an existing package. Without this check, 7430 // we will never be able to change the ABI of any package belonging to a shared 7431 // user, even if it's compatible with other packages. 7432 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7433 if (ps.primaryCpuAbiString == null) { 7434 continue; 7435 } 7436 7437 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7438 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7439 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7440 // this but there's not much we can do. 7441 String errorMessage = "Instruction set mismatch, " 7442 + ((requirer == null) ? "[caller]" : requirer) 7443 + " requires " + requiredInstructionSet + " whereas " + ps 7444 + " requires " + instructionSet; 7445 Slog.w(TAG, errorMessage); 7446 } 7447 7448 if (requiredInstructionSet == null) { 7449 requiredInstructionSet = instructionSet; 7450 requirer = ps; 7451 } 7452 } 7453 } 7454 7455 if (requiredInstructionSet != null) { 7456 String adjustedAbi; 7457 if (requirer != null) { 7458 // requirer != null implies that either scannedPackage was null or that scannedPackage 7459 // did not require an ABI, in which case we have to adjust scannedPackage to match 7460 // the ABI of the set (which is the same as requirer's ABI) 7461 adjustedAbi = requirer.primaryCpuAbiString; 7462 if (scannedPackage != null) { 7463 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7464 } 7465 } else { 7466 // requirer == null implies that we're updating all ABIs in the set to 7467 // match scannedPackage. 7468 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7469 } 7470 7471 for (PackageSetting ps : packagesForUser) { 7472 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7473 if (ps.primaryCpuAbiString != null) { 7474 continue; 7475 } 7476 7477 ps.primaryCpuAbiString = adjustedAbi; 7478 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7479 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7480 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7481 7482 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7483 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7484 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7485 ps.primaryCpuAbiString = null; 7486 ps.pkg.applicationInfo.primaryCpuAbi = null; 7487 return; 7488 } else { 7489 mInstaller.rmdex(ps.codePathString, 7490 getDexCodeInstructionSet(getPreferredInstructionSet())); 7491 } 7492 } 7493 } 7494 } 7495 } 7496 } 7497 7498 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7499 synchronized (mPackages) { 7500 mResolverReplaced = true; 7501 // Set up information for custom user intent resolution activity. 7502 mResolveActivity.applicationInfo = pkg.applicationInfo; 7503 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7504 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7505 mResolveActivity.processName = pkg.applicationInfo.packageName; 7506 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7507 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7508 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7509 mResolveActivity.theme = 0; 7510 mResolveActivity.exported = true; 7511 mResolveActivity.enabled = true; 7512 mResolveInfo.activityInfo = mResolveActivity; 7513 mResolveInfo.priority = 0; 7514 mResolveInfo.preferredOrder = 0; 7515 mResolveInfo.match = 0; 7516 mResolveComponentName = mCustomResolverComponentName; 7517 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7518 mResolveComponentName); 7519 } 7520 } 7521 7522 private static String calculateBundledApkRoot(final String codePathString) { 7523 final File codePath = new File(codePathString); 7524 final File codeRoot; 7525 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7526 codeRoot = Environment.getRootDirectory(); 7527 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7528 codeRoot = Environment.getOemDirectory(); 7529 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7530 codeRoot = Environment.getVendorDirectory(); 7531 } else { 7532 // Unrecognized code path; take its top real segment as the apk root: 7533 // e.g. /something/app/blah.apk => /something 7534 try { 7535 File f = codePath.getCanonicalFile(); 7536 File parent = f.getParentFile(); // non-null because codePath is a file 7537 File tmp; 7538 while ((tmp = parent.getParentFile()) != null) { 7539 f = parent; 7540 parent = tmp; 7541 } 7542 codeRoot = f; 7543 Slog.w(TAG, "Unrecognized code path " 7544 + codePath + " - using " + codeRoot); 7545 } catch (IOException e) { 7546 // Can't canonicalize the code path -- shenanigans? 7547 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7548 return Environment.getRootDirectory().getPath(); 7549 } 7550 } 7551 return codeRoot.getPath(); 7552 } 7553 7554 /** 7555 * Derive and set the location of native libraries for the given package, 7556 * which varies depending on where and how the package was installed. 7557 */ 7558 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7559 final ApplicationInfo info = pkg.applicationInfo; 7560 final String codePath = pkg.codePath; 7561 final File codeFile = new File(codePath); 7562 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7563 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7564 7565 info.nativeLibraryRootDir = null; 7566 info.nativeLibraryRootRequiresIsa = false; 7567 info.nativeLibraryDir = null; 7568 info.secondaryNativeLibraryDir = null; 7569 7570 if (isApkFile(codeFile)) { 7571 // Monolithic install 7572 if (bundledApp) { 7573 // If "/system/lib64/apkname" exists, assume that is the per-package 7574 // native library directory to use; otherwise use "/system/lib/apkname". 7575 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7576 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7577 getPrimaryInstructionSet(info)); 7578 7579 // This is a bundled system app so choose the path based on the ABI. 7580 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7581 // is just the default path. 7582 final String apkName = deriveCodePathName(codePath); 7583 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7584 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7585 apkName).getAbsolutePath(); 7586 7587 if (info.secondaryCpuAbi != null) { 7588 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7589 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7590 secondaryLibDir, apkName).getAbsolutePath(); 7591 } 7592 } else if (asecApp) { 7593 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7594 .getAbsolutePath(); 7595 } else { 7596 final String apkName = deriveCodePathName(codePath); 7597 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7598 .getAbsolutePath(); 7599 } 7600 7601 info.nativeLibraryRootRequiresIsa = false; 7602 info.nativeLibraryDir = info.nativeLibraryRootDir; 7603 } else { 7604 // Cluster install 7605 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7606 info.nativeLibraryRootRequiresIsa = true; 7607 7608 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7609 getPrimaryInstructionSet(info)).getAbsolutePath(); 7610 7611 if (info.secondaryCpuAbi != null) { 7612 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7613 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7614 } 7615 } 7616 } 7617 7618 /** 7619 * Calculate the abis and roots for a bundled app. These can uniquely 7620 * be determined from the contents of the system partition, i.e whether 7621 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7622 * of this information, and instead assume that the system was built 7623 * sensibly. 7624 */ 7625 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7626 PackageSetting pkgSetting) { 7627 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7628 7629 // If "/system/lib64/apkname" exists, assume that is the per-package 7630 // native library directory to use; otherwise use "/system/lib/apkname". 7631 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7632 setBundledAppAbi(pkg, apkRoot, apkName); 7633 // pkgSetting might be null during rescan following uninstall of updates 7634 // to a bundled app, so accommodate that possibility. The settings in 7635 // that case will be established later from the parsed package. 7636 // 7637 // If the settings aren't null, sync them up with what we've just derived. 7638 // note that apkRoot isn't stored in the package settings. 7639 if (pkgSetting != null) { 7640 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7641 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7642 } 7643 } 7644 7645 /** 7646 * Deduces the ABI of a bundled app and sets the relevant fields on the 7647 * parsed pkg object. 7648 * 7649 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7650 * under which system libraries are installed. 7651 * @param apkName the name of the installed package. 7652 */ 7653 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7654 final File codeFile = new File(pkg.codePath); 7655 7656 final boolean has64BitLibs; 7657 final boolean has32BitLibs; 7658 if (isApkFile(codeFile)) { 7659 // Monolithic install 7660 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7661 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7662 } else { 7663 // Cluster install 7664 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7665 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7666 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7667 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7668 has64BitLibs = (new File(rootDir, isa)).exists(); 7669 } else { 7670 has64BitLibs = false; 7671 } 7672 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7673 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7674 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7675 has32BitLibs = (new File(rootDir, isa)).exists(); 7676 } else { 7677 has32BitLibs = false; 7678 } 7679 } 7680 7681 if (has64BitLibs && !has32BitLibs) { 7682 // The package has 64 bit libs, but not 32 bit libs. Its primary 7683 // ABI should be 64 bit. We can safely assume here that the bundled 7684 // native libraries correspond to the most preferred ABI in the list. 7685 7686 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7687 pkg.applicationInfo.secondaryCpuAbi = null; 7688 } else if (has32BitLibs && !has64BitLibs) { 7689 // The package has 32 bit libs but not 64 bit libs. Its primary 7690 // ABI should be 32 bit. 7691 7692 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7693 pkg.applicationInfo.secondaryCpuAbi = null; 7694 } else if (has32BitLibs && has64BitLibs) { 7695 // The application has both 64 and 32 bit bundled libraries. We check 7696 // here that the app declares multiArch support, and warn if it doesn't. 7697 // 7698 // We will be lenient here and record both ABIs. The primary will be the 7699 // ABI that's higher on the list, i.e, a device that's configured to prefer 7700 // 64 bit apps will see a 64 bit primary ABI, 7701 7702 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7703 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7704 } 7705 7706 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7707 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7708 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7709 } else { 7710 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7711 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7712 } 7713 } else { 7714 pkg.applicationInfo.primaryCpuAbi = null; 7715 pkg.applicationInfo.secondaryCpuAbi = null; 7716 } 7717 } 7718 7719 private void killApplication(String pkgName, int appId, String reason) { 7720 // Request the ActivityManager to kill the process(only for existing packages) 7721 // so that we do not end up in a confused state while the user is still using the older 7722 // version of the application while the new one gets installed. 7723 IActivityManager am = ActivityManagerNative.getDefault(); 7724 if (am != null) { 7725 try { 7726 am.killApplicationWithAppId(pkgName, appId, reason); 7727 } catch (RemoteException e) { 7728 } 7729 } 7730 } 7731 7732 void removePackageLI(PackageSetting ps, boolean chatty) { 7733 if (DEBUG_INSTALL) { 7734 if (chatty) 7735 Log.d(TAG, "Removing package " + ps.name); 7736 } 7737 7738 // writer 7739 synchronized (mPackages) { 7740 mPackages.remove(ps.name); 7741 final PackageParser.Package pkg = ps.pkg; 7742 if (pkg != null) { 7743 cleanPackageDataStructuresLILPw(pkg, chatty); 7744 } 7745 } 7746 } 7747 7748 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7749 if (DEBUG_INSTALL) { 7750 if (chatty) 7751 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7752 } 7753 7754 // writer 7755 synchronized (mPackages) { 7756 mPackages.remove(pkg.applicationInfo.packageName); 7757 cleanPackageDataStructuresLILPw(pkg, chatty); 7758 } 7759 } 7760 7761 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7762 int N = pkg.providers.size(); 7763 StringBuilder r = null; 7764 int i; 7765 for (i=0; i<N; i++) { 7766 PackageParser.Provider p = pkg.providers.get(i); 7767 mProviders.removeProvider(p); 7768 if (p.info.authority == null) { 7769 7770 /* There was another ContentProvider with this authority when 7771 * this app was installed so this authority is null, 7772 * Ignore it as we don't have to unregister the provider. 7773 */ 7774 continue; 7775 } 7776 String names[] = p.info.authority.split(";"); 7777 for (int j = 0; j < names.length; j++) { 7778 if (mProvidersByAuthority.get(names[j]) == p) { 7779 mProvidersByAuthority.remove(names[j]); 7780 if (DEBUG_REMOVE) { 7781 if (chatty) 7782 Log.d(TAG, "Unregistered content provider: " + names[j] 7783 + ", className = " + p.info.name + ", isSyncable = " 7784 + p.info.isSyncable); 7785 } 7786 } 7787 } 7788 if (DEBUG_REMOVE && chatty) { 7789 if (r == null) { 7790 r = new StringBuilder(256); 7791 } else { 7792 r.append(' '); 7793 } 7794 r.append(p.info.name); 7795 } 7796 } 7797 if (r != null) { 7798 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7799 } 7800 7801 N = pkg.services.size(); 7802 r = null; 7803 for (i=0; i<N; i++) { 7804 PackageParser.Service s = pkg.services.get(i); 7805 mServices.removeService(s); 7806 if (chatty) { 7807 if (r == null) { 7808 r = new StringBuilder(256); 7809 } else { 7810 r.append(' '); 7811 } 7812 r.append(s.info.name); 7813 } 7814 } 7815 if (r != null) { 7816 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7817 } 7818 7819 N = pkg.receivers.size(); 7820 r = null; 7821 for (i=0; i<N; i++) { 7822 PackageParser.Activity a = pkg.receivers.get(i); 7823 mReceivers.removeActivity(a, "receiver"); 7824 if (DEBUG_REMOVE && chatty) { 7825 if (r == null) { 7826 r = new StringBuilder(256); 7827 } else { 7828 r.append(' '); 7829 } 7830 r.append(a.info.name); 7831 } 7832 } 7833 if (r != null) { 7834 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7835 } 7836 7837 N = pkg.activities.size(); 7838 r = null; 7839 for (i=0; i<N; i++) { 7840 PackageParser.Activity a = pkg.activities.get(i); 7841 mActivities.removeActivity(a, "activity"); 7842 if (DEBUG_REMOVE && chatty) { 7843 if (r == null) { 7844 r = new StringBuilder(256); 7845 } else { 7846 r.append(' '); 7847 } 7848 r.append(a.info.name); 7849 } 7850 } 7851 if (r != null) { 7852 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7853 } 7854 7855 N = pkg.permissions.size(); 7856 r = null; 7857 for (i=0; i<N; i++) { 7858 PackageParser.Permission p = pkg.permissions.get(i); 7859 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7860 if (bp == null) { 7861 bp = mSettings.mPermissionTrees.get(p.info.name); 7862 } 7863 if (bp != null && bp.perm == p) { 7864 bp.perm = null; 7865 if (DEBUG_REMOVE && chatty) { 7866 if (r == null) { 7867 r = new StringBuilder(256); 7868 } else { 7869 r.append(' '); 7870 } 7871 r.append(p.info.name); 7872 } 7873 } 7874 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7875 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7876 if (appOpPerms != null) { 7877 appOpPerms.remove(pkg.packageName); 7878 } 7879 } 7880 } 7881 if (r != null) { 7882 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7883 } 7884 7885 N = pkg.requestedPermissions.size(); 7886 r = null; 7887 for (i=0; i<N; i++) { 7888 String perm = pkg.requestedPermissions.get(i); 7889 BasePermission bp = mSettings.mPermissions.get(perm); 7890 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7891 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7892 if (appOpPerms != null) { 7893 appOpPerms.remove(pkg.packageName); 7894 if (appOpPerms.isEmpty()) { 7895 mAppOpPermissionPackages.remove(perm); 7896 } 7897 } 7898 } 7899 } 7900 if (r != null) { 7901 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7902 } 7903 7904 N = pkg.instrumentation.size(); 7905 r = null; 7906 for (i=0; i<N; i++) { 7907 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7908 mInstrumentation.remove(a.getComponentName()); 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, " Instrumentation: " + r); 7920 } 7921 7922 r = null; 7923 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7924 // Only system apps can hold shared libraries. 7925 if (pkg.libraryNames != null) { 7926 for (i=0; i<pkg.libraryNames.size(); i++) { 7927 String name = pkg.libraryNames.get(i); 7928 SharedLibraryEntry cur = mSharedLibraries.get(name); 7929 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7930 mSharedLibraries.remove(name); 7931 if (DEBUG_REMOVE && chatty) { 7932 if (r == null) { 7933 r = new StringBuilder(256); 7934 } else { 7935 r.append(' '); 7936 } 7937 r.append(name); 7938 } 7939 } 7940 } 7941 } 7942 } 7943 if (r != null) { 7944 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7945 } 7946 } 7947 7948 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7949 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7950 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7951 return true; 7952 } 7953 } 7954 return false; 7955 } 7956 7957 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7958 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7959 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7960 7961 private void updatePermissionsLPw(String changingPkg, 7962 PackageParser.Package pkgInfo, int flags) { 7963 // Make sure there are no dangling permission trees. 7964 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7965 while (it.hasNext()) { 7966 final BasePermission bp = it.next(); 7967 if (bp.packageSetting == null) { 7968 // We may not yet have parsed the package, so just see if 7969 // we still know about its settings. 7970 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7971 } 7972 if (bp.packageSetting == null) { 7973 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7974 + " from package " + bp.sourcePackage); 7975 it.remove(); 7976 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7977 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7978 Slog.i(TAG, "Removing old permission tree: " + bp.name 7979 + " from package " + bp.sourcePackage); 7980 flags |= UPDATE_PERMISSIONS_ALL; 7981 it.remove(); 7982 } 7983 } 7984 } 7985 7986 // Make sure all dynamic permissions have been assigned to a package, 7987 // and make sure there are no dangling permissions. 7988 it = mSettings.mPermissions.values().iterator(); 7989 while (it.hasNext()) { 7990 final BasePermission bp = it.next(); 7991 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7992 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7993 + bp.name + " pkg=" + bp.sourcePackage 7994 + " info=" + bp.pendingInfo); 7995 if (bp.packageSetting == null && bp.pendingInfo != null) { 7996 final BasePermission tree = findPermissionTreeLP(bp.name); 7997 if (tree != null && tree.perm != null) { 7998 bp.packageSetting = tree.packageSetting; 7999 bp.perm = new PackageParser.Permission(tree.perm.owner, 8000 new PermissionInfo(bp.pendingInfo)); 8001 bp.perm.info.packageName = tree.perm.info.packageName; 8002 bp.perm.info.name = bp.name; 8003 bp.uid = tree.uid; 8004 } 8005 } 8006 } 8007 if (bp.packageSetting == null) { 8008 // We may not yet have parsed the package, so just see if 8009 // we still know about its settings. 8010 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8011 } 8012 if (bp.packageSetting == null) { 8013 Slog.w(TAG, "Removing dangling permission: " + bp.name 8014 + " from package " + bp.sourcePackage); 8015 it.remove(); 8016 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8017 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8018 Slog.i(TAG, "Removing old permission: " + bp.name 8019 + " from package " + bp.sourcePackage); 8020 flags |= UPDATE_PERMISSIONS_ALL; 8021 it.remove(); 8022 } 8023 } 8024 } 8025 8026 // Now update the permissions for all packages, in particular 8027 // replace the granted permissions of the system packages. 8028 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8029 for (PackageParser.Package pkg : mPackages.values()) { 8030 if (pkg != pkgInfo) { 8031 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8032 changingPkg); 8033 } 8034 } 8035 } 8036 8037 if (pkgInfo != null) { 8038 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8039 } 8040 } 8041 8042 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8043 String packageOfInterest) { 8044 // IMPORTANT: There are two types of permissions: install and runtime. 8045 // Install time permissions are granted when the app is installed to 8046 // all device users and users added in the future. Runtime permissions 8047 // are granted at runtime explicitly to specific users. Normal and signature 8048 // protected permissions are install time permissions. Dangerous permissions 8049 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8050 // otherwise they are runtime permissions. This function does not manage 8051 // runtime permissions except for the case an app targeting Lollipop MR1 8052 // being upgraded to target a newer SDK, in which case dangerous permissions 8053 // are transformed from install time to runtime ones. 8054 8055 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8056 if (ps == null) { 8057 return; 8058 } 8059 8060 PermissionsState permissionsState = ps.getPermissionsState(); 8061 PermissionsState origPermissions = permissionsState; 8062 8063 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8064 8065 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8066 8067 boolean changedInstallPermission = false; 8068 8069 if (replace) { 8070 ps.installPermissionsFixed = false; 8071 if (!ps.isSharedUser()) { 8072 origPermissions = new PermissionsState(permissionsState); 8073 permissionsState.reset(); 8074 } 8075 } 8076 8077 permissionsState.setGlobalGids(mGlobalGids); 8078 8079 final int N = pkg.requestedPermissions.size(); 8080 for (int i=0; i<N; i++) { 8081 final String name = pkg.requestedPermissions.get(i); 8082 final BasePermission bp = mSettings.mPermissions.get(name); 8083 8084 if (DEBUG_INSTALL) { 8085 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8086 } 8087 8088 if (bp == null || bp.packageSetting == null) { 8089 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8090 Slog.w(TAG, "Unknown permission " + name 8091 + " in package " + pkg.packageName); 8092 } 8093 continue; 8094 } 8095 8096 final String perm = bp.name; 8097 boolean allowedSig = false; 8098 int grant = GRANT_DENIED; 8099 8100 // Keep track of app op permissions. 8101 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8102 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8103 if (pkgs == null) { 8104 pkgs = new ArraySet<>(); 8105 mAppOpPermissionPackages.put(bp.name, pkgs); 8106 } 8107 pkgs.add(pkg.packageName); 8108 } 8109 8110 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8111 switch (level) { 8112 case PermissionInfo.PROTECTION_NORMAL: { 8113 // For all apps normal permissions are install time ones. 8114 grant = GRANT_INSTALL; 8115 } break; 8116 8117 case PermissionInfo.PROTECTION_DANGEROUS: { 8118 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8119 // For legacy apps dangerous permissions are install time ones. 8120 grant = GRANT_INSTALL_LEGACY; 8121 } else if (origPermissions.hasInstallPermission(bp.name)) { 8122 // For legacy apps that became modern, install becomes runtime. 8123 grant = GRANT_UPGRADE; 8124 } else { 8125 // For modern apps keep runtime permissions unchanged. 8126 grant = GRANT_RUNTIME; 8127 } 8128 } break; 8129 8130 case PermissionInfo.PROTECTION_SIGNATURE: { 8131 // For all apps signature permissions are install time ones. 8132 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8133 if (allowedSig) { 8134 grant = GRANT_INSTALL; 8135 } 8136 } break; 8137 } 8138 8139 if (DEBUG_INSTALL) { 8140 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8141 } 8142 8143 if (grant != GRANT_DENIED) { 8144 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8145 // If this is an existing, non-system package, then 8146 // we can't add any new permissions to it. 8147 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8148 // Except... if this is a permission that was added 8149 // to the platform (note: need to only do this when 8150 // updating the platform). 8151 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8152 grant = GRANT_DENIED; 8153 } 8154 } 8155 } 8156 8157 switch (grant) { 8158 case GRANT_INSTALL: { 8159 // Revoke this as runtime permission to handle the case of 8160 // a runtime permission being downgraded to an install one. 8161 for (int userId : UserManagerService.getInstance().getUserIds()) { 8162 if (origPermissions.getRuntimePermissionState( 8163 bp.name, userId) != null) { 8164 // Revoke the runtime permission and clear the flags. 8165 origPermissions.revokeRuntimePermission(bp, userId); 8166 origPermissions.updatePermissionFlags(bp, userId, 8167 PackageManager.MASK_PERMISSION_FLAGS, 0); 8168 // If we revoked a permission permission, we have to write. 8169 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8170 changedRuntimePermissionUserIds, userId); 8171 } 8172 } 8173 // Grant an install permission. 8174 if (permissionsState.grantInstallPermission(bp) != 8175 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8176 changedInstallPermission = true; 8177 } 8178 } break; 8179 8180 case GRANT_INSTALL_LEGACY: { 8181 // Grant an install permission. 8182 if (permissionsState.grantInstallPermission(bp) != 8183 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8184 changedInstallPermission = true; 8185 } 8186 } break; 8187 8188 case GRANT_RUNTIME: { 8189 // Grant previously granted runtime permissions. 8190 for (int userId : UserManagerService.getInstance().getUserIds()) { 8191 PermissionState permissionState = origPermissions 8192 .getRuntimePermissionState(bp.name, userId); 8193 final int flags = permissionState != null 8194 ? permissionState.getFlags() : 0; 8195 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8196 if (permissionsState.grantRuntimePermission(bp, userId) == 8197 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8198 // If we cannot put the permission as it was, we have to write. 8199 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8200 changedRuntimePermissionUserIds, userId); 8201 } 8202 } 8203 // Propagate the permission flags. 8204 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8205 } 8206 } break; 8207 8208 case GRANT_UPGRADE: { 8209 // Grant runtime permissions for a previously held install permission. 8210 PermissionState permissionState = origPermissions 8211 .getInstallPermissionState(bp.name); 8212 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8213 8214 if (origPermissions.revokeInstallPermission(bp) 8215 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8216 // We will be transferring the permission flags, so clear them. 8217 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8218 PackageManager.MASK_PERMISSION_FLAGS, 0); 8219 changedInstallPermission = true; 8220 } 8221 8222 // If the permission is not to be promoted to runtime we ignore it and 8223 // also its other flags as they are not applicable to install permissions. 8224 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8225 for (int userId : currentUserIds) { 8226 if (permissionsState.grantRuntimePermission(bp, userId) != 8227 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8228 // Transfer the permission flags. 8229 permissionsState.updatePermissionFlags(bp, userId, 8230 flags, flags); 8231 // If we granted the permission, we have to write. 8232 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8233 changedRuntimePermissionUserIds, userId); 8234 } 8235 } 8236 } 8237 } break; 8238 8239 default: { 8240 if (packageOfInterest == null 8241 || packageOfInterest.equals(pkg.packageName)) { 8242 Slog.w(TAG, "Not granting permission " + perm 8243 + " to package " + pkg.packageName 8244 + " because it was previously installed without"); 8245 } 8246 } break; 8247 } 8248 } else { 8249 if (permissionsState.revokeInstallPermission(bp) != 8250 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8251 // Also drop the permission flags. 8252 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8253 PackageManager.MASK_PERMISSION_FLAGS, 0); 8254 changedInstallPermission = true; 8255 Slog.i(TAG, "Un-granting permission " + perm 8256 + " from package " + pkg.packageName 8257 + " (protectionLevel=" + bp.protectionLevel 8258 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8259 + ")"); 8260 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8261 // Don't print warning for app op permissions, since it is fine for them 8262 // not to be granted, there is a UI for the user to decide. 8263 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8264 Slog.w(TAG, "Not granting permission " + perm 8265 + " to package " + pkg.packageName 8266 + " (protectionLevel=" + bp.protectionLevel 8267 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8268 + ")"); 8269 } 8270 } 8271 } 8272 } 8273 8274 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8275 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8276 // This is the first that we have heard about this package, so the 8277 // permissions we have now selected are fixed until explicitly 8278 // changed. 8279 ps.installPermissionsFixed = true; 8280 } 8281 8282 // Persist the runtime permissions state for users with changes. 8283 for (int userId : changedRuntimePermissionUserIds) { 8284 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8285 } 8286 } 8287 8288 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8289 boolean allowed = false; 8290 final int NP = PackageParser.NEW_PERMISSIONS.length; 8291 for (int ip=0; ip<NP; ip++) { 8292 final PackageParser.NewPermissionInfo npi 8293 = PackageParser.NEW_PERMISSIONS[ip]; 8294 if (npi.name.equals(perm) 8295 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8296 allowed = true; 8297 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8298 + pkg.packageName); 8299 break; 8300 } 8301 } 8302 return allowed; 8303 } 8304 8305 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8306 BasePermission bp, PermissionsState origPermissions) { 8307 boolean allowed; 8308 allowed = (compareSignatures( 8309 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8310 == PackageManager.SIGNATURE_MATCH) 8311 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8312 == PackageManager.SIGNATURE_MATCH); 8313 if (!allowed && (bp.protectionLevel 8314 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8315 if (isSystemApp(pkg)) { 8316 // For updated system applications, a system permission 8317 // is granted only if it had been defined by the original application. 8318 if (pkg.isUpdatedSystemApp()) { 8319 final PackageSetting sysPs = mSettings 8320 .getDisabledSystemPkgLPr(pkg.packageName); 8321 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8322 // If the original was granted this permission, we take 8323 // that grant decision as read and propagate it to the 8324 // update. 8325 if (sysPs.isPrivileged()) { 8326 allowed = true; 8327 } 8328 } else { 8329 // The system apk may have been updated with an older 8330 // version of the one on the data partition, but which 8331 // granted a new system permission that it didn't have 8332 // before. In this case we do want to allow the app to 8333 // now get the new permission if the ancestral apk is 8334 // privileged to get it. 8335 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8336 for (int j=0; 8337 j<sysPs.pkg.requestedPermissions.size(); j++) { 8338 if (perm.equals( 8339 sysPs.pkg.requestedPermissions.get(j))) { 8340 allowed = true; 8341 break; 8342 } 8343 } 8344 } 8345 } 8346 } else { 8347 allowed = isPrivilegedApp(pkg); 8348 } 8349 } 8350 } 8351 if (!allowed && (bp.protectionLevel 8352 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8353 // For development permissions, a development permission 8354 // is granted only if it was already granted. 8355 allowed = origPermissions.hasInstallPermission(perm); 8356 } 8357 return allowed; 8358 } 8359 8360 final class ActivityIntentResolver 8361 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8362 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8363 boolean defaultOnly, int userId) { 8364 if (!sUserManager.exists(userId)) return null; 8365 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8366 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8367 } 8368 8369 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8370 int userId) { 8371 if (!sUserManager.exists(userId)) return null; 8372 mFlags = flags; 8373 return super.queryIntent(intent, resolvedType, 8374 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8375 } 8376 8377 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8378 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8379 if (!sUserManager.exists(userId)) return null; 8380 if (packageActivities == null) { 8381 return null; 8382 } 8383 mFlags = flags; 8384 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8385 final int N = packageActivities.size(); 8386 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8387 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8388 8389 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8390 for (int i = 0; i < N; ++i) { 8391 intentFilters = packageActivities.get(i).intents; 8392 if (intentFilters != null && intentFilters.size() > 0) { 8393 PackageParser.ActivityIntentInfo[] array = 8394 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8395 intentFilters.toArray(array); 8396 listCut.add(array); 8397 } 8398 } 8399 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8400 } 8401 8402 public final void addActivity(PackageParser.Activity a, String type) { 8403 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8404 mActivities.put(a.getComponentName(), a); 8405 if (DEBUG_SHOW_INFO) 8406 Log.v( 8407 TAG, " " + type + " " + 8408 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8409 if (DEBUG_SHOW_INFO) 8410 Log.v(TAG, " Class=" + a.info.name); 8411 final int NI = a.intents.size(); 8412 for (int j=0; j<NI; j++) { 8413 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8414 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8415 intent.setPriority(0); 8416 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8417 + a.className + " with priority > 0, forcing to 0"); 8418 } 8419 if (DEBUG_SHOW_INFO) { 8420 Log.v(TAG, " IntentFilter:"); 8421 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8422 } 8423 if (!intent.debugCheck()) { 8424 Log.w(TAG, "==> For Activity " + a.info.name); 8425 } 8426 addFilter(intent); 8427 } 8428 } 8429 8430 public final void removeActivity(PackageParser.Activity a, String type) { 8431 mActivities.remove(a.getComponentName()); 8432 if (DEBUG_SHOW_INFO) { 8433 Log.v(TAG, " " + type + " " 8434 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8435 : a.info.name) + ":"); 8436 Log.v(TAG, " Class=" + a.info.name); 8437 } 8438 final int NI = a.intents.size(); 8439 for (int j=0; j<NI; j++) { 8440 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8441 if (DEBUG_SHOW_INFO) { 8442 Log.v(TAG, " IntentFilter:"); 8443 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8444 } 8445 removeFilter(intent); 8446 } 8447 } 8448 8449 @Override 8450 protected boolean allowFilterResult( 8451 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8452 ActivityInfo filterAi = filter.activity.info; 8453 for (int i=dest.size()-1; i>=0; i--) { 8454 ActivityInfo destAi = dest.get(i).activityInfo; 8455 if (destAi.name == filterAi.name 8456 && destAi.packageName == filterAi.packageName) { 8457 return false; 8458 } 8459 } 8460 return true; 8461 } 8462 8463 @Override 8464 protected ActivityIntentInfo[] newArray(int size) { 8465 return new ActivityIntentInfo[size]; 8466 } 8467 8468 @Override 8469 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8470 if (!sUserManager.exists(userId)) return true; 8471 PackageParser.Package p = filter.activity.owner; 8472 if (p != null) { 8473 PackageSetting ps = (PackageSetting)p.mExtras; 8474 if (ps != null) { 8475 // System apps are never considered stopped for purposes of 8476 // filtering, because there may be no way for the user to 8477 // actually re-launch them. 8478 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8479 && ps.getStopped(userId); 8480 } 8481 } 8482 return false; 8483 } 8484 8485 @Override 8486 protected boolean isPackageForFilter(String packageName, 8487 PackageParser.ActivityIntentInfo info) { 8488 return packageName.equals(info.activity.owner.packageName); 8489 } 8490 8491 @Override 8492 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8493 int match, int userId) { 8494 if (!sUserManager.exists(userId)) return null; 8495 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8496 return null; 8497 } 8498 final PackageParser.Activity activity = info.activity; 8499 if (mSafeMode && (activity.info.applicationInfo.flags 8500 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8501 return null; 8502 } 8503 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8504 if (ps == null) { 8505 return null; 8506 } 8507 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8508 ps.readUserState(userId), userId); 8509 if (ai == null) { 8510 return null; 8511 } 8512 final ResolveInfo res = new ResolveInfo(); 8513 res.activityInfo = ai; 8514 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8515 res.filter = info; 8516 } 8517 if (info != null) { 8518 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8519 } 8520 res.priority = info.getPriority(); 8521 res.preferredOrder = activity.owner.mPreferredOrder; 8522 //System.out.println("Result: " + res.activityInfo.className + 8523 // " = " + res.priority); 8524 res.match = match; 8525 res.isDefault = info.hasDefault; 8526 res.labelRes = info.labelRes; 8527 res.nonLocalizedLabel = info.nonLocalizedLabel; 8528 if (userNeedsBadging(userId)) { 8529 res.noResourceId = true; 8530 } else { 8531 res.icon = info.icon; 8532 } 8533 res.iconResourceId = info.icon; 8534 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8535 return res; 8536 } 8537 8538 @Override 8539 protected void sortResults(List<ResolveInfo> results) { 8540 Collections.sort(results, mResolvePrioritySorter); 8541 } 8542 8543 @Override 8544 protected void dumpFilter(PrintWriter out, String prefix, 8545 PackageParser.ActivityIntentInfo filter) { 8546 out.print(prefix); out.print( 8547 Integer.toHexString(System.identityHashCode(filter.activity))); 8548 out.print(' '); 8549 filter.activity.printComponentShortName(out); 8550 out.print(" filter "); 8551 out.println(Integer.toHexString(System.identityHashCode(filter))); 8552 } 8553 8554 @Override 8555 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8556 return filter.activity; 8557 } 8558 8559 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8560 PackageParser.Activity activity = (PackageParser.Activity)label; 8561 out.print(prefix); out.print( 8562 Integer.toHexString(System.identityHashCode(activity))); 8563 out.print(' '); 8564 activity.printComponentShortName(out); 8565 if (count > 1) { 8566 out.print(" ("); out.print(count); out.print(" filters)"); 8567 } 8568 out.println(); 8569 } 8570 8571// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8572// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8573// final List<ResolveInfo> retList = Lists.newArrayList(); 8574// while (i.hasNext()) { 8575// final ResolveInfo resolveInfo = i.next(); 8576// if (isEnabledLP(resolveInfo.activityInfo)) { 8577// retList.add(resolveInfo); 8578// } 8579// } 8580// return retList; 8581// } 8582 8583 // Keys are String (activity class name), values are Activity. 8584 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8585 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8586 private int mFlags; 8587 } 8588 8589 private final class ServiceIntentResolver 8590 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8591 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8592 boolean defaultOnly, int userId) { 8593 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8594 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8595 } 8596 8597 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8598 int userId) { 8599 if (!sUserManager.exists(userId)) return null; 8600 mFlags = flags; 8601 return super.queryIntent(intent, resolvedType, 8602 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8603 } 8604 8605 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8606 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8607 if (!sUserManager.exists(userId)) return null; 8608 if (packageServices == null) { 8609 return null; 8610 } 8611 mFlags = flags; 8612 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8613 final int N = packageServices.size(); 8614 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8615 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8616 8617 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8618 for (int i = 0; i < N; ++i) { 8619 intentFilters = packageServices.get(i).intents; 8620 if (intentFilters != null && intentFilters.size() > 0) { 8621 PackageParser.ServiceIntentInfo[] array = 8622 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8623 intentFilters.toArray(array); 8624 listCut.add(array); 8625 } 8626 } 8627 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8628 } 8629 8630 public final void addService(PackageParser.Service s) { 8631 mServices.put(s.getComponentName(), s); 8632 if (DEBUG_SHOW_INFO) { 8633 Log.v(TAG, " " 8634 + (s.info.nonLocalizedLabel != null 8635 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8636 Log.v(TAG, " Class=" + s.info.name); 8637 } 8638 final int NI = s.intents.size(); 8639 int j; 8640 for (j=0; j<NI; j++) { 8641 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8642 if (DEBUG_SHOW_INFO) { 8643 Log.v(TAG, " IntentFilter:"); 8644 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8645 } 8646 if (!intent.debugCheck()) { 8647 Log.w(TAG, "==> For Service " + s.info.name); 8648 } 8649 addFilter(intent); 8650 } 8651 } 8652 8653 public final void removeService(PackageParser.Service s) { 8654 mServices.remove(s.getComponentName()); 8655 if (DEBUG_SHOW_INFO) { 8656 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8657 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8658 Log.v(TAG, " Class=" + s.info.name); 8659 } 8660 final int NI = s.intents.size(); 8661 int j; 8662 for (j=0; j<NI; j++) { 8663 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8664 if (DEBUG_SHOW_INFO) { 8665 Log.v(TAG, " IntentFilter:"); 8666 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8667 } 8668 removeFilter(intent); 8669 } 8670 } 8671 8672 @Override 8673 protected boolean allowFilterResult( 8674 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8675 ServiceInfo filterSi = filter.service.info; 8676 for (int i=dest.size()-1; i>=0; i--) { 8677 ServiceInfo destAi = dest.get(i).serviceInfo; 8678 if (destAi.name == filterSi.name 8679 && destAi.packageName == filterSi.packageName) { 8680 return false; 8681 } 8682 } 8683 return true; 8684 } 8685 8686 @Override 8687 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8688 return new PackageParser.ServiceIntentInfo[size]; 8689 } 8690 8691 @Override 8692 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8693 if (!sUserManager.exists(userId)) return true; 8694 PackageParser.Package p = filter.service.owner; 8695 if (p != null) { 8696 PackageSetting ps = (PackageSetting)p.mExtras; 8697 if (ps != null) { 8698 // System apps are never considered stopped for purposes of 8699 // filtering, because there may be no way for the user to 8700 // actually re-launch them. 8701 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8702 && ps.getStopped(userId); 8703 } 8704 } 8705 return false; 8706 } 8707 8708 @Override 8709 protected boolean isPackageForFilter(String packageName, 8710 PackageParser.ServiceIntentInfo info) { 8711 return packageName.equals(info.service.owner.packageName); 8712 } 8713 8714 @Override 8715 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8716 int match, int userId) { 8717 if (!sUserManager.exists(userId)) return null; 8718 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8719 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8720 return null; 8721 } 8722 final PackageParser.Service service = info.service; 8723 if (mSafeMode && (service.info.applicationInfo.flags 8724 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8725 return null; 8726 } 8727 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8728 if (ps == null) { 8729 return null; 8730 } 8731 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8732 ps.readUserState(userId), userId); 8733 if (si == null) { 8734 return null; 8735 } 8736 final ResolveInfo res = new ResolveInfo(); 8737 res.serviceInfo = si; 8738 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8739 res.filter = filter; 8740 } 8741 res.priority = info.getPriority(); 8742 res.preferredOrder = service.owner.mPreferredOrder; 8743 res.match = match; 8744 res.isDefault = info.hasDefault; 8745 res.labelRes = info.labelRes; 8746 res.nonLocalizedLabel = info.nonLocalizedLabel; 8747 res.icon = info.icon; 8748 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8749 return res; 8750 } 8751 8752 @Override 8753 protected void sortResults(List<ResolveInfo> results) { 8754 Collections.sort(results, mResolvePrioritySorter); 8755 } 8756 8757 @Override 8758 protected void dumpFilter(PrintWriter out, String prefix, 8759 PackageParser.ServiceIntentInfo filter) { 8760 out.print(prefix); out.print( 8761 Integer.toHexString(System.identityHashCode(filter.service))); 8762 out.print(' '); 8763 filter.service.printComponentShortName(out); 8764 out.print(" filter "); 8765 out.println(Integer.toHexString(System.identityHashCode(filter))); 8766 } 8767 8768 @Override 8769 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8770 return filter.service; 8771 } 8772 8773 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8774 PackageParser.Service service = (PackageParser.Service)label; 8775 out.print(prefix); out.print( 8776 Integer.toHexString(System.identityHashCode(service))); 8777 out.print(' '); 8778 service.printComponentShortName(out); 8779 if (count > 1) { 8780 out.print(" ("); out.print(count); out.print(" filters)"); 8781 } 8782 out.println(); 8783 } 8784 8785// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8786// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8787// final List<ResolveInfo> retList = Lists.newArrayList(); 8788// while (i.hasNext()) { 8789// final ResolveInfo resolveInfo = (ResolveInfo) i; 8790// if (isEnabledLP(resolveInfo.serviceInfo)) { 8791// retList.add(resolveInfo); 8792// } 8793// } 8794// return retList; 8795// } 8796 8797 // Keys are String (activity class name), values are Activity. 8798 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8799 = new ArrayMap<ComponentName, PackageParser.Service>(); 8800 private int mFlags; 8801 }; 8802 8803 private final class ProviderIntentResolver 8804 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8805 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8806 boolean defaultOnly, int userId) { 8807 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8808 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8809 } 8810 8811 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8812 int userId) { 8813 if (!sUserManager.exists(userId)) 8814 return null; 8815 mFlags = flags; 8816 return super.queryIntent(intent, resolvedType, 8817 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8818 } 8819 8820 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8821 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8822 if (!sUserManager.exists(userId)) 8823 return null; 8824 if (packageProviders == null) { 8825 return null; 8826 } 8827 mFlags = flags; 8828 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8829 final int N = packageProviders.size(); 8830 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8831 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8832 8833 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8834 for (int i = 0; i < N; ++i) { 8835 intentFilters = packageProviders.get(i).intents; 8836 if (intentFilters != null && intentFilters.size() > 0) { 8837 PackageParser.ProviderIntentInfo[] array = 8838 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8839 intentFilters.toArray(array); 8840 listCut.add(array); 8841 } 8842 } 8843 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8844 } 8845 8846 public final void addProvider(PackageParser.Provider p) { 8847 if (mProviders.containsKey(p.getComponentName())) { 8848 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8849 return; 8850 } 8851 8852 mProviders.put(p.getComponentName(), p); 8853 if (DEBUG_SHOW_INFO) { 8854 Log.v(TAG, " " 8855 + (p.info.nonLocalizedLabel != null 8856 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8857 Log.v(TAG, " Class=" + p.info.name); 8858 } 8859 final int NI = p.intents.size(); 8860 int j; 8861 for (j = 0; j < NI; j++) { 8862 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8863 if (DEBUG_SHOW_INFO) { 8864 Log.v(TAG, " IntentFilter:"); 8865 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8866 } 8867 if (!intent.debugCheck()) { 8868 Log.w(TAG, "==> For Provider " + p.info.name); 8869 } 8870 addFilter(intent); 8871 } 8872 } 8873 8874 public final void removeProvider(PackageParser.Provider p) { 8875 mProviders.remove(p.getComponentName()); 8876 if (DEBUG_SHOW_INFO) { 8877 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8878 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8879 Log.v(TAG, " Class=" + p.info.name); 8880 } 8881 final int NI = p.intents.size(); 8882 int j; 8883 for (j = 0; j < NI; j++) { 8884 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8885 if (DEBUG_SHOW_INFO) { 8886 Log.v(TAG, " IntentFilter:"); 8887 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8888 } 8889 removeFilter(intent); 8890 } 8891 } 8892 8893 @Override 8894 protected boolean allowFilterResult( 8895 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8896 ProviderInfo filterPi = filter.provider.info; 8897 for (int i = dest.size() - 1; i >= 0; i--) { 8898 ProviderInfo destPi = dest.get(i).providerInfo; 8899 if (destPi.name == filterPi.name 8900 && destPi.packageName == filterPi.packageName) { 8901 return false; 8902 } 8903 } 8904 return true; 8905 } 8906 8907 @Override 8908 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8909 return new PackageParser.ProviderIntentInfo[size]; 8910 } 8911 8912 @Override 8913 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8914 if (!sUserManager.exists(userId)) 8915 return true; 8916 PackageParser.Package p = filter.provider.owner; 8917 if (p != null) { 8918 PackageSetting ps = (PackageSetting) p.mExtras; 8919 if (ps != null) { 8920 // System apps are never considered stopped for purposes of 8921 // filtering, because there may be no way for the user to 8922 // actually re-launch them. 8923 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8924 && ps.getStopped(userId); 8925 } 8926 } 8927 return false; 8928 } 8929 8930 @Override 8931 protected boolean isPackageForFilter(String packageName, 8932 PackageParser.ProviderIntentInfo info) { 8933 return packageName.equals(info.provider.owner.packageName); 8934 } 8935 8936 @Override 8937 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8938 int match, int userId) { 8939 if (!sUserManager.exists(userId)) 8940 return null; 8941 final PackageParser.ProviderIntentInfo info = filter; 8942 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8943 return null; 8944 } 8945 final PackageParser.Provider provider = info.provider; 8946 if (mSafeMode && (provider.info.applicationInfo.flags 8947 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8948 return null; 8949 } 8950 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8951 if (ps == null) { 8952 return null; 8953 } 8954 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8955 ps.readUserState(userId), userId); 8956 if (pi == null) { 8957 return null; 8958 } 8959 final ResolveInfo res = new ResolveInfo(); 8960 res.providerInfo = pi; 8961 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8962 res.filter = filter; 8963 } 8964 res.priority = info.getPriority(); 8965 res.preferredOrder = provider.owner.mPreferredOrder; 8966 res.match = match; 8967 res.isDefault = info.hasDefault; 8968 res.labelRes = info.labelRes; 8969 res.nonLocalizedLabel = info.nonLocalizedLabel; 8970 res.icon = info.icon; 8971 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8972 return res; 8973 } 8974 8975 @Override 8976 protected void sortResults(List<ResolveInfo> results) { 8977 Collections.sort(results, mResolvePrioritySorter); 8978 } 8979 8980 @Override 8981 protected void dumpFilter(PrintWriter out, String prefix, 8982 PackageParser.ProviderIntentInfo filter) { 8983 out.print(prefix); 8984 out.print( 8985 Integer.toHexString(System.identityHashCode(filter.provider))); 8986 out.print(' '); 8987 filter.provider.printComponentShortName(out); 8988 out.print(" filter "); 8989 out.println(Integer.toHexString(System.identityHashCode(filter))); 8990 } 8991 8992 @Override 8993 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8994 return filter.provider; 8995 } 8996 8997 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8998 PackageParser.Provider provider = (PackageParser.Provider)label; 8999 out.print(prefix); out.print( 9000 Integer.toHexString(System.identityHashCode(provider))); 9001 out.print(' '); 9002 provider.printComponentShortName(out); 9003 if (count > 1) { 9004 out.print(" ("); out.print(count); out.print(" filters)"); 9005 } 9006 out.println(); 9007 } 9008 9009 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9010 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9011 private int mFlags; 9012 }; 9013 9014 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9015 new Comparator<ResolveInfo>() { 9016 public int compare(ResolveInfo r1, ResolveInfo r2) { 9017 int v1 = r1.priority; 9018 int v2 = r2.priority; 9019 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9020 if (v1 != v2) { 9021 return (v1 > v2) ? -1 : 1; 9022 } 9023 v1 = r1.preferredOrder; 9024 v2 = r2.preferredOrder; 9025 if (v1 != v2) { 9026 return (v1 > v2) ? -1 : 1; 9027 } 9028 if (r1.isDefault != r2.isDefault) { 9029 return r1.isDefault ? -1 : 1; 9030 } 9031 v1 = r1.match; 9032 v2 = r2.match; 9033 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9034 if (v1 != v2) { 9035 return (v1 > v2) ? -1 : 1; 9036 } 9037 if (r1.system != r2.system) { 9038 return r1.system ? -1 : 1; 9039 } 9040 return 0; 9041 } 9042 }; 9043 9044 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9045 new Comparator<ProviderInfo>() { 9046 public int compare(ProviderInfo p1, ProviderInfo p2) { 9047 final int v1 = p1.initOrder; 9048 final int v2 = p2.initOrder; 9049 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9050 } 9051 }; 9052 9053 final void sendPackageBroadcast(final String action, final String pkg, 9054 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9055 final int[] userIds) { 9056 mHandler.post(new Runnable() { 9057 @Override 9058 public void run() { 9059 try { 9060 final IActivityManager am = ActivityManagerNative.getDefault(); 9061 if (am == null) return; 9062 final int[] resolvedUserIds; 9063 if (userIds == null) { 9064 resolvedUserIds = am.getRunningUserIds(); 9065 } else { 9066 resolvedUserIds = userIds; 9067 } 9068 for (int id : resolvedUserIds) { 9069 final Intent intent = new Intent(action, 9070 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9071 if (extras != null) { 9072 intent.putExtras(extras); 9073 } 9074 if (targetPkg != null) { 9075 intent.setPackage(targetPkg); 9076 } 9077 // Modify the UID when posting to other users 9078 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9079 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9080 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9081 intent.putExtra(Intent.EXTRA_UID, uid); 9082 } 9083 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9084 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9085 if (DEBUG_BROADCASTS) { 9086 RuntimeException here = new RuntimeException("here"); 9087 here.fillInStackTrace(); 9088 Slog.d(TAG, "Sending to user " + id + ": " 9089 + intent.toShortString(false, true, false, false) 9090 + " " + intent.getExtras(), here); 9091 } 9092 am.broadcastIntent(null, intent, null, finishedReceiver, 9093 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9094 null, finishedReceiver != null, false, id); 9095 } 9096 } catch (RemoteException ex) { 9097 } 9098 } 9099 }); 9100 } 9101 9102 /** 9103 * Check if the external storage media is available. This is true if there 9104 * is a mounted external storage medium or if the external storage is 9105 * emulated. 9106 */ 9107 private boolean isExternalMediaAvailable() { 9108 return mMediaMounted || Environment.isExternalStorageEmulated(); 9109 } 9110 9111 @Override 9112 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9113 // writer 9114 synchronized (mPackages) { 9115 if (!isExternalMediaAvailable()) { 9116 // If the external storage is no longer mounted at this point, 9117 // the caller may not have been able to delete all of this 9118 // packages files and can not delete any more. Bail. 9119 return null; 9120 } 9121 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9122 if (lastPackage != null) { 9123 pkgs.remove(lastPackage); 9124 } 9125 if (pkgs.size() > 0) { 9126 return pkgs.get(0); 9127 } 9128 } 9129 return null; 9130 } 9131 9132 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9133 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9134 userId, andCode ? 1 : 0, packageName); 9135 if (mSystemReady) { 9136 msg.sendToTarget(); 9137 } else { 9138 if (mPostSystemReadyMessages == null) { 9139 mPostSystemReadyMessages = new ArrayList<>(); 9140 } 9141 mPostSystemReadyMessages.add(msg); 9142 } 9143 } 9144 9145 void startCleaningPackages() { 9146 // reader 9147 synchronized (mPackages) { 9148 if (!isExternalMediaAvailable()) { 9149 return; 9150 } 9151 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9152 return; 9153 } 9154 } 9155 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9156 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9157 IActivityManager am = ActivityManagerNative.getDefault(); 9158 if (am != null) { 9159 try { 9160 am.startService(null, intent, null, UserHandle.USER_OWNER); 9161 } catch (RemoteException e) { 9162 } 9163 } 9164 } 9165 9166 @Override 9167 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9168 int installFlags, String installerPackageName, VerificationParams verificationParams, 9169 String packageAbiOverride) { 9170 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9171 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9172 } 9173 9174 @Override 9175 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9176 int installFlags, String installerPackageName, VerificationParams verificationParams, 9177 String packageAbiOverride, int userId) { 9178 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9179 9180 final int callingUid = Binder.getCallingUid(); 9181 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9182 9183 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9184 try { 9185 if (observer != null) { 9186 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9187 } 9188 } catch (RemoteException re) { 9189 } 9190 return; 9191 } 9192 9193 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9194 installFlags |= PackageManager.INSTALL_FROM_ADB; 9195 9196 } else { 9197 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9198 // about installerPackageName. 9199 9200 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9201 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9202 } 9203 9204 UserHandle user; 9205 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9206 user = UserHandle.ALL; 9207 } else { 9208 user = new UserHandle(userId); 9209 } 9210 9211 // Only system components can circumvent runtime permissions when installing. 9212 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9213 && mContext.checkCallingOrSelfPermission(Manifest.permission 9214 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9215 throw new SecurityException("You need the " 9216 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9217 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9218 } 9219 9220 verificationParams.setInstallerUid(callingUid); 9221 9222 final File originFile = new File(originPath); 9223 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9224 9225 final Message msg = mHandler.obtainMessage(INIT_COPY); 9226 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9227 null, verificationParams, user, packageAbiOverride); 9228 mHandler.sendMessage(msg); 9229 } 9230 9231 void installStage(String packageName, File stagedDir, String stagedCid, 9232 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9233 String installerPackageName, int installerUid, UserHandle user) { 9234 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9235 params.referrerUri, installerUid, null); 9236 verifParams.setInstallerUid(installerUid); 9237 9238 final OriginInfo origin; 9239 if (stagedDir != null) { 9240 origin = OriginInfo.fromStagedFile(stagedDir); 9241 } else { 9242 origin = OriginInfo.fromStagedContainer(stagedCid); 9243 } 9244 9245 final Message msg = mHandler.obtainMessage(INIT_COPY); 9246 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9247 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9248 mHandler.sendMessage(msg); 9249 } 9250 9251 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9252 Bundle extras = new Bundle(1); 9253 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9254 9255 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9256 packageName, extras, null, null, new int[] {userId}); 9257 try { 9258 IActivityManager am = ActivityManagerNative.getDefault(); 9259 final boolean isSystem = 9260 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9261 if (isSystem && am.isUserRunning(userId, false)) { 9262 // The just-installed/enabled app is bundled on the system, so presumed 9263 // to be able to run automatically without needing an explicit launch. 9264 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9265 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9266 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9267 .setPackage(packageName); 9268 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9269 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9270 } 9271 } catch (RemoteException e) { 9272 // shouldn't happen 9273 Slog.w(TAG, "Unable to bootstrap installed package", e); 9274 } 9275 } 9276 9277 @Override 9278 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9279 int userId) { 9280 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9281 PackageSetting pkgSetting; 9282 final int uid = Binder.getCallingUid(); 9283 enforceCrossUserPermission(uid, userId, true, true, 9284 "setApplicationHiddenSetting for user " + userId); 9285 9286 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9287 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9288 return false; 9289 } 9290 9291 long callingId = Binder.clearCallingIdentity(); 9292 try { 9293 boolean sendAdded = false; 9294 boolean sendRemoved = false; 9295 // writer 9296 synchronized (mPackages) { 9297 pkgSetting = mSettings.mPackages.get(packageName); 9298 if (pkgSetting == null) { 9299 return false; 9300 } 9301 if (pkgSetting.getHidden(userId) != hidden) { 9302 pkgSetting.setHidden(hidden, userId); 9303 mSettings.writePackageRestrictionsLPr(userId); 9304 if (hidden) { 9305 sendRemoved = true; 9306 } else { 9307 sendAdded = true; 9308 } 9309 } 9310 } 9311 if (sendAdded) { 9312 sendPackageAddedForUser(packageName, pkgSetting, userId); 9313 return true; 9314 } 9315 if (sendRemoved) { 9316 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9317 "hiding pkg"); 9318 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9319 } 9320 } finally { 9321 Binder.restoreCallingIdentity(callingId); 9322 } 9323 return false; 9324 } 9325 9326 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9327 int userId) { 9328 final PackageRemovedInfo info = new PackageRemovedInfo(); 9329 info.removedPackage = packageName; 9330 info.removedUsers = new int[] {userId}; 9331 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9332 info.sendBroadcast(false, false, false); 9333 } 9334 9335 /** 9336 * Returns true if application is not found or there was an error. Otherwise it returns 9337 * the hidden state of the package for the given user. 9338 */ 9339 @Override 9340 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9341 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9342 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9343 false, "getApplicationHidden for user " + userId); 9344 PackageSetting pkgSetting; 9345 long callingId = Binder.clearCallingIdentity(); 9346 try { 9347 // writer 9348 synchronized (mPackages) { 9349 pkgSetting = mSettings.mPackages.get(packageName); 9350 if (pkgSetting == null) { 9351 return true; 9352 } 9353 return pkgSetting.getHidden(userId); 9354 } 9355 } finally { 9356 Binder.restoreCallingIdentity(callingId); 9357 } 9358 } 9359 9360 /** 9361 * @hide 9362 */ 9363 @Override 9364 public int installExistingPackageAsUser(String packageName, int userId) { 9365 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9366 null); 9367 PackageSetting pkgSetting; 9368 final int uid = Binder.getCallingUid(); 9369 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9370 + userId); 9371 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9372 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9373 } 9374 9375 long callingId = Binder.clearCallingIdentity(); 9376 try { 9377 boolean sendAdded = false; 9378 9379 // writer 9380 synchronized (mPackages) { 9381 pkgSetting = mSettings.mPackages.get(packageName); 9382 if (pkgSetting == null) { 9383 return PackageManager.INSTALL_FAILED_INVALID_URI; 9384 } 9385 if (!pkgSetting.getInstalled(userId)) { 9386 pkgSetting.setInstalled(true, userId); 9387 pkgSetting.setHidden(false, userId); 9388 mSettings.writePackageRestrictionsLPr(userId); 9389 sendAdded = true; 9390 } 9391 } 9392 9393 if (sendAdded) { 9394 sendPackageAddedForUser(packageName, pkgSetting, userId); 9395 } 9396 } finally { 9397 Binder.restoreCallingIdentity(callingId); 9398 } 9399 9400 return PackageManager.INSTALL_SUCCEEDED; 9401 } 9402 9403 boolean isUserRestricted(int userId, String restrictionKey) { 9404 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9405 if (restrictions.getBoolean(restrictionKey, false)) { 9406 Log.w(TAG, "User is restricted: " + restrictionKey); 9407 return true; 9408 } 9409 return false; 9410 } 9411 9412 @Override 9413 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9414 mContext.enforceCallingOrSelfPermission( 9415 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9416 "Only package verification agents can verify applications"); 9417 9418 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9419 final PackageVerificationResponse response = new PackageVerificationResponse( 9420 verificationCode, Binder.getCallingUid()); 9421 msg.arg1 = id; 9422 msg.obj = response; 9423 mHandler.sendMessage(msg); 9424 } 9425 9426 @Override 9427 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9428 long millisecondsToDelay) { 9429 mContext.enforceCallingOrSelfPermission( 9430 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9431 "Only package verification agents can extend verification timeouts"); 9432 9433 final PackageVerificationState state = mPendingVerification.get(id); 9434 final PackageVerificationResponse response = new PackageVerificationResponse( 9435 verificationCodeAtTimeout, Binder.getCallingUid()); 9436 9437 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9438 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9439 } 9440 if (millisecondsToDelay < 0) { 9441 millisecondsToDelay = 0; 9442 } 9443 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9444 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9445 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9446 } 9447 9448 if ((state != null) && !state.timeoutExtended()) { 9449 state.extendTimeout(); 9450 9451 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9452 msg.arg1 = id; 9453 msg.obj = response; 9454 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9455 } 9456 } 9457 9458 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9459 int verificationCode, UserHandle user) { 9460 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9461 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9462 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9463 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9464 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9465 9466 mContext.sendBroadcastAsUser(intent, user, 9467 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9468 } 9469 9470 private ComponentName matchComponentForVerifier(String packageName, 9471 List<ResolveInfo> receivers) { 9472 ActivityInfo targetReceiver = null; 9473 9474 final int NR = receivers.size(); 9475 for (int i = 0; i < NR; i++) { 9476 final ResolveInfo info = receivers.get(i); 9477 if (info.activityInfo == null) { 9478 continue; 9479 } 9480 9481 if (packageName.equals(info.activityInfo.packageName)) { 9482 targetReceiver = info.activityInfo; 9483 break; 9484 } 9485 } 9486 9487 if (targetReceiver == null) { 9488 return null; 9489 } 9490 9491 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9492 } 9493 9494 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9495 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9496 if (pkgInfo.verifiers.length == 0) { 9497 return null; 9498 } 9499 9500 final int N = pkgInfo.verifiers.length; 9501 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9502 for (int i = 0; i < N; i++) { 9503 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9504 9505 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9506 receivers); 9507 if (comp == null) { 9508 continue; 9509 } 9510 9511 final int verifierUid = getUidForVerifier(verifierInfo); 9512 if (verifierUid == -1) { 9513 continue; 9514 } 9515 9516 if (DEBUG_VERIFY) { 9517 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9518 + " with the correct signature"); 9519 } 9520 sufficientVerifiers.add(comp); 9521 verificationState.addSufficientVerifier(verifierUid); 9522 } 9523 9524 return sufficientVerifiers; 9525 } 9526 9527 private int getUidForVerifier(VerifierInfo verifierInfo) { 9528 synchronized (mPackages) { 9529 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9530 if (pkg == null) { 9531 return -1; 9532 } else if (pkg.mSignatures.length != 1) { 9533 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9534 + " has more than one signature; ignoring"); 9535 return -1; 9536 } 9537 9538 /* 9539 * If the public key of the package's signature does not match 9540 * our expected public key, then this is a different package and 9541 * we should skip. 9542 */ 9543 9544 final byte[] expectedPublicKey; 9545 try { 9546 final Signature verifierSig = pkg.mSignatures[0]; 9547 final PublicKey publicKey = verifierSig.getPublicKey(); 9548 expectedPublicKey = publicKey.getEncoded(); 9549 } catch (CertificateException e) { 9550 return -1; 9551 } 9552 9553 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9554 9555 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9556 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9557 + " does not have the expected public key; ignoring"); 9558 return -1; 9559 } 9560 9561 return pkg.applicationInfo.uid; 9562 } 9563 } 9564 9565 @Override 9566 public void finishPackageInstall(int token) { 9567 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9568 9569 if (DEBUG_INSTALL) { 9570 Slog.v(TAG, "BM finishing package install for " + token); 9571 } 9572 9573 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9574 mHandler.sendMessage(msg); 9575 } 9576 9577 /** 9578 * Get the verification agent timeout. 9579 * 9580 * @return verification timeout in milliseconds 9581 */ 9582 private long getVerificationTimeout() { 9583 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9584 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9585 DEFAULT_VERIFICATION_TIMEOUT); 9586 } 9587 9588 /** 9589 * Get the default verification agent response code. 9590 * 9591 * @return default verification response code 9592 */ 9593 private int getDefaultVerificationResponse() { 9594 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9595 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9596 DEFAULT_VERIFICATION_RESPONSE); 9597 } 9598 9599 /** 9600 * Check whether or not package verification has been enabled. 9601 * 9602 * @return true if verification should be performed 9603 */ 9604 private boolean isVerificationEnabled(int userId, int installFlags) { 9605 if (!DEFAULT_VERIFY_ENABLE) { 9606 return false; 9607 } 9608 9609 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9610 9611 // Check if installing from ADB 9612 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9613 // Do not run verification in a test harness environment 9614 if (ActivityManager.isRunningInTestHarness()) { 9615 return false; 9616 } 9617 if (ensureVerifyAppsEnabled) { 9618 return true; 9619 } 9620 // Check if the developer does not want package verification for ADB installs 9621 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9622 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9623 return false; 9624 } 9625 } 9626 9627 if (ensureVerifyAppsEnabled) { 9628 return true; 9629 } 9630 9631 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9632 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9633 } 9634 9635 @Override 9636 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9637 throws RemoteException { 9638 mContext.enforceCallingOrSelfPermission( 9639 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9640 "Only intentfilter verification agents can verify applications"); 9641 9642 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9643 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9644 Binder.getCallingUid(), verificationCode, failedDomains); 9645 msg.arg1 = id; 9646 msg.obj = response; 9647 mHandler.sendMessage(msg); 9648 } 9649 9650 @Override 9651 public int getIntentVerificationStatus(String packageName, int userId) { 9652 synchronized (mPackages) { 9653 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9654 } 9655 } 9656 9657 @Override 9658 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9659 mContext.enforceCallingOrSelfPermission( 9660 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9661 9662 boolean result = false; 9663 synchronized (mPackages) { 9664 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9665 } 9666 if (result) { 9667 scheduleWritePackageRestrictionsLocked(userId); 9668 } 9669 return result; 9670 } 9671 9672 @Override 9673 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9674 synchronized (mPackages) { 9675 return mSettings.getIntentFilterVerificationsLPr(packageName); 9676 } 9677 } 9678 9679 @Override 9680 public List<IntentFilter> getAllIntentFilters(String packageName) { 9681 if (TextUtils.isEmpty(packageName)) { 9682 return Collections.<IntentFilter>emptyList(); 9683 } 9684 synchronized (mPackages) { 9685 PackageParser.Package pkg = mPackages.get(packageName); 9686 if (pkg == null || pkg.activities == null) { 9687 return Collections.<IntentFilter>emptyList(); 9688 } 9689 final int count = pkg.activities.size(); 9690 ArrayList<IntentFilter> result = new ArrayList<>(); 9691 for (int n=0; n<count; n++) { 9692 PackageParser.Activity activity = pkg.activities.get(n); 9693 if (activity.intents != null || activity.intents.size() > 0) { 9694 result.addAll(activity.intents); 9695 } 9696 } 9697 return result; 9698 } 9699 } 9700 9701 @Override 9702 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9703 mContext.enforceCallingOrSelfPermission( 9704 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9705 9706 synchronized (mPackages) { 9707 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9708 if (packageName != null) { 9709 result |= updateIntentVerificationStatus(packageName, 9710 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9711 UserHandle.myUserId()); 9712 } 9713 return result; 9714 } 9715 } 9716 9717 @Override 9718 public String getDefaultBrowserPackageName(int userId) { 9719 synchronized (mPackages) { 9720 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9721 } 9722 } 9723 9724 /** 9725 * Get the "allow unknown sources" setting. 9726 * 9727 * @return the current "allow unknown sources" setting 9728 */ 9729 private int getUnknownSourcesSettings() { 9730 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9731 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9732 -1); 9733 } 9734 9735 @Override 9736 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9737 final int uid = Binder.getCallingUid(); 9738 // writer 9739 synchronized (mPackages) { 9740 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9741 if (targetPackageSetting == null) { 9742 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9743 } 9744 9745 PackageSetting installerPackageSetting; 9746 if (installerPackageName != null) { 9747 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9748 if (installerPackageSetting == null) { 9749 throw new IllegalArgumentException("Unknown installer package: " 9750 + installerPackageName); 9751 } 9752 } else { 9753 installerPackageSetting = null; 9754 } 9755 9756 Signature[] callerSignature; 9757 Object obj = mSettings.getUserIdLPr(uid); 9758 if (obj != null) { 9759 if (obj instanceof SharedUserSetting) { 9760 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9761 } else if (obj instanceof PackageSetting) { 9762 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9763 } else { 9764 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9765 } 9766 } else { 9767 throw new SecurityException("Unknown calling uid " + uid); 9768 } 9769 9770 // Verify: can't set installerPackageName to a package that is 9771 // not signed with the same cert as the caller. 9772 if (installerPackageSetting != null) { 9773 if (compareSignatures(callerSignature, 9774 installerPackageSetting.signatures.mSignatures) 9775 != PackageManager.SIGNATURE_MATCH) { 9776 throw new SecurityException( 9777 "Caller does not have same cert as new installer package " 9778 + installerPackageName); 9779 } 9780 } 9781 9782 // Verify: if target already has an installer package, it must 9783 // be signed with the same cert as the caller. 9784 if (targetPackageSetting.installerPackageName != null) { 9785 PackageSetting setting = mSettings.mPackages.get( 9786 targetPackageSetting.installerPackageName); 9787 // If the currently set package isn't valid, then it's always 9788 // okay to change it. 9789 if (setting != null) { 9790 if (compareSignatures(callerSignature, 9791 setting.signatures.mSignatures) 9792 != PackageManager.SIGNATURE_MATCH) { 9793 throw new SecurityException( 9794 "Caller does not have same cert as old installer package " 9795 + targetPackageSetting.installerPackageName); 9796 } 9797 } 9798 } 9799 9800 // Okay! 9801 targetPackageSetting.installerPackageName = installerPackageName; 9802 scheduleWriteSettingsLocked(); 9803 } 9804 } 9805 9806 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9807 // Queue up an async operation since the package installation may take a little while. 9808 mHandler.post(new Runnable() { 9809 public void run() { 9810 mHandler.removeCallbacks(this); 9811 // Result object to be returned 9812 PackageInstalledInfo res = new PackageInstalledInfo(); 9813 res.returnCode = currentStatus; 9814 res.uid = -1; 9815 res.pkg = null; 9816 res.removedInfo = new PackageRemovedInfo(); 9817 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9818 args.doPreInstall(res.returnCode); 9819 synchronized (mInstallLock) { 9820 installPackageLI(args, res); 9821 } 9822 args.doPostInstall(res.returnCode, res.uid); 9823 } 9824 9825 // A restore should be performed at this point if (a) the install 9826 // succeeded, (b) the operation is not an update, and (c) the new 9827 // package has not opted out of backup participation. 9828 final boolean update = res.removedInfo.removedPackage != null; 9829 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9830 boolean doRestore = !update 9831 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9832 9833 // Set up the post-install work request bookkeeping. This will be used 9834 // and cleaned up by the post-install event handling regardless of whether 9835 // there's a restore pass performed. Token values are >= 1. 9836 int token; 9837 if (mNextInstallToken < 0) mNextInstallToken = 1; 9838 token = mNextInstallToken++; 9839 9840 PostInstallData data = new PostInstallData(args, res); 9841 mRunningInstalls.put(token, data); 9842 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9843 9844 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9845 // Pass responsibility to the Backup Manager. It will perform a 9846 // restore if appropriate, then pass responsibility back to the 9847 // Package Manager to run the post-install observer callbacks 9848 // and broadcasts. 9849 IBackupManager bm = IBackupManager.Stub.asInterface( 9850 ServiceManager.getService(Context.BACKUP_SERVICE)); 9851 if (bm != null) { 9852 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9853 + " to BM for possible restore"); 9854 try { 9855 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9856 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9857 } else { 9858 doRestore = false; 9859 } 9860 } catch (RemoteException e) { 9861 // can't happen; the backup manager is local 9862 } catch (Exception e) { 9863 Slog.e(TAG, "Exception trying to enqueue restore", e); 9864 doRestore = false; 9865 } 9866 } else { 9867 Slog.e(TAG, "Backup Manager not found!"); 9868 doRestore = false; 9869 } 9870 } 9871 9872 if (!doRestore) { 9873 // No restore possible, or the Backup Manager was mysteriously not 9874 // available -- just fire the post-install work request directly. 9875 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9876 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9877 mHandler.sendMessage(msg); 9878 } 9879 } 9880 }); 9881 } 9882 9883 private abstract class HandlerParams { 9884 private static final int MAX_RETRIES = 4; 9885 9886 /** 9887 * Number of times startCopy() has been attempted and had a non-fatal 9888 * error. 9889 */ 9890 private int mRetries = 0; 9891 9892 /** User handle for the user requesting the information or installation. */ 9893 private final UserHandle mUser; 9894 9895 HandlerParams(UserHandle user) { 9896 mUser = user; 9897 } 9898 9899 UserHandle getUser() { 9900 return mUser; 9901 } 9902 9903 final boolean startCopy() { 9904 boolean res; 9905 try { 9906 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9907 9908 if (++mRetries > MAX_RETRIES) { 9909 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9910 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9911 handleServiceError(); 9912 return false; 9913 } else { 9914 handleStartCopy(); 9915 res = true; 9916 } 9917 } catch (RemoteException e) { 9918 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9919 mHandler.sendEmptyMessage(MCS_RECONNECT); 9920 res = false; 9921 } 9922 handleReturnCode(); 9923 return res; 9924 } 9925 9926 final void serviceError() { 9927 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9928 handleServiceError(); 9929 handleReturnCode(); 9930 } 9931 9932 abstract void handleStartCopy() throws RemoteException; 9933 abstract void handleServiceError(); 9934 abstract void handleReturnCode(); 9935 } 9936 9937 class MeasureParams extends HandlerParams { 9938 private final PackageStats mStats; 9939 private boolean mSuccess; 9940 9941 private final IPackageStatsObserver mObserver; 9942 9943 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9944 super(new UserHandle(stats.userHandle)); 9945 mObserver = observer; 9946 mStats = stats; 9947 } 9948 9949 @Override 9950 public String toString() { 9951 return "MeasureParams{" 9952 + Integer.toHexString(System.identityHashCode(this)) 9953 + " " + mStats.packageName + "}"; 9954 } 9955 9956 @Override 9957 void handleStartCopy() throws RemoteException { 9958 synchronized (mInstallLock) { 9959 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9960 } 9961 9962 if (mSuccess) { 9963 final boolean mounted; 9964 if (Environment.isExternalStorageEmulated()) { 9965 mounted = true; 9966 } else { 9967 final String status = Environment.getExternalStorageState(); 9968 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9969 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9970 } 9971 9972 if (mounted) { 9973 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9974 9975 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9976 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9977 9978 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9979 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9980 9981 // Always subtract cache size, since it's a subdirectory 9982 mStats.externalDataSize -= mStats.externalCacheSize; 9983 9984 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9985 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9986 9987 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9988 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9989 } 9990 } 9991 } 9992 9993 @Override 9994 void handleReturnCode() { 9995 if (mObserver != null) { 9996 try { 9997 mObserver.onGetStatsCompleted(mStats, mSuccess); 9998 } catch (RemoteException e) { 9999 Slog.i(TAG, "Observer no longer exists."); 10000 } 10001 } 10002 } 10003 10004 @Override 10005 void handleServiceError() { 10006 Slog.e(TAG, "Could not measure application " + mStats.packageName 10007 + " external storage"); 10008 } 10009 } 10010 10011 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10012 throws RemoteException { 10013 long result = 0; 10014 for (File path : paths) { 10015 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10016 } 10017 return result; 10018 } 10019 10020 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10021 for (File path : paths) { 10022 try { 10023 mcs.clearDirectory(path.getAbsolutePath()); 10024 } catch (RemoteException e) { 10025 } 10026 } 10027 } 10028 10029 static class OriginInfo { 10030 /** 10031 * Location where install is coming from, before it has been 10032 * copied/renamed into place. This could be a single monolithic APK 10033 * file, or a cluster directory. This location may be untrusted. 10034 */ 10035 final File file; 10036 final String cid; 10037 10038 /** 10039 * Flag indicating that {@link #file} or {@link #cid} has already been 10040 * staged, meaning downstream users don't need to defensively copy the 10041 * contents. 10042 */ 10043 final boolean staged; 10044 10045 /** 10046 * Flag indicating that {@link #file} or {@link #cid} is an already 10047 * installed app that is being moved. 10048 */ 10049 final boolean existing; 10050 10051 final String resolvedPath; 10052 final File resolvedFile; 10053 10054 static OriginInfo fromNothing() { 10055 return new OriginInfo(null, null, false, false); 10056 } 10057 10058 static OriginInfo fromUntrustedFile(File file) { 10059 return new OriginInfo(file, null, false, false); 10060 } 10061 10062 static OriginInfo fromExistingFile(File file) { 10063 return new OriginInfo(file, null, false, true); 10064 } 10065 10066 static OriginInfo fromStagedFile(File file) { 10067 return new OriginInfo(file, null, true, false); 10068 } 10069 10070 static OriginInfo fromStagedContainer(String cid) { 10071 return new OriginInfo(null, cid, true, false); 10072 } 10073 10074 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10075 this.file = file; 10076 this.cid = cid; 10077 this.staged = staged; 10078 this.existing = existing; 10079 10080 if (cid != null) { 10081 resolvedPath = PackageHelper.getSdDir(cid); 10082 resolvedFile = new File(resolvedPath); 10083 } else if (file != null) { 10084 resolvedPath = file.getAbsolutePath(); 10085 resolvedFile = file; 10086 } else { 10087 resolvedPath = null; 10088 resolvedFile = null; 10089 } 10090 } 10091 } 10092 10093 class MoveInfo { 10094 final int moveId; 10095 final String fromUuid; 10096 final String toUuid; 10097 final String packageName; 10098 final String dataAppName; 10099 final int appId; 10100 final String seinfo; 10101 10102 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10103 String dataAppName, int appId, String seinfo) { 10104 this.moveId = moveId; 10105 this.fromUuid = fromUuid; 10106 this.toUuid = toUuid; 10107 this.packageName = packageName; 10108 this.dataAppName = dataAppName; 10109 this.appId = appId; 10110 this.seinfo = seinfo; 10111 } 10112 } 10113 10114 class InstallParams extends HandlerParams { 10115 final OriginInfo origin; 10116 final MoveInfo move; 10117 final IPackageInstallObserver2 observer; 10118 int installFlags; 10119 final String installerPackageName; 10120 final String volumeUuid; 10121 final VerificationParams verificationParams; 10122 private InstallArgs mArgs; 10123 private int mRet; 10124 final String packageAbiOverride; 10125 10126 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10127 int installFlags, String installerPackageName, String volumeUuid, 10128 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10129 super(user); 10130 this.origin = origin; 10131 this.move = move; 10132 this.observer = observer; 10133 this.installFlags = installFlags; 10134 this.installerPackageName = installerPackageName; 10135 this.volumeUuid = volumeUuid; 10136 this.verificationParams = verificationParams; 10137 this.packageAbiOverride = packageAbiOverride; 10138 } 10139 10140 @Override 10141 public String toString() { 10142 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10143 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10144 } 10145 10146 public ManifestDigest getManifestDigest() { 10147 if (verificationParams == null) { 10148 return null; 10149 } 10150 return verificationParams.getManifestDigest(); 10151 } 10152 10153 private int installLocationPolicy(PackageInfoLite pkgLite) { 10154 String packageName = pkgLite.packageName; 10155 int installLocation = pkgLite.installLocation; 10156 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10157 // reader 10158 synchronized (mPackages) { 10159 PackageParser.Package pkg = mPackages.get(packageName); 10160 if (pkg != null) { 10161 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10162 // Check for downgrading. 10163 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10164 try { 10165 checkDowngrade(pkg, pkgLite); 10166 } catch (PackageManagerException e) { 10167 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10168 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10169 } 10170 } 10171 // Check for updated system application. 10172 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10173 if (onSd) { 10174 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10175 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10176 } 10177 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10178 } else { 10179 if (onSd) { 10180 // Install flag overrides everything. 10181 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10182 } 10183 // If current upgrade specifies particular preference 10184 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10185 // Application explicitly specified internal. 10186 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10187 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10188 // App explictly prefers external. Let policy decide 10189 } else { 10190 // Prefer previous location 10191 if (isExternal(pkg)) { 10192 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10193 } 10194 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10195 } 10196 } 10197 } else { 10198 // Invalid install. Return error code 10199 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10200 } 10201 } 10202 } 10203 // All the special cases have been taken care of. 10204 // Return result based on recommended install location. 10205 if (onSd) { 10206 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10207 } 10208 return pkgLite.recommendedInstallLocation; 10209 } 10210 10211 /* 10212 * Invoke remote method to get package information and install 10213 * location values. Override install location based on default 10214 * policy if needed and then create install arguments based 10215 * on the install location. 10216 */ 10217 public void handleStartCopy() throws RemoteException { 10218 int ret = PackageManager.INSTALL_SUCCEEDED; 10219 10220 // If we're already staged, we've firmly committed to an install location 10221 if (origin.staged) { 10222 if (origin.file != null) { 10223 installFlags |= PackageManager.INSTALL_INTERNAL; 10224 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10225 } else if (origin.cid != null) { 10226 installFlags |= PackageManager.INSTALL_EXTERNAL; 10227 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10228 } else { 10229 throw new IllegalStateException("Invalid stage location"); 10230 } 10231 } 10232 10233 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10234 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10235 10236 PackageInfoLite pkgLite = null; 10237 10238 if (onInt && onSd) { 10239 // Check if both bits are set. 10240 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10241 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10242 } else { 10243 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10244 packageAbiOverride); 10245 10246 /* 10247 * If we have too little free space, try to free cache 10248 * before giving up. 10249 */ 10250 if (!origin.staged && pkgLite.recommendedInstallLocation 10251 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10252 // TODO: focus freeing disk space on the target device 10253 final StorageManager storage = StorageManager.from(mContext); 10254 final long lowThreshold = storage.getStorageLowBytes( 10255 Environment.getDataDirectory()); 10256 10257 final long sizeBytes = mContainerService.calculateInstalledSize( 10258 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10259 10260 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10261 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10262 installFlags, packageAbiOverride); 10263 } 10264 10265 /* 10266 * The cache free must have deleted the file we 10267 * downloaded to install. 10268 * 10269 * TODO: fix the "freeCache" call to not delete 10270 * the file we care about. 10271 */ 10272 if (pkgLite.recommendedInstallLocation 10273 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10274 pkgLite.recommendedInstallLocation 10275 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10276 } 10277 } 10278 } 10279 10280 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10281 int loc = pkgLite.recommendedInstallLocation; 10282 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10283 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10284 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10285 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10286 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10287 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10288 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10289 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10290 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10291 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10292 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10293 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10294 } else { 10295 // Override with defaults if needed. 10296 loc = installLocationPolicy(pkgLite); 10297 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10298 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10299 } else if (!onSd && !onInt) { 10300 // Override install location with flags 10301 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10302 // Set the flag to install on external media. 10303 installFlags |= PackageManager.INSTALL_EXTERNAL; 10304 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10305 } else { 10306 // Make sure the flag for installing on external 10307 // media is unset 10308 installFlags |= PackageManager.INSTALL_INTERNAL; 10309 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10310 } 10311 } 10312 } 10313 } 10314 10315 final InstallArgs args = createInstallArgs(this); 10316 mArgs = args; 10317 10318 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10319 /* 10320 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10321 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10322 */ 10323 int userIdentifier = getUser().getIdentifier(); 10324 if (userIdentifier == UserHandle.USER_ALL 10325 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10326 userIdentifier = UserHandle.USER_OWNER; 10327 } 10328 10329 /* 10330 * Determine if we have any installed package verifiers. If we 10331 * do, then we'll defer to them to verify the packages. 10332 */ 10333 final int requiredUid = mRequiredVerifierPackage == null ? -1 10334 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10335 if (!origin.existing && requiredUid != -1 10336 && isVerificationEnabled(userIdentifier, installFlags)) { 10337 final Intent verification = new Intent( 10338 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10339 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10340 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10341 PACKAGE_MIME_TYPE); 10342 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10343 10344 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10345 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10346 0 /* TODO: Which userId? */); 10347 10348 if (DEBUG_VERIFY) { 10349 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10350 + verification.toString() + " with " + pkgLite.verifiers.length 10351 + " optional verifiers"); 10352 } 10353 10354 final int verificationId = mPendingVerificationToken++; 10355 10356 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10357 10358 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10359 installerPackageName); 10360 10361 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10362 installFlags); 10363 10364 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10365 pkgLite.packageName); 10366 10367 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10368 pkgLite.versionCode); 10369 10370 if (verificationParams != null) { 10371 if (verificationParams.getVerificationURI() != null) { 10372 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10373 verificationParams.getVerificationURI()); 10374 } 10375 if (verificationParams.getOriginatingURI() != null) { 10376 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10377 verificationParams.getOriginatingURI()); 10378 } 10379 if (verificationParams.getReferrer() != null) { 10380 verification.putExtra(Intent.EXTRA_REFERRER, 10381 verificationParams.getReferrer()); 10382 } 10383 if (verificationParams.getOriginatingUid() >= 0) { 10384 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10385 verificationParams.getOriginatingUid()); 10386 } 10387 if (verificationParams.getInstallerUid() >= 0) { 10388 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10389 verificationParams.getInstallerUid()); 10390 } 10391 } 10392 10393 final PackageVerificationState verificationState = new PackageVerificationState( 10394 requiredUid, args); 10395 10396 mPendingVerification.append(verificationId, verificationState); 10397 10398 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10399 receivers, verificationState); 10400 10401 /* 10402 * If any sufficient verifiers were listed in the package 10403 * manifest, attempt to ask them. 10404 */ 10405 if (sufficientVerifiers != null) { 10406 final int N = sufficientVerifiers.size(); 10407 if (N == 0) { 10408 Slog.i(TAG, "Additional verifiers required, but none installed."); 10409 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10410 } else { 10411 for (int i = 0; i < N; i++) { 10412 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10413 10414 final Intent sufficientIntent = new Intent(verification); 10415 sufficientIntent.setComponent(verifierComponent); 10416 10417 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10418 } 10419 } 10420 } 10421 10422 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10423 mRequiredVerifierPackage, receivers); 10424 if (ret == PackageManager.INSTALL_SUCCEEDED 10425 && mRequiredVerifierPackage != null) { 10426 /* 10427 * Send the intent to the required verification agent, 10428 * but only start the verification timeout after the 10429 * target BroadcastReceivers have run. 10430 */ 10431 verification.setComponent(requiredVerifierComponent); 10432 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10433 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10434 new BroadcastReceiver() { 10435 @Override 10436 public void onReceive(Context context, Intent intent) { 10437 final Message msg = mHandler 10438 .obtainMessage(CHECK_PENDING_VERIFICATION); 10439 msg.arg1 = verificationId; 10440 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10441 } 10442 }, null, 0, null, null); 10443 10444 /* 10445 * We don't want the copy to proceed until verification 10446 * succeeds, so null out this field. 10447 */ 10448 mArgs = null; 10449 } 10450 } else { 10451 /* 10452 * No package verification is enabled, so immediately start 10453 * the remote call to initiate copy using temporary file. 10454 */ 10455 ret = args.copyApk(mContainerService, true); 10456 } 10457 } 10458 10459 mRet = ret; 10460 } 10461 10462 @Override 10463 void handleReturnCode() { 10464 // If mArgs is null, then MCS couldn't be reached. When it 10465 // reconnects, it will try again to install. At that point, this 10466 // will succeed. 10467 if (mArgs != null) { 10468 processPendingInstall(mArgs, mRet); 10469 } 10470 } 10471 10472 @Override 10473 void handleServiceError() { 10474 mArgs = createInstallArgs(this); 10475 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10476 } 10477 10478 public boolean isForwardLocked() { 10479 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10480 } 10481 } 10482 10483 /** 10484 * Used during creation of InstallArgs 10485 * 10486 * @param installFlags package installation flags 10487 * @return true if should be installed on external storage 10488 */ 10489 private static boolean installOnExternalAsec(int installFlags) { 10490 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10491 return false; 10492 } 10493 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10494 return true; 10495 } 10496 return false; 10497 } 10498 10499 /** 10500 * Used during creation of InstallArgs 10501 * 10502 * @param installFlags package installation flags 10503 * @return true if should be installed as forward locked 10504 */ 10505 private static boolean installForwardLocked(int installFlags) { 10506 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10507 } 10508 10509 private InstallArgs createInstallArgs(InstallParams params) { 10510 if (params.move != null) { 10511 return new MoveInstallArgs(params); 10512 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10513 return new AsecInstallArgs(params); 10514 } else { 10515 return new FileInstallArgs(params); 10516 } 10517 } 10518 10519 /** 10520 * Create args that describe an existing installed package. Typically used 10521 * when cleaning up old installs, or used as a move source. 10522 */ 10523 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10524 String resourcePath, String[] instructionSets) { 10525 final boolean isInAsec; 10526 if (installOnExternalAsec(installFlags)) { 10527 /* Apps on SD card are always in ASEC containers. */ 10528 isInAsec = true; 10529 } else if (installForwardLocked(installFlags) 10530 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10531 /* 10532 * Forward-locked apps are only in ASEC containers if they're the 10533 * new style 10534 */ 10535 isInAsec = true; 10536 } else { 10537 isInAsec = false; 10538 } 10539 10540 if (isInAsec) { 10541 return new AsecInstallArgs(codePath, instructionSets, 10542 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10543 } else { 10544 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10545 } 10546 } 10547 10548 static abstract class InstallArgs { 10549 /** @see InstallParams#origin */ 10550 final OriginInfo origin; 10551 /** @see InstallParams#move */ 10552 final MoveInfo move; 10553 10554 final IPackageInstallObserver2 observer; 10555 // Always refers to PackageManager flags only 10556 final int installFlags; 10557 final String installerPackageName; 10558 final String volumeUuid; 10559 final ManifestDigest manifestDigest; 10560 final UserHandle user; 10561 final String abiOverride; 10562 10563 // The list of instruction sets supported by this app. This is currently 10564 // only used during the rmdex() phase to clean up resources. We can get rid of this 10565 // if we move dex files under the common app path. 10566 /* nullable */ String[] instructionSets; 10567 10568 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10569 int installFlags, String installerPackageName, String volumeUuid, 10570 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10571 String abiOverride) { 10572 this.origin = origin; 10573 this.move = move; 10574 this.installFlags = installFlags; 10575 this.observer = observer; 10576 this.installerPackageName = installerPackageName; 10577 this.volumeUuid = volumeUuid; 10578 this.manifestDigest = manifestDigest; 10579 this.user = user; 10580 this.instructionSets = instructionSets; 10581 this.abiOverride = abiOverride; 10582 } 10583 10584 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10585 abstract int doPreInstall(int status); 10586 10587 /** 10588 * Rename package into final resting place. All paths on the given 10589 * scanned package should be updated to reflect the rename. 10590 */ 10591 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10592 abstract int doPostInstall(int status, int uid); 10593 10594 /** @see PackageSettingBase#codePathString */ 10595 abstract String getCodePath(); 10596 /** @see PackageSettingBase#resourcePathString */ 10597 abstract String getResourcePath(); 10598 10599 // Need installer lock especially for dex file removal. 10600 abstract void cleanUpResourcesLI(); 10601 abstract boolean doPostDeleteLI(boolean delete); 10602 10603 /** 10604 * Called before the source arguments are copied. This is used mostly 10605 * for MoveParams when it needs to read the source file to put it in the 10606 * destination. 10607 */ 10608 int doPreCopy() { 10609 return PackageManager.INSTALL_SUCCEEDED; 10610 } 10611 10612 /** 10613 * Called after the source arguments are copied. This is used mostly for 10614 * MoveParams when it needs to read the source file to put it in the 10615 * destination. 10616 * 10617 * @return 10618 */ 10619 int doPostCopy(int uid) { 10620 return PackageManager.INSTALL_SUCCEEDED; 10621 } 10622 10623 protected boolean isFwdLocked() { 10624 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10625 } 10626 10627 protected boolean isExternalAsec() { 10628 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10629 } 10630 10631 UserHandle getUser() { 10632 return user; 10633 } 10634 } 10635 10636 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10637 if (!allCodePaths.isEmpty()) { 10638 if (instructionSets == null) { 10639 throw new IllegalStateException("instructionSet == null"); 10640 } 10641 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10642 for (String codePath : allCodePaths) { 10643 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10644 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10645 if (retCode < 0) { 10646 Slog.w(TAG, "Couldn't remove dex file for package: " 10647 + " at location " + codePath + ", retcode=" + retCode); 10648 // we don't consider this to be a failure of the core package deletion 10649 } 10650 } 10651 } 10652 } 10653 } 10654 10655 /** 10656 * Logic to handle installation of non-ASEC applications, including copying 10657 * and renaming logic. 10658 */ 10659 class FileInstallArgs extends InstallArgs { 10660 private File codeFile; 10661 private File resourceFile; 10662 10663 // Example topology: 10664 // /data/app/com.example/base.apk 10665 // /data/app/com.example/split_foo.apk 10666 // /data/app/com.example/lib/arm/libfoo.so 10667 // /data/app/com.example/lib/arm64/libfoo.so 10668 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10669 10670 /** New install */ 10671 FileInstallArgs(InstallParams params) { 10672 super(params.origin, params.move, params.observer, params.installFlags, 10673 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10674 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10675 if (isFwdLocked()) { 10676 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10677 } 10678 } 10679 10680 /** Existing install */ 10681 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10682 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10683 null); 10684 this.codeFile = (codePath != null) ? new File(codePath) : null; 10685 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10686 } 10687 10688 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10689 if (origin.staged) { 10690 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10691 codeFile = origin.file; 10692 resourceFile = origin.file; 10693 return PackageManager.INSTALL_SUCCEEDED; 10694 } 10695 10696 try { 10697 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10698 codeFile = tempDir; 10699 resourceFile = tempDir; 10700 } catch (IOException e) { 10701 Slog.w(TAG, "Failed to create copy file: " + e); 10702 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10703 } 10704 10705 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10706 @Override 10707 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10708 if (!FileUtils.isValidExtFilename(name)) { 10709 throw new IllegalArgumentException("Invalid filename: " + name); 10710 } 10711 try { 10712 final File file = new File(codeFile, name); 10713 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10714 O_RDWR | O_CREAT, 0644); 10715 Os.chmod(file.getAbsolutePath(), 0644); 10716 return new ParcelFileDescriptor(fd); 10717 } catch (ErrnoException e) { 10718 throw new RemoteException("Failed to open: " + e.getMessage()); 10719 } 10720 } 10721 }; 10722 10723 int ret = PackageManager.INSTALL_SUCCEEDED; 10724 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10725 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10726 Slog.e(TAG, "Failed to copy package"); 10727 return ret; 10728 } 10729 10730 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10731 NativeLibraryHelper.Handle handle = null; 10732 try { 10733 handle = NativeLibraryHelper.Handle.create(codeFile); 10734 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10735 abiOverride); 10736 } catch (IOException e) { 10737 Slog.e(TAG, "Copying native libraries failed", e); 10738 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10739 } finally { 10740 IoUtils.closeQuietly(handle); 10741 } 10742 10743 return ret; 10744 } 10745 10746 int doPreInstall(int status) { 10747 if (status != PackageManager.INSTALL_SUCCEEDED) { 10748 cleanUp(); 10749 } 10750 return status; 10751 } 10752 10753 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10754 if (status != PackageManager.INSTALL_SUCCEEDED) { 10755 cleanUp(); 10756 return false; 10757 } 10758 10759 final File targetDir = codeFile.getParentFile(); 10760 final File beforeCodeFile = codeFile; 10761 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10762 10763 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10764 try { 10765 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10766 } catch (ErrnoException e) { 10767 Slog.w(TAG, "Failed to rename", e); 10768 return false; 10769 } 10770 10771 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10772 Slog.w(TAG, "Failed to restorecon"); 10773 return false; 10774 } 10775 10776 // Reflect the rename internally 10777 codeFile = afterCodeFile; 10778 resourceFile = afterCodeFile; 10779 10780 // Reflect the rename in scanned details 10781 pkg.codePath = afterCodeFile.getAbsolutePath(); 10782 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10783 pkg.baseCodePath); 10784 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10785 pkg.splitCodePaths); 10786 10787 // Reflect the rename in app info 10788 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10789 pkg.applicationInfo.setCodePath(pkg.codePath); 10790 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10791 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10792 pkg.applicationInfo.setResourcePath(pkg.codePath); 10793 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10794 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10795 10796 return true; 10797 } 10798 10799 int doPostInstall(int status, int uid) { 10800 if (status != PackageManager.INSTALL_SUCCEEDED) { 10801 cleanUp(); 10802 } 10803 return status; 10804 } 10805 10806 @Override 10807 String getCodePath() { 10808 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10809 } 10810 10811 @Override 10812 String getResourcePath() { 10813 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10814 } 10815 10816 private boolean cleanUp() { 10817 if (codeFile == null || !codeFile.exists()) { 10818 return false; 10819 } 10820 10821 if (codeFile.isDirectory()) { 10822 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10823 } else { 10824 codeFile.delete(); 10825 } 10826 10827 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10828 resourceFile.delete(); 10829 } 10830 10831 return true; 10832 } 10833 10834 void cleanUpResourcesLI() { 10835 // Try enumerating all code paths before deleting 10836 List<String> allCodePaths = Collections.EMPTY_LIST; 10837 if (codeFile != null && codeFile.exists()) { 10838 try { 10839 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10840 allCodePaths = pkg.getAllCodePaths(); 10841 } catch (PackageParserException e) { 10842 // Ignored; we tried our best 10843 } 10844 } 10845 10846 cleanUp(); 10847 removeDexFiles(allCodePaths, instructionSets); 10848 } 10849 10850 boolean doPostDeleteLI(boolean delete) { 10851 // XXX err, shouldn't we respect the delete flag? 10852 cleanUpResourcesLI(); 10853 return true; 10854 } 10855 } 10856 10857 private boolean isAsecExternal(String cid) { 10858 final String asecPath = PackageHelper.getSdFilesystem(cid); 10859 return !asecPath.startsWith(mAsecInternalPath); 10860 } 10861 10862 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10863 PackageManagerException { 10864 if (copyRet < 0) { 10865 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10866 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10867 throw new PackageManagerException(copyRet, message); 10868 } 10869 } 10870 } 10871 10872 /** 10873 * Extract the MountService "container ID" from the full code path of an 10874 * .apk. 10875 */ 10876 static String cidFromCodePath(String fullCodePath) { 10877 int eidx = fullCodePath.lastIndexOf("/"); 10878 String subStr1 = fullCodePath.substring(0, eidx); 10879 int sidx = subStr1.lastIndexOf("/"); 10880 return subStr1.substring(sidx+1, eidx); 10881 } 10882 10883 /** 10884 * Logic to handle installation of ASEC applications, including copying and 10885 * renaming logic. 10886 */ 10887 class AsecInstallArgs extends InstallArgs { 10888 static final String RES_FILE_NAME = "pkg.apk"; 10889 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10890 10891 String cid; 10892 String packagePath; 10893 String resourcePath; 10894 10895 /** New install */ 10896 AsecInstallArgs(InstallParams params) { 10897 super(params.origin, params.move, params.observer, params.installFlags, 10898 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10899 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10900 } 10901 10902 /** Existing install */ 10903 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10904 boolean isExternal, boolean isForwardLocked) { 10905 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10906 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10907 instructionSets, null); 10908 // Hackily pretend we're still looking at a full code path 10909 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10910 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10911 } 10912 10913 // Extract cid from fullCodePath 10914 int eidx = fullCodePath.lastIndexOf("/"); 10915 String subStr1 = fullCodePath.substring(0, eidx); 10916 int sidx = subStr1.lastIndexOf("/"); 10917 cid = subStr1.substring(sidx+1, eidx); 10918 setMountPath(subStr1); 10919 } 10920 10921 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10922 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10923 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10924 instructionSets, null); 10925 this.cid = cid; 10926 setMountPath(PackageHelper.getSdDir(cid)); 10927 } 10928 10929 void createCopyFile() { 10930 cid = mInstallerService.allocateExternalStageCidLegacy(); 10931 } 10932 10933 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10934 if (origin.staged) { 10935 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10936 cid = origin.cid; 10937 setMountPath(PackageHelper.getSdDir(cid)); 10938 return PackageManager.INSTALL_SUCCEEDED; 10939 } 10940 10941 if (temp) { 10942 createCopyFile(); 10943 } else { 10944 /* 10945 * Pre-emptively destroy the container since it's destroyed if 10946 * copying fails due to it existing anyway. 10947 */ 10948 PackageHelper.destroySdDir(cid); 10949 } 10950 10951 final String newMountPath = imcs.copyPackageToContainer( 10952 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10953 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10954 10955 if (newMountPath != null) { 10956 setMountPath(newMountPath); 10957 return PackageManager.INSTALL_SUCCEEDED; 10958 } else { 10959 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10960 } 10961 } 10962 10963 @Override 10964 String getCodePath() { 10965 return packagePath; 10966 } 10967 10968 @Override 10969 String getResourcePath() { 10970 return resourcePath; 10971 } 10972 10973 int doPreInstall(int status) { 10974 if (status != PackageManager.INSTALL_SUCCEEDED) { 10975 // Destroy container 10976 PackageHelper.destroySdDir(cid); 10977 } else { 10978 boolean mounted = PackageHelper.isContainerMounted(cid); 10979 if (!mounted) { 10980 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10981 Process.SYSTEM_UID); 10982 if (newMountPath != null) { 10983 setMountPath(newMountPath); 10984 } else { 10985 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10986 } 10987 } 10988 } 10989 return status; 10990 } 10991 10992 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10993 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10994 String newMountPath = null; 10995 if (PackageHelper.isContainerMounted(cid)) { 10996 // Unmount the container 10997 if (!PackageHelper.unMountSdDir(cid)) { 10998 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10999 return false; 11000 } 11001 } 11002 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11003 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11004 " which might be stale. Will try to clean up."); 11005 // Clean up the stale container and proceed to recreate. 11006 if (!PackageHelper.destroySdDir(newCacheId)) { 11007 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11008 return false; 11009 } 11010 // Successfully cleaned up stale container. Try to rename again. 11011 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11012 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11013 + " inspite of cleaning it up."); 11014 return false; 11015 } 11016 } 11017 if (!PackageHelper.isContainerMounted(newCacheId)) { 11018 Slog.w(TAG, "Mounting container " + newCacheId); 11019 newMountPath = PackageHelper.mountSdDir(newCacheId, 11020 getEncryptKey(), Process.SYSTEM_UID); 11021 } else { 11022 newMountPath = PackageHelper.getSdDir(newCacheId); 11023 } 11024 if (newMountPath == null) { 11025 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11026 return false; 11027 } 11028 Log.i(TAG, "Succesfully renamed " + cid + 11029 " to " + newCacheId + 11030 " at new path: " + newMountPath); 11031 cid = newCacheId; 11032 11033 final File beforeCodeFile = new File(packagePath); 11034 setMountPath(newMountPath); 11035 final File afterCodeFile = new File(packagePath); 11036 11037 // Reflect the rename in scanned details 11038 pkg.codePath = afterCodeFile.getAbsolutePath(); 11039 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11040 pkg.baseCodePath); 11041 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11042 pkg.splitCodePaths); 11043 11044 // Reflect the rename in app info 11045 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11046 pkg.applicationInfo.setCodePath(pkg.codePath); 11047 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11048 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11049 pkg.applicationInfo.setResourcePath(pkg.codePath); 11050 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11051 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11052 11053 return true; 11054 } 11055 11056 private void setMountPath(String mountPath) { 11057 final File mountFile = new File(mountPath); 11058 11059 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11060 if (monolithicFile.exists()) { 11061 packagePath = monolithicFile.getAbsolutePath(); 11062 if (isFwdLocked()) { 11063 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11064 } else { 11065 resourcePath = packagePath; 11066 } 11067 } else { 11068 packagePath = mountFile.getAbsolutePath(); 11069 resourcePath = packagePath; 11070 } 11071 } 11072 11073 int doPostInstall(int status, int uid) { 11074 if (status != PackageManager.INSTALL_SUCCEEDED) { 11075 cleanUp(); 11076 } else { 11077 final int groupOwner; 11078 final String protectedFile; 11079 if (isFwdLocked()) { 11080 groupOwner = UserHandle.getSharedAppGid(uid); 11081 protectedFile = RES_FILE_NAME; 11082 } else { 11083 groupOwner = -1; 11084 protectedFile = null; 11085 } 11086 11087 if (uid < Process.FIRST_APPLICATION_UID 11088 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11089 Slog.e(TAG, "Failed to finalize " + cid); 11090 PackageHelper.destroySdDir(cid); 11091 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11092 } 11093 11094 boolean mounted = PackageHelper.isContainerMounted(cid); 11095 if (!mounted) { 11096 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11097 } 11098 } 11099 return status; 11100 } 11101 11102 private void cleanUp() { 11103 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11104 11105 // Destroy secure container 11106 PackageHelper.destroySdDir(cid); 11107 } 11108 11109 private List<String> getAllCodePaths() { 11110 final File codeFile = new File(getCodePath()); 11111 if (codeFile != null && codeFile.exists()) { 11112 try { 11113 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11114 return pkg.getAllCodePaths(); 11115 } catch (PackageParserException e) { 11116 // Ignored; we tried our best 11117 } 11118 } 11119 return Collections.EMPTY_LIST; 11120 } 11121 11122 void cleanUpResourcesLI() { 11123 // Enumerate all code paths before deleting 11124 cleanUpResourcesLI(getAllCodePaths()); 11125 } 11126 11127 private void cleanUpResourcesLI(List<String> allCodePaths) { 11128 cleanUp(); 11129 removeDexFiles(allCodePaths, instructionSets); 11130 } 11131 11132 String getPackageName() { 11133 return getAsecPackageName(cid); 11134 } 11135 11136 boolean doPostDeleteLI(boolean delete) { 11137 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11138 final List<String> allCodePaths = getAllCodePaths(); 11139 boolean mounted = PackageHelper.isContainerMounted(cid); 11140 if (mounted) { 11141 // Unmount first 11142 if (PackageHelper.unMountSdDir(cid)) { 11143 mounted = false; 11144 } 11145 } 11146 if (!mounted && delete) { 11147 cleanUpResourcesLI(allCodePaths); 11148 } 11149 return !mounted; 11150 } 11151 11152 @Override 11153 int doPreCopy() { 11154 if (isFwdLocked()) { 11155 if (!PackageHelper.fixSdPermissions(cid, 11156 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11157 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11158 } 11159 } 11160 11161 return PackageManager.INSTALL_SUCCEEDED; 11162 } 11163 11164 @Override 11165 int doPostCopy(int uid) { 11166 if (isFwdLocked()) { 11167 if (uid < Process.FIRST_APPLICATION_UID 11168 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11169 RES_FILE_NAME)) { 11170 Slog.e(TAG, "Failed to finalize " + cid); 11171 PackageHelper.destroySdDir(cid); 11172 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11173 } 11174 } 11175 11176 return PackageManager.INSTALL_SUCCEEDED; 11177 } 11178 } 11179 11180 /** 11181 * Logic to handle movement of existing installed applications. 11182 */ 11183 class MoveInstallArgs extends InstallArgs { 11184 private File codeFile; 11185 private File resourceFile; 11186 11187 /** New install */ 11188 MoveInstallArgs(InstallParams params) { 11189 super(params.origin, params.move, params.observer, params.installFlags, 11190 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11191 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11192 } 11193 11194 int copyApk(IMediaContainerService imcs, boolean temp) { 11195 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11196 + move.fromUuid + " to " + move.toUuid); 11197 synchronized (mInstaller) { 11198 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11199 move.dataAppName, move.appId, move.seinfo) != 0) { 11200 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11201 } 11202 } 11203 11204 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11205 resourceFile = codeFile; 11206 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11207 11208 return PackageManager.INSTALL_SUCCEEDED; 11209 } 11210 11211 int doPreInstall(int status) { 11212 if (status != PackageManager.INSTALL_SUCCEEDED) { 11213 cleanUp(); 11214 } 11215 return status; 11216 } 11217 11218 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11219 if (status != PackageManager.INSTALL_SUCCEEDED) { 11220 cleanUp(); 11221 return false; 11222 } 11223 11224 // Reflect the move in app info 11225 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11226 pkg.applicationInfo.setCodePath(pkg.codePath); 11227 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11228 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11229 pkg.applicationInfo.setResourcePath(pkg.codePath); 11230 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11231 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11232 11233 return true; 11234 } 11235 11236 int doPostInstall(int status, int uid) { 11237 if (status != PackageManager.INSTALL_SUCCEEDED) { 11238 cleanUp(); 11239 } 11240 return status; 11241 } 11242 11243 @Override 11244 String getCodePath() { 11245 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11246 } 11247 11248 @Override 11249 String getResourcePath() { 11250 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11251 } 11252 11253 private boolean cleanUp() { 11254 if (codeFile == null || !codeFile.exists()) { 11255 return false; 11256 } 11257 11258 if (codeFile.isDirectory()) { 11259 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11260 } else { 11261 codeFile.delete(); 11262 } 11263 11264 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11265 resourceFile.delete(); 11266 } 11267 11268 return true; 11269 } 11270 11271 void cleanUpResourcesLI() { 11272 cleanUp(); 11273 } 11274 11275 boolean doPostDeleteLI(boolean delete) { 11276 // XXX err, shouldn't we respect the delete flag? 11277 cleanUpResourcesLI(); 11278 return true; 11279 } 11280 } 11281 11282 static String getAsecPackageName(String packageCid) { 11283 int idx = packageCid.lastIndexOf("-"); 11284 if (idx == -1) { 11285 return packageCid; 11286 } 11287 return packageCid.substring(0, idx); 11288 } 11289 11290 // Utility method used to create code paths based on package name and available index. 11291 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11292 String idxStr = ""; 11293 int idx = 1; 11294 // Fall back to default value of idx=1 if prefix is not 11295 // part of oldCodePath 11296 if (oldCodePath != null) { 11297 String subStr = oldCodePath; 11298 // Drop the suffix right away 11299 if (suffix != null && subStr.endsWith(suffix)) { 11300 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11301 } 11302 // If oldCodePath already contains prefix find out the 11303 // ending index to either increment or decrement. 11304 int sidx = subStr.lastIndexOf(prefix); 11305 if (sidx != -1) { 11306 subStr = subStr.substring(sidx + prefix.length()); 11307 if (subStr != null) { 11308 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11309 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11310 } 11311 try { 11312 idx = Integer.parseInt(subStr); 11313 if (idx <= 1) { 11314 idx++; 11315 } else { 11316 idx--; 11317 } 11318 } catch(NumberFormatException e) { 11319 } 11320 } 11321 } 11322 } 11323 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11324 return prefix + idxStr; 11325 } 11326 11327 private File getNextCodePath(File targetDir, String packageName) { 11328 int suffix = 1; 11329 File result; 11330 do { 11331 result = new File(targetDir, packageName + "-" + suffix); 11332 suffix++; 11333 } while (result.exists()); 11334 return result; 11335 } 11336 11337 // Utility method that returns the relative package path with respect 11338 // to the installation directory. Like say for /data/data/com.test-1.apk 11339 // string com.test-1 is returned. 11340 static String deriveCodePathName(String codePath) { 11341 if (codePath == null) { 11342 return null; 11343 } 11344 final File codeFile = new File(codePath); 11345 final String name = codeFile.getName(); 11346 if (codeFile.isDirectory()) { 11347 return name; 11348 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11349 final int lastDot = name.lastIndexOf('.'); 11350 return name.substring(0, lastDot); 11351 } else { 11352 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11353 return null; 11354 } 11355 } 11356 11357 class PackageInstalledInfo { 11358 String name; 11359 int uid; 11360 // The set of users that originally had this package installed. 11361 int[] origUsers; 11362 // The set of users that now have this package installed. 11363 int[] newUsers; 11364 PackageParser.Package pkg; 11365 int returnCode; 11366 String returnMsg; 11367 PackageRemovedInfo removedInfo; 11368 11369 public void setError(int code, String msg) { 11370 returnCode = code; 11371 returnMsg = msg; 11372 Slog.w(TAG, msg); 11373 } 11374 11375 public void setError(String msg, PackageParserException e) { 11376 returnCode = e.error; 11377 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11378 Slog.w(TAG, msg, e); 11379 } 11380 11381 public void setError(String msg, PackageManagerException e) { 11382 returnCode = e.error; 11383 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11384 Slog.w(TAG, msg, e); 11385 } 11386 11387 // In some error cases we want to convey more info back to the observer 11388 String origPackage; 11389 String origPermission; 11390 } 11391 11392 /* 11393 * Install a non-existing package. 11394 */ 11395 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11396 UserHandle user, String installerPackageName, String volumeUuid, 11397 PackageInstalledInfo res) { 11398 // Remember this for later, in case we need to rollback this install 11399 String pkgName = pkg.packageName; 11400 11401 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11402 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11403 UserHandle.USER_OWNER).exists(); 11404 synchronized(mPackages) { 11405 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11406 // A package with the same name is already installed, though 11407 // it has been renamed to an older name. The package we 11408 // are trying to install should be installed as an update to 11409 // the existing one, but that has not been requested, so bail. 11410 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11411 + " without first uninstalling package running as " 11412 + mSettings.mRenamedPackages.get(pkgName)); 11413 return; 11414 } 11415 if (mPackages.containsKey(pkgName)) { 11416 // Don't allow installation over an existing package with the same name. 11417 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11418 + " without first uninstalling."); 11419 return; 11420 } 11421 } 11422 11423 try { 11424 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11425 System.currentTimeMillis(), user); 11426 11427 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11428 // delete the partially installed application. the data directory will have to be 11429 // restored if it was already existing 11430 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11431 // remove package from internal structures. Note that we want deletePackageX to 11432 // delete the package data and cache directories that it created in 11433 // scanPackageLocked, unless those directories existed before we even tried to 11434 // install. 11435 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11436 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11437 res.removedInfo, true); 11438 } 11439 11440 } catch (PackageManagerException e) { 11441 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11442 } 11443 } 11444 11445 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11446 // Can't rotate keys during boot or if sharedUser. 11447 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11448 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11449 return false; 11450 } 11451 // app is using upgradeKeySets; make sure all are valid 11452 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11453 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11454 for (int i = 0; i < upgradeKeySets.length; i++) { 11455 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11456 Slog.wtf(TAG, "Package " 11457 + (oldPs.name != null ? oldPs.name : "<null>") 11458 + " contains upgrade-key-set reference to unknown key-set: " 11459 + upgradeKeySets[i] 11460 + " reverting to signatures check."); 11461 return false; 11462 } 11463 } 11464 return true; 11465 } 11466 11467 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11468 // Upgrade keysets are being used. Determine if new package has a superset of the 11469 // required keys. 11470 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11471 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11472 for (int i = 0; i < upgradeKeySets.length; i++) { 11473 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11474 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11475 return true; 11476 } 11477 } 11478 return false; 11479 } 11480 11481 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11482 UserHandle user, String installerPackageName, String volumeUuid, 11483 PackageInstalledInfo res) { 11484 final PackageParser.Package oldPackage; 11485 final String pkgName = pkg.packageName; 11486 final int[] allUsers; 11487 final boolean[] perUserInstalled; 11488 final boolean weFroze; 11489 11490 // First find the old package info and check signatures 11491 synchronized(mPackages) { 11492 oldPackage = mPackages.get(pkgName); 11493 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11494 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11495 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11496 if(!checkUpgradeKeySetLP(ps, pkg)) { 11497 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11498 "New package not signed by keys specified by upgrade-keysets: " 11499 + pkgName); 11500 return; 11501 } 11502 } else { 11503 // default to original signature matching 11504 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11505 != PackageManager.SIGNATURE_MATCH) { 11506 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11507 "New package has a different signature: " + pkgName); 11508 return; 11509 } 11510 } 11511 11512 // In case of rollback, remember per-user/profile install state 11513 allUsers = sUserManager.getUserIds(); 11514 perUserInstalled = new boolean[allUsers.length]; 11515 for (int i = 0; i < allUsers.length; i++) { 11516 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11517 } 11518 11519 // Mark the app as frozen to prevent launching during the upgrade 11520 // process, and then kill all running instances 11521 if (!ps.frozen) { 11522 ps.frozen = true; 11523 weFroze = true; 11524 } else { 11525 weFroze = false; 11526 } 11527 } 11528 11529 // Now that we're guarded by frozen state, kill app during upgrade 11530 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11531 11532 try { 11533 boolean sysPkg = (isSystemApp(oldPackage)); 11534 if (sysPkg) { 11535 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11536 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11537 } else { 11538 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11539 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11540 } 11541 } finally { 11542 // Regardless of success or failure of upgrade steps above, always 11543 // unfreeze the package if we froze it 11544 if (weFroze) { 11545 unfreezePackage(pkgName); 11546 } 11547 } 11548 } 11549 11550 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11551 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11552 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11553 String volumeUuid, PackageInstalledInfo res) { 11554 String pkgName = deletedPackage.packageName; 11555 boolean deletedPkg = true; 11556 boolean updatedSettings = false; 11557 11558 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11559 + deletedPackage); 11560 long origUpdateTime; 11561 if (pkg.mExtras != null) { 11562 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11563 } else { 11564 origUpdateTime = 0; 11565 } 11566 11567 // First delete the existing package while retaining the data directory 11568 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11569 res.removedInfo, true)) { 11570 // If the existing package wasn't successfully deleted 11571 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11572 deletedPkg = false; 11573 } else { 11574 // Successfully deleted the old package; proceed with replace. 11575 11576 // If deleted package lived in a container, give users a chance to 11577 // relinquish resources before killing. 11578 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11579 if (DEBUG_INSTALL) { 11580 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11581 } 11582 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11583 final ArrayList<String> pkgList = new ArrayList<String>(1); 11584 pkgList.add(deletedPackage.applicationInfo.packageName); 11585 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11586 } 11587 11588 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11589 try { 11590 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11591 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11592 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11593 perUserInstalled, res, user); 11594 updatedSettings = true; 11595 } catch (PackageManagerException e) { 11596 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11597 } 11598 } 11599 11600 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11601 // remove package from internal structures. Note that we want deletePackageX to 11602 // delete the package data and cache directories that it created in 11603 // scanPackageLocked, unless those directories existed before we even tried to 11604 // install. 11605 if(updatedSettings) { 11606 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11607 deletePackageLI( 11608 pkgName, null, true, allUsers, perUserInstalled, 11609 PackageManager.DELETE_KEEP_DATA, 11610 res.removedInfo, true); 11611 } 11612 // Since we failed to install the new package we need to restore the old 11613 // package that we deleted. 11614 if (deletedPkg) { 11615 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11616 File restoreFile = new File(deletedPackage.codePath); 11617 // Parse old package 11618 boolean oldExternal = isExternal(deletedPackage); 11619 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11620 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11621 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11622 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11623 try { 11624 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11625 } catch (PackageManagerException e) { 11626 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11627 + e.getMessage()); 11628 return; 11629 } 11630 // Restore of old package succeeded. Update permissions. 11631 // writer 11632 synchronized (mPackages) { 11633 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11634 UPDATE_PERMISSIONS_ALL); 11635 // can downgrade to reader 11636 mSettings.writeLPr(); 11637 } 11638 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11639 } 11640 } 11641 } 11642 11643 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11644 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11645 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11646 String volumeUuid, PackageInstalledInfo res) { 11647 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11648 + ", old=" + deletedPackage); 11649 boolean disabledSystem = false; 11650 boolean updatedSettings = false; 11651 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11652 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11653 != 0) { 11654 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11655 } 11656 String packageName = deletedPackage.packageName; 11657 if (packageName == null) { 11658 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11659 "Attempt to delete null packageName."); 11660 return; 11661 } 11662 PackageParser.Package oldPkg; 11663 PackageSetting oldPkgSetting; 11664 // reader 11665 synchronized (mPackages) { 11666 oldPkg = mPackages.get(packageName); 11667 oldPkgSetting = mSettings.mPackages.get(packageName); 11668 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11669 (oldPkgSetting == null)) { 11670 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11671 "Couldn't find package:" + packageName + " information"); 11672 return; 11673 } 11674 } 11675 11676 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11677 res.removedInfo.removedPackage = packageName; 11678 // Remove existing system package 11679 removePackageLI(oldPkgSetting, true); 11680 // writer 11681 synchronized (mPackages) { 11682 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11683 if (!disabledSystem && deletedPackage != null) { 11684 // We didn't need to disable the .apk as a current system package, 11685 // which means we are replacing another update that is already 11686 // installed. We need to make sure to delete the older one's .apk. 11687 res.removedInfo.args = createInstallArgsForExisting(0, 11688 deletedPackage.applicationInfo.getCodePath(), 11689 deletedPackage.applicationInfo.getResourcePath(), 11690 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11691 } else { 11692 res.removedInfo.args = null; 11693 } 11694 } 11695 11696 // Successfully disabled the old package. Now proceed with re-installation 11697 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11698 11699 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11700 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11701 11702 PackageParser.Package newPackage = null; 11703 try { 11704 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11705 if (newPackage.mExtras != null) { 11706 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11707 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11708 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11709 11710 // is the update attempting to change shared user? that isn't going to work... 11711 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11712 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11713 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11714 + " to " + newPkgSetting.sharedUser); 11715 updatedSettings = true; 11716 } 11717 } 11718 11719 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11720 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11721 perUserInstalled, res, user); 11722 updatedSettings = true; 11723 } 11724 11725 } catch (PackageManagerException e) { 11726 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11727 } 11728 11729 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11730 // Re installation failed. Restore old information 11731 // Remove new pkg information 11732 if (newPackage != null) { 11733 removeInstalledPackageLI(newPackage, true); 11734 } 11735 // Add back the old system package 11736 try { 11737 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11738 } catch (PackageManagerException e) { 11739 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11740 } 11741 // Restore the old system information in Settings 11742 synchronized (mPackages) { 11743 if (disabledSystem) { 11744 mSettings.enableSystemPackageLPw(packageName); 11745 } 11746 if (updatedSettings) { 11747 mSettings.setInstallerPackageName(packageName, 11748 oldPkgSetting.installerPackageName); 11749 } 11750 mSettings.writeLPr(); 11751 } 11752 } 11753 } 11754 11755 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11756 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11757 UserHandle user) { 11758 String pkgName = newPackage.packageName; 11759 synchronized (mPackages) { 11760 //write settings. the installStatus will be incomplete at this stage. 11761 //note that the new package setting would have already been 11762 //added to mPackages. It hasn't been persisted yet. 11763 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11764 mSettings.writeLPr(); 11765 } 11766 11767 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11768 11769 synchronized (mPackages) { 11770 updatePermissionsLPw(newPackage.packageName, newPackage, 11771 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11772 ? UPDATE_PERMISSIONS_ALL : 0)); 11773 // For system-bundled packages, we assume that installing an upgraded version 11774 // of the package implies that the user actually wants to run that new code, 11775 // so we enable the package. 11776 PackageSetting ps = mSettings.mPackages.get(pkgName); 11777 if (ps != null) { 11778 if (isSystemApp(newPackage)) { 11779 // NB: implicit assumption that system package upgrades apply to all users 11780 if (DEBUG_INSTALL) { 11781 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11782 } 11783 if (res.origUsers != null) { 11784 for (int userHandle : res.origUsers) { 11785 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11786 userHandle, installerPackageName); 11787 } 11788 } 11789 // Also convey the prior install/uninstall state 11790 if (allUsers != null && perUserInstalled != null) { 11791 for (int i = 0; i < allUsers.length; i++) { 11792 if (DEBUG_INSTALL) { 11793 Slog.d(TAG, " user " + allUsers[i] 11794 + " => " + perUserInstalled[i]); 11795 } 11796 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11797 } 11798 // these install state changes will be persisted in the 11799 // upcoming call to mSettings.writeLPr(). 11800 } 11801 } 11802 // It's implied that when a user requests installation, they want the app to be 11803 // installed and enabled. 11804 int userId = user.getIdentifier(); 11805 if (userId != UserHandle.USER_ALL) { 11806 ps.setInstalled(true, userId); 11807 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11808 } 11809 } 11810 res.name = pkgName; 11811 res.uid = newPackage.applicationInfo.uid; 11812 res.pkg = newPackage; 11813 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11814 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11815 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11816 //to update install status 11817 mSettings.writeLPr(); 11818 } 11819 } 11820 11821 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11822 final int installFlags = args.installFlags; 11823 final String installerPackageName = args.installerPackageName; 11824 final String volumeUuid = args.volumeUuid; 11825 final File tmpPackageFile = new File(args.getCodePath()); 11826 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11827 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11828 || (args.volumeUuid != null)); 11829 boolean replace = false; 11830 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11831 if (args.move != null) { 11832 // moving a complete application; perfom an initial scan on the new install location 11833 scanFlags |= SCAN_INITIAL; 11834 } 11835 // Result object to be returned 11836 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11837 11838 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11839 // Retrieve PackageSettings and parse package 11840 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11841 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11842 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11843 PackageParser pp = new PackageParser(); 11844 pp.setSeparateProcesses(mSeparateProcesses); 11845 pp.setDisplayMetrics(mMetrics); 11846 11847 final PackageParser.Package pkg; 11848 try { 11849 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11850 } catch (PackageParserException e) { 11851 res.setError("Failed parse during installPackageLI", e); 11852 return; 11853 } 11854 11855 // Mark that we have an install time CPU ABI override. 11856 pkg.cpuAbiOverride = args.abiOverride; 11857 11858 String pkgName = res.name = pkg.packageName; 11859 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11860 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11861 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11862 return; 11863 } 11864 } 11865 11866 try { 11867 pp.collectCertificates(pkg, parseFlags); 11868 pp.collectManifestDigest(pkg); 11869 } catch (PackageParserException e) { 11870 res.setError("Failed collect during installPackageLI", e); 11871 return; 11872 } 11873 11874 /* If the installer passed in a manifest digest, compare it now. */ 11875 if (args.manifestDigest != null) { 11876 if (DEBUG_INSTALL) { 11877 final String parsedManifest = pkg.manifestDigest == null ? "null" 11878 : pkg.manifestDigest.toString(); 11879 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11880 + parsedManifest); 11881 } 11882 11883 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11884 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11885 return; 11886 } 11887 } else if (DEBUG_INSTALL) { 11888 final String parsedManifest = pkg.manifestDigest == null 11889 ? "null" : pkg.manifestDigest.toString(); 11890 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11891 } 11892 11893 // Get rid of all references to package scan path via parser. 11894 pp = null; 11895 String oldCodePath = null; 11896 boolean systemApp = false; 11897 synchronized (mPackages) { 11898 // Check if installing already existing package 11899 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11900 String oldName = mSettings.mRenamedPackages.get(pkgName); 11901 if (pkg.mOriginalPackages != null 11902 && pkg.mOriginalPackages.contains(oldName) 11903 && mPackages.containsKey(oldName)) { 11904 // This package is derived from an original package, 11905 // and this device has been updating from that original 11906 // name. We must continue using the original name, so 11907 // rename the new package here. 11908 pkg.setPackageName(oldName); 11909 pkgName = pkg.packageName; 11910 replace = true; 11911 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11912 + oldName + " pkgName=" + pkgName); 11913 } else if (mPackages.containsKey(pkgName)) { 11914 // This package, under its official name, already exists 11915 // on the device; we should replace it. 11916 replace = true; 11917 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11918 } 11919 11920 // Prevent apps opting out from runtime permissions 11921 if (replace) { 11922 PackageParser.Package oldPackage = mPackages.get(pkgName); 11923 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11924 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11925 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11926 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11927 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11928 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11929 + " doesn't support runtime permissions but the old" 11930 + " target SDK " + oldTargetSdk + " does."); 11931 return; 11932 } 11933 } 11934 } 11935 11936 PackageSetting ps = mSettings.mPackages.get(pkgName); 11937 if (ps != null) { 11938 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11939 11940 // Quick sanity check that we're signed correctly if updating; 11941 // we'll check this again later when scanning, but we want to 11942 // bail early here before tripping over redefined permissions. 11943 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11944 if (!checkUpgradeKeySetLP(ps, pkg)) { 11945 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11946 + pkg.packageName + " upgrade keys do not match the " 11947 + "previously installed version"); 11948 return; 11949 } 11950 } else { 11951 try { 11952 verifySignaturesLP(ps, pkg); 11953 } catch (PackageManagerException e) { 11954 res.setError(e.error, e.getMessage()); 11955 return; 11956 } 11957 } 11958 11959 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11960 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11961 systemApp = (ps.pkg.applicationInfo.flags & 11962 ApplicationInfo.FLAG_SYSTEM) != 0; 11963 } 11964 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11965 } 11966 11967 // Check whether the newly-scanned package wants to define an already-defined perm 11968 int N = pkg.permissions.size(); 11969 for (int i = N-1; i >= 0; i--) { 11970 PackageParser.Permission perm = pkg.permissions.get(i); 11971 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11972 if (bp != null) { 11973 // If the defining package is signed with our cert, it's okay. This 11974 // also includes the "updating the same package" case, of course. 11975 // "updating same package" could also involve key-rotation. 11976 final boolean sigsOk; 11977 if (bp.sourcePackage.equals(pkg.packageName) 11978 && (bp.packageSetting instanceof PackageSetting) 11979 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11980 scanFlags))) { 11981 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11982 } else { 11983 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11984 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11985 } 11986 if (!sigsOk) { 11987 // If the owning package is the system itself, we log but allow 11988 // install to proceed; we fail the install on all other permission 11989 // redefinitions. 11990 if (!bp.sourcePackage.equals("android")) { 11991 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11992 + pkg.packageName + " attempting to redeclare permission " 11993 + perm.info.name + " already owned by " + bp.sourcePackage); 11994 res.origPermission = perm.info.name; 11995 res.origPackage = bp.sourcePackage; 11996 return; 11997 } else { 11998 Slog.w(TAG, "Package " + pkg.packageName 11999 + " attempting to redeclare system permission " 12000 + perm.info.name + "; ignoring new declaration"); 12001 pkg.permissions.remove(i); 12002 } 12003 } 12004 } 12005 } 12006 12007 } 12008 12009 if (systemApp && onExternal) { 12010 // Disable updates to system apps on sdcard 12011 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12012 "Cannot install updates to system apps on sdcard"); 12013 return; 12014 } 12015 12016 if (args.move != null) { 12017 // We did an in-place move, so dex is ready to roll 12018 scanFlags |= SCAN_NO_DEX; 12019 scanFlags |= SCAN_MOVE; 12020 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12021 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12022 scanFlags |= SCAN_NO_DEX; 12023 12024 try { 12025 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12026 true /* extract libs */); 12027 } catch (PackageManagerException pme) { 12028 Slog.e(TAG, "Error deriving application ABI", pme); 12029 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12030 return; 12031 } 12032 12033 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12034 int result = mPackageDexOptimizer 12035 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12036 false /* defer */, false /* inclDependencies */); 12037 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12038 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12039 return; 12040 } 12041 } 12042 12043 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12044 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12045 return; 12046 } 12047 12048 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12049 12050 if (replace) { 12051 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12052 installerPackageName, volumeUuid, res); 12053 } else { 12054 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12055 args.user, installerPackageName, volumeUuid, res); 12056 } 12057 synchronized (mPackages) { 12058 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12059 if (ps != null) { 12060 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12061 } 12062 } 12063 } 12064 12065 private void startIntentFilterVerifications(int userId, boolean replacing, 12066 PackageParser.Package pkg) { 12067 if (mIntentFilterVerifierComponent == null) { 12068 Slog.w(TAG, "No IntentFilter verification will not be done as " 12069 + "there is no IntentFilterVerifier available!"); 12070 return; 12071 } 12072 12073 final int verifierUid = getPackageUid( 12074 mIntentFilterVerifierComponent.getPackageName(), 12075 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12076 12077 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12078 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12079 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12080 mHandler.sendMessage(msg); 12081 } 12082 12083 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12084 PackageParser.Package pkg) { 12085 int size = pkg.activities.size(); 12086 if (size == 0) { 12087 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12088 "No activity, so no need to verify any IntentFilter!"); 12089 return; 12090 } 12091 12092 final boolean hasDomainURLs = hasDomainURLs(pkg); 12093 if (!hasDomainURLs) { 12094 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12095 "No domain URLs, so no need to verify any IntentFilter!"); 12096 return; 12097 } 12098 12099 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12100 + " if any IntentFilter from the " + size 12101 + " Activities needs verification ..."); 12102 12103 int count = 0; 12104 final String packageName = pkg.packageName; 12105 12106 synchronized (mPackages) { 12107 // If this is a new install and we see that we've already run verification for this 12108 // package, we have nothing to do: it means the state was restored from backup. 12109 if (!replacing) { 12110 IntentFilterVerificationInfo ivi = 12111 mSettings.getIntentFilterVerificationLPr(packageName); 12112 if (ivi != null) { 12113 if (DEBUG_DOMAIN_VERIFICATION) { 12114 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12115 + ivi.getStatusString()); 12116 } 12117 return; 12118 } 12119 } 12120 12121 // If any filters need to be verified, then all need to be. 12122 boolean needToVerify = false; 12123 for (PackageParser.Activity a : pkg.activities) { 12124 for (ActivityIntentInfo filter : a.intents) { 12125 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12126 if (DEBUG_DOMAIN_VERIFICATION) { 12127 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12128 } 12129 needToVerify = true; 12130 break; 12131 } 12132 } 12133 } 12134 12135 if (needToVerify) { 12136 final int verificationId = mIntentFilterVerificationToken++; 12137 for (PackageParser.Activity a : pkg.activities) { 12138 for (ActivityIntentInfo filter : a.intents) { 12139 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12140 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12141 "Verification needed for IntentFilter:" + filter.toString()); 12142 mIntentFilterVerifier.addOneIntentFilterVerification( 12143 verifierUid, userId, verificationId, filter, packageName); 12144 count++; 12145 } 12146 } 12147 } 12148 } 12149 } 12150 12151 if (count > 0) { 12152 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12153 + " IntentFilter verification" + (count > 1 ? "s" : "") 12154 + " for userId:" + userId); 12155 mIntentFilterVerifier.startVerifications(userId); 12156 } else { 12157 if (DEBUG_DOMAIN_VERIFICATION) { 12158 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12159 } 12160 } 12161 } 12162 12163 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12164 final ComponentName cn = filter.activity.getComponentName(); 12165 final String packageName = cn.getPackageName(); 12166 12167 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12168 packageName); 12169 if (ivi == null) { 12170 return true; 12171 } 12172 int status = ivi.getStatus(); 12173 switch (status) { 12174 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12175 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12176 return true; 12177 12178 default: 12179 // Nothing to do 12180 return false; 12181 } 12182 } 12183 12184 private static boolean isMultiArch(PackageSetting ps) { 12185 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12186 } 12187 12188 private static boolean isMultiArch(ApplicationInfo info) { 12189 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12190 } 12191 12192 private static boolean isExternal(PackageParser.Package pkg) { 12193 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12194 } 12195 12196 private static boolean isExternal(PackageSetting ps) { 12197 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12198 } 12199 12200 private static boolean isExternal(ApplicationInfo info) { 12201 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12202 } 12203 12204 private static boolean isSystemApp(PackageParser.Package pkg) { 12205 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12206 } 12207 12208 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12209 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12210 } 12211 12212 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12213 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12214 } 12215 12216 private static boolean isSystemApp(PackageSetting ps) { 12217 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12218 } 12219 12220 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12221 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12222 } 12223 12224 private int packageFlagsToInstallFlags(PackageSetting ps) { 12225 int installFlags = 0; 12226 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12227 // This existing package was an external ASEC install when we have 12228 // the external flag without a UUID 12229 installFlags |= PackageManager.INSTALL_EXTERNAL; 12230 } 12231 if (ps.isForwardLocked()) { 12232 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12233 } 12234 return installFlags; 12235 } 12236 12237 private void deleteTempPackageFiles() { 12238 final FilenameFilter filter = new FilenameFilter() { 12239 public boolean accept(File dir, String name) { 12240 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12241 } 12242 }; 12243 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12244 file.delete(); 12245 } 12246 } 12247 12248 @Override 12249 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12250 int flags) { 12251 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12252 flags); 12253 } 12254 12255 @Override 12256 public void deletePackage(final String packageName, 12257 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12258 mContext.enforceCallingOrSelfPermission( 12259 android.Manifest.permission.DELETE_PACKAGES, null); 12260 final int uid = Binder.getCallingUid(); 12261 if (UserHandle.getUserId(uid) != userId) { 12262 mContext.enforceCallingPermission( 12263 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12264 "deletePackage for user " + userId); 12265 } 12266 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12267 try { 12268 observer.onPackageDeleted(packageName, 12269 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12270 } catch (RemoteException re) { 12271 } 12272 return; 12273 } 12274 12275 boolean uninstallBlocked = false; 12276 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12277 int[] users = sUserManager.getUserIds(); 12278 for (int i = 0; i < users.length; ++i) { 12279 if (getBlockUninstallForUser(packageName, users[i])) { 12280 uninstallBlocked = true; 12281 break; 12282 } 12283 } 12284 } else { 12285 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12286 } 12287 if (uninstallBlocked) { 12288 try { 12289 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12290 null); 12291 } catch (RemoteException re) { 12292 } 12293 return; 12294 } 12295 12296 if (DEBUG_REMOVE) { 12297 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12298 } 12299 // Queue up an async operation since the package deletion may take a little while. 12300 mHandler.post(new Runnable() { 12301 public void run() { 12302 mHandler.removeCallbacks(this); 12303 final int returnCode = deletePackageX(packageName, userId, flags); 12304 if (observer != null) { 12305 try { 12306 observer.onPackageDeleted(packageName, returnCode, null); 12307 } catch (RemoteException e) { 12308 Log.i(TAG, "Observer no longer exists."); 12309 } //end catch 12310 } //end if 12311 } //end run 12312 }); 12313 } 12314 12315 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12316 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12317 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12318 try { 12319 if (dpm != null) { 12320 if (dpm.isDeviceOwner(packageName)) { 12321 return true; 12322 } 12323 int[] users; 12324 if (userId == UserHandle.USER_ALL) { 12325 users = sUserManager.getUserIds(); 12326 } else { 12327 users = new int[]{userId}; 12328 } 12329 for (int i = 0; i < users.length; ++i) { 12330 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12331 return true; 12332 } 12333 } 12334 } 12335 } catch (RemoteException e) { 12336 } 12337 return false; 12338 } 12339 12340 /** 12341 * This method is an internal method that could be get invoked either 12342 * to delete an installed package or to clean up a failed installation. 12343 * After deleting an installed package, a broadcast is sent to notify any 12344 * listeners that the package has been installed. For cleaning up a failed 12345 * installation, the broadcast is not necessary since the package's 12346 * installation wouldn't have sent the initial broadcast either 12347 * The key steps in deleting a package are 12348 * deleting the package information in internal structures like mPackages, 12349 * deleting the packages base directories through installd 12350 * updating mSettings to reflect current status 12351 * persisting settings for later use 12352 * sending a broadcast if necessary 12353 */ 12354 private int deletePackageX(String packageName, int userId, int flags) { 12355 final PackageRemovedInfo info = new PackageRemovedInfo(); 12356 final boolean res; 12357 12358 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12359 ? UserHandle.ALL : new UserHandle(userId); 12360 12361 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12362 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12363 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12364 } 12365 12366 boolean removedForAllUsers = false; 12367 boolean systemUpdate = false; 12368 12369 // for the uninstall-updates case and restricted profiles, remember the per- 12370 // userhandle installed state 12371 int[] allUsers; 12372 boolean[] perUserInstalled; 12373 synchronized (mPackages) { 12374 PackageSetting ps = mSettings.mPackages.get(packageName); 12375 allUsers = sUserManager.getUserIds(); 12376 perUserInstalled = new boolean[allUsers.length]; 12377 for (int i = 0; i < allUsers.length; i++) { 12378 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12379 } 12380 } 12381 12382 synchronized (mInstallLock) { 12383 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12384 res = deletePackageLI(packageName, removeForUser, 12385 true, allUsers, perUserInstalled, 12386 flags | REMOVE_CHATTY, info, true); 12387 systemUpdate = info.isRemovedPackageSystemUpdate; 12388 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12389 removedForAllUsers = true; 12390 } 12391 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12392 + " removedForAllUsers=" + removedForAllUsers); 12393 } 12394 12395 if (res) { 12396 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12397 12398 // If the removed package was a system update, the old system package 12399 // was re-enabled; we need to broadcast this information 12400 if (systemUpdate) { 12401 Bundle extras = new Bundle(1); 12402 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12403 ? info.removedAppId : info.uid); 12404 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12405 12406 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12407 extras, null, null, null); 12408 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12409 extras, null, null, null); 12410 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12411 null, packageName, null, null); 12412 } 12413 } 12414 // Force a gc here. 12415 Runtime.getRuntime().gc(); 12416 // Delete the resources here after sending the broadcast to let 12417 // other processes clean up before deleting resources. 12418 if (info.args != null) { 12419 synchronized (mInstallLock) { 12420 info.args.doPostDeleteLI(true); 12421 } 12422 } 12423 12424 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12425 } 12426 12427 class PackageRemovedInfo { 12428 String removedPackage; 12429 int uid = -1; 12430 int removedAppId = -1; 12431 int[] removedUsers = null; 12432 boolean isRemovedPackageSystemUpdate = false; 12433 // Clean up resources deleted packages. 12434 InstallArgs args = null; 12435 12436 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12437 Bundle extras = new Bundle(1); 12438 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12439 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12440 if (replacing) { 12441 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12442 } 12443 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12444 if (removedPackage != null) { 12445 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12446 extras, null, null, removedUsers); 12447 if (fullRemove && !replacing) { 12448 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12449 extras, null, null, removedUsers); 12450 } 12451 } 12452 if (removedAppId >= 0) { 12453 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12454 removedUsers); 12455 } 12456 } 12457 } 12458 12459 /* 12460 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12461 * flag is not set, the data directory is removed as well. 12462 * make sure this flag is set for partially installed apps. If not its meaningless to 12463 * delete a partially installed application. 12464 */ 12465 private void removePackageDataLI(PackageSetting ps, 12466 int[] allUserHandles, boolean[] perUserInstalled, 12467 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12468 String packageName = ps.name; 12469 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12470 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12471 // Retrieve object to delete permissions for shared user later on 12472 final PackageSetting deletedPs; 12473 // reader 12474 synchronized (mPackages) { 12475 deletedPs = mSettings.mPackages.get(packageName); 12476 if (outInfo != null) { 12477 outInfo.removedPackage = packageName; 12478 outInfo.removedUsers = deletedPs != null 12479 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12480 : null; 12481 } 12482 } 12483 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12484 removeDataDirsLI(ps.volumeUuid, packageName); 12485 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12486 } 12487 // writer 12488 synchronized (mPackages) { 12489 if (deletedPs != null) { 12490 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12491 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12492 clearDefaultBrowserIfNeeded(packageName); 12493 if (outInfo != null) { 12494 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12495 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12496 } 12497 updatePermissionsLPw(deletedPs.name, null, 0); 12498 if (deletedPs.sharedUser != null) { 12499 // Remove permissions associated with package. Since runtime 12500 // permissions are per user we have to kill the removed package 12501 // or packages running under the shared user of the removed 12502 // package if revoking the permissions requested only by the removed 12503 // package is successful and this causes a change in gids. 12504 for (int userId : UserManagerService.getInstance().getUserIds()) { 12505 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12506 userId); 12507 if (userIdToKill == UserHandle.USER_ALL 12508 || userIdToKill >= UserHandle.USER_OWNER) { 12509 // If gids changed for this user, kill all affected packages. 12510 mHandler.post(new Runnable() { 12511 @Override 12512 public void run() { 12513 // This has to happen with no lock held. 12514 killSettingPackagesForUser(deletedPs, userIdToKill, 12515 KILL_APP_REASON_GIDS_CHANGED); 12516 } 12517 }); 12518 break; 12519 } 12520 } 12521 } 12522 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12523 } 12524 // make sure to preserve per-user disabled state if this removal was just 12525 // a downgrade of a system app to the factory package 12526 if (allUserHandles != null && perUserInstalled != null) { 12527 if (DEBUG_REMOVE) { 12528 Slog.d(TAG, "Propagating install state across downgrade"); 12529 } 12530 for (int i = 0; i < allUserHandles.length; i++) { 12531 if (DEBUG_REMOVE) { 12532 Slog.d(TAG, " user " + allUserHandles[i] 12533 + " => " + perUserInstalled[i]); 12534 } 12535 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12536 } 12537 } 12538 } 12539 // can downgrade to reader 12540 if (writeSettings) { 12541 // Save settings now 12542 mSettings.writeLPr(); 12543 } 12544 } 12545 if (outInfo != null) { 12546 // A user ID was deleted here. Go through all users and remove it 12547 // from KeyStore. 12548 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12549 } 12550 } 12551 12552 static boolean locationIsPrivileged(File path) { 12553 try { 12554 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12555 .getCanonicalPath(); 12556 return path.getCanonicalPath().startsWith(privilegedAppDir); 12557 } catch (IOException e) { 12558 Slog.e(TAG, "Unable to access code path " + path); 12559 } 12560 return false; 12561 } 12562 12563 /* 12564 * Tries to delete system package. 12565 */ 12566 private boolean deleteSystemPackageLI(PackageSetting newPs, 12567 int[] allUserHandles, boolean[] perUserInstalled, 12568 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12569 final boolean applyUserRestrictions 12570 = (allUserHandles != null) && (perUserInstalled != null); 12571 PackageSetting disabledPs = null; 12572 // Confirm if the system package has been updated 12573 // An updated system app can be deleted. This will also have to restore 12574 // the system pkg from system partition 12575 // reader 12576 synchronized (mPackages) { 12577 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12578 } 12579 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12580 + " disabledPs=" + disabledPs); 12581 if (disabledPs == null) { 12582 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12583 return false; 12584 } else if (DEBUG_REMOVE) { 12585 Slog.d(TAG, "Deleting system pkg from data partition"); 12586 } 12587 if (DEBUG_REMOVE) { 12588 if (applyUserRestrictions) { 12589 Slog.d(TAG, "Remembering install states:"); 12590 for (int i = 0; i < allUserHandles.length; i++) { 12591 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12592 } 12593 } 12594 } 12595 // Delete the updated package 12596 outInfo.isRemovedPackageSystemUpdate = true; 12597 if (disabledPs.versionCode < newPs.versionCode) { 12598 // Delete data for downgrades 12599 flags &= ~PackageManager.DELETE_KEEP_DATA; 12600 } else { 12601 // Preserve data by setting flag 12602 flags |= PackageManager.DELETE_KEEP_DATA; 12603 } 12604 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12605 allUserHandles, perUserInstalled, outInfo, writeSettings); 12606 if (!ret) { 12607 return false; 12608 } 12609 // writer 12610 synchronized (mPackages) { 12611 // Reinstate the old system package 12612 mSettings.enableSystemPackageLPw(newPs.name); 12613 // Remove any native libraries from the upgraded package. 12614 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12615 } 12616 // Install the system package 12617 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12618 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12619 if (locationIsPrivileged(disabledPs.codePath)) { 12620 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12621 } 12622 12623 final PackageParser.Package newPkg; 12624 try { 12625 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12626 } catch (PackageManagerException e) { 12627 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12628 return false; 12629 } 12630 12631 // writer 12632 synchronized (mPackages) { 12633 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12634 updatePermissionsLPw(newPkg.packageName, newPkg, 12635 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12636 if (applyUserRestrictions) { 12637 if (DEBUG_REMOVE) { 12638 Slog.d(TAG, "Propagating install state across reinstall"); 12639 } 12640 for (int i = 0; i < allUserHandles.length; i++) { 12641 if (DEBUG_REMOVE) { 12642 Slog.d(TAG, " user " + allUserHandles[i] 12643 + " => " + perUserInstalled[i]); 12644 } 12645 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12646 } 12647 // Regardless of writeSettings we need to ensure that this restriction 12648 // state propagation is persisted 12649 mSettings.writeAllUsersPackageRestrictionsLPr(); 12650 } 12651 // can downgrade to reader here 12652 if (writeSettings) { 12653 mSettings.writeLPr(); 12654 } 12655 } 12656 return true; 12657 } 12658 12659 private boolean deleteInstalledPackageLI(PackageSetting ps, 12660 boolean deleteCodeAndResources, int flags, 12661 int[] allUserHandles, boolean[] perUserInstalled, 12662 PackageRemovedInfo outInfo, boolean writeSettings) { 12663 if (outInfo != null) { 12664 outInfo.uid = ps.appId; 12665 } 12666 12667 // Delete package data from internal structures and also remove data if flag is set 12668 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12669 12670 // Delete application code and resources 12671 if (deleteCodeAndResources && (outInfo != null)) { 12672 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12673 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12674 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12675 } 12676 return true; 12677 } 12678 12679 @Override 12680 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12681 int userId) { 12682 mContext.enforceCallingOrSelfPermission( 12683 android.Manifest.permission.DELETE_PACKAGES, null); 12684 synchronized (mPackages) { 12685 PackageSetting ps = mSettings.mPackages.get(packageName); 12686 if (ps == null) { 12687 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12688 return false; 12689 } 12690 if (!ps.getInstalled(userId)) { 12691 // Can't block uninstall for an app that is not installed or enabled. 12692 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12693 return false; 12694 } 12695 ps.setBlockUninstall(blockUninstall, userId); 12696 mSettings.writePackageRestrictionsLPr(userId); 12697 } 12698 return true; 12699 } 12700 12701 @Override 12702 public boolean getBlockUninstallForUser(String packageName, int userId) { 12703 synchronized (mPackages) { 12704 PackageSetting ps = mSettings.mPackages.get(packageName); 12705 if (ps == null) { 12706 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12707 return false; 12708 } 12709 return ps.getBlockUninstall(userId); 12710 } 12711 } 12712 12713 /* 12714 * This method handles package deletion in general 12715 */ 12716 private boolean deletePackageLI(String packageName, UserHandle user, 12717 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12718 int flags, PackageRemovedInfo outInfo, 12719 boolean writeSettings) { 12720 if (packageName == null) { 12721 Slog.w(TAG, "Attempt to delete null packageName."); 12722 return false; 12723 } 12724 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12725 PackageSetting ps; 12726 boolean dataOnly = false; 12727 int removeUser = -1; 12728 int appId = -1; 12729 synchronized (mPackages) { 12730 ps = mSettings.mPackages.get(packageName); 12731 if (ps == null) { 12732 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12733 return false; 12734 } 12735 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12736 && user.getIdentifier() != UserHandle.USER_ALL) { 12737 // The caller is asking that the package only be deleted for a single 12738 // user. To do this, we just mark its uninstalled state and delete 12739 // its data. If this is a system app, we only allow this to happen if 12740 // they have set the special DELETE_SYSTEM_APP which requests different 12741 // semantics than normal for uninstalling system apps. 12742 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12743 ps.setUserState(user.getIdentifier(), 12744 COMPONENT_ENABLED_STATE_DEFAULT, 12745 false, //installed 12746 true, //stopped 12747 true, //notLaunched 12748 false, //hidden 12749 null, null, null, 12750 false, // blockUninstall 12751 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12752 if (!isSystemApp(ps)) { 12753 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12754 // Other user still have this package installed, so all 12755 // we need to do is clear this user's data and save that 12756 // it is uninstalled. 12757 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12758 removeUser = user.getIdentifier(); 12759 appId = ps.appId; 12760 scheduleWritePackageRestrictionsLocked(removeUser); 12761 } else { 12762 // We need to set it back to 'installed' so the uninstall 12763 // broadcasts will be sent correctly. 12764 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12765 ps.setInstalled(true, user.getIdentifier()); 12766 } 12767 } else { 12768 // This is a system app, so we assume that the 12769 // other users still have this package installed, so all 12770 // we need to do is clear this user's data and save that 12771 // it is uninstalled. 12772 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12773 removeUser = user.getIdentifier(); 12774 appId = ps.appId; 12775 scheduleWritePackageRestrictionsLocked(removeUser); 12776 } 12777 } 12778 } 12779 12780 if (removeUser >= 0) { 12781 // From above, we determined that we are deleting this only 12782 // for a single user. Continue the work here. 12783 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12784 if (outInfo != null) { 12785 outInfo.removedPackage = packageName; 12786 outInfo.removedAppId = appId; 12787 outInfo.removedUsers = new int[] {removeUser}; 12788 } 12789 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12790 removeKeystoreDataIfNeeded(removeUser, appId); 12791 schedulePackageCleaning(packageName, removeUser, false); 12792 synchronized (mPackages) { 12793 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12794 scheduleWritePackageRestrictionsLocked(removeUser); 12795 } 12796 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12797 removeUser); 12798 } 12799 return true; 12800 } 12801 12802 if (dataOnly) { 12803 // Delete application data first 12804 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12805 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12806 return true; 12807 } 12808 12809 boolean ret = false; 12810 if (isSystemApp(ps)) { 12811 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12812 // When an updated system application is deleted we delete the existing resources as well and 12813 // fall back to existing code in system partition 12814 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12815 flags, outInfo, writeSettings); 12816 } else { 12817 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12818 // Kill application pre-emptively especially for apps on sd. 12819 killApplication(packageName, ps.appId, "uninstall pkg"); 12820 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12821 allUserHandles, perUserInstalled, 12822 outInfo, writeSettings); 12823 } 12824 12825 return ret; 12826 } 12827 12828 private final class ClearStorageConnection implements ServiceConnection { 12829 IMediaContainerService mContainerService; 12830 12831 @Override 12832 public void onServiceConnected(ComponentName name, IBinder service) { 12833 synchronized (this) { 12834 mContainerService = IMediaContainerService.Stub.asInterface(service); 12835 notifyAll(); 12836 } 12837 } 12838 12839 @Override 12840 public void onServiceDisconnected(ComponentName name) { 12841 } 12842 } 12843 12844 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12845 final boolean mounted; 12846 if (Environment.isExternalStorageEmulated()) { 12847 mounted = true; 12848 } else { 12849 final String status = Environment.getExternalStorageState(); 12850 12851 mounted = status.equals(Environment.MEDIA_MOUNTED) 12852 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12853 } 12854 12855 if (!mounted) { 12856 return; 12857 } 12858 12859 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12860 int[] users; 12861 if (userId == UserHandle.USER_ALL) { 12862 users = sUserManager.getUserIds(); 12863 } else { 12864 users = new int[] { userId }; 12865 } 12866 final ClearStorageConnection conn = new ClearStorageConnection(); 12867 if (mContext.bindServiceAsUser( 12868 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12869 try { 12870 for (int curUser : users) { 12871 long timeout = SystemClock.uptimeMillis() + 5000; 12872 synchronized (conn) { 12873 long now = SystemClock.uptimeMillis(); 12874 while (conn.mContainerService == null && now < timeout) { 12875 try { 12876 conn.wait(timeout - now); 12877 } catch (InterruptedException e) { 12878 } 12879 } 12880 } 12881 if (conn.mContainerService == null) { 12882 return; 12883 } 12884 12885 final UserEnvironment userEnv = new UserEnvironment(curUser); 12886 clearDirectory(conn.mContainerService, 12887 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12888 if (allData) { 12889 clearDirectory(conn.mContainerService, 12890 userEnv.buildExternalStorageAppDataDirs(packageName)); 12891 clearDirectory(conn.mContainerService, 12892 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12893 } 12894 } 12895 } finally { 12896 mContext.unbindService(conn); 12897 } 12898 } 12899 } 12900 12901 @Override 12902 public void clearApplicationUserData(final String packageName, 12903 final IPackageDataObserver observer, final int userId) { 12904 mContext.enforceCallingOrSelfPermission( 12905 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12906 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12907 // Queue up an async operation since the package deletion may take a little while. 12908 mHandler.post(new Runnable() { 12909 public void run() { 12910 mHandler.removeCallbacks(this); 12911 final boolean succeeded; 12912 synchronized (mInstallLock) { 12913 succeeded = clearApplicationUserDataLI(packageName, userId); 12914 } 12915 clearExternalStorageDataSync(packageName, userId, true); 12916 if (succeeded) { 12917 // invoke DeviceStorageMonitor's update method to clear any notifications 12918 DeviceStorageMonitorInternal 12919 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12920 if (dsm != null) { 12921 dsm.checkMemory(); 12922 } 12923 } 12924 if(observer != null) { 12925 try { 12926 observer.onRemoveCompleted(packageName, succeeded); 12927 } catch (RemoteException e) { 12928 Log.i(TAG, "Observer no longer exists."); 12929 } 12930 } //end if observer 12931 } //end run 12932 }); 12933 } 12934 12935 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12936 if (packageName == null) { 12937 Slog.w(TAG, "Attempt to delete null packageName."); 12938 return false; 12939 } 12940 12941 // Try finding details about the requested package 12942 PackageParser.Package pkg; 12943 synchronized (mPackages) { 12944 pkg = mPackages.get(packageName); 12945 if (pkg == null) { 12946 final PackageSetting ps = mSettings.mPackages.get(packageName); 12947 if (ps != null) { 12948 pkg = ps.pkg; 12949 } 12950 } 12951 12952 if (pkg == null) { 12953 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12954 return false; 12955 } 12956 12957 PackageSetting ps = (PackageSetting) pkg.mExtras; 12958 PermissionsState permissionsState = ps.getPermissionsState(); 12959 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12960 } 12961 12962 // Always delete data directories for package, even if we found no other 12963 // record of app. This helps users recover from UID mismatches without 12964 // resorting to a full data wipe. 12965 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12966 if (retCode < 0) { 12967 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12968 return false; 12969 } 12970 12971 final int appId = pkg.applicationInfo.uid; 12972 removeKeystoreDataIfNeeded(userId, appId); 12973 12974 // Create a native library symlink only if we have native libraries 12975 // and if the native libraries are 32 bit libraries. We do not provide 12976 // this symlink for 64 bit libraries. 12977 if (pkg.applicationInfo.primaryCpuAbi != null && 12978 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12979 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12980 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12981 nativeLibPath, userId) < 0) { 12982 Slog.w(TAG, "Failed linking native library dir"); 12983 return false; 12984 } 12985 } 12986 12987 return true; 12988 } 12989 12990 12991 /** 12992 * Revokes granted runtime permissions and clears resettable flags 12993 * which are flags that can be set by a user interaction. 12994 * 12995 * @param permissionsState The permission state to reset. 12996 * @param userId The device user for which to do a reset. 12997 */ 12998 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12999 PermissionsState permissionsState, int userId) { 13000 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 13001 | PackageManager.FLAG_PERMISSION_USER_FIXED 13002 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13003 13004 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 13005 } 13006 13007 /** 13008 * Revokes granted runtime permissions and clears all flags. 13009 * 13010 * @param permissionsState The permission state to reset. 13011 * @param userId The device user for which to do a reset. 13012 */ 13013 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 13014 PermissionsState permissionsState, int userId) { 13015 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 13016 PackageManager.MASK_PERMISSION_FLAGS); 13017 } 13018 13019 /** 13020 * Revokes granted runtime permissions and clears certain flags. 13021 * 13022 * @param permissionsState The permission state to reset. 13023 * @param userId The device user for which to do a reset. 13024 * @param flags The flags that is going to be reset. 13025 */ 13026 private void revokeRuntimePermissionsAndClearFlagsLocked( 13027 PermissionsState permissionsState, int userId, int flags) { 13028 boolean needsWrite = false; 13029 13030 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 13031 BasePermission bp = mSettings.mPermissions.get(state.getName()); 13032 if (bp != null) { 13033 permissionsState.revokeRuntimePermission(bp, userId); 13034 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 13035 needsWrite = true; 13036 } 13037 } 13038 13039 // Ensure default permissions are never cleared. 13040 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13041 13042 if (needsWrite) { 13043 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13044 } 13045 } 13046 13047 /** 13048 * Remove entries from the keystore daemon. Will only remove it if the 13049 * {@code appId} is valid. 13050 */ 13051 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13052 if (appId < 0) { 13053 return; 13054 } 13055 13056 final KeyStore keyStore = KeyStore.getInstance(); 13057 if (keyStore != null) { 13058 if (userId == UserHandle.USER_ALL) { 13059 for (final int individual : sUserManager.getUserIds()) { 13060 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13061 } 13062 } else { 13063 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13064 } 13065 } else { 13066 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13067 } 13068 } 13069 13070 @Override 13071 public void deleteApplicationCacheFiles(final String packageName, 13072 final IPackageDataObserver observer) { 13073 mContext.enforceCallingOrSelfPermission( 13074 android.Manifest.permission.DELETE_CACHE_FILES, null); 13075 // Queue up an async operation since the package deletion may take a little while. 13076 final int userId = UserHandle.getCallingUserId(); 13077 mHandler.post(new Runnable() { 13078 public void run() { 13079 mHandler.removeCallbacks(this); 13080 final boolean succeded; 13081 synchronized (mInstallLock) { 13082 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13083 } 13084 clearExternalStorageDataSync(packageName, userId, false); 13085 if (observer != null) { 13086 try { 13087 observer.onRemoveCompleted(packageName, succeded); 13088 } catch (RemoteException e) { 13089 Log.i(TAG, "Observer no longer exists."); 13090 } 13091 } //end if observer 13092 } //end run 13093 }); 13094 } 13095 13096 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13097 if (packageName == null) { 13098 Slog.w(TAG, "Attempt to delete null packageName."); 13099 return false; 13100 } 13101 PackageParser.Package p; 13102 synchronized (mPackages) { 13103 p = mPackages.get(packageName); 13104 } 13105 if (p == null) { 13106 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13107 return false; 13108 } 13109 final ApplicationInfo applicationInfo = p.applicationInfo; 13110 if (applicationInfo == null) { 13111 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13112 return false; 13113 } 13114 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13115 if (retCode < 0) { 13116 Slog.w(TAG, "Couldn't remove cache files for package: " 13117 + packageName + " u" + userId); 13118 return false; 13119 } 13120 return true; 13121 } 13122 13123 @Override 13124 public void getPackageSizeInfo(final String packageName, int userHandle, 13125 final IPackageStatsObserver observer) { 13126 mContext.enforceCallingOrSelfPermission( 13127 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13128 if (packageName == null) { 13129 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13130 } 13131 13132 PackageStats stats = new PackageStats(packageName, userHandle); 13133 13134 /* 13135 * Queue up an async operation since the package measurement may take a 13136 * little while. 13137 */ 13138 Message msg = mHandler.obtainMessage(INIT_COPY); 13139 msg.obj = new MeasureParams(stats, observer); 13140 mHandler.sendMessage(msg); 13141 } 13142 13143 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13144 PackageStats pStats) { 13145 if (packageName == null) { 13146 Slog.w(TAG, "Attempt to get size of null packageName."); 13147 return false; 13148 } 13149 PackageParser.Package p; 13150 boolean dataOnly = false; 13151 String libDirRoot = null; 13152 String asecPath = null; 13153 PackageSetting ps = null; 13154 synchronized (mPackages) { 13155 p = mPackages.get(packageName); 13156 ps = mSettings.mPackages.get(packageName); 13157 if(p == null) { 13158 dataOnly = true; 13159 if((ps == null) || (ps.pkg == null)) { 13160 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13161 return false; 13162 } 13163 p = ps.pkg; 13164 } 13165 if (ps != null) { 13166 libDirRoot = ps.legacyNativeLibraryPathString; 13167 } 13168 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13169 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13170 if (secureContainerId != null) { 13171 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13172 } 13173 } 13174 } 13175 String publicSrcDir = null; 13176 if(!dataOnly) { 13177 final ApplicationInfo applicationInfo = p.applicationInfo; 13178 if (applicationInfo == null) { 13179 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13180 return false; 13181 } 13182 if (p.isForwardLocked()) { 13183 publicSrcDir = applicationInfo.getBaseResourcePath(); 13184 } 13185 } 13186 // TODO: extend to measure size of split APKs 13187 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13188 // not just the first level. 13189 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13190 // just the primary. 13191 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13192 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13193 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13194 if (res < 0) { 13195 return false; 13196 } 13197 13198 // Fix-up for forward-locked applications in ASEC containers. 13199 if (!isExternal(p)) { 13200 pStats.codeSize += pStats.externalCodeSize; 13201 pStats.externalCodeSize = 0L; 13202 } 13203 13204 return true; 13205 } 13206 13207 13208 @Override 13209 public void addPackageToPreferred(String packageName) { 13210 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13211 } 13212 13213 @Override 13214 public void removePackageFromPreferred(String packageName) { 13215 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13216 } 13217 13218 @Override 13219 public List<PackageInfo> getPreferredPackages(int flags) { 13220 return new ArrayList<PackageInfo>(); 13221 } 13222 13223 private int getUidTargetSdkVersionLockedLPr(int uid) { 13224 Object obj = mSettings.getUserIdLPr(uid); 13225 if (obj instanceof SharedUserSetting) { 13226 final SharedUserSetting sus = (SharedUserSetting) obj; 13227 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13228 final Iterator<PackageSetting> it = sus.packages.iterator(); 13229 while (it.hasNext()) { 13230 final PackageSetting ps = it.next(); 13231 if (ps.pkg != null) { 13232 int v = ps.pkg.applicationInfo.targetSdkVersion; 13233 if (v < vers) vers = v; 13234 } 13235 } 13236 return vers; 13237 } else if (obj instanceof PackageSetting) { 13238 final PackageSetting ps = (PackageSetting) obj; 13239 if (ps.pkg != null) { 13240 return ps.pkg.applicationInfo.targetSdkVersion; 13241 } 13242 } 13243 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13244 } 13245 13246 @Override 13247 public void addPreferredActivity(IntentFilter filter, int match, 13248 ComponentName[] set, ComponentName activity, int userId) { 13249 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13250 "Adding preferred"); 13251 } 13252 13253 private void addPreferredActivityInternal(IntentFilter filter, int match, 13254 ComponentName[] set, ComponentName activity, boolean always, int userId, 13255 String opname) { 13256 // writer 13257 int callingUid = Binder.getCallingUid(); 13258 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13259 if (filter.countActions() == 0) { 13260 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13261 return; 13262 } 13263 synchronized (mPackages) { 13264 if (mContext.checkCallingOrSelfPermission( 13265 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13266 != PackageManager.PERMISSION_GRANTED) { 13267 if (getUidTargetSdkVersionLockedLPr(callingUid) 13268 < Build.VERSION_CODES.FROYO) { 13269 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13270 + callingUid); 13271 return; 13272 } 13273 mContext.enforceCallingOrSelfPermission( 13274 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13275 } 13276 13277 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13278 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13279 + userId + ":"); 13280 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13281 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13282 scheduleWritePackageRestrictionsLocked(userId); 13283 } 13284 } 13285 13286 @Override 13287 public void replacePreferredActivity(IntentFilter filter, int match, 13288 ComponentName[] set, ComponentName activity, int userId) { 13289 if (filter.countActions() != 1) { 13290 throw new IllegalArgumentException( 13291 "replacePreferredActivity expects filter to have only 1 action."); 13292 } 13293 if (filter.countDataAuthorities() != 0 13294 || filter.countDataPaths() != 0 13295 || filter.countDataSchemes() > 1 13296 || filter.countDataTypes() != 0) { 13297 throw new IllegalArgumentException( 13298 "replacePreferredActivity expects filter to have no data authorities, " + 13299 "paths, or types; and at most one scheme."); 13300 } 13301 13302 final int callingUid = Binder.getCallingUid(); 13303 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13304 synchronized (mPackages) { 13305 if (mContext.checkCallingOrSelfPermission( 13306 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13307 != PackageManager.PERMISSION_GRANTED) { 13308 if (getUidTargetSdkVersionLockedLPr(callingUid) 13309 < Build.VERSION_CODES.FROYO) { 13310 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13311 + Binder.getCallingUid()); 13312 return; 13313 } 13314 mContext.enforceCallingOrSelfPermission( 13315 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13316 } 13317 13318 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13319 if (pir != null) { 13320 // Get all of the existing entries that exactly match this filter. 13321 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13322 if (existing != null && existing.size() == 1) { 13323 PreferredActivity cur = existing.get(0); 13324 if (DEBUG_PREFERRED) { 13325 Slog.i(TAG, "Checking replace of preferred:"); 13326 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13327 if (!cur.mPref.mAlways) { 13328 Slog.i(TAG, " -- CUR; not mAlways!"); 13329 } else { 13330 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13331 Slog.i(TAG, " -- CUR: mSet=" 13332 + Arrays.toString(cur.mPref.mSetComponents)); 13333 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13334 Slog.i(TAG, " -- NEW: mMatch=" 13335 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13336 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13337 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13338 } 13339 } 13340 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13341 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13342 && cur.mPref.sameSet(set)) { 13343 // Setting the preferred activity to what it happens to be already 13344 if (DEBUG_PREFERRED) { 13345 Slog.i(TAG, "Replacing with same preferred activity " 13346 + cur.mPref.mShortComponent + " for user " 13347 + userId + ":"); 13348 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13349 } 13350 return; 13351 } 13352 } 13353 13354 if (existing != null) { 13355 if (DEBUG_PREFERRED) { 13356 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13357 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13358 } 13359 for (int i = 0; i < existing.size(); i++) { 13360 PreferredActivity pa = existing.get(i); 13361 if (DEBUG_PREFERRED) { 13362 Slog.i(TAG, "Removing existing preferred activity " 13363 + pa.mPref.mComponent + ":"); 13364 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13365 } 13366 pir.removeFilter(pa); 13367 } 13368 } 13369 } 13370 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13371 "Replacing preferred"); 13372 } 13373 } 13374 13375 @Override 13376 public void clearPackagePreferredActivities(String packageName) { 13377 final int uid = Binder.getCallingUid(); 13378 // writer 13379 synchronized (mPackages) { 13380 PackageParser.Package pkg = mPackages.get(packageName); 13381 if (pkg == null || pkg.applicationInfo.uid != uid) { 13382 if (mContext.checkCallingOrSelfPermission( 13383 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13384 != PackageManager.PERMISSION_GRANTED) { 13385 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13386 < Build.VERSION_CODES.FROYO) { 13387 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13388 + Binder.getCallingUid()); 13389 return; 13390 } 13391 mContext.enforceCallingOrSelfPermission( 13392 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13393 } 13394 } 13395 13396 int user = UserHandle.getCallingUserId(); 13397 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13398 scheduleWritePackageRestrictionsLocked(user); 13399 } 13400 } 13401 } 13402 13403 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13404 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13405 ArrayList<PreferredActivity> removed = null; 13406 boolean changed = false; 13407 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13408 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13409 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13410 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13411 continue; 13412 } 13413 Iterator<PreferredActivity> it = pir.filterIterator(); 13414 while (it.hasNext()) { 13415 PreferredActivity pa = it.next(); 13416 // Mark entry for removal only if it matches the package name 13417 // and the entry is of type "always". 13418 if (packageName == null || 13419 (pa.mPref.mComponent.getPackageName().equals(packageName) 13420 && pa.mPref.mAlways)) { 13421 if (removed == null) { 13422 removed = new ArrayList<PreferredActivity>(); 13423 } 13424 removed.add(pa); 13425 } 13426 } 13427 if (removed != null) { 13428 for (int j=0; j<removed.size(); j++) { 13429 PreferredActivity pa = removed.get(j); 13430 pir.removeFilter(pa); 13431 } 13432 changed = true; 13433 } 13434 } 13435 return changed; 13436 } 13437 13438 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13439 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13440 if (userId == UserHandle.USER_ALL) { 13441 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13442 sUserManager.getUserIds())) { 13443 for (int oneUserId : sUserManager.getUserIds()) { 13444 scheduleWritePackageRestrictionsLocked(oneUserId); 13445 } 13446 } 13447 } else { 13448 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13449 scheduleWritePackageRestrictionsLocked(userId); 13450 } 13451 } 13452 } 13453 13454 13455 void clearDefaultBrowserIfNeeded(String packageName) { 13456 for (int oneUserId : sUserManager.getUserIds()) { 13457 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13458 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13459 if (packageName.equals(defaultBrowserPackageName)) { 13460 setDefaultBrowserPackageName(null, oneUserId); 13461 } 13462 } 13463 } 13464 13465 @Override 13466 public void resetPreferredActivities(int userId) { 13467 mContext.enforceCallingOrSelfPermission( 13468 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13469 // writer 13470 synchronized (mPackages) { 13471 clearPackagePreferredActivitiesLPw(null, userId); 13472 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13473 applyFactoryDefaultBrowserLPw(userId); 13474 13475 scheduleWritePackageRestrictionsLocked(userId); 13476 } 13477 } 13478 13479 @Override 13480 public int getPreferredActivities(List<IntentFilter> outFilters, 13481 List<ComponentName> outActivities, String packageName) { 13482 13483 int num = 0; 13484 final int userId = UserHandle.getCallingUserId(); 13485 // reader 13486 synchronized (mPackages) { 13487 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13488 if (pir != null) { 13489 final Iterator<PreferredActivity> it = pir.filterIterator(); 13490 while (it.hasNext()) { 13491 final PreferredActivity pa = it.next(); 13492 if (packageName == null 13493 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13494 && pa.mPref.mAlways)) { 13495 if (outFilters != null) { 13496 outFilters.add(new IntentFilter(pa)); 13497 } 13498 if (outActivities != null) { 13499 outActivities.add(pa.mPref.mComponent); 13500 } 13501 } 13502 } 13503 } 13504 } 13505 13506 return num; 13507 } 13508 13509 @Override 13510 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13511 int userId) { 13512 int callingUid = Binder.getCallingUid(); 13513 if (callingUid != Process.SYSTEM_UID) { 13514 throw new SecurityException( 13515 "addPersistentPreferredActivity can only be run by the system"); 13516 } 13517 if (filter.countActions() == 0) { 13518 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13519 return; 13520 } 13521 synchronized (mPackages) { 13522 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13523 " :"); 13524 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13525 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13526 new PersistentPreferredActivity(filter, activity)); 13527 scheduleWritePackageRestrictionsLocked(userId); 13528 } 13529 } 13530 13531 @Override 13532 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13533 int callingUid = Binder.getCallingUid(); 13534 if (callingUid != Process.SYSTEM_UID) { 13535 throw new SecurityException( 13536 "clearPackagePersistentPreferredActivities can only be run by the system"); 13537 } 13538 ArrayList<PersistentPreferredActivity> removed = null; 13539 boolean changed = false; 13540 synchronized (mPackages) { 13541 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13542 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13543 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13544 .valueAt(i); 13545 if (userId != thisUserId) { 13546 continue; 13547 } 13548 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13549 while (it.hasNext()) { 13550 PersistentPreferredActivity ppa = it.next(); 13551 // Mark entry for removal only if it matches the package name. 13552 if (ppa.mComponent.getPackageName().equals(packageName)) { 13553 if (removed == null) { 13554 removed = new ArrayList<PersistentPreferredActivity>(); 13555 } 13556 removed.add(ppa); 13557 } 13558 } 13559 if (removed != null) { 13560 for (int j=0; j<removed.size(); j++) { 13561 PersistentPreferredActivity ppa = removed.get(j); 13562 ppir.removeFilter(ppa); 13563 } 13564 changed = true; 13565 } 13566 } 13567 13568 if (changed) { 13569 scheduleWritePackageRestrictionsLocked(userId); 13570 } 13571 } 13572 } 13573 13574 /** 13575 * Common machinery for picking apart a restored XML blob and passing 13576 * it to a caller-supplied functor to be applied to the running system. 13577 */ 13578 private void restoreFromXml(XmlPullParser parser, int userId, 13579 String expectedStartTag, BlobXmlRestorer functor) 13580 throws IOException, XmlPullParserException { 13581 int type; 13582 while ((type = parser.next()) != XmlPullParser.START_TAG 13583 && type != XmlPullParser.END_DOCUMENT) { 13584 } 13585 if (type != XmlPullParser.START_TAG) { 13586 // oops didn't find a start tag?! 13587 if (DEBUG_BACKUP) { 13588 Slog.e(TAG, "Didn't find start tag during restore"); 13589 } 13590 return; 13591 } 13592 13593 // this is supposed to be TAG_PREFERRED_BACKUP 13594 if (!expectedStartTag.equals(parser.getName())) { 13595 if (DEBUG_BACKUP) { 13596 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13597 } 13598 return; 13599 } 13600 13601 // skip interfering stuff, then we're aligned with the backing implementation 13602 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13603 functor.apply(parser, userId); 13604 } 13605 13606 private interface BlobXmlRestorer { 13607 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13608 } 13609 13610 /** 13611 * Non-Binder method, support for the backup/restore mechanism: write the 13612 * full set of preferred activities in its canonical XML format. Returns the 13613 * XML output as a byte array, or null if there is none. 13614 */ 13615 @Override 13616 public byte[] getPreferredActivityBackup(int userId) { 13617 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13618 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13619 } 13620 13621 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13622 try { 13623 final XmlSerializer serializer = new FastXmlSerializer(); 13624 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13625 serializer.startDocument(null, true); 13626 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13627 13628 synchronized (mPackages) { 13629 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13630 } 13631 13632 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13633 serializer.endDocument(); 13634 serializer.flush(); 13635 } catch (Exception e) { 13636 if (DEBUG_BACKUP) { 13637 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13638 } 13639 return null; 13640 } 13641 13642 return dataStream.toByteArray(); 13643 } 13644 13645 @Override 13646 public void restorePreferredActivities(byte[] backup, int userId) { 13647 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13648 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13649 } 13650 13651 try { 13652 final XmlPullParser parser = Xml.newPullParser(); 13653 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13654 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13655 new BlobXmlRestorer() { 13656 @Override 13657 public void apply(XmlPullParser parser, int userId) 13658 throws XmlPullParserException, IOException { 13659 synchronized (mPackages) { 13660 mSettings.readPreferredActivitiesLPw(parser, userId); 13661 } 13662 } 13663 } ); 13664 } catch (Exception e) { 13665 if (DEBUG_BACKUP) { 13666 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13667 } 13668 } 13669 } 13670 13671 /** 13672 * Non-Binder method, support for the backup/restore mechanism: write the 13673 * default browser (etc) settings in its canonical XML format. Returns the default 13674 * browser XML representation as a byte array, or null if there is none. 13675 */ 13676 @Override 13677 public byte[] getDefaultAppsBackup(int userId) { 13678 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13679 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13680 } 13681 13682 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13683 try { 13684 final XmlSerializer serializer = new FastXmlSerializer(); 13685 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13686 serializer.startDocument(null, true); 13687 serializer.startTag(null, TAG_DEFAULT_APPS); 13688 13689 synchronized (mPackages) { 13690 mSettings.writeDefaultAppsLPr(serializer, userId); 13691 } 13692 13693 serializer.endTag(null, TAG_DEFAULT_APPS); 13694 serializer.endDocument(); 13695 serializer.flush(); 13696 } catch (Exception e) { 13697 if (DEBUG_BACKUP) { 13698 Slog.e(TAG, "Unable to write default apps for backup", e); 13699 } 13700 return null; 13701 } 13702 13703 return dataStream.toByteArray(); 13704 } 13705 13706 @Override 13707 public void restoreDefaultApps(byte[] backup, int userId) { 13708 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13709 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13710 } 13711 13712 try { 13713 final XmlPullParser parser = Xml.newPullParser(); 13714 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13715 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13716 new BlobXmlRestorer() { 13717 @Override 13718 public void apply(XmlPullParser parser, int userId) 13719 throws XmlPullParserException, IOException { 13720 synchronized (mPackages) { 13721 mSettings.readDefaultAppsLPw(parser, userId); 13722 } 13723 } 13724 } ); 13725 } catch (Exception e) { 13726 if (DEBUG_BACKUP) { 13727 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13728 } 13729 } 13730 } 13731 13732 @Override 13733 public byte[] getIntentFilterVerificationBackup(int userId) { 13734 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13735 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13736 } 13737 13738 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13739 try { 13740 final XmlSerializer serializer = new FastXmlSerializer(); 13741 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13742 serializer.startDocument(null, true); 13743 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13744 13745 synchronized (mPackages) { 13746 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13747 } 13748 13749 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13750 serializer.endDocument(); 13751 serializer.flush(); 13752 } catch (Exception e) { 13753 if (DEBUG_BACKUP) { 13754 Slog.e(TAG, "Unable to write default apps for backup", e); 13755 } 13756 return null; 13757 } 13758 13759 return dataStream.toByteArray(); 13760 } 13761 13762 @Override 13763 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13764 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13765 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13766 } 13767 13768 try { 13769 final XmlPullParser parser = Xml.newPullParser(); 13770 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13771 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13772 new BlobXmlRestorer() { 13773 @Override 13774 public void apply(XmlPullParser parser, int userId) 13775 throws XmlPullParserException, IOException { 13776 synchronized (mPackages) { 13777 mSettings.readAllDomainVerificationsLPr(parser, userId); 13778 mSettings.writeLPr(); 13779 } 13780 } 13781 } ); 13782 } catch (Exception e) { 13783 if (DEBUG_BACKUP) { 13784 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13785 } 13786 } 13787 } 13788 13789 @Override 13790 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13791 int sourceUserId, int targetUserId, int flags) { 13792 mContext.enforceCallingOrSelfPermission( 13793 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13794 int callingUid = Binder.getCallingUid(); 13795 enforceOwnerRights(ownerPackage, callingUid); 13796 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13797 if (intentFilter.countActions() == 0) { 13798 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13799 return; 13800 } 13801 synchronized (mPackages) { 13802 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13803 ownerPackage, targetUserId, flags); 13804 CrossProfileIntentResolver resolver = 13805 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13806 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13807 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13808 if (existing != null) { 13809 int size = existing.size(); 13810 for (int i = 0; i < size; i++) { 13811 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13812 return; 13813 } 13814 } 13815 } 13816 resolver.addFilter(newFilter); 13817 scheduleWritePackageRestrictionsLocked(sourceUserId); 13818 } 13819 } 13820 13821 @Override 13822 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13823 mContext.enforceCallingOrSelfPermission( 13824 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13825 int callingUid = Binder.getCallingUid(); 13826 enforceOwnerRights(ownerPackage, callingUid); 13827 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13828 synchronized (mPackages) { 13829 CrossProfileIntentResolver resolver = 13830 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13831 ArraySet<CrossProfileIntentFilter> set = 13832 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13833 for (CrossProfileIntentFilter filter : set) { 13834 if (filter.getOwnerPackage().equals(ownerPackage)) { 13835 resolver.removeFilter(filter); 13836 } 13837 } 13838 scheduleWritePackageRestrictionsLocked(sourceUserId); 13839 } 13840 } 13841 13842 // Enforcing that callingUid is owning pkg on userId 13843 private void enforceOwnerRights(String pkg, int callingUid) { 13844 // The system owns everything. 13845 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13846 return; 13847 } 13848 int callingUserId = UserHandle.getUserId(callingUid); 13849 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13850 if (pi == null) { 13851 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13852 + callingUserId); 13853 } 13854 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13855 throw new SecurityException("Calling uid " + callingUid 13856 + " does not own package " + pkg); 13857 } 13858 } 13859 13860 @Override 13861 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13862 Intent intent = new Intent(Intent.ACTION_MAIN); 13863 intent.addCategory(Intent.CATEGORY_HOME); 13864 13865 final int callingUserId = UserHandle.getCallingUserId(); 13866 List<ResolveInfo> list = queryIntentActivities(intent, null, 13867 PackageManager.GET_META_DATA, callingUserId); 13868 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13869 true, false, false, callingUserId); 13870 13871 allHomeCandidates.clear(); 13872 if (list != null) { 13873 for (ResolveInfo ri : list) { 13874 allHomeCandidates.add(ri); 13875 } 13876 } 13877 return (preferred == null || preferred.activityInfo == null) 13878 ? null 13879 : new ComponentName(preferred.activityInfo.packageName, 13880 preferred.activityInfo.name); 13881 } 13882 13883 @Override 13884 public void setApplicationEnabledSetting(String appPackageName, 13885 int newState, int flags, int userId, String callingPackage) { 13886 if (!sUserManager.exists(userId)) return; 13887 if (callingPackage == null) { 13888 callingPackage = Integer.toString(Binder.getCallingUid()); 13889 } 13890 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13891 } 13892 13893 @Override 13894 public void setComponentEnabledSetting(ComponentName componentName, 13895 int newState, int flags, int userId) { 13896 if (!sUserManager.exists(userId)) return; 13897 setEnabledSetting(componentName.getPackageName(), 13898 componentName.getClassName(), newState, flags, userId, null); 13899 } 13900 13901 private void setEnabledSetting(final String packageName, String className, int newState, 13902 final int flags, int userId, String callingPackage) { 13903 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13904 || newState == COMPONENT_ENABLED_STATE_ENABLED 13905 || newState == COMPONENT_ENABLED_STATE_DISABLED 13906 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13907 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13908 throw new IllegalArgumentException("Invalid new component state: " 13909 + newState); 13910 } 13911 PackageSetting pkgSetting; 13912 final int uid = Binder.getCallingUid(); 13913 final int permission = mContext.checkCallingOrSelfPermission( 13914 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13915 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13916 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13917 boolean sendNow = false; 13918 boolean isApp = (className == null); 13919 String componentName = isApp ? packageName : className; 13920 int packageUid = -1; 13921 ArrayList<String> components; 13922 13923 // writer 13924 synchronized (mPackages) { 13925 pkgSetting = mSettings.mPackages.get(packageName); 13926 if (pkgSetting == null) { 13927 if (className == null) { 13928 throw new IllegalArgumentException( 13929 "Unknown package: " + packageName); 13930 } 13931 throw new IllegalArgumentException( 13932 "Unknown component: " + packageName 13933 + "/" + className); 13934 } 13935 // Allow root and verify that userId is not being specified by a different user 13936 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13937 throw new SecurityException( 13938 "Permission Denial: attempt to change component state from pid=" 13939 + Binder.getCallingPid() 13940 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13941 } 13942 if (className == null) { 13943 // We're dealing with an application/package level state change 13944 if (pkgSetting.getEnabled(userId) == newState) { 13945 // Nothing to do 13946 return; 13947 } 13948 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13949 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13950 // Don't care about who enables an app. 13951 callingPackage = null; 13952 } 13953 pkgSetting.setEnabled(newState, userId, callingPackage); 13954 // pkgSetting.pkg.mSetEnabled = newState; 13955 } else { 13956 // We're dealing with a component level state change 13957 // First, verify that this is a valid class name. 13958 PackageParser.Package pkg = pkgSetting.pkg; 13959 if (pkg == null || !pkg.hasComponentClassName(className)) { 13960 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13961 throw new IllegalArgumentException("Component class " + className 13962 + " does not exist in " + packageName); 13963 } else { 13964 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13965 + className + " does not exist in " + packageName); 13966 } 13967 } 13968 switch (newState) { 13969 case COMPONENT_ENABLED_STATE_ENABLED: 13970 if (!pkgSetting.enableComponentLPw(className, userId)) { 13971 return; 13972 } 13973 break; 13974 case COMPONENT_ENABLED_STATE_DISABLED: 13975 if (!pkgSetting.disableComponentLPw(className, userId)) { 13976 return; 13977 } 13978 break; 13979 case COMPONENT_ENABLED_STATE_DEFAULT: 13980 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13981 return; 13982 } 13983 break; 13984 default: 13985 Slog.e(TAG, "Invalid new component state: " + newState); 13986 return; 13987 } 13988 } 13989 scheduleWritePackageRestrictionsLocked(userId); 13990 components = mPendingBroadcasts.get(userId, packageName); 13991 final boolean newPackage = components == null; 13992 if (newPackage) { 13993 components = new ArrayList<String>(); 13994 } 13995 if (!components.contains(componentName)) { 13996 components.add(componentName); 13997 } 13998 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13999 sendNow = true; 14000 // Purge entry from pending broadcast list if another one exists already 14001 // since we are sending one right away. 14002 mPendingBroadcasts.remove(userId, packageName); 14003 } else { 14004 if (newPackage) { 14005 mPendingBroadcasts.put(userId, packageName, components); 14006 } 14007 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14008 // Schedule a message 14009 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14010 } 14011 } 14012 } 14013 14014 long callingId = Binder.clearCallingIdentity(); 14015 try { 14016 if (sendNow) { 14017 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14018 sendPackageChangedBroadcast(packageName, 14019 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14020 } 14021 } finally { 14022 Binder.restoreCallingIdentity(callingId); 14023 } 14024 } 14025 14026 private void sendPackageChangedBroadcast(String packageName, 14027 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14028 if (DEBUG_INSTALL) 14029 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14030 + componentNames); 14031 Bundle extras = new Bundle(4); 14032 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14033 String nameList[] = new String[componentNames.size()]; 14034 componentNames.toArray(nameList); 14035 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14036 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14037 extras.putInt(Intent.EXTRA_UID, packageUid); 14038 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14039 new int[] {UserHandle.getUserId(packageUid)}); 14040 } 14041 14042 @Override 14043 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14044 if (!sUserManager.exists(userId)) return; 14045 final int uid = Binder.getCallingUid(); 14046 final int permission = mContext.checkCallingOrSelfPermission( 14047 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14048 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14049 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14050 // writer 14051 synchronized (mPackages) { 14052 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14053 allowedByPermission, uid, userId)) { 14054 scheduleWritePackageRestrictionsLocked(userId); 14055 } 14056 } 14057 } 14058 14059 @Override 14060 public String getInstallerPackageName(String packageName) { 14061 // reader 14062 synchronized (mPackages) { 14063 return mSettings.getInstallerPackageNameLPr(packageName); 14064 } 14065 } 14066 14067 @Override 14068 public int getApplicationEnabledSetting(String packageName, int userId) { 14069 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14070 int uid = Binder.getCallingUid(); 14071 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14072 // reader 14073 synchronized (mPackages) { 14074 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14075 } 14076 } 14077 14078 @Override 14079 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14080 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14081 int uid = Binder.getCallingUid(); 14082 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14083 // reader 14084 synchronized (mPackages) { 14085 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14086 } 14087 } 14088 14089 @Override 14090 public void enterSafeMode() { 14091 enforceSystemOrRoot("Only the system can request entering safe mode"); 14092 14093 if (!mSystemReady) { 14094 mSafeMode = true; 14095 } 14096 } 14097 14098 @Override 14099 public void systemReady() { 14100 mSystemReady = true; 14101 14102 // Read the compatibilty setting when the system is ready. 14103 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14104 mContext.getContentResolver(), 14105 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14106 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14107 if (DEBUG_SETTINGS) { 14108 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14109 } 14110 14111 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14112 14113 synchronized (mPackages) { 14114 // Verify that all of the preferred activity components actually 14115 // exist. It is possible for applications to be updated and at 14116 // that point remove a previously declared activity component that 14117 // had been set as a preferred activity. We try to clean this up 14118 // the next time we encounter that preferred activity, but it is 14119 // possible for the user flow to never be able to return to that 14120 // situation so here we do a sanity check to make sure we haven't 14121 // left any junk around. 14122 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14123 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14124 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14125 removed.clear(); 14126 for (PreferredActivity pa : pir.filterSet()) { 14127 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14128 removed.add(pa); 14129 } 14130 } 14131 if (removed.size() > 0) { 14132 for (int r=0; r<removed.size(); r++) { 14133 PreferredActivity pa = removed.get(r); 14134 Slog.w(TAG, "Removing dangling preferred activity: " 14135 + pa.mPref.mComponent); 14136 pir.removeFilter(pa); 14137 } 14138 mSettings.writePackageRestrictionsLPr( 14139 mSettings.mPreferredActivities.keyAt(i)); 14140 } 14141 } 14142 14143 for (int userId : UserManagerService.getInstance().getUserIds()) { 14144 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14145 grantPermissionsUserIds = ArrayUtils.appendInt( 14146 grantPermissionsUserIds, userId); 14147 } 14148 } 14149 } 14150 sUserManager.systemReady(); 14151 14152 // If we upgraded grant all default permissions before kicking off. 14153 for (int userId : grantPermissionsUserIds) { 14154 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14155 } 14156 14157 // Kick off any messages waiting for system ready 14158 if (mPostSystemReadyMessages != null) { 14159 for (Message msg : mPostSystemReadyMessages) { 14160 msg.sendToTarget(); 14161 } 14162 mPostSystemReadyMessages = null; 14163 } 14164 14165 // Watch for external volumes that come and go over time 14166 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14167 storage.registerListener(mStorageListener); 14168 14169 mInstallerService.systemReady(); 14170 mPackageDexOptimizer.systemReady(); 14171 } 14172 14173 @Override 14174 public boolean isSafeMode() { 14175 return mSafeMode; 14176 } 14177 14178 @Override 14179 public boolean hasSystemUidErrors() { 14180 return mHasSystemUidErrors; 14181 } 14182 14183 static String arrayToString(int[] array) { 14184 StringBuffer buf = new StringBuffer(128); 14185 buf.append('['); 14186 if (array != null) { 14187 for (int i=0; i<array.length; i++) { 14188 if (i > 0) buf.append(", "); 14189 buf.append(array[i]); 14190 } 14191 } 14192 buf.append(']'); 14193 return buf.toString(); 14194 } 14195 14196 static class DumpState { 14197 public static final int DUMP_LIBS = 1 << 0; 14198 public static final int DUMP_FEATURES = 1 << 1; 14199 public static final int DUMP_RESOLVERS = 1 << 2; 14200 public static final int DUMP_PERMISSIONS = 1 << 3; 14201 public static final int DUMP_PACKAGES = 1 << 4; 14202 public static final int DUMP_SHARED_USERS = 1 << 5; 14203 public static final int DUMP_MESSAGES = 1 << 6; 14204 public static final int DUMP_PROVIDERS = 1 << 7; 14205 public static final int DUMP_VERIFIERS = 1 << 8; 14206 public static final int DUMP_PREFERRED = 1 << 9; 14207 public static final int DUMP_PREFERRED_XML = 1 << 10; 14208 public static final int DUMP_KEYSETS = 1 << 11; 14209 public static final int DUMP_VERSION = 1 << 12; 14210 public static final int DUMP_INSTALLS = 1 << 13; 14211 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14212 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14213 14214 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14215 14216 private int mTypes; 14217 14218 private int mOptions; 14219 14220 private boolean mTitlePrinted; 14221 14222 private SharedUserSetting mSharedUser; 14223 14224 public boolean isDumping(int type) { 14225 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14226 return true; 14227 } 14228 14229 return (mTypes & type) != 0; 14230 } 14231 14232 public void setDump(int type) { 14233 mTypes |= type; 14234 } 14235 14236 public boolean isOptionEnabled(int option) { 14237 return (mOptions & option) != 0; 14238 } 14239 14240 public void setOptionEnabled(int option) { 14241 mOptions |= option; 14242 } 14243 14244 public boolean onTitlePrinted() { 14245 final boolean printed = mTitlePrinted; 14246 mTitlePrinted = true; 14247 return printed; 14248 } 14249 14250 public boolean getTitlePrinted() { 14251 return mTitlePrinted; 14252 } 14253 14254 public void setTitlePrinted(boolean enabled) { 14255 mTitlePrinted = enabled; 14256 } 14257 14258 public SharedUserSetting getSharedUser() { 14259 return mSharedUser; 14260 } 14261 14262 public void setSharedUser(SharedUserSetting user) { 14263 mSharedUser = user; 14264 } 14265 } 14266 14267 @Override 14268 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14269 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14270 != PackageManager.PERMISSION_GRANTED) { 14271 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14272 + Binder.getCallingPid() 14273 + ", uid=" + Binder.getCallingUid() 14274 + " without permission " 14275 + android.Manifest.permission.DUMP); 14276 return; 14277 } 14278 14279 DumpState dumpState = new DumpState(); 14280 boolean fullPreferred = false; 14281 boolean checkin = false; 14282 14283 String packageName = null; 14284 ArraySet<String> permissionNames = null; 14285 14286 int opti = 0; 14287 while (opti < args.length) { 14288 String opt = args[opti]; 14289 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14290 break; 14291 } 14292 opti++; 14293 14294 if ("-a".equals(opt)) { 14295 // Right now we only know how to print all. 14296 } else if ("-h".equals(opt)) { 14297 pw.println("Package manager dump options:"); 14298 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14299 pw.println(" --checkin: dump for a checkin"); 14300 pw.println(" -f: print details of intent filters"); 14301 pw.println(" -h: print this help"); 14302 pw.println(" cmd may be one of:"); 14303 pw.println(" l[ibraries]: list known shared libraries"); 14304 pw.println(" f[ibraries]: list device features"); 14305 pw.println(" k[eysets]: print known keysets"); 14306 pw.println(" r[esolvers]: dump intent resolvers"); 14307 pw.println(" perm[issions]: dump permissions"); 14308 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14309 pw.println(" pref[erred]: print preferred package settings"); 14310 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14311 pw.println(" prov[iders]: dump content providers"); 14312 pw.println(" p[ackages]: dump installed packages"); 14313 pw.println(" s[hared-users]: dump shared user IDs"); 14314 pw.println(" m[essages]: print collected runtime messages"); 14315 pw.println(" v[erifiers]: print package verifier info"); 14316 pw.println(" version: print database version info"); 14317 pw.println(" write: write current settings now"); 14318 pw.println(" <package.name>: info about given package"); 14319 pw.println(" installs: details about install sessions"); 14320 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14321 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14322 return; 14323 } else if ("--checkin".equals(opt)) { 14324 checkin = true; 14325 } else if ("-f".equals(opt)) { 14326 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14327 } else { 14328 pw.println("Unknown argument: " + opt + "; use -h for help"); 14329 } 14330 } 14331 14332 // Is the caller requesting to dump a particular piece of data? 14333 if (opti < args.length) { 14334 String cmd = args[opti]; 14335 opti++; 14336 // Is this a package name? 14337 if ("android".equals(cmd) || cmd.contains(".")) { 14338 packageName = cmd; 14339 // When dumping a single package, we always dump all of its 14340 // filter information since the amount of data will be reasonable. 14341 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14342 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14343 dumpState.setDump(DumpState.DUMP_LIBS); 14344 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14345 dumpState.setDump(DumpState.DUMP_FEATURES); 14346 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14347 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14348 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14349 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14350 } else if ("permission".equals(cmd)) { 14351 if (opti >= args.length) { 14352 pw.println("Error: permission requires permission name"); 14353 return; 14354 } 14355 permissionNames = new ArraySet<>(); 14356 while (opti < args.length) { 14357 permissionNames.add(args[opti]); 14358 opti++; 14359 } 14360 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14361 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14362 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14363 dumpState.setDump(DumpState.DUMP_PREFERRED); 14364 } else if ("preferred-xml".equals(cmd)) { 14365 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14366 if (opti < args.length && "--full".equals(args[opti])) { 14367 fullPreferred = true; 14368 opti++; 14369 } 14370 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14371 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14372 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14373 dumpState.setDump(DumpState.DUMP_PACKAGES); 14374 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14375 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14376 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14377 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14378 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14379 dumpState.setDump(DumpState.DUMP_MESSAGES); 14380 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14381 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14382 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14383 || "intent-filter-verifiers".equals(cmd)) { 14384 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14385 } else if ("version".equals(cmd)) { 14386 dumpState.setDump(DumpState.DUMP_VERSION); 14387 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14388 dumpState.setDump(DumpState.DUMP_KEYSETS); 14389 } else if ("installs".equals(cmd)) { 14390 dumpState.setDump(DumpState.DUMP_INSTALLS); 14391 } else if ("write".equals(cmd)) { 14392 synchronized (mPackages) { 14393 mSettings.writeLPr(); 14394 pw.println("Settings written."); 14395 return; 14396 } 14397 } 14398 } 14399 14400 if (checkin) { 14401 pw.println("vers,1"); 14402 } 14403 14404 // reader 14405 synchronized (mPackages) { 14406 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14407 if (!checkin) { 14408 if (dumpState.onTitlePrinted()) 14409 pw.println(); 14410 pw.println("Database versions:"); 14411 pw.print(" SDK Version:"); 14412 pw.print(" internal="); 14413 pw.print(mSettings.mInternalSdkPlatform); 14414 pw.print(" external="); 14415 pw.println(mSettings.mExternalSdkPlatform); 14416 pw.print(" DB Version:"); 14417 pw.print(" internal="); 14418 pw.print(mSettings.mInternalDatabaseVersion); 14419 pw.print(" external="); 14420 pw.println(mSettings.mExternalDatabaseVersion); 14421 } 14422 } 14423 14424 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14425 if (!checkin) { 14426 if (dumpState.onTitlePrinted()) 14427 pw.println(); 14428 pw.println("Verifiers:"); 14429 pw.print(" Required: "); 14430 pw.print(mRequiredVerifierPackage); 14431 pw.print(" (uid="); 14432 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14433 pw.println(")"); 14434 } else if (mRequiredVerifierPackage != null) { 14435 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14436 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14437 } 14438 } 14439 14440 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14441 packageName == null) { 14442 if (mIntentFilterVerifierComponent != null) { 14443 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14444 if (!checkin) { 14445 if (dumpState.onTitlePrinted()) 14446 pw.println(); 14447 pw.println("Intent Filter Verifier:"); 14448 pw.print(" Using: "); 14449 pw.print(verifierPackageName); 14450 pw.print(" (uid="); 14451 pw.print(getPackageUid(verifierPackageName, 0)); 14452 pw.println(")"); 14453 } else if (verifierPackageName != null) { 14454 pw.print("ifv,"); pw.print(verifierPackageName); 14455 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14456 } 14457 } else { 14458 pw.println(); 14459 pw.println("No Intent Filter Verifier available!"); 14460 } 14461 } 14462 14463 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14464 boolean printedHeader = false; 14465 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14466 while (it.hasNext()) { 14467 String name = it.next(); 14468 SharedLibraryEntry ent = mSharedLibraries.get(name); 14469 if (!checkin) { 14470 if (!printedHeader) { 14471 if (dumpState.onTitlePrinted()) 14472 pw.println(); 14473 pw.println("Libraries:"); 14474 printedHeader = true; 14475 } 14476 pw.print(" "); 14477 } else { 14478 pw.print("lib,"); 14479 } 14480 pw.print(name); 14481 if (!checkin) { 14482 pw.print(" -> "); 14483 } 14484 if (ent.path != null) { 14485 if (!checkin) { 14486 pw.print("(jar) "); 14487 pw.print(ent.path); 14488 } else { 14489 pw.print(",jar,"); 14490 pw.print(ent.path); 14491 } 14492 } else { 14493 if (!checkin) { 14494 pw.print("(apk) "); 14495 pw.print(ent.apk); 14496 } else { 14497 pw.print(",apk,"); 14498 pw.print(ent.apk); 14499 } 14500 } 14501 pw.println(); 14502 } 14503 } 14504 14505 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14506 if (dumpState.onTitlePrinted()) 14507 pw.println(); 14508 if (!checkin) { 14509 pw.println("Features:"); 14510 } 14511 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14512 while (it.hasNext()) { 14513 String name = it.next(); 14514 if (!checkin) { 14515 pw.print(" "); 14516 } else { 14517 pw.print("feat,"); 14518 } 14519 pw.println(name); 14520 } 14521 } 14522 14523 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14524 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14525 : "Activity Resolver Table:", " ", packageName, 14526 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14527 dumpState.setTitlePrinted(true); 14528 } 14529 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14530 : "Receiver Resolver Table:", " ", packageName, 14531 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14532 dumpState.setTitlePrinted(true); 14533 } 14534 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14535 : "Service Resolver Table:", " ", packageName, 14536 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14537 dumpState.setTitlePrinted(true); 14538 } 14539 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14540 : "Provider Resolver Table:", " ", packageName, 14541 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14542 dumpState.setTitlePrinted(true); 14543 } 14544 } 14545 14546 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14547 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14548 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14549 int user = mSettings.mPreferredActivities.keyAt(i); 14550 if (pir.dump(pw, 14551 dumpState.getTitlePrinted() 14552 ? "\nPreferred Activities User " + user + ":" 14553 : "Preferred Activities User " + user + ":", " ", 14554 packageName, true, false)) { 14555 dumpState.setTitlePrinted(true); 14556 } 14557 } 14558 } 14559 14560 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14561 pw.flush(); 14562 FileOutputStream fout = new FileOutputStream(fd); 14563 BufferedOutputStream str = new BufferedOutputStream(fout); 14564 XmlSerializer serializer = new FastXmlSerializer(); 14565 try { 14566 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14567 serializer.startDocument(null, true); 14568 serializer.setFeature( 14569 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14570 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14571 serializer.endDocument(); 14572 serializer.flush(); 14573 } catch (IllegalArgumentException e) { 14574 pw.println("Failed writing: " + e); 14575 } catch (IllegalStateException e) { 14576 pw.println("Failed writing: " + e); 14577 } catch (IOException e) { 14578 pw.println("Failed writing: " + e); 14579 } 14580 } 14581 14582 if (!checkin 14583 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14584 && packageName == null) { 14585 pw.println(); 14586 int count = mSettings.mPackages.size(); 14587 if (count == 0) { 14588 pw.println("No domain preferred apps!"); 14589 pw.println(); 14590 } else { 14591 final String prefix = " "; 14592 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14593 if (allPackageSettings.size() == 0) { 14594 pw.println("No domain preferred apps!"); 14595 pw.println(); 14596 } else { 14597 pw.println("Domain preferred apps status:"); 14598 pw.println(); 14599 count = 0; 14600 for (PackageSetting ps : allPackageSettings) { 14601 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14602 if (ivi == null || ivi.getPackageName() == null) continue; 14603 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14604 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14605 pw.println(prefix + "Status: " + ivi.getStatusString()); 14606 pw.println(); 14607 count++; 14608 } 14609 if (count == 0) { 14610 pw.println(prefix + "No domain preferred app status!"); 14611 pw.println(); 14612 } 14613 for (int userId : sUserManager.getUserIds()) { 14614 pw.println("Domain preferred apps for User " + userId + ":"); 14615 pw.println(); 14616 count = 0; 14617 for (PackageSetting ps : allPackageSettings) { 14618 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14619 if (ivi == null || ivi.getPackageName() == null) { 14620 continue; 14621 } 14622 final int status = ps.getDomainVerificationStatusForUser(userId); 14623 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14624 continue; 14625 } 14626 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14627 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14628 String statusStr = IntentFilterVerificationInfo. 14629 getStatusStringFromValue(status); 14630 pw.println(prefix + "Status: " + statusStr); 14631 pw.println(); 14632 count++; 14633 } 14634 if (count == 0) { 14635 pw.println(prefix + "No domain preferred apps!"); 14636 pw.println(); 14637 } 14638 } 14639 } 14640 } 14641 } 14642 14643 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14644 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14645 if (packageName == null && permissionNames == null) { 14646 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14647 if (iperm == 0) { 14648 if (dumpState.onTitlePrinted()) 14649 pw.println(); 14650 pw.println("AppOp Permissions:"); 14651 } 14652 pw.print(" AppOp Permission "); 14653 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14654 pw.println(":"); 14655 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14656 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14657 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14658 } 14659 } 14660 } 14661 } 14662 14663 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14664 boolean printedSomething = false; 14665 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14666 if (packageName != null && !packageName.equals(p.info.packageName)) { 14667 continue; 14668 } 14669 if (!printedSomething) { 14670 if (dumpState.onTitlePrinted()) 14671 pw.println(); 14672 pw.println("Registered ContentProviders:"); 14673 printedSomething = true; 14674 } 14675 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14676 pw.print(" "); pw.println(p.toString()); 14677 } 14678 printedSomething = false; 14679 for (Map.Entry<String, PackageParser.Provider> entry : 14680 mProvidersByAuthority.entrySet()) { 14681 PackageParser.Provider p = entry.getValue(); 14682 if (packageName != null && !packageName.equals(p.info.packageName)) { 14683 continue; 14684 } 14685 if (!printedSomething) { 14686 if (dumpState.onTitlePrinted()) 14687 pw.println(); 14688 pw.println("ContentProvider Authorities:"); 14689 printedSomething = true; 14690 } 14691 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14692 pw.print(" "); pw.println(p.toString()); 14693 if (p.info != null && p.info.applicationInfo != null) { 14694 final String appInfo = p.info.applicationInfo.toString(); 14695 pw.print(" applicationInfo="); pw.println(appInfo); 14696 } 14697 } 14698 } 14699 14700 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14701 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14702 } 14703 14704 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14705 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14706 } 14707 14708 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14709 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14710 } 14711 14712 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14713 // XXX should handle packageName != null by dumping only install data that 14714 // the given package is involved with. 14715 if (dumpState.onTitlePrinted()) pw.println(); 14716 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14717 } 14718 14719 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14720 if (dumpState.onTitlePrinted()) pw.println(); 14721 mSettings.dumpReadMessagesLPr(pw, dumpState); 14722 14723 pw.println(); 14724 pw.println("Package warning messages:"); 14725 BufferedReader in = null; 14726 String line = null; 14727 try { 14728 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14729 while ((line = in.readLine()) != null) { 14730 if (line.contains("ignored: updated version")) continue; 14731 pw.println(line); 14732 } 14733 } catch (IOException ignored) { 14734 } finally { 14735 IoUtils.closeQuietly(in); 14736 } 14737 } 14738 14739 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14740 BufferedReader in = null; 14741 String line = null; 14742 try { 14743 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14744 while ((line = in.readLine()) != null) { 14745 if (line.contains("ignored: updated version")) continue; 14746 pw.print("msg,"); 14747 pw.println(line); 14748 } 14749 } catch (IOException ignored) { 14750 } finally { 14751 IoUtils.closeQuietly(in); 14752 } 14753 } 14754 } 14755 } 14756 14757 // ------- apps on sdcard specific code ------- 14758 static final boolean DEBUG_SD_INSTALL = false; 14759 14760 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14761 14762 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14763 14764 private boolean mMediaMounted = false; 14765 14766 static String getEncryptKey() { 14767 try { 14768 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14769 SD_ENCRYPTION_KEYSTORE_NAME); 14770 if (sdEncKey == null) { 14771 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14772 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14773 if (sdEncKey == null) { 14774 Slog.e(TAG, "Failed to create encryption keys"); 14775 return null; 14776 } 14777 } 14778 return sdEncKey; 14779 } catch (NoSuchAlgorithmException nsae) { 14780 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14781 return null; 14782 } catch (IOException ioe) { 14783 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14784 return null; 14785 } 14786 } 14787 14788 /* 14789 * Update media status on PackageManager. 14790 */ 14791 @Override 14792 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14793 int callingUid = Binder.getCallingUid(); 14794 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14795 throw new SecurityException("Media status can only be updated by the system"); 14796 } 14797 // reader; this apparently protects mMediaMounted, but should probably 14798 // be a different lock in that case. 14799 synchronized (mPackages) { 14800 Log.i(TAG, "Updating external media status from " 14801 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14802 + (mediaStatus ? "mounted" : "unmounted")); 14803 if (DEBUG_SD_INSTALL) 14804 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14805 + ", mMediaMounted=" + mMediaMounted); 14806 if (mediaStatus == mMediaMounted) { 14807 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14808 : 0, -1); 14809 mHandler.sendMessage(msg); 14810 return; 14811 } 14812 mMediaMounted = mediaStatus; 14813 } 14814 // Queue up an async operation since the package installation may take a 14815 // little while. 14816 mHandler.post(new Runnable() { 14817 public void run() { 14818 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14819 } 14820 }); 14821 } 14822 14823 /** 14824 * Called by MountService when the initial ASECs to scan are available. 14825 * Should block until all the ASEC containers are finished being scanned. 14826 */ 14827 public void scanAvailableAsecs() { 14828 updateExternalMediaStatusInner(true, false, false); 14829 if (mShouldRestoreconData) { 14830 SELinuxMMAC.setRestoreconDone(); 14831 mShouldRestoreconData = false; 14832 } 14833 } 14834 14835 /* 14836 * Collect information of applications on external media, map them against 14837 * existing containers and update information based on current mount status. 14838 * Please note that we always have to report status if reportStatus has been 14839 * set to true especially when unloading packages. 14840 */ 14841 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14842 boolean externalStorage) { 14843 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14844 int[] uidArr = EmptyArray.INT; 14845 14846 final String[] list = PackageHelper.getSecureContainerList(); 14847 if (ArrayUtils.isEmpty(list)) { 14848 Log.i(TAG, "No secure containers found"); 14849 } else { 14850 // Process list of secure containers and categorize them 14851 // as active or stale based on their package internal state. 14852 14853 // reader 14854 synchronized (mPackages) { 14855 for (String cid : list) { 14856 // Leave stages untouched for now; installer service owns them 14857 if (PackageInstallerService.isStageName(cid)) continue; 14858 14859 if (DEBUG_SD_INSTALL) 14860 Log.i(TAG, "Processing container " + cid); 14861 String pkgName = getAsecPackageName(cid); 14862 if (pkgName == null) { 14863 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14864 continue; 14865 } 14866 if (DEBUG_SD_INSTALL) 14867 Log.i(TAG, "Looking for pkg : " + pkgName); 14868 14869 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14870 if (ps == null) { 14871 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14872 continue; 14873 } 14874 14875 /* 14876 * Skip packages that are not external if we're unmounting 14877 * external storage. 14878 */ 14879 if (externalStorage && !isMounted && !isExternal(ps)) { 14880 continue; 14881 } 14882 14883 final AsecInstallArgs args = new AsecInstallArgs(cid, 14884 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14885 // The package status is changed only if the code path 14886 // matches between settings and the container id. 14887 if (ps.codePathString != null 14888 && ps.codePathString.startsWith(args.getCodePath())) { 14889 if (DEBUG_SD_INSTALL) { 14890 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14891 + " at code path: " + ps.codePathString); 14892 } 14893 14894 // We do have a valid package installed on sdcard 14895 processCids.put(args, ps.codePathString); 14896 final int uid = ps.appId; 14897 if (uid != -1) { 14898 uidArr = ArrayUtils.appendInt(uidArr, uid); 14899 } 14900 } else { 14901 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14902 + ps.codePathString); 14903 } 14904 } 14905 } 14906 14907 Arrays.sort(uidArr); 14908 } 14909 14910 // Process packages with valid entries. 14911 if (isMounted) { 14912 if (DEBUG_SD_INSTALL) 14913 Log.i(TAG, "Loading packages"); 14914 loadMediaPackages(processCids, uidArr); 14915 startCleaningPackages(); 14916 mInstallerService.onSecureContainersAvailable(); 14917 } else { 14918 if (DEBUG_SD_INSTALL) 14919 Log.i(TAG, "Unloading packages"); 14920 unloadMediaPackages(processCids, uidArr, reportStatus); 14921 } 14922 } 14923 14924 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14925 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14926 final int size = infos.size(); 14927 final String[] packageNames = new String[size]; 14928 final int[] packageUids = new int[size]; 14929 for (int i = 0; i < size; i++) { 14930 final ApplicationInfo info = infos.get(i); 14931 packageNames[i] = info.packageName; 14932 packageUids[i] = info.uid; 14933 } 14934 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14935 finishedReceiver); 14936 } 14937 14938 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14939 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14940 sendResourcesChangedBroadcast(mediaStatus, replacing, 14941 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14942 } 14943 14944 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14945 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14946 int size = pkgList.length; 14947 if (size > 0) { 14948 // Send broadcasts here 14949 Bundle extras = new Bundle(); 14950 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14951 if (uidArr != null) { 14952 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14953 } 14954 if (replacing) { 14955 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14956 } 14957 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14958 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14959 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14960 } 14961 } 14962 14963 /* 14964 * Look at potentially valid container ids from processCids If package 14965 * information doesn't match the one on record or package scanning fails, 14966 * the cid is added to list of removeCids. We currently don't delete stale 14967 * containers. 14968 */ 14969 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14970 ArrayList<String> pkgList = new ArrayList<String>(); 14971 Set<AsecInstallArgs> keys = processCids.keySet(); 14972 14973 for (AsecInstallArgs args : keys) { 14974 String codePath = processCids.get(args); 14975 if (DEBUG_SD_INSTALL) 14976 Log.i(TAG, "Loading container : " + args.cid); 14977 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14978 try { 14979 // Make sure there are no container errors first. 14980 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14981 Slog.e(TAG, "Failed to mount cid : " + args.cid 14982 + " when installing from sdcard"); 14983 continue; 14984 } 14985 // Check code path here. 14986 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14987 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14988 + " does not match one in settings " + codePath); 14989 continue; 14990 } 14991 // Parse package 14992 int parseFlags = mDefParseFlags; 14993 if (args.isExternalAsec()) { 14994 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14995 } 14996 if (args.isFwdLocked()) { 14997 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14998 } 14999 15000 synchronized (mInstallLock) { 15001 PackageParser.Package pkg = null; 15002 try { 15003 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15004 } catch (PackageManagerException e) { 15005 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15006 } 15007 // Scan the package 15008 if (pkg != null) { 15009 /* 15010 * TODO why is the lock being held? doPostInstall is 15011 * called in other places without the lock. This needs 15012 * to be straightened out. 15013 */ 15014 // writer 15015 synchronized (mPackages) { 15016 retCode = PackageManager.INSTALL_SUCCEEDED; 15017 pkgList.add(pkg.packageName); 15018 // Post process args 15019 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15020 pkg.applicationInfo.uid); 15021 } 15022 } else { 15023 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15024 } 15025 } 15026 15027 } finally { 15028 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15029 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15030 } 15031 } 15032 } 15033 // writer 15034 synchronized (mPackages) { 15035 // If the platform SDK has changed since the last time we booted, 15036 // we need to re-grant app permission to catch any new ones that 15037 // appear. This is really a hack, and means that apps can in some 15038 // cases get permissions that the user didn't initially explicitly 15039 // allow... it would be nice to have some better way to handle 15040 // this situation. 15041 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15042 if (regrantPermissions) 15043 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15044 + mSdkVersion + "; regranting permissions for external storage"); 15045 mSettings.mExternalSdkPlatform = mSdkVersion; 15046 15047 // Make sure group IDs have been assigned, and any permission 15048 // changes in other apps are accounted for 15049 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15050 | (regrantPermissions 15051 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15052 : 0)); 15053 15054 mSettings.updateExternalDatabaseVersion(); 15055 15056 // can downgrade to reader 15057 // Persist settings 15058 mSettings.writeLPr(); 15059 } 15060 // Send a broadcast to let everyone know we are done processing 15061 if (pkgList.size() > 0) { 15062 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15063 } 15064 } 15065 15066 /* 15067 * Utility method to unload a list of specified containers 15068 */ 15069 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15070 // Just unmount all valid containers. 15071 for (AsecInstallArgs arg : cidArgs) { 15072 synchronized (mInstallLock) { 15073 arg.doPostDeleteLI(false); 15074 } 15075 } 15076 } 15077 15078 /* 15079 * Unload packages mounted on external media. This involves deleting package 15080 * data from internal structures, sending broadcasts about diabled packages, 15081 * gc'ing to free up references, unmounting all secure containers 15082 * corresponding to packages on external media, and posting a 15083 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15084 * that we always have to post this message if status has been requested no 15085 * matter what. 15086 */ 15087 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15088 final boolean reportStatus) { 15089 if (DEBUG_SD_INSTALL) 15090 Log.i(TAG, "unloading media packages"); 15091 ArrayList<String> pkgList = new ArrayList<String>(); 15092 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15093 final Set<AsecInstallArgs> keys = processCids.keySet(); 15094 for (AsecInstallArgs args : keys) { 15095 String pkgName = args.getPackageName(); 15096 if (DEBUG_SD_INSTALL) 15097 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15098 // Delete package internally 15099 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15100 synchronized (mInstallLock) { 15101 boolean res = deletePackageLI(pkgName, null, false, null, null, 15102 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15103 if (res) { 15104 pkgList.add(pkgName); 15105 } else { 15106 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15107 failedList.add(args); 15108 } 15109 } 15110 } 15111 15112 // reader 15113 synchronized (mPackages) { 15114 // We didn't update the settings after removing each package; 15115 // write them now for all packages. 15116 mSettings.writeLPr(); 15117 } 15118 15119 // We have to absolutely send UPDATED_MEDIA_STATUS only 15120 // after confirming that all the receivers processed the ordered 15121 // broadcast when packages get disabled, force a gc to clean things up. 15122 // and unload all the containers. 15123 if (pkgList.size() > 0) { 15124 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15125 new IIntentReceiver.Stub() { 15126 public void performReceive(Intent intent, int resultCode, String data, 15127 Bundle extras, boolean ordered, boolean sticky, 15128 int sendingUser) throws RemoteException { 15129 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15130 reportStatus ? 1 : 0, 1, keys); 15131 mHandler.sendMessage(msg); 15132 } 15133 }); 15134 } else { 15135 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15136 keys); 15137 mHandler.sendMessage(msg); 15138 } 15139 } 15140 15141 private void loadPrivatePackages(VolumeInfo vol) { 15142 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15143 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15144 synchronized (mInstallLock) { 15145 synchronized (mPackages) { 15146 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15147 for (PackageSetting ps : packages) { 15148 final PackageParser.Package pkg; 15149 try { 15150 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15151 loaded.add(pkg.applicationInfo); 15152 } catch (PackageManagerException e) { 15153 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15154 } 15155 } 15156 15157 // TODO: regrant any permissions that changed based since original install 15158 15159 mSettings.writeLPr(); 15160 } 15161 } 15162 15163 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15164 sendResourcesChangedBroadcast(true, false, loaded, null); 15165 } 15166 15167 private void unloadPrivatePackages(VolumeInfo vol) { 15168 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15169 synchronized (mInstallLock) { 15170 synchronized (mPackages) { 15171 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15172 for (PackageSetting ps : packages) { 15173 if (ps.pkg == null) continue; 15174 15175 final ApplicationInfo info = ps.pkg.applicationInfo; 15176 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15177 if (deletePackageLI(ps.name, null, false, null, null, 15178 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15179 unloaded.add(info); 15180 } else { 15181 Slog.w(TAG, "Failed to unload " + ps.codePath); 15182 } 15183 } 15184 15185 mSettings.writeLPr(); 15186 } 15187 } 15188 15189 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15190 sendResourcesChangedBroadcast(false, false, unloaded, null); 15191 } 15192 15193 private void unfreezePackage(String packageName) { 15194 synchronized (mPackages) { 15195 final PackageSetting ps = mSettings.mPackages.get(packageName); 15196 if (ps != null) { 15197 ps.frozen = false; 15198 } 15199 } 15200 } 15201 15202 @Override 15203 public int movePackage(final String packageName, final String volumeUuid) { 15204 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15205 15206 final int moveId = mNextMoveId.getAndIncrement(); 15207 try { 15208 movePackageInternal(packageName, volumeUuid, moveId); 15209 } catch (PackageManagerException e) { 15210 Slog.w(TAG, "Failed to move " + packageName, e); 15211 mMoveCallbacks.notifyStatusChanged(moveId, 15212 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15213 } 15214 return moveId; 15215 } 15216 15217 private void movePackageInternal(final String packageName, final String volumeUuid, 15218 final int moveId) throws PackageManagerException { 15219 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15220 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15221 final PackageManager pm = mContext.getPackageManager(); 15222 15223 final boolean currentAsec; 15224 final String currentVolumeUuid; 15225 final File codeFile; 15226 final String installerPackageName; 15227 final String packageAbiOverride; 15228 final int appId; 15229 final String seinfo; 15230 final String label; 15231 15232 // reader 15233 synchronized (mPackages) { 15234 final PackageParser.Package pkg = mPackages.get(packageName); 15235 final PackageSetting ps = mSettings.mPackages.get(packageName); 15236 if (pkg == null || ps == null) { 15237 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15238 } 15239 15240 if (pkg.applicationInfo.isSystemApp()) { 15241 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15242 "Cannot move system application"); 15243 } 15244 15245 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15246 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15247 "Package already moved to " + volumeUuid); 15248 } 15249 15250 final File probe = new File(pkg.codePath); 15251 final File probeOat = new File(probe, "oat"); 15252 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15253 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15254 "Move only supported for modern cluster style installs"); 15255 } 15256 15257 if (ps.frozen) { 15258 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15259 "Failed to move already frozen package"); 15260 } 15261 ps.frozen = true; 15262 15263 currentAsec = pkg.applicationInfo.isForwardLocked() 15264 || pkg.applicationInfo.isExternalAsec(); 15265 currentVolumeUuid = ps.volumeUuid; 15266 codeFile = new File(pkg.codePath); 15267 installerPackageName = ps.installerPackageName; 15268 packageAbiOverride = ps.cpuAbiOverrideString; 15269 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15270 seinfo = pkg.applicationInfo.seinfo; 15271 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15272 } 15273 15274 // Now that we're guarded by frozen state, kill app during move 15275 killApplication(packageName, appId, "move pkg"); 15276 15277 final Bundle extras = new Bundle(); 15278 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15279 extras.putString(Intent.EXTRA_TITLE, label); 15280 mMoveCallbacks.notifyCreated(moveId, extras); 15281 15282 int installFlags; 15283 final boolean moveCompleteApp; 15284 final File measurePath; 15285 15286 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15287 installFlags = INSTALL_INTERNAL; 15288 moveCompleteApp = !currentAsec; 15289 measurePath = Environment.getDataAppDirectory(volumeUuid); 15290 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15291 installFlags = INSTALL_EXTERNAL; 15292 moveCompleteApp = false; 15293 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15294 } else { 15295 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15296 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15297 || !volume.isMountedWritable()) { 15298 unfreezePackage(packageName); 15299 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15300 "Move location not mounted private volume"); 15301 } 15302 15303 Preconditions.checkState(!currentAsec); 15304 15305 installFlags = INSTALL_INTERNAL; 15306 moveCompleteApp = true; 15307 measurePath = Environment.getDataAppDirectory(volumeUuid); 15308 } 15309 15310 final PackageStats stats = new PackageStats(null, -1); 15311 synchronized (mInstaller) { 15312 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15313 unfreezePackage(packageName); 15314 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15315 "Failed to measure package size"); 15316 } 15317 } 15318 15319 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15320 + stats.dataSize); 15321 15322 final long startFreeBytes = measurePath.getFreeSpace(); 15323 final long sizeBytes; 15324 if (moveCompleteApp) { 15325 sizeBytes = stats.codeSize + stats.dataSize; 15326 } else { 15327 sizeBytes = stats.codeSize; 15328 } 15329 15330 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15331 unfreezePackage(packageName); 15332 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15333 "Not enough free space to move"); 15334 } 15335 15336 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15337 15338 final CountDownLatch installedLatch = new CountDownLatch(1); 15339 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15340 @Override 15341 public void onUserActionRequired(Intent intent) throws RemoteException { 15342 throw new IllegalStateException(); 15343 } 15344 15345 @Override 15346 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15347 Bundle extras) throws RemoteException { 15348 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15349 + PackageManager.installStatusToString(returnCode, msg)); 15350 15351 installedLatch.countDown(); 15352 15353 // Regardless of success or failure of the move operation, 15354 // always unfreeze the package 15355 unfreezePackage(packageName); 15356 15357 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15358 switch (status) { 15359 case PackageInstaller.STATUS_SUCCESS: 15360 mMoveCallbacks.notifyStatusChanged(moveId, 15361 PackageManager.MOVE_SUCCEEDED); 15362 break; 15363 case PackageInstaller.STATUS_FAILURE_STORAGE: 15364 mMoveCallbacks.notifyStatusChanged(moveId, 15365 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15366 break; 15367 default: 15368 mMoveCallbacks.notifyStatusChanged(moveId, 15369 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15370 break; 15371 } 15372 } 15373 }; 15374 15375 final MoveInfo move; 15376 if (moveCompleteApp) { 15377 // Kick off a thread to report progress estimates 15378 new Thread() { 15379 @Override 15380 public void run() { 15381 while (true) { 15382 try { 15383 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15384 break; 15385 } 15386 } catch (InterruptedException ignored) { 15387 } 15388 15389 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15390 final int progress = 10 + (int) MathUtils.constrain( 15391 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15392 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15393 } 15394 } 15395 }.start(); 15396 15397 final String dataAppName = codeFile.getName(); 15398 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15399 dataAppName, appId, seinfo); 15400 } else { 15401 move = null; 15402 } 15403 15404 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15405 15406 final Message msg = mHandler.obtainMessage(INIT_COPY); 15407 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15408 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15409 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15410 mHandler.sendMessage(msg); 15411 } 15412 15413 @Override 15414 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15415 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15416 15417 final int realMoveId = mNextMoveId.getAndIncrement(); 15418 final Bundle extras = new Bundle(); 15419 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15420 mMoveCallbacks.notifyCreated(realMoveId, extras); 15421 15422 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15423 @Override 15424 public void onCreated(int moveId, Bundle extras) { 15425 // Ignored 15426 } 15427 15428 @Override 15429 public void onStatusChanged(int moveId, int status, long estMillis) { 15430 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15431 } 15432 }; 15433 15434 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15435 storage.setPrimaryStorageUuid(volumeUuid, callback); 15436 return realMoveId; 15437 } 15438 15439 @Override 15440 public int getMoveStatus(int moveId) { 15441 mContext.enforceCallingOrSelfPermission( 15442 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15443 return mMoveCallbacks.mLastStatus.get(moveId); 15444 } 15445 15446 @Override 15447 public void registerMoveCallback(IPackageMoveObserver callback) { 15448 mContext.enforceCallingOrSelfPermission( 15449 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15450 mMoveCallbacks.register(callback); 15451 } 15452 15453 @Override 15454 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15455 mContext.enforceCallingOrSelfPermission( 15456 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15457 mMoveCallbacks.unregister(callback); 15458 } 15459 15460 @Override 15461 public boolean setInstallLocation(int loc) { 15462 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15463 null); 15464 if (getInstallLocation() == loc) { 15465 return true; 15466 } 15467 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15468 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15469 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15470 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15471 return true; 15472 } 15473 return false; 15474 } 15475 15476 @Override 15477 public int getInstallLocation() { 15478 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15479 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15480 PackageHelper.APP_INSTALL_AUTO); 15481 } 15482 15483 /** Called by UserManagerService */ 15484 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15485 mDirtyUsers.remove(userHandle); 15486 mSettings.removeUserLPw(userHandle); 15487 mPendingBroadcasts.remove(userHandle); 15488 if (mInstaller != null) { 15489 // Technically, we shouldn't be doing this with the package lock 15490 // held. However, this is very rare, and there is already so much 15491 // other disk I/O going on, that we'll let it slide for now. 15492 final StorageManager storage = StorageManager.from(mContext); 15493 final List<VolumeInfo> vols = storage.getVolumes(); 15494 for (VolumeInfo vol : vols) { 15495 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15496 final String volumeUuid = vol.getFsUuid(); 15497 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15498 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15499 } 15500 } 15501 } 15502 mUserNeedsBadging.delete(userHandle); 15503 removeUnusedPackagesLILPw(userManager, userHandle); 15504 } 15505 15506 /** 15507 * We're removing userHandle and would like to remove any downloaded packages 15508 * that are no longer in use by any other user. 15509 * @param userHandle the user being removed 15510 */ 15511 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15512 final boolean DEBUG_CLEAN_APKS = false; 15513 int [] users = userManager.getUserIdsLPr(); 15514 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15515 while (psit.hasNext()) { 15516 PackageSetting ps = psit.next(); 15517 if (ps.pkg == null) { 15518 continue; 15519 } 15520 final String packageName = ps.pkg.packageName; 15521 // Skip over if system app 15522 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15523 continue; 15524 } 15525 if (DEBUG_CLEAN_APKS) { 15526 Slog.i(TAG, "Checking package " + packageName); 15527 } 15528 boolean keep = false; 15529 for (int i = 0; i < users.length; i++) { 15530 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15531 keep = true; 15532 if (DEBUG_CLEAN_APKS) { 15533 Slog.i(TAG, " Keeping package " + packageName + " for user " 15534 + users[i]); 15535 } 15536 break; 15537 } 15538 } 15539 if (!keep) { 15540 if (DEBUG_CLEAN_APKS) { 15541 Slog.i(TAG, " Removing package " + packageName); 15542 } 15543 mHandler.post(new Runnable() { 15544 public void run() { 15545 deletePackageX(packageName, userHandle, 0); 15546 } //end run 15547 }); 15548 } 15549 } 15550 } 15551 15552 /** Called by UserManagerService */ 15553 void createNewUserLILPw(int userHandle, File path) { 15554 if (mInstaller != null) { 15555 mInstaller.createUserConfig(userHandle); 15556 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15557 applyFactoryDefaultBrowserLPw(userHandle); 15558 } 15559 } 15560 15561 void newUserCreatedLILPw(final int userHandle) { 15562 // We cannot grant the default permissions with a lock held as 15563 // we query providers from other components for default handlers 15564 // such as enabled IMEs, etc. 15565 mHandler.post(new Runnable() { 15566 @Override 15567 public void run() { 15568 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15569 } 15570 }); 15571 } 15572 15573 @Override 15574 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15575 mContext.enforceCallingOrSelfPermission( 15576 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15577 "Only package verification agents can read the verifier device identity"); 15578 15579 synchronized (mPackages) { 15580 return mSettings.getVerifierDeviceIdentityLPw(); 15581 } 15582 } 15583 15584 @Override 15585 public void setPermissionEnforced(String permission, boolean enforced) { 15586 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15587 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15588 synchronized (mPackages) { 15589 if (mSettings.mReadExternalStorageEnforced == null 15590 || mSettings.mReadExternalStorageEnforced != enforced) { 15591 mSettings.mReadExternalStorageEnforced = enforced; 15592 mSettings.writeLPr(); 15593 } 15594 } 15595 // kill any non-foreground processes so we restart them and 15596 // grant/revoke the GID. 15597 final IActivityManager am = ActivityManagerNative.getDefault(); 15598 if (am != null) { 15599 final long token = Binder.clearCallingIdentity(); 15600 try { 15601 am.killProcessesBelowForeground("setPermissionEnforcement"); 15602 } catch (RemoteException e) { 15603 } finally { 15604 Binder.restoreCallingIdentity(token); 15605 } 15606 } 15607 } else { 15608 throw new IllegalArgumentException("No selective enforcement for " + permission); 15609 } 15610 } 15611 15612 @Override 15613 @Deprecated 15614 public boolean isPermissionEnforced(String permission) { 15615 return true; 15616 } 15617 15618 @Override 15619 public boolean isStorageLow() { 15620 final long token = Binder.clearCallingIdentity(); 15621 try { 15622 final DeviceStorageMonitorInternal 15623 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15624 if (dsm != null) { 15625 return dsm.isMemoryLow(); 15626 } else { 15627 return false; 15628 } 15629 } finally { 15630 Binder.restoreCallingIdentity(token); 15631 } 15632 } 15633 15634 @Override 15635 public IPackageInstaller getPackageInstaller() { 15636 return mInstallerService; 15637 } 15638 15639 private boolean userNeedsBadging(int userId) { 15640 int index = mUserNeedsBadging.indexOfKey(userId); 15641 if (index < 0) { 15642 final UserInfo userInfo; 15643 final long token = Binder.clearCallingIdentity(); 15644 try { 15645 userInfo = sUserManager.getUserInfo(userId); 15646 } finally { 15647 Binder.restoreCallingIdentity(token); 15648 } 15649 final boolean b; 15650 if (userInfo != null && userInfo.isManagedProfile()) { 15651 b = true; 15652 } else { 15653 b = false; 15654 } 15655 mUserNeedsBadging.put(userId, b); 15656 return b; 15657 } 15658 return mUserNeedsBadging.valueAt(index); 15659 } 15660 15661 @Override 15662 public KeySet getKeySetByAlias(String packageName, String alias) { 15663 if (packageName == null || alias == null) { 15664 return null; 15665 } 15666 synchronized(mPackages) { 15667 final PackageParser.Package pkg = mPackages.get(packageName); 15668 if (pkg == null) { 15669 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15670 throw new IllegalArgumentException("Unknown package: " + packageName); 15671 } 15672 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15673 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15674 } 15675 } 15676 15677 @Override 15678 public KeySet getSigningKeySet(String packageName) { 15679 if (packageName == null) { 15680 return null; 15681 } 15682 synchronized(mPackages) { 15683 final PackageParser.Package pkg = mPackages.get(packageName); 15684 if (pkg == null) { 15685 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15686 throw new IllegalArgumentException("Unknown package: " + packageName); 15687 } 15688 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15689 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15690 throw new SecurityException("May not access signing KeySet of other apps."); 15691 } 15692 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15693 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15694 } 15695 } 15696 15697 @Override 15698 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15699 if (packageName == null || ks == null) { 15700 return false; 15701 } 15702 synchronized(mPackages) { 15703 final PackageParser.Package pkg = mPackages.get(packageName); 15704 if (pkg == null) { 15705 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15706 throw new IllegalArgumentException("Unknown package: " + packageName); 15707 } 15708 IBinder ksh = ks.getToken(); 15709 if (ksh instanceof KeySetHandle) { 15710 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15711 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15712 } 15713 return false; 15714 } 15715 } 15716 15717 @Override 15718 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15719 if (packageName == null || ks == null) { 15720 return false; 15721 } 15722 synchronized(mPackages) { 15723 final PackageParser.Package pkg = mPackages.get(packageName); 15724 if (pkg == null) { 15725 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15726 throw new IllegalArgumentException("Unknown package: " + packageName); 15727 } 15728 IBinder ksh = ks.getToken(); 15729 if (ksh instanceof KeySetHandle) { 15730 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15731 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15732 } 15733 return false; 15734 } 15735 } 15736 15737 public void getUsageStatsIfNoPackageUsageInfo() { 15738 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15739 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15740 if (usm == null) { 15741 throw new IllegalStateException("UsageStatsManager must be initialized"); 15742 } 15743 long now = System.currentTimeMillis(); 15744 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15745 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15746 String packageName = entry.getKey(); 15747 PackageParser.Package pkg = mPackages.get(packageName); 15748 if (pkg == null) { 15749 continue; 15750 } 15751 UsageStats usage = entry.getValue(); 15752 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15753 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15754 } 15755 } 15756 } 15757 15758 /** 15759 * Check and throw if the given before/after packages would be considered a 15760 * downgrade. 15761 */ 15762 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15763 throws PackageManagerException { 15764 if (after.versionCode < before.mVersionCode) { 15765 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15766 "Update version code " + after.versionCode + " is older than current " 15767 + before.mVersionCode); 15768 } else if (after.versionCode == before.mVersionCode) { 15769 if (after.baseRevisionCode < before.baseRevisionCode) { 15770 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15771 "Update base revision code " + after.baseRevisionCode 15772 + " is older than current " + before.baseRevisionCode); 15773 } 15774 15775 if (!ArrayUtils.isEmpty(after.splitNames)) { 15776 for (int i = 0; i < after.splitNames.length; i++) { 15777 final String splitName = after.splitNames[i]; 15778 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15779 if (j != -1) { 15780 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15781 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15782 "Update split " + splitName + " revision code " 15783 + after.splitRevisionCodes[i] + " is older than current " 15784 + before.splitRevisionCodes[j]); 15785 } 15786 } 15787 } 15788 } 15789 } 15790 } 15791 15792 private static class MoveCallbacks extends Handler { 15793 private static final int MSG_CREATED = 1; 15794 private static final int MSG_STATUS_CHANGED = 2; 15795 15796 private final RemoteCallbackList<IPackageMoveObserver> 15797 mCallbacks = new RemoteCallbackList<>(); 15798 15799 private final SparseIntArray mLastStatus = new SparseIntArray(); 15800 15801 public MoveCallbacks(Looper looper) { 15802 super(looper); 15803 } 15804 15805 public void register(IPackageMoveObserver callback) { 15806 mCallbacks.register(callback); 15807 } 15808 15809 public void unregister(IPackageMoveObserver callback) { 15810 mCallbacks.unregister(callback); 15811 } 15812 15813 @Override 15814 public void handleMessage(Message msg) { 15815 final SomeArgs args = (SomeArgs) msg.obj; 15816 final int n = mCallbacks.beginBroadcast(); 15817 for (int i = 0; i < n; i++) { 15818 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15819 try { 15820 invokeCallback(callback, msg.what, args); 15821 } catch (RemoteException ignored) { 15822 } 15823 } 15824 mCallbacks.finishBroadcast(); 15825 args.recycle(); 15826 } 15827 15828 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15829 throws RemoteException { 15830 switch (what) { 15831 case MSG_CREATED: { 15832 callback.onCreated(args.argi1, (Bundle) args.arg2); 15833 break; 15834 } 15835 case MSG_STATUS_CHANGED: { 15836 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15837 break; 15838 } 15839 } 15840 } 15841 15842 private void notifyCreated(int moveId, Bundle extras) { 15843 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15844 15845 final SomeArgs args = SomeArgs.obtain(); 15846 args.argi1 = moveId; 15847 args.arg2 = extras; 15848 obtainMessage(MSG_CREATED, args).sendToTarget(); 15849 } 15850 15851 private void notifyStatusChanged(int moveId, int status) { 15852 notifyStatusChanged(moveId, status, -1); 15853 } 15854 15855 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15856 Slog.v(TAG, "Move " + moveId + " status " + status); 15857 15858 final SomeArgs args = SomeArgs.obtain(); 15859 args.argi1 = moveId; 15860 args.argi2 = status; 15861 args.arg3 = estMillis; 15862 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15863 15864 synchronized (mLastStatus) { 15865 mLastStatus.put(moveId, status); 15866 } 15867 } 15868 } 15869 15870 private final class OnPermissionChangeListeners extends Handler { 15871 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15872 15873 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15874 new RemoteCallbackList<>(); 15875 15876 public OnPermissionChangeListeners(Looper looper) { 15877 super(looper); 15878 } 15879 15880 @Override 15881 public void handleMessage(Message msg) { 15882 switch (msg.what) { 15883 case MSG_ON_PERMISSIONS_CHANGED: { 15884 final int uid = msg.arg1; 15885 handleOnPermissionsChanged(uid); 15886 } break; 15887 } 15888 } 15889 15890 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15891 mPermissionListeners.register(listener); 15892 15893 } 15894 15895 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15896 mPermissionListeners.unregister(listener); 15897 } 15898 15899 public void onPermissionsChanged(int uid) { 15900 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15901 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15902 } 15903 } 15904 15905 private void handleOnPermissionsChanged(int uid) { 15906 final int count = mPermissionListeners.beginBroadcast(); 15907 try { 15908 for (int i = 0; i < count; i++) { 15909 IOnPermissionsChangeListener callback = mPermissionListeners 15910 .getBroadcastItem(i); 15911 try { 15912 callback.onPermissionsChanged(uid); 15913 } catch (RemoteException e) { 15914 Log.e(TAG, "Permission listener is dead", e); 15915 } 15916 } 15917 } finally { 15918 mPermissionListeners.finishBroadcast(); 15919 } 15920 } 15921 } 15922 15923 private class PackageManagerInternalImpl extends PackageManagerInternal { 15924 @Override 15925 public void setLocationPackagesProvider(PackagesProvider provider) { 15926 synchronized (mPackages) { 15927 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15928 } 15929 } 15930 15931 @Override 15932 public void setImePackagesProvider(PackagesProvider provider) { 15933 synchronized (mPackages) { 15934 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15935 } 15936 } 15937 15938 @Override 15939 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15940 synchronized (mPackages) { 15941 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15942 } 15943 } 15944 } 15945 15946 @Override 15947 public void grantDefaultPermissions(final int userId) { 15948 enforceSystemOrPhoneCaller("grantDefaultPermissions"); 15949 long token = Binder.clearCallingIdentity(); 15950 try { 15951 // We cannot grant the default permissions with a lock held as 15952 // we query providers from other components for default handlers 15953 // such as enabled IMEs, etc. 15954 mHandler.post(new Runnable() { 15955 @Override 15956 public void run() { 15957 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15958 } 15959 }); 15960 } finally { 15961 Binder.restoreCallingIdentity(token); 15962 } 15963 } 15964 15965 @Override 15966 public void setCarrierAppPackagesProvider(final IPackagesProvider provider) { 15967 enforceSystemOrPhoneCaller("setCarrierAppPackagesProvider"); 15968 long token = Binder.clearCallingIdentity(); 15969 try { 15970 PackageManagerInternal.PackagesProvider wrapper = 15971 new PackageManagerInternal.PackagesProvider() { 15972 @Override 15973 public String[] getPackages(int userId) { 15974 try { 15975 return provider.getPackages(userId); 15976 } catch (RemoteException e) { 15977 return null; 15978 } 15979 } 15980 }; 15981 synchronized (mPackages) { 15982 mDefaultPermissionPolicy.setCarrierAppPackagesProviderLPw(wrapper); 15983 } 15984 } finally { 15985 Binder.restoreCallingIdentity(token); 15986 } 15987 } 15988 15989 private static void enforceSystemOrPhoneCaller(String tag) { 15990 int callingUid = Binder.getCallingUid(); 15991 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 15992 throw new SecurityException( 15993 "Cannot call " + tag + " from UID " + callingUid); 15994 } 15995 } 15996} 15997