PackageManagerService.java revision 2bd8e97f996bba0b52ed213f4feb4f367fe019c2
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.PACKAGE_INFO_GID; 59import static android.os.Process.SYSTEM_UID; 60import static android.system.OsConstants.O_CREAT; 61import static android.system.OsConstants.O_RDWR; 62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 66import static com.android.internal.util.ArrayUtils.appendInt; 67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 72 73import android.Manifest; 74import android.app.ActivityManager; 75import android.app.ActivityManagerNative; 76import android.app.AppGlobals; 77import android.app.IActivityManager; 78import android.app.admin.IDevicePolicyManager; 79import android.app.backup.IBackupManager; 80import android.app.usage.UsageStats; 81import android.app.usage.UsageStatsManager; 82import android.content.BroadcastReceiver; 83import android.content.ComponentName; 84import android.content.Context; 85import android.content.IIntentReceiver; 86import android.content.Intent; 87import android.content.IntentFilter; 88import android.content.IntentSender; 89import android.content.IntentSender.SendIntentException; 90import android.content.ServiceConnection; 91import android.content.pm.ActivityInfo; 92import android.content.pm.ApplicationInfo; 93import android.content.pm.FeatureInfo; 94import android.content.pm.IOnPermissionsChangeListener; 95import android.content.pm.IPackageDataObserver; 96import android.content.pm.IPackageDeleteObserver; 97import android.content.pm.IPackageDeleteObserver2; 98import android.content.pm.IPackageInstallObserver2; 99import android.content.pm.IPackageInstaller; 100import android.content.pm.IPackageManager; 101import android.content.pm.IPackageMoveObserver; 102import android.content.pm.IPackageStatsObserver; 103import android.content.pm.InstrumentationInfo; 104import android.content.pm.IntentFilterVerificationInfo; 105import android.content.pm.KeySet; 106import android.content.pm.ManifestDigest; 107import android.content.pm.PackageCleanItem; 108import android.content.pm.PackageInfo; 109import android.content.pm.PackageInfoLite; 110import android.content.pm.PackageInstaller; 111import android.content.pm.PackageManager; 112import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 113import android.content.pm.PackageManagerInternal; 114import android.content.pm.PackageParser; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageStats; 119import android.content.pm.PackageUserState; 120import android.content.pm.ParceledListSlice; 121import android.content.pm.PermissionGroupInfo; 122import android.content.pm.PermissionInfo; 123import android.content.pm.ProviderInfo; 124import android.content.pm.ResolveInfo; 125import android.content.pm.ServiceInfo; 126import android.content.pm.Signature; 127import android.content.pm.UserInfo; 128import android.content.pm.VerificationParams; 129import android.content.pm.VerifierDeviceIdentity; 130import android.content.pm.VerifierInfo; 131import android.content.res.Resources; 132import android.hardware.display.DisplayManager; 133import android.net.Uri; 134import android.os.Binder; 135import android.os.Build; 136import android.os.Bundle; 137import android.os.Debug; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.FileUtils; 141import android.os.Handler; 142import android.os.IBinder; 143import android.os.Looper; 144import android.os.Message; 145import android.os.Parcel; 146import android.os.ParcelFileDescriptor; 147import android.os.Process; 148import android.os.RemoteCallbackList; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.os.storage.IMountService; 157import android.os.storage.StorageEventListener; 158import android.os.storage.StorageManager; 159import android.os.storage.VolumeInfo; 160import android.os.storage.VolumeRecord; 161import android.security.KeyStore; 162import android.security.SystemKeyStore; 163import android.system.ErrnoException; 164import android.system.Os; 165import android.system.StructStat; 166import android.text.TextUtils; 167import android.text.format.DateUtils; 168import android.util.ArrayMap; 169import android.util.ArraySet; 170import android.util.AtomicFile; 171import android.util.DisplayMetrics; 172import android.util.EventLog; 173import android.util.ExceptionUtils; 174import android.util.Log; 175import android.util.LogPrinter; 176import android.util.MathUtils; 177import android.util.PrintStreamPrinter; 178import android.util.Slog; 179import android.util.SparseArray; 180import android.util.SparseBooleanArray; 181import android.util.SparseIntArray; 182import android.util.Xml; 183import android.view.Display; 184 185import dalvik.system.DexFile; 186import dalvik.system.VMRuntime; 187 188import libcore.io.IoUtils; 189import libcore.util.EmptyArray; 190 191import com.android.internal.R; 192import com.android.internal.app.IMediaContainerService; 193import com.android.internal.app.ResolverActivity; 194import com.android.internal.content.NativeLibraryHelper; 195import com.android.internal.content.PackageHelper; 196import com.android.internal.os.IParcelFileDescriptorFactory; 197import com.android.internal.os.SomeArgs; 198import com.android.internal.util.ArrayUtils; 199import com.android.internal.util.FastPrintWriter; 200import com.android.internal.util.FastXmlSerializer; 201import com.android.internal.util.IndentingPrintWriter; 202import com.android.internal.util.Preconditions; 203import com.android.server.EventLogTags; 204import com.android.server.FgThread; 205import com.android.server.IntentResolver; 206import com.android.server.LocalServices; 207import com.android.server.ServiceThread; 208import com.android.server.SystemConfig; 209import com.android.server.Watchdog; 210import com.android.server.pm.Settings.DatabaseVersion; 211import com.android.server.pm.PermissionsState.PermissionState; 212import com.android.server.storage.DeviceStorageMonitorInternal; 213 214import org.xmlpull.v1.XmlPullParser; 215import org.xmlpull.v1.XmlSerializer; 216 217import java.io.BufferedInputStream; 218import java.io.BufferedOutputStream; 219import java.io.BufferedReader; 220import java.io.ByteArrayInputStream; 221import java.io.ByteArrayOutputStream; 222import java.io.File; 223import java.io.FileDescriptor; 224import java.io.FileNotFoundException; 225import java.io.FileOutputStream; 226import java.io.FileReader; 227import java.io.FilenameFilter; 228import java.io.IOException; 229import java.io.InputStream; 230import java.io.PrintWriter; 231import java.nio.charset.StandardCharsets; 232import java.security.NoSuchAlgorithmException; 233import java.security.PublicKey; 234import java.security.cert.CertificateEncodingException; 235import java.security.cert.CertificateException; 236import java.text.SimpleDateFormat; 237import java.util.ArrayList; 238import java.util.Arrays; 239import java.util.Collection; 240import java.util.Collections; 241import java.util.Comparator; 242import java.util.Date; 243import java.util.Iterator; 244import java.util.List; 245import java.util.Map; 246import java.util.Objects; 247import java.util.Set; 248import java.util.concurrent.CountDownLatch; 249import java.util.concurrent.TimeUnit; 250import java.util.concurrent.atomic.AtomicBoolean; 251import java.util.concurrent.atomic.AtomicInteger; 252import java.util.concurrent.atomic.AtomicLong; 253 254/** 255 * Keep track of all those .apks everywhere. 256 * 257 * This is very central to the platform's security; please run the unit 258 * tests whenever making modifications here: 259 * 260mmm frameworks/base/tests/AndroidTests 261adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 262adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 263 * 264 * {@hide} 265 */ 266public class PackageManagerService extends IPackageManager.Stub { 267 static final String TAG = "PackageManager"; 268 static final boolean DEBUG_SETTINGS = false; 269 static final boolean DEBUG_PREFERRED = false; 270 static final boolean DEBUG_UPGRADE = false; 271 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 272 private static final boolean DEBUG_BACKUP = true; 273 private static final boolean DEBUG_INSTALL = false; 274 private static final boolean DEBUG_REMOVE = false; 275 private static final boolean DEBUG_BROADCASTS = false; 276 private static final boolean DEBUG_SHOW_INFO = false; 277 private static final boolean DEBUG_PACKAGE_INFO = false; 278 private static final boolean DEBUG_INTENT_MATCHING = false; 279 private static final boolean DEBUG_PACKAGE_SCANNING = false; 280 private static final boolean DEBUG_VERIFY = false; 281 private static final boolean DEBUG_DEXOPT = false; 282 private static final boolean DEBUG_ABI_SELECTION = false; 283 284 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 285 286 private static final int RADIO_UID = Process.PHONE_UID; 287 private static final int LOG_UID = Process.LOG_UID; 288 private static final int NFC_UID = Process.NFC_UID; 289 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 290 private static final int SHELL_UID = Process.SHELL_UID; 291 292 // Cap the size of permission trees that 3rd party apps can define 293 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 294 295 // Suffix used during package installation when copying/moving 296 // package apks to install directory. 297 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 298 299 static final int SCAN_NO_DEX = 1<<1; 300 static final int SCAN_FORCE_DEX = 1<<2; 301 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 302 static final int SCAN_NEW_INSTALL = 1<<4; 303 static final int SCAN_NO_PATHS = 1<<5; 304 static final int SCAN_UPDATE_TIME = 1<<6; 305 static final int SCAN_DEFER_DEX = 1<<7; 306 static final int SCAN_BOOTING = 1<<8; 307 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 308 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 309 static final int SCAN_REQUIRE_KNOWN = 1<<12; 310 static final int SCAN_MOVE = 1<<13; 311 312 static final int REMOVE_CHATTY = 1<<16; 313 314 private static final int[] EMPTY_INT_ARRAY = new int[0]; 315 316 /** 317 * Timeout (in milliseconds) after which the watchdog should declare that 318 * our handler thread is wedged. The usual default for such things is one 319 * minute but we sometimes do very lengthy I/O operations on this thread, 320 * such as installing multi-gigabyte applications, so ours needs to be longer. 321 */ 322 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 323 324 /** 325 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 326 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 327 * settings entry if available, otherwise we use the hardcoded default. If it's been 328 * more than this long since the last fstrim, we force one during the boot sequence. 329 * 330 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 331 * one gets run at the next available charging+idle time. This final mandatory 332 * no-fstrim check kicks in only of the other scheduling criteria is never met. 333 */ 334 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 335 336 /** 337 * Whether verification is enabled by default. 338 */ 339 private static final boolean DEFAULT_VERIFY_ENABLE = true; 340 341 /** 342 * The default maximum time to wait for the verification agent to return in 343 * milliseconds. 344 */ 345 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 346 347 /** 348 * The default response for package verification timeout. 349 * 350 * This can be either PackageManager.VERIFICATION_ALLOW or 351 * PackageManager.VERIFICATION_REJECT. 352 */ 353 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 354 355 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 356 357 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 358 DEFAULT_CONTAINER_PACKAGE, 359 "com.android.defcontainer.DefaultContainerService"); 360 361 private static final String KILL_APP_REASON_GIDS_CHANGED = 362 "permission grant or revoke changed gids"; 363 364 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 365 "permissions revoked"; 366 367 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 368 369 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 370 371 /** Permission grant: not grant the permission. */ 372 private static final int GRANT_DENIED = 1; 373 374 /** Permission grant: grant the permission as an install permission. */ 375 private static final int GRANT_INSTALL = 2; 376 377 /** Permission grant: grant the permission as an install permission for a legacy app. */ 378 private static final int GRANT_INSTALL_LEGACY = 3; 379 380 /** Permission grant: grant the permission as a runtime one. */ 381 private static final int GRANT_RUNTIME = 4; 382 383 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 384 private static final int GRANT_UPGRADE = 5; 385 386 final ServiceThread mHandlerThread; 387 388 final PackageHandler mHandler; 389 390 /** 391 * Messages for {@link #mHandler} that need to wait for system ready before 392 * being dispatched. 393 */ 394 private ArrayList<Message> mPostSystemReadyMessages; 395 396 final int mSdkVersion = Build.VERSION.SDK_INT; 397 398 final Context mContext; 399 final boolean mFactoryTest; 400 final boolean mOnlyCore; 401 final boolean mLazyDexOpt; 402 final long mDexOptLRUThresholdInMills; 403 final DisplayMetrics mMetrics; 404 final int mDefParseFlags; 405 final String[] mSeparateProcesses; 406 final boolean mIsUpgrade; 407 408 // This is where all application persistent data goes. 409 final File mAppDataDir; 410 411 // This is where all application persistent data goes for secondary users. 412 final File mUserAppDataDir; 413 414 /** The location for ASEC container files on internal storage. */ 415 final String mAsecInternalPath; 416 417 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 418 // LOCK HELD. Can be called with mInstallLock held. 419 final Installer mInstaller; 420 421 /** Directory where installed third-party apps stored */ 422 final File mAppInstallDir; 423 424 /** 425 * Directory to which applications installed internally have their 426 * 32 bit native libraries copied. 427 */ 428 private File mAppLib32InstallDir; 429 430 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 431 // apps. 432 final File mDrmAppPrivateInstallDir; 433 434 // ---------------------------------------------------------------- 435 436 // Lock for state used when installing and doing other long running 437 // operations. Methods that must be called with this lock held have 438 // the suffix "LI". 439 final Object mInstallLock = new Object(); 440 441 // ---------------------------------------------------------------- 442 443 // Keys are String (package name), values are Package. This also serves 444 // as the lock for the global state. Methods that must be called with 445 // this lock held have the prefix "LP". 446 final ArrayMap<String, PackageParser.Package> mPackages = 447 new ArrayMap<String, PackageParser.Package>(); 448 449 // Tracks available target package names -> overlay package paths. 450 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 451 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 452 453 final Settings mSettings; 454 boolean mRestoredSettings; 455 456 // System configuration read by SystemConfig. 457 final int[] mGlobalGids; 458 final SparseArray<ArraySet<String>> mSystemPermissions; 459 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 460 461 // If mac_permissions.xml was found for seinfo labeling. 462 boolean mFoundPolicyFile; 463 464 // If a recursive restorecon of /data/data/<pkg> is needed. 465 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 466 467 public static final class SharedLibraryEntry { 468 public final String path; 469 public final String apk; 470 471 SharedLibraryEntry(String _path, String _apk) { 472 path = _path; 473 apk = _apk; 474 } 475 } 476 477 // Currently known shared libraries. 478 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 479 new ArrayMap<String, SharedLibraryEntry>(); 480 481 // All available activities, for your resolving pleasure. 482 final ActivityIntentResolver mActivities = 483 new ActivityIntentResolver(); 484 485 // All available receivers, for your resolving pleasure. 486 final ActivityIntentResolver mReceivers = 487 new ActivityIntentResolver(); 488 489 // All available services, for your resolving pleasure. 490 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 491 492 // All available providers, for your resolving pleasure. 493 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 494 495 // Mapping from provider base names (first directory in content URI codePath) 496 // to the provider information. 497 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 498 new ArrayMap<String, PackageParser.Provider>(); 499 500 // Mapping from instrumentation class names to info about them. 501 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 502 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 503 504 // Mapping from permission names to info about them. 505 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 506 new ArrayMap<String, PackageParser.PermissionGroup>(); 507 508 // Packages whose data we have transfered into another package, thus 509 // should no longer exist. 510 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 511 512 // Broadcast actions that are only available to the system. 513 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 514 515 /** List of packages waiting for verification. */ 516 final SparseArray<PackageVerificationState> mPendingVerification 517 = new SparseArray<PackageVerificationState>(); 518 519 /** Set of packages associated with each app op permission. */ 520 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 521 522 final PackageInstallerService mInstallerService; 523 524 private final PackageDexOptimizer mPackageDexOptimizer; 525 526 private AtomicInteger mNextMoveId = new AtomicInteger(); 527 private final MoveCallbacks mMoveCallbacks; 528 529 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 530 531 // Cache of users who need badging. 532 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 533 534 /** Token for keys in mPendingVerification. */ 535 private int mPendingVerificationToken = 0; 536 537 volatile boolean mSystemReady; 538 volatile boolean mSafeMode; 539 volatile boolean mHasSystemUidErrors; 540 541 ApplicationInfo mAndroidApplication; 542 final ActivityInfo mResolveActivity = new ActivityInfo(); 543 final ResolveInfo mResolveInfo = new ResolveInfo(); 544 ComponentName mResolveComponentName; 545 PackageParser.Package mPlatformPackage; 546 ComponentName mCustomResolverComponentName; 547 548 boolean mResolverReplaced = false; 549 550 private final ComponentName mIntentFilterVerifierComponent; 551 private int mIntentFilterVerificationToken = 0; 552 553 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 554 = new SparseArray<IntentFilterVerificationState>(); 555 556 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 557 new DefaultPermissionGrantPolicy(this); 558 559 private interface IntentFilterVerifier<T extends IntentFilter> { 560 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 561 T filter, String packageName); 562 void startVerifications(int userId); 563 void receiveVerificationResponse(int verificationId); 564 } 565 566 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 567 private Context mContext; 568 private ComponentName mIntentFilterVerifierComponent; 569 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 570 571 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 572 mContext = context; 573 mIntentFilterVerifierComponent = verifierComponent; 574 } 575 576 private String getDefaultScheme() { 577 return IntentFilter.SCHEME_HTTPS; 578 } 579 580 @Override 581 public void startVerifications(int userId) { 582 // Launch verifications requests 583 int count = mCurrentIntentFilterVerifications.size(); 584 for (int n=0; n<count; n++) { 585 int verificationId = mCurrentIntentFilterVerifications.get(n); 586 final IntentFilterVerificationState ivs = 587 mIntentFilterVerificationStates.get(verificationId); 588 589 String packageName = ivs.getPackageName(); 590 591 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 592 final int filterCount = filters.size(); 593 ArraySet<String> domainsSet = new ArraySet<>(); 594 for (int m=0; m<filterCount; m++) { 595 PackageParser.ActivityIntentInfo filter = filters.get(m); 596 domainsSet.addAll(filter.getHostsList()); 597 } 598 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 599 synchronized (mPackages) { 600 if (mSettings.createIntentFilterVerificationIfNeededLPw( 601 packageName, domainsList) != null) { 602 scheduleWriteSettingsLocked(); 603 } 604 } 605 sendVerificationRequest(userId, verificationId, ivs); 606 } 607 mCurrentIntentFilterVerifications.clear(); 608 } 609 610 private void sendVerificationRequest(int userId, int verificationId, 611 IntentFilterVerificationState ivs) { 612 613 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 614 verificationIntent.putExtra( 615 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 616 verificationId); 617 verificationIntent.putExtra( 618 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 619 getDefaultScheme()); 620 verificationIntent.putExtra( 621 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 622 ivs.getHostsString()); 623 verificationIntent.putExtra( 624 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 625 ivs.getPackageName()); 626 verificationIntent.setComponent(mIntentFilterVerifierComponent); 627 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 628 629 UserHandle user = new UserHandle(userId); 630 mContext.sendBroadcastAsUser(verificationIntent, user); 631 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 632 "Sending IntenFilter verification broadcast"); 633 } 634 635 public void receiveVerificationResponse(int verificationId) { 636 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 637 638 final boolean verified = ivs.isVerified(); 639 640 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 641 final int count = filters.size(); 642 for (int n=0; n<count; n++) { 643 PackageParser.ActivityIntentInfo filter = filters.get(n); 644 filter.setVerified(verified); 645 646 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 647 + " verified with result:" + verified + " and hosts:" 648 + ivs.getHostsString()); 649 } 650 651 mIntentFilterVerificationStates.remove(verificationId); 652 653 final String packageName = ivs.getPackageName(); 654 IntentFilterVerificationInfo ivi = null; 655 656 synchronized (mPackages) { 657 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 658 } 659 if (ivi == null) { 660 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 661 + verificationId + " packageName:" + packageName); 662 return; 663 } 664 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 665 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 666 667 synchronized (mPackages) { 668 if (verified) { 669 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 670 } else { 671 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 672 } 673 scheduleWriteSettingsLocked(); 674 675 final int userId = ivs.getUserId(); 676 if (userId != UserHandle.USER_ALL) { 677 final int userStatus = 678 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 679 680 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 681 boolean needUpdate = false; 682 683 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 684 // already been set by the User thru the Disambiguation dialog 685 switch (userStatus) { 686 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 687 if (verified) { 688 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 689 } else { 690 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 691 } 692 needUpdate = true; 693 break; 694 695 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 696 if (verified) { 697 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 698 needUpdate = true; 699 } 700 break; 701 702 default: 703 // Nothing to do 704 } 705 706 if (needUpdate) { 707 mSettings.updateIntentFilterVerificationStatusLPw( 708 packageName, updatedStatus, userId); 709 scheduleWritePackageRestrictionsLocked(userId); 710 } 711 } 712 } 713 } 714 715 @Override 716 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 717 ActivityIntentInfo filter, String packageName) { 718 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 719 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 720 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 721 "IntentFilter does not contain HTTP nor HTTPS data scheme"); 722 return false; 723 } 724 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 725 if (ivs == null) { 726 ivs = createDomainVerificationState(verifierId, userId, verificationId, 727 packageName); 728 } 729 if (!hasValidDomains(filter)) { 730 return false; 731 } 732 ivs.addFilter(filter); 733 return true; 734 } 735 736 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 737 int userId, int verificationId, String packageName) { 738 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 739 verifierId, userId, packageName); 740 ivs.setPendingState(); 741 synchronized (mPackages) { 742 mIntentFilterVerificationStates.append(verificationId, ivs); 743 mCurrentIntentFilterVerifications.add(verificationId); 744 } 745 return ivs; 746 } 747 } 748 749 private static boolean hasValidDomains(ActivityIntentInfo filter) { 750 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 751 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 752 if (!hasHTTPorHTTPS) { 753 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 754 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 755 return false; 756 } 757 return true; 758 } 759 760 private IntentFilterVerifier mIntentFilterVerifier; 761 762 // Set of pending broadcasts for aggregating enable/disable of components. 763 static class PendingPackageBroadcasts { 764 // for each user id, a map of <package name -> components within that package> 765 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 766 767 public PendingPackageBroadcasts() { 768 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 769 } 770 771 public ArrayList<String> get(int userId, String packageName) { 772 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 773 return packages.get(packageName); 774 } 775 776 public void put(int userId, String packageName, ArrayList<String> components) { 777 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 778 packages.put(packageName, components); 779 } 780 781 public void remove(int userId, String packageName) { 782 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 783 if (packages != null) { 784 packages.remove(packageName); 785 } 786 } 787 788 public void remove(int userId) { 789 mUidMap.remove(userId); 790 } 791 792 public int userIdCount() { 793 return mUidMap.size(); 794 } 795 796 public int userIdAt(int n) { 797 return mUidMap.keyAt(n); 798 } 799 800 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 801 return mUidMap.get(userId); 802 } 803 804 public int size() { 805 // total number of pending broadcast entries across all userIds 806 int num = 0; 807 for (int i = 0; i< mUidMap.size(); i++) { 808 num += mUidMap.valueAt(i).size(); 809 } 810 return num; 811 } 812 813 public void clear() { 814 mUidMap.clear(); 815 } 816 817 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 818 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 819 if (map == null) { 820 map = new ArrayMap<String, ArrayList<String>>(); 821 mUidMap.put(userId, map); 822 } 823 return map; 824 } 825 } 826 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 827 828 // Service Connection to remote media container service to copy 829 // package uri's from external media onto secure containers 830 // or internal storage. 831 private IMediaContainerService mContainerService = null; 832 833 static final int SEND_PENDING_BROADCAST = 1; 834 static final int MCS_BOUND = 3; 835 static final int END_COPY = 4; 836 static final int INIT_COPY = 5; 837 static final int MCS_UNBIND = 6; 838 static final int START_CLEANING_PACKAGE = 7; 839 static final int FIND_INSTALL_LOC = 8; 840 static final int POST_INSTALL = 9; 841 static final int MCS_RECONNECT = 10; 842 static final int MCS_GIVE_UP = 11; 843 static final int UPDATED_MEDIA_STATUS = 12; 844 static final int WRITE_SETTINGS = 13; 845 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 846 static final int PACKAGE_VERIFIED = 15; 847 static final int CHECK_PENDING_VERIFICATION = 16; 848 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 849 static final int INTENT_FILTER_VERIFIED = 18; 850 851 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 852 853 // Delay time in millisecs 854 static final int BROADCAST_DELAY = 10 * 1000; 855 856 static UserManagerService sUserManager; 857 858 // Stores a list of users whose package restrictions file needs to be updated 859 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 860 861 final private DefaultContainerConnection mDefContainerConn = 862 new DefaultContainerConnection(); 863 class DefaultContainerConnection implements ServiceConnection { 864 public void onServiceConnected(ComponentName name, IBinder service) { 865 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 866 IMediaContainerService imcs = 867 IMediaContainerService.Stub.asInterface(service); 868 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 869 } 870 871 public void onServiceDisconnected(ComponentName name) { 872 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 873 } 874 } 875 876 // Recordkeeping of restore-after-install operations that are currently in flight 877 // between the Package Manager and the Backup Manager 878 class PostInstallData { 879 public InstallArgs args; 880 public PackageInstalledInfo res; 881 882 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 883 args = _a; 884 res = _r; 885 } 886 } 887 888 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 889 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 890 891 // backup/restore of preferred activity state 892 private static final String TAG_PREFERRED_BACKUP = "pa"; 893 894 private final String mRequiredVerifierPackage; 895 896 private final PackageUsage mPackageUsage = new PackageUsage(); 897 898 private class PackageUsage { 899 private static final int WRITE_INTERVAL 900 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 901 902 private final Object mFileLock = new Object(); 903 private final AtomicLong mLastWritten = new AtomicLong(0); 904 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 905 906 private boolean mIsHistoricalPackageUsageAvailable = true; 907 908 boolean isHistoricalPackageUsageAvailable() { 909 return mIsHistoricalPackageUsageAvailable; 910 } 911 912 void write(boolean force) { 913 if (force) { 914 writeInternal(); 915 return; 916 } 917 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 918 && !DEBUG_DEXOPT) { 919 return; 920 } 921 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 922 new Thread("PackageUsage_DiskWriter") { 923 @Override 924 public void run() { 925 try { 926 writeInternal(); 927 } finally { 928 mBackgroundWriteRunning.set(false); 929 } 930 } 931 }.start(); 932 } 933 } 934 935 private void writeInternal() { 936 synchronized (mPackages) { 937 synchronized (mFileLock) { 938 AtomicFile file = getFile(); 939 FileOutputStream f = null; 940 try { 941 f = file.startWrite(); 942 BufferedOutputStream out = new BufferedOutputStream(f); 943 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 944 StringBuilder sb = new StringBuilder(); 945 for (PackageParser.Package pkg : mPackages.values()) { 946 if (pkg.mLastPackageUsageTimeInMills == 0) { 947 continue; 948 } 949 sb.setLength(0); 950 sb.append(pkg.packageName); 951 sb.append(' '); 952 sb.append((long)pkg.mLastPackageUsageTimeInMills); 953 sb.append('\n'); 954 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 955 } 956 out.flush(); 957 file.finishWrite(f); 958 } catch (IOException e) { 959 if (f != null) { 960 file.failWrite(f); 961 } 962 Log.e(TAG, "Failed to write package usage times", e); 963 } 964 } 965 } 966 mLastWritten.set(SystemClock.elapsedRealtime()); 967 } 968 969 void readLP() { 970 synchronized (mFileLock) { 971 AtomicFile file = getFile(); 972 BufferedInputStream in = null; 973 try { 974 in = new BufferedInputStream(file.openRead()); 975 StringBuffer sb = new StringBuffer(); 976 while (true) { 977 String packageName = readToken(in, sb, ' '); 978 if (packageName == null) { 979 break; 980 } 981 String timeInMillisString = readToken(in, sb, '\n'); 982 if (timeInMillisString == null) { 983 throw new IOException("Failed to find last usage time for package " 984 + packageName); 985 } 986 PackageParser.Package pkg = mPackages.get(packageName); 987 if (pkg == null) { 988 continue; 989 } 990 long timeInMillis; 991 try { 992 timeInMillis = Long.parseLong(timeInMillisString.toString()); 993 } catch (NumberFormatException e) { 994 throw new IOException("Failed to parse " + timeInMillisString 995 + " as a long.", e); 996 } 997 pkg.mLastPackageUsageTimeInMills = timeInMillis; 998 } 999 } catch (FileNotFoundException expected) { 1000 mIsHistoricalPackageUsageAvailable = false; 1001 } catch (IOException e) { 1002 Log.w(TAG, "Failed to read package usage times", e); 1003 } finally { 1004 IoUtils.closeQuietly(in); 1005 } 1006 } 1007 mLastWritten.set(SystemClock.elapsedRealtime()); 1008 } 1009 1010 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1011 throws IOException { 1012 sb.setLength(0); 1013 while (true) { 1014 int ch = in.read(); 1015 if (ch == -1) { 1016 if (sb.length() == 0) { 1017 return null; 1018 } 1019 throw new IOException("Unexpected EOF"); 1020 } 1021 if (ch == endOfToken) { 1022 return sb.toString(); 1023 } 1024 sb.append((char)ch); 1025 } 1026 } 1027 1028 private AtomicFile getFile() { 1029 File dataDir = Environment.getDataDirectory(); 1030 File systemDir = new File(dataDir, "system"); 1031 File fname = new File(systemDir, "package-usage.list"); 1032 return new AtomicFile(fname); 1033 } 1034 } 1035 1036 class PackageHandler extends Handler { 1037 private boolean mBound = false; 1038 final ArrayList<HandlerParams> mPendingInstalls = 1039 new ArrayList<HandlerParams>(); 1040 1041 private boolean connectToService() { 1042 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1043 " DefaultContainerService"); 1044 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1045 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1046 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1047 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1048 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1049 mBound = true; 1050 return true; 1051 } 1052 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1053 return false; 1054 } 1055 1056 private void disconnectService() { 1057 mContainerService = null; 1058 mBound = false; 1059 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1060 mContext.unbindService(mDefContainerConn); 1061 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1062 } 1063 1064 PackageHandler(Looper looper) { 1065 super(looper); 1066 } 1067 1068 public void handleMessage(Message msg) { 1069 try { 1070 doHandleMessage(msg); 1071 } finally { 1072 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1073 } 1074 } 1075 1076 void doHandleMessage(Message msg) { 1077 switch (msg.what) { 1078 case INIT_COPY: { 1079 HandlerParams params = (HandlerParams) msg.obj; 1080 int idx = mPendingInstalls.size(); 1081 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1082 // If a bind was already initiated we dont really 1083 // need to do anything. The pending install 1084 // will be processed later on. 1085 if (!mBound) { 1086 // If this is the only one pending we might 1087 // have to bind to the service again. 1088 if (!connectToService()) { 1089 Slog.e(TAG, "Failed to bind to media container service"); 1090 params.serviceError(); 1091 return; 1092 } else { 1093 // Once we bind to the service, the first 1094 // pending request will be processed. 1095 mPendingInstalls.add(idx, params); 1096 } 1097 } else { 1098 mPendingInstalls.add(idx, params); 1099 // Already bound to the service. Just make 1100 // sure we trigger off processing the first request. 1101 if (idx == 0) { 1102 mHandler.sendEmptyMessage(MCS_BOUND); 1103 } 1104 } 1105 break; 1106 } 1107 case MCS_BOUND: { 1108 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1109 if (msg.obj != null) { 1110 mContainerService = (IMediaContainerService) msg.obj; 1111 } 1112 if (mContainerService == null) { 1113 if (!mBound) { 1114 // Something seriously wrong since we are not bound and we are not 1115 // waiting for connection. Bail out. 1116 Slog.e(TAG, "Cannot bind to media container service"); 1117 for (HandlerParams params : mPendingInstalls) { 1118 // Indicate service bind error 1119 params.serviceError(); 1120 } 1121 mPendingInstalls.clear(); 1122 } else { 1123 Slog.w(TAG, "Waiting to connect to media container service"); 1124 } 1125 } else if (mPendingInstalls.size() > 0) { 1126 HandlerParams params = mPendingInstalls.get(0); 1127 if (params != null) { 1128 if (params.startCopy()) { 1129 // We are done... look for more work or to 1130 // go idle. 1131 if (DEBUG_SD_INSTALL) Log.i(TAG, 1132 "Checking for more work or unbind..."); 1133 // Delete pending install 1134 if (mPendingInstalls.size() > 0) { 1135 mPendingInstalls.remove(0); 1136 } 1137 if (mPendingInstalls.size() == 0) { 1138 if (mBound) { 1139 if (DEBUG_SD_INSTALL) Log.i(TAG, 1140 "Posting delayed MCS_UNBIND"); 1141 removeMessages(MCS_UNBIND); 1142 Message ubmsg = obtainMessage(MCS_UNBIND); 1143 // Unbind after a little delay, to avoid 1144 // continual thrashing. 1145 sendMessageDelayed(ubmsg, 10000); 1146 } 1147 } else { 1148 // There are more pending requests in queue. 1149 // Just post MCS_BOUND message to trigger processing 1150 // of next pending install. 1151 if (DEBUG_SD_INSTALL) Log.i(TAG, 1152 "Posting MCS_BOUND for next work"); 1153 mHandler.sendEmptyMessage(MCS_BOUND); 1154 } 1155 } 1156 } 1157 } else { 1158 // Should never happen ideally. 1159 Slog.w(TAG, "Empty queue"); 1160 } 1161 break; 1162 } 1163 case MCS_RECONNECT: { 1164 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1165 if (mPendingInstalls.size() > 0) { 1166 if (mBound) { 1167 disconnectService(); 1168 } 1169 if (!connectToService()) { 1170 Slog.e(TAG, "Failed to bind to media container service"); 1171 for (HandlerParams params : mPendingInstalls) { 1172 // Indicate service bind error 1173 params.serviceError(); 1174 } 1175 mPendingInstalls.clear(); 1176 } 1177 } 1178 break; 1179 } 1180 case MCS_UNBIND: { 1181 // If there is no actual work left, then time to unbind. 1182 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1183 1184 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1185 if (mBound) { 1186 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1187 1188 disconnectService(); 1189 } 1190 } else if (mPendingInstalls.size() > 0) { 1191 // There are more pending requests in queue. 1192 // Just post MCS_BOUND message to trigger processing 1193 // of next pending install. 1194 mHandler.sendEmptyMessage(MCS_BOUND); 1195 } 1196 1197 break; 1198 } 1199 case MCS_GIVE_UP: { 1200 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1201 mPendingInstalls.remove(0); 1202 break; 1203 } 1204 case SEND_PENDING_BROADCAST: { 1205 String packages[]; 1206 ArrayList<String> components[]; 1207 int size = 0; 1208 int uids[]; 1209 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1210 synchronized (mPackages) { 1211 if (mPendingBroadcasts == null) { 1212 return; 1213 } 1214 size = mPendingBroadcasts.size(); 1215 if (size <= 0) { 1216 // Nothing to be done. Just return 1217 return; 1218 } 1219 packages = new String[size]; 1220 components = new ArrayList[size]; 1221 uids = new int[size]; 1222 int i = 0; // filling out the above arrays 1223 1224 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1225 int packageUserId = mPendingBroadcasts.userIdAt(n); 1226 Iterator<Map.Entry<String, ArrayList<String>>> it 1227 = mPendingBroadcasts.packagesForUserId(packageUserId) 1228 .entrySet().iterator(); 1229 while (it.hasNext() && i < size) { 1230 Map.Entry<String, ArrayList<String>> ent = it.next(); 1231 packages[i] = ent.getKey(); 1232 components[i] = ent.getValue(); 1233 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1234 uids[i] = (ps != null) 1235 ? UserHandle.getUid(packageUserId, ps.appId) 1236 : -1; 1237 i++; 1238 } 1239 } 1240 size = i; 1241 mPendingBroadcasts.clear(); 1242 } 1243 // Send broadcasts 1244 for (int i = 0; i < size; i++) { 1245 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1246 } 1247 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1248 break; 1249 } 1250 case START_CLEANING_PACKAGE: { 1251 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1252 final String packageName = (String)msg.obj; 1253 final int userId = msg.arg1; 1254 final boolean andCode = msg.arg2 != 0; 1255 synchronized (mPackages) { 1256 if (userId == UserHandle.USER_ALL) { 1257 int[] users = sUserManager.getUserIds(); 1258 for (int user : users) { 1259 mSettings.addPackageToCleanLPw( 1260 new PackageCleanItem(user, packageName, andCode)); 1261 } 1262 } else { 1263 mSettings.addPackageToCleanLPw( 1264 new PackageCleanItem(userId, packageName, andCode)); 1265 } 1266 } 1267 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1268 startCleaningPackages(); 1269 } break; 1270 case POST_INSTALL: { 1271 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1272 PostInstallData data = mRunningInstalls.get(msg.arg1); 1273 mRunningInstalls.delete(msg.arg1); 1274 boolean deleteOld = false; 1275 1276 if (data != null) { 1277 InstallArgs args = data.args; 1278 PackageInstalledInfo res = data.res; 1279 1280 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1281 res.removedInfo.sendBroadcast(false, true, false); 1282 Bundle extras = new Bundle(1); 1283 extras.putInt(Intent.EXTRA_UID, res.uid); 1284 1285 // Now that we successfully installed the package, grant runtime 1286 // permissions if requested before broadcasting the install. 1287 if ((args.installFlags 1288 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1289 grantRequestedRuntimePermissions(res.pkg, 1290 args.user.getIdentifier()); 1291 } 1292 1293 // Determine the set of users who are adding this 1294 // package for the first time vs. those who are seeing 1295 // an update. 1296 int[] firstUsers; 1297 int[] updateUsers = new int[0]; 1298 if (res.origUsers == null || res.origUsers.length == 0) { 1299 firstUsers = res.newUsers; 1300 } else { 1301 firstUsers = new int[0]; 1302 for (int i=0; i<res.newUsers.length; i++) { 1303 int user = res.newUsers[i]; 1304 boolean isNew = true; 1305 for (int j=0; j<res.origUsers.length; j++) { 1306 if (res.origUsers[j] == user) { 1307 isNew = false; 1308 break; 1309 } 1310 } 1311 if (isNew) { 1312 int[] newFirst = new int[firstUsers.length+1]; 1313 System.arraycopy(firstUsers, 0, newFirst, 0, 1314 firstUsers.length); 1315 newFirst[firstUsers.length] = user; 1316 firstUsers = newFirst; 1317 } else { 1318 int[] newUpdate = new int[updateUsers.length+1]; 1319 System.arraycopy(updateUsers, 0, newUpdate, 0, 1320 updateUsers.length); 1321 newUpdate[updateUsers.length] = user; 1322 updateUsers = newUpdate; 1323 } 1324 } 1325 } 1326 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1327 res.pkg.applicationInfo.packageName, 1328 extras, null, null, firstUsers); 1329 final boolean update = res.removedInfo.removedPackage != null; 1330 if (update) { 1331 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1332 } 1333 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1334 res.pkg.applicationInfo.packageName, 1335 extras, null, null, updateUsers); 1336 if (update) { 1337 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1338 res.pkg.applicationInfo.packageName, 1339 extras, null, null, updateUsers); 1340 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1341 null, null, 1342 res.pkg.applicationInfo.packageName, null, updateUsers); 1343 1344 // treat asec-hosted packages like removable media on upgrade 1345 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1346 if (DEBUG_INSTALL) { 1347 Slog.i(TAG, "upgrading pkg " + res.pkg 1348 + " is ASEC-hosted -> AVAILABLE"); 1349 } 1350 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1351 ArrayList<String> pkgList = new ArrayList<String>(1); 1352 pkgList.add(res.pkg.applicationInfo.packageName); 1353 sendResourcesChangedBroadcast(true, true, 1354 pkgList,uidArray, null); 1355 } 1356 } 1357 if (res.removedInfo.args != null) { 1358 // Remove the replaced package's older resources safely now 1359 deleteOld = true; 1360 } 1361 1362 // Log current value of "unknown sources" setting 1363 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1364 getUnknownSourcesSettings()); 1365 } 1366 // Force a gc to clear up things 1367 Runtime.getRuntime().gc(); 1368 // We delete after a gc for applications on sdcard. 1369 if (deleteOld) { 1370 synchronized (mInstallLock) { 1371 res.removedInfo.args.doPostDeleteLI(true); 1372 } 1373 } 1374 if (args.observer != null) { 1375 try { 1376 Bundle extras = extrasForInstallResult(res); 1377 args.observer.onPackageInstalled(res.name, res.returnCode, 1378 res.returnMsg, extras); 1379 } catch (RemoteException e) { 1380 Slog.i(TAG, "Observer no longer exists."); 1381 } 1382 } 1383 } else { 1384 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1385 } 1386 } break; 1387 case UPDATED_MEDIA_STATUS: { 1388 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1389 boolean reportStatus = msg.arg1 == 1; 1390 boolean doGc = msg.arg2 == 1; 1391 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1392 if (doGc) { 1393 // Force a gc to clear up stale containers. 1394 Runtime.getRuntime().gc(); 1395 } 1396 if (msg.obj != null) { 1397 @SuppressWarnings("unchecked") 1398 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1399 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1400 // Unload containers 1401 unloadAllContainers(args); 1402 } 1403 if (reportStatus) { 1404 try { 1405 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1406 PackageHelper.getMountService().finishMediaUpdate(); 1407 } catch (RemoteException e) { 1408 Log.e(TAG, "MountService not running?"); 1409 } 1410 } 1411 } break; 1412 case WRITE_SETTINGS: { 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 synchronized (mPackages) { 1415 removeMessages(WRITE_SETTINGS); 1416 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1417 mSettings.writeLPr(); 1418 mDirtyUsers.clear(); 1419 } 1420 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1421 } break; 1422 case WRITE_PACKAGE_RESTRICTIONS: { 1423 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1424 synchronized (mPackages) { 1425 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1426 for (int userId : mDirtyUsers) { 1427 mSettings.writePackageRestrictionsLPr(userId); 1428 } 1429 mDirtyUsers.clear(); 1430 } 1431 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1432 } break; 1433 case CHECK_PENDING_VERIFICATION: { 1434 final int verificationId = msg.arg1; 1435 final PackageVerificationState state = mPendingVerification.get(verificationId); 1436 1437 if ((state != null) && !state.timeoutExtended()) { 1438 final InstallArgs args = state.getInstallArgs(); 1439 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1440 1441 Slog.i(TAG, "Verification timed out for " + originUri); 1442 mPendingVerification.remove(verificationId); 1443 1444 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1445 1446 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1447 Slog.i(TAG, "Continuing with installation of " + originUri); 1448 state.setVerifierResponse(Binder.getCallingUid(), 1449 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1450 broadcastPackageVerified(verificationId, originUri, 1451 PackageManager.VERIFICATION_ALLOW, 1452 state.getInstallArgs().getUser()); 1453 try { 1454 ret = args.copyApk(mContainerService, true); 1455 } catch (RemoteException e) { 1456 Slog.e(TAG, "Could not contact the ContainerService"); 1457 } 1458 } else { 1459 broadcastPackageVerified(verificationId, originUri, 1460 PackageManager.VERIFICATION_REJECT, 1461 state.getInstallArgs().getUser()); 1462 } 1463 1464 processPendingInstall(args, ret); 1465 mHandler.sendEmptyMessage(MCS_UNBIND); 1466 } 1467 break; 1468 } 1469 case PACKAGE_VERIFIED: { 1470 final int verificationId = msg.arg1; 1471 1472 final PackageVerificationState state = mPendingVerification.get(verificationId); 1473 if (state == null) { 1474 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1475 break; 1476 } 1477 1478 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1479 1480 state.setVerifierResponse(response.callerUid, response.code); 1481 1482 if (state.isVerificationComplete()) { 1483 mPendingVerification.remove(verificationId); 1484 1485 final InstallArgs args = state.getInstallArgs(); 1486 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1487 1488 int ret; 1489 if (state.isInstallAllowed()) { 1490 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1491 broadcastPackageVerified(verificationId, originUri, 1492 response.code, state.getInstallArgs().getUser()); 1493 try { 1494 ret = args.copyApk(mContainerService, true); 1495 } catch (RemoteException e) { 1496 Slog.e(TAG, "Could not contact the ContainerService"); 1497 } 1498 } else { 1499 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1500 } 1501 1502 processPendingInstall(args, ret); 1503 1504 mHandler.sendEmptyMessage(MCS_UNBIND); 1505 } 1506 1507 break; 1508 } 1509 case START_INTENT_FILTER_VERIFICATIONS: { 1510 int userId = msg.arg1; 1511 int verifierUid = msg.arg2; 1512 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1513 1514 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1515 break; 1516 } 1517 case INTENT_FILTER_VERIFIED: { 1518 final int verificationId = msg.arg1; 1519 1520 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1521 verificationId); 1522 if (state == null) { 1523 Slog.w(TAG, "Invalid IntentFilter verification token " 1524 + verificationId + " received"); 1525 break; 1526 } 1527 1528 final int userId = state.getUserId(); 1529 1530 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1531 "Processing IntentFilter verification with token:" 1532 + verificationId + " and userId:" + userId); 1533 1534 final IntentFilterVerificationResponse response = 1535 (IntentFilterVerificationResponse) msg.obj; 1536 1537 state.setVerifierResponse(response.callerUid, response.code); 1538 1539 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1540 "IntentFilter verification with token:" + verificationId 1541 + " and userId:" + userId 1542 + " is settings verifier response with response code:" 1543 + response.code); 1544 1545 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1546 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1547 + response.getFailedDomainsString()); 1548 } 1549 1550 if (state.isVerificationComplete()) { 1551 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1552 } else { 1553 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1554 "IntentFilter verification with token:" + verificationId 1555 + " was not said to be complete"); 1556 } 1557 1558 break; 1559 } 1560 } 1561 } 1562 } 1563 1564 private StorageEventListener mStorageListener = new StorageEventListener() { 1565 @Override 1566 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1567 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1568 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1569 // TODO: ensure that private directories exist for all active users 1570 // TODO: remove user data whose serial number doesn't match 1571 loadPrivatePackages(vol); 1572 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1573 unloadPrivatePackages(vol); 1574 } 1575 } 1576 1577 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1578 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1579 updateExternalMediaStatus(true, false); 1580 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1581 updateExternalMediaStatus(false, false); 1582 } 1583 } 1584 } 1585 1586 @Override 1587 public void onVolumeForgotten(String fsUuid) { 1588 // TODO: remove all packages hosted on this uuid 1589 } 1590 }; 1591 1592 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1593 if (userId >= UserHandle.USER_OWNER) { 1594 grantRequestedRuntimePermissionsForUser(pkg, userId); 1595 } else if (userId == UserHandle.USER_ALL) { 1596 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1597 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1598 } 1599 } 1600 1601 // We could have touched GID membership, so flush out packages.list 1602 synchronized (mPackages) { 1603 mSettings.writePackageListLPr(); 1604 } 1605 } 1606 1607 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1608 SettingBase sb = (SettingBase) pkg.mExtras; 1609 if (sb == null) { 1610 return; 1611 } 1612 1613 PermissionsState permissionsState = sb.getPermissionsState(); 1614 1615 for (String permission : pkg.requestedPermissions) { 1616 BasePermission bp = mSettings.mPermissions.get(permission); 1617 if (bp != null && bp.isRuntime()) { 1618 permissionsState.grantRuntimePermission(bp, userId); 1619 } 1620 } 1621 } 1622 1623 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1624 Bundle extras = null; 1625 switch (res.returnCode) { 1626 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1627 extras = new Bundle(); 1628 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1629 res.origPermission); 1630 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1631 res.origPackage); 1632 break; 1633 } 1634 case PackageManager.INSTALL_SUCCEEDED: { 1635 extras = new Bundle(); 1636 extras.putBoolean(Intent.EXTRA_REPLACING, 1637 res.removedInfo != null && res.removedInfo.removedPackage != null); 1638 break; 1639 } 1640 } 1641 return extras; 1642 } 1643 1644 void scheduleWriteSettingsLocked() { 1645 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1646 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1647 } 1648 } 1649 1650 void scheduleWritePackageRestrictionsLocked(int userId) { 1651 if (!sUserManager.exists(userId)) return; 1652 mDirtyUsers.add(userId); 1653 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1654 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1655 } 1656 } 1657 1658 public static PackageManagerService main(Context context, Installer installer, 1659 boolean factoryTest, boolean onlyCore) { 1660 PackageManagerService m = new PackageManagerService(context, installer, 1661 factoryTest, onlyCore); 1662 ServiceManager.addService("package", m); 1663 return m; 1664 } 1665 1666 static String[] splitString(String str, char sep) { 1667 int count = 1; 1668 int i = 0; 1669 while ((i=str.indexOf(sep, i)) >= 0) { 1670 count++; 1671 i++; 1672 } 1673 1674 String[] res = new String[count]; 1675 i=0; 1676 count = 0; 1677 int lastI=0; 1678 while ((i=str.indexOf(sep, i)) >= 0) { 1679 res[count] = str.substring(lastI, i); 1680 count++; 1681 i++; 1682 lastI = i; 1683 } 1684 res[count] = str.substring(lastI, str.length()); 1685 return res; 1686 } 1687 1688 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1689 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1690 Context.DISPLAY_SERVICE); 1691 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1692 } 1693 1694 public PackageManagerService(Context context, Installer installer, 1695 boolean factoryTest, boolean onlyCore) { 1696 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1697 SystemClock.uptimeMillis()); 1698 1699 if (mSdkVersion <= 0) { 1700 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1701 } 1702 1703 mContext = context; 1704 mFactoryTest = factoryTest; 1705 mOnlyCore = onlyCore; 1706 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1707 mMetrics = new DisplayMetrics(); 1708 mSettings = new Settings(mPackages); 1709 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1710 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1711 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1712 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1713 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1714 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1715 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1716 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1717 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1718 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1719 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1720 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1721 1722 // TODO: add a property to control this? 1723 long dexOptLRUThresholdInMinutes; 1724 if (mLazyDexOpt) { 1725 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1726 } else { 1727 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1728 } 1729 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1730 1731 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1732 if (separateProcesses != null && separateProcesses.length() > 0) { 1733 if ("*".equals(separateProcesses)) { 1734 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1735 mSeparateProcesses = null; 1736 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1737 } else { 1738 mDefParseFlags = 0; 1739 mSeparateProcesses = separateProcesses.split(","); 1740 Slog.w(TAG, "Running with debug.separate_processes: " 1741 + separateProcesses); 1742 } 1743 } else { 1744 mDefParseFlags = 0; 1745 mSeparateProcesses = null; 1746 } 1747 1748 mInstaller = installer; 1749 mPackageDexOptimizer = new PackageDexOptimizer(this); 1750 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1751 1752 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1753 FgThread.get().getLooper()); 1754 1755 getDefaultDisplayMetrics(context, mMetrics); 1756 1757 SystemConfig systemConfig = SystemConfig.getInstance(); 1758 mGlobalGids = systemConfig.getGlobalGids(); 1759 mSystemPermissions = systemConfig.getSystemPermissions(); 1760 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1761 1762 synchronized (mInstallLock) { 1763 // writer 1764 synchronized (mPackages) { 1765 mHandlerThread = new ServiceThread(TAG, 1766 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1767 mHandlerThread.start(); 1768 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1769 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1770 1771 File dataDir = Environment.getDataDirectory(); 1772 mAppDataDir = new File(dataDir, "data"); 1773 mAppInstallDir = new File(dataDir, "app"); 1774 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1775 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1776 mUserAppDataDir = new File(dataDir, "user"); 1777 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1778 1779 sUserManager = new UserManagerService(context, this, 1780 mInstallLock, mPackages); 1781 1782 // Propagate permission configuration in to package manager. 1783 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1784 = systemConfig.getPermissions(); 1785 for (int i=0; i<permConfig.size(); i++) { 1786 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1787 BasePermission bp = mSettings.mPermissions.get(perm.name); 1788 if (bp == null) { 1789 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1790 mSettings.mPermissions.put(perm.name, bp); 1791 } 1792 if (perm.gids != null) { 1793 bp.setGids(perm.gids, perm.perUser); 1794 } 1795 } 1796 1797 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1798 for (int i=0; i<libConfig.size(); i++) { 1799 mSharedLibraries.put(libConfig.keyAt(i), 1800 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1801 } 1802 1803 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1804 1805 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1806 mSdkVersion, mOnlyCore); 1807 1808 String customResolverActivity = Resources.getSystem().getString( 1809 R.string.config_customResolverActivity); 1810 if (TextUtils.isEmpty(customResolverActivity)) { 1811 customResolverActivity = null; 1812 } else { 1813 mCustomResolverComponentName = ComponentName.unflattenFromString( 1814 customResolverActivity); 1815 } 1816 1817 long startTime = SystemClock.uptimeMillis(); 1818 1819 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1820 startTime); 1821 1822 // Set flag to monitor and not change apk file paths when 1823 // scanning install directories. 1824 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1825 1826 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1827 1828 /** 1829 * Add everything in the in the boot class path to the 1830 * list of process files because dexopt will have been run 1831 * if necessary during zygote startup. 1832 */ 1833 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1834 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1835 1836 if (bootClassPath != null) { 1837 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1838 for (String element : bootClassPathElements) { 1839 alreadyDexOpted.add(element); 1840 } 1841 } else { 1842 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1843 } 1844 1845 if (systemServerClassPath != null) { 1846 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1847 for (String element : systemServerClassPathElements) { 1848 alreadyDexOpted.add(element); 1849 } 1850 } else { 1851 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1852 } 1853 1854 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1855 final String[] dexCodeInstructionSets = 1856 getDexCodeInstructionSets( 1857 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1858 1859 /** 1860 * Ensure all external libraries have had dexopt run on them. 1861 */ 1862 if (mSharedLibraries.size() > 0) { 1863 // NOTE: For now, we're compiling these system "shared libraries" 1864 // (and framework jars) into all available architectures. It's possible 1865 // to compile them only when we come across an app that uses them (there's 1866 // already logic for that in scanPackageLI) but that adds some complexity. 1867 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1868 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1869 final String lib = libEntry.path; 1870 if (lib == null) { 1871 continue; 1872 } 1873 1874 try { 1875 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1876 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1877 alreadyDexOpted.add(lib); 1878 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1879 } 1880 } catch (FileNotFoundException e) { 1881 Slog.w(TAG, "Library not found: " + lib); 1882 } catch (IOException e) { 1883 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1884 + e.getMessage()); 1885 } 1886 } 1887 } 1888 } 1889 1890 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1891 1892 // Gross hack for now: we know this file doesn't contain any 1893 // code, so don't dexopt it to avoid the resulting log spew. 1894 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1895 1896 // Gross hack for now: we know this file is only part of 1897 // the boot class path for art, so don't dexopt it to 1898 // avoid the resulting log spew. 1899 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1900 1901 /** 1902 * There are a number of commands implemented in Java, which 1903 * we currently need to do the dexopt on so that they can be 1904 * run from a non-root shell. 1905 */ 1906 String[] frameworkFiles = frameworkDir.list(); 1907 if (frameworkFiles != null) { 1908 // TODO: We could compile these only for the most preferred ABI. We should 1909 // first double check that the dex files for these commands are not referenced 1910 // by other system apps. 1911 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1912 for (int i=0; i<frameworkFiles.length; i++) { 1913 File libPath = new File(frameworkDir, frameworkFiles[i]); 1914 String path = libPath.getPath(); 1915 // Skip the file if we already did it. 1916 if (alreadyDexOpted.contains(path)) { 1917 continue; 1918 } 1919 // Skip the file if it is not a type we want to dexopt. 1920 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1921 continue; 1922 } 1923 try { 1924 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1925 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1926 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1927 } 1928 } catch (FileNotFoundException e) { 1929 Slog.w(TAG, "Jar not found: " + path); 1930 } catch (IOException e) { 1931 Slog.w(TAG, "Exception reading jar: " + path, e); 1932 } 1933 } 1934 } 1935 } 1936 1937 // Collect vendor overlay packages. 1938 // (Do this before scanning any apps.) 1939 // For security and version matching reason, only consider 1940 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1941 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1942 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1943 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1944 1945 // Find base frameworks (resource packages without code). 1946 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1947 | PackageParser.PARSE_IS_SYSTEM_DIR 1948 | PackageParser.PARSE_IS_PRIVILEGED, 1949 scanFlags | SCAN_NO_DEX, 0); 1950 1951 // Collected privileged system packages. 1952 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1953 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1954 | PackageParser.PARSE_IS_SYSTEM_DIR 1955 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1956 1957 // Collect ordinary system packages. 1958 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1959 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1960 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1961 1962 // Collect all vendor packages. 1963 File vendorAppDir = new File("/vendor/app"); 1964 try { 1965 vendorAppDir = vendorAppDir.getCanonicalFile(); 1966 } catch (IOException e) { 1967 // failed to look up canonical path, continue with original one 1968 } 1969 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1970 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1971 1972 // Collect all OEM packages. 1973 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1974 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1975 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1976 1977 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1978 mInstaller.moveFiles(); 1979 1980 // Prune any system packages that no longer exist. 1981 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1982 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1983 if (!mOnlyCore) { 1984 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1985 while (psit.hasNext()) { 1986 PackageSetting ps = psit.next(); 1987 1988 /* 1989 * If this is not a system app, it can't be a 1990 * disable system app. 1991 */ 1992 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1993 continue; 1994 } 1995 1996 /* 1997 * If the package is scanned, it's not erased. 1998 */ 1999 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2000 if (scannedPkg != null) { 2001 /* 2002 * If the system app is both scanned and in the 2003 * disabled packages list, then it must have been 2004 * added via OTA. Remove it from the currently 2005 * scanned package so the previously user-installed 2006 * application can be scanned. 2007 */ 2008 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2009 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2010 + ps.name + "; removing system app. Last known codePath=" 2011 + ps.codePathString + ", installStatus=" + ps.installStatus 2012 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2013 + scannedPkg.mVersionCode); 2014 removePackageLI(ps, true); 2015 expectingBetter.put(ps.name, ps.codePath); 2016 } 2017 2018 continue; 2019 } 2020 2021 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2022 psit.remove(); 2023 logCriticalInfo(Log.WARN, "System package " + ps.name 2024 + " no longer exists; wiping its data"); 2025 removeDataDirsLI(null, ps.name); 2026 } else { 2027 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2028 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2029 possiblyDeletedUpdatedSystemApps.add(ps.name); 2030 } 2031 } 2032 } 2033 } 2034 2035 //look for any incomplete package installations 2036 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2037 //clean up list 2038 for(int i = 0; i < deletePkgsList.size(); i++) { 2039 //clean up here 2040 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2041 } 2042 //delete tmp files 2043 deleteTempPackageFiles(); 2044 2045 // Remove any shared userIDs that have no associated packages 2046 mSettings.pruneSharedUsersLPw(); 2047 2048 if (!mOnlyCore) { 2049 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2050 SystemClock.uptimeMillis()); 2051 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2052 2053 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2054 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2055 2056 /** 2057 * Remove disable package settings for any updated system 2058 * apps that were removed via an OTA. If they're not a 2059 * previously-updated app, remove them completely. 2060 * Otherwise, just revoke their system-level permissions. 2061 */ 2062 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2063 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2064 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2065 2066 String msg; 2067 if (deletedPkg == null) { 2068 msg = "Updated system package " + deletedAppName 2069 + " no longer exists; wiping its data"; 2070 removeDataDirsLI(null, deletedAppName); 2071 } else { 2072 msg = "Updated system app + " + deletedAppName 2073 + " no longer present; removing system privileges for " 2074 + deletedAppName; 2075 2076 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2077 2078 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2079 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2080 } 2081 logCriticalInfo(Log.WARN, msg); 2082 } 2083 2084 /** 2085 * Make sure all system apps that we expected to appear on 2086 * the userdata partition actually showed up. If they never 2087 * appeared, crawl back and revive the system version. 2088 */ 2089 for (int i = 0; i < expectingBetter.size(); i++) { 2090 final String packageName = expectingBetter.keyAt(i); 2091 if (!mPackages.containsKey(packageName)) { 2092 final File scanFile = expectingBetter.valueAt(i); 2093 2094 logCriticalInfo(Log.WARN, "Expected better " + packageName 2095 + " but never showed up; reverting to system"); 2096 2097 final int reparseFlags; 2098 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2099 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2100 | PackageParser.PARSE_IS_SYSTEM_DIR 2101 | PackageParser.PARSE_IS_PRIVILEGED; 2102 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2103 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2104 | PackageParser.PARSE_IS_SYSTEM_DIR; 2105 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2106 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2107 | PackageParser.PARSE_IS_SYSTEM_DIR; 2108 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2109 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2110 | PackageParser.PARSE_IS_SYSTEM_DIR; 2111 } else { 2112 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2113 continue; 2114 } 2115 2116 mSettings.enableSystemPackageLPw(packageName); 2117 2118 try { 2119 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2120 } catch (PackageManagerException e) { 2121 Slog.e(TAG, "Failed to parse original system package: " 2122 + e.getMessage()); 2123 } 2124 } 2125 } 2126 } 2127 2128 // Now that we know all of the shared libraries, update all clients to have 2129 // the correct library paths. 2130 updateAllSharedLibrariesLPw(); 2131 2132 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2133 // NOTE: We ignore potential failures here during a system scan (like 2134 // the rest of the commands above) because there's precious little we 2135 // can do about it. A settings error is reported, though. 2136 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2137 false /* force dexopt */, false /* defer dexopt */); 2138 } 2139 2140 // Now that we know all the packages we are keeping, 2141 // read and update their last usage times. 2142 mPackageUsage.readLP(); 2143 2144 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2145 SystemClock.uptimeMillis()); 2146 Slog.i(TAG, "Time to scan packages: " 2147 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2148 + " seconds"); 2149 2150 // If the platform SDK has changed since the last time we booted, 2151 // we need to re-grant app permission to catch any new ones that 2152 // appear. This is really a hack, and means that apps can in some 2153 // cases get permissions that the user didn't initially explicitly 2154 // allow... it would be nice to have some better way to handle 2155 // this situation. 2156 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2157 != mSdkVersion; 2158 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2159 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2160 + "; regranting permissions for internal storage"); 2161 mSettings.mInternalSdkPlatform = mSdkVersion; 2162 2163 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2164 | (regrantPermissions 2165 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2166 : 0)); 2167 2168 // If this is the first boot, and it is a normal boot, then 2169 // we need to initialize the default preferred apps. 2170 if (!mRestoredSettings && !onlyCore) { 2171 mSettings.readDefaultPreferredAppsLPw(this, 0); 2172 } 2173 2174 // If this is first boot after an OTA, and a normal boot, then 2175 // we need to clear code cache directories. 2176 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2177 if (mIsUpgrade && !onlyCore) { 2178 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2179 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2180 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2181 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2182 } 2183 mSettings.mFingerprint = Build.FINGERPRINT; 2184 } 2185 2186 primeDomainVerificationsLPw(); 2187 checkDefaultBrowser(); 2188 2189 // All the changes are done during package scanning. 2190 mSettings.updateInternalDatabaseVersion(); 2191 2192 // can downgrade to reader 2193 mSettings.writeLPr(); 2194 2195 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2196 SystemClock.uptimeMillis()); 2197 2198 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2199 2200 mInstallerService = new PackageInstallerService(context, this); 2201 2202 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2203 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2204 mIntentFilterVerifierComponent); 2205 2206 } // synchronized (mPackages) 2207 } // synchronized (mInstallLock) 2208 2209 // Now after opening every single application zip, make sure they 2210 // are all flushed. Not really needed, but keeps things nice and 2211 // tidy. 2212 Runtime.getRuntime().gc(); 2213 2214 // Expose private service for system components to use. 2215 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2216 } 2217 2218 @Override 2219 public boolean isFirstBoot() { 2220 return !mRestoredSettings; 2221 } 2222 2223 @Override 2224 public boolean isOnlyCoreApps() { 2225 return mOnlyCore; 2226 } 2227 2228 @Override 2229 public boolean isUpgrade() { 2230 return mIsUpgrade; 2231 } 2232 2233 private String getRequiredVerifierLPr() { 2234 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2235 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2236 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2237 2238 String requiredVerifier = null; 2239 2240 final int N = receivers.size(); 2241 for (int i = 0; i < N; i++) { 2242 final ResolveInfo info = receivers.get(i); 2243 2244 if (info.activityInfo == null) { 2245 continue; 2246 } 2247 2248 final String packageName = info.activityInfo.packageName; 2249 2250 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2251 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2252 continue; 2253 } 2254 2255 if (requiredVerifier != null) { 2256 throw new RuntimeException("There can be only one required verifier"); 2257 } 2258 2259 requiredVerifier = packageName; 2260 } 2261 2262 return requiredVerifier; 2263 } 2264 2265 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2266 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2267 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2268 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2269 2270 ComponentName verifierComponentName = null; 2271 2272 int priority = -1000; 2273 final int N = receivers.size(); 2274 for (int i = 0; i < N; i++) { 2275 final ResolveInfo info = receivers.get(i); 2276 2277 if (info.activityInfo == null) { 2278 continue; 2279 } 2280 2281 final String packageName = info.activityInfo.packageName; 2282 2283 final PackageSetting ps = mSettings.mPackages.get(packageName); 2284 if (ps == null) { 2285 continue; 2286 } 2287 2288 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2289 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2290 continue; 2291 } 2292 2293 // Select the IntentFilterVerifier with the highest priority 2294 if (priority < info.priority) { 2295 priority = info.priority; 2296 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2297 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2298 + verifierComponentName + " with priority: " + info.priority); 2299 } 2300 } 2301 2302 return verifierComponentName; 2303 } 2304 2305 private void primeDomainVerificationsLPw() { 2306 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2307 boolean updated = false; 2308 ArraySet<String> allHostsSet = new ArraySet<>(); 2309 for (PackageParser.Package pkg : mPackages.values()) { 2310 final String packageName = pkg.packageName; 2311 if (!hasDomainURLs(pkg)) { 2312 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2313 "package with no domain URLs: " + packageName); 2314 continue; 2315 } 2316 if (!pkg.isSystemApp()) { 2317 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2318 "No priming domain verifications for a non system package : " + 2319 packageName); 2320 continue; 2321 } 2322 for (PackageParser.Activity a : pkg.activities) { 2323 for (ActivityIntentInfo filter : a.intents) { 2324 if (hasValidDomains(filter)) { 2325 allHostsSet.addAll(filter.getHostsList()); 2326 } 2327 } 2328 } 2329 if (allHostsSet.size() == 0) { 2330 allHostsSet.add("*"); 2331 } 2332 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2333 IntentFilterVerificationInfo ivi = 2334 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2335 if (ivi != null) { 2336 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2337 "Priming domain verifications for package: " + packageName + 2338 " with hosts:" + ivi.getDomainsString()); 2339 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2340 updated = true; 2341 } 2342 else { 2343 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2344 "No priming domain verifications for package: " + packageName); 2345 } 2346 allHostsSet.clear(); 2347 } 2348 if (updated) { 2349 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2350 "Will need to write primed domain verifications"); 2351 } 2352 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2353 } 2354 2355 private void checkDefaultBrowser() { 2356 final int myUserId = UserHandle.myUserId(); 2357 final String packageName = getDefaultBrowserPackageName(myUserId); 2358 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2359 if (info == null) { 2360 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2361 packageName); 2362 setDefaultBrowserPackageName(null, myUserId); 2363 } 2364 } 2365 2366 @Override 2367 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2368 throws RemoteException { 2369 try { 2370 return super.onTransact(code, data, reply, flags); 2371 } catch (RuntimeException e) { 2372 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2373 Slog.wtf(TAG, "Package Manager Crash", e); 2374 } 2375 throw e; 2376 } 2377 } 2378 2379 void cleanupInstallFailedPackage(PackageSetting ps) { 2380 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2381 2382 removeDataDirsLI(ps.volumeUuid, ps.name); 2383 if (ps.codePath != null) { 2384 if (ps.codePath.isDirectory()) { 2385 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2386 } else { 2387 ps.codePath.delete(); 2388 } 2389 } 2390 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2391 if (ps.resourcePath.isDirectory()) { 2392 FileUtils.deleteContents(ps.resourcePath); 2393 } 2394 ps.resourcePath.delete(); 2395 } 2396 mSettings.removePackageLPw(ps.name); 2397 } 2398 2399 static int[] appendInts(int[] cur, int[] add) { 2400 if (add == null) return cur; 2401 if (cur == null) return add; 2402 final int N = add.length; 2403 for (int i=0; i<N; i++) { 2404 cur = appendInt(cur, add[i]); 2405 } 2406 return cur; 2407 } 2408 2409 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2410 if (!sUserManager.exists(userId)) return null; 2411 final PackageSetting ps = (PackageSetting) p.mExtras; 2412 if (ps == null) { 2413 return null; 2414 } 2415 2416 final PermissionsState permissionsState = ps.getPermissionsState(); 2417 2418 final int[] gids = permissionsState.computeGids(userId); 2419 final Set<String> permissions = permissionsState.getPermissions(userId); 2420 final PackageUserState state = ps.readUserState(userId); 2421 2422 return PackageParser.generatePackageInfo(p, gids, flags, 2423 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2424 } 2425 2426 @Override 2427 public boolean isPackageFrozen(String packageName) { 2428 synchronized (mPackages) { 2429 final PackageSetting ps = mSettings.mPackages.get(packageName); 2430 if (ps != null) { 2431 return ps.frozen; 2432 } 2433 } 2434 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2435 return true; 2436 } 2437 2438 @Override 2439 public boolean isPackageAvailable(String packageName, int userId) { 2440 if (!sUserManager.exists(userId)) return false; 2441 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2442 synchronized (mPackages) { 2443 PackageParser.Package p = mPackages.get(packageName); 2444 if (p != null) { 2445 final PackageSetting ps = (PackageSetting) p.mExtras; 2446 if (ps != null) { 2447 final PackageUserState state = ps.readUserState(userId); 2448 if (state != null) { 2449 return PackageParser.isAvailable(state); 2450 } 2451 } 2452 } 2453 } 2454 return false; 2455 } 2456 2457 @Override 2458 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2459 if (!sUserManager.exists(userId)) return null; 2460 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2461 // reader 2462 synchronized (mPackages) { 2463 PackageParser.Package p = mPackages.get(packageName); 2464 if (DEBUG_PACKAGE_INFO) 2465 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2466 if (p != null) { 2467 return generatePackageInfo(p, flags, userId); 2468 } 2469 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2470 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2471 } 2472 } 2473 return null; 2474 } 2475 2476 @Override 2477 public String[] currentToCanonicalPackageNames(String[] names) { 2478 String[] out = new String[names.length]; 2479 // reader 2480 synchronized (mPackages) { 2481 for (int i=names.length-1; i>=0; i--) { 2482 PackageSetting ps = mSettings.mPackages.get(names[i]); 2483 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2484 } 2485 } 2486 return out; 2487 } 2488 2489 @Override 2490 public String[] canonicalToCurrentPackageNames(String[] names) { 2491 String[] out = new String[names.length]; 2492 // reader 2493 synchronized (mPackages) { 2494 for (int i=names.length-1; i>=0; i--) { 2495 String cur = mSettings.mRenamedPackages.get(names[i]); 2496 out[i] = cur != null ? cur : names[i]; 2497 } 2498 } 2499 return out; 2500 } 2501 2502 @Override 2503 public int getPackageUid(String packageName, int userId) { 2504 if (!sUserManager.exists(userId)) return -1; 2505 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2506 2507 // reader 2508 synchronized (mPackages) { 2509 PackageParser.Package p = mPackages.get(packageName); 2510 if(p != null) { 2511 return UserHandle.getUid(userId, p.applicationInfo.uid); 2512 } 2513 PackageSetting ps = mSettings.mPackages.get(packageName); 2514 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2515 return -1; 2516 } 2517 p = ps.pkg; 2518 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2519 } 2520 } 2521 2522 @Override 2523 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2524 if (!sUserManager.exists(userId)) { 2525 return null; 2526 } 2527 2528 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2529 "getPackageGids"); 2530 2531 // reader 2532 synchronized (mPackages) { 2533 PackageParser.Package p = mPackages.get(packageName); 2534 if (DEBUG_PACKAGE_INFO) { 2535 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2536 } 2537 if (p != null) { 2538 PackageSetting ps = (PackageSetting) p.mExtras; 2539 return ps.getPermissionsState().computeGids(userId); 2540 } 2541 } 2542 2543 return null; 2544 } 2545 2546 static PermissionInfo generatePermissionInfo( 2547 BasePermission bp, int flags) { 2548 if (bp.perm != null) { 2549 return PackageParser.generatePermissionInfo(bp.perm, flags); 2550 } 2551 PermissionInfo pi = new PermissionInfo(); 2552 pi.name = bp.name; 2553 pi.packageName = bp.sourcePackage; 2554 pi.nonLocalizedLabel = bp.name; 2555 pi.protectionLevel = bp.protectionLevel; 2556 return pi; 2557 } 2558 2559 @Override 2560 public PermissionInfo getPermissionInfo(String name, int flags) { 2561 // reader 2562 synchronized (mPackages) { 2563 final BasePermission p = mSettings.mPermissions.get(name); 2564 if (p != null) { 2565 return generatePermissionInfo(p, flags); 2566 } 2567 return null; 2568 } 2569 } 2570 2571 @Override 2572 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2573 // reader 2574 synchronized (mPackages) { 2575 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2576 for (BasePermission p : mSettings.mPermissions.values()) { 2577 if (group == null) { 2578 if (p.perm == null || p.perm.info.group == null) { 2579 out.add(generatePermissionInfo(p, flags)); 2580 } 2581 } else { 2582 if (p.perm != null && group.equals(p.perm.info.group)) { 2583 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2584 } 2585 } 2586 } 2587 2588 if (out.size() > 0) { 2589 return out; 2590 } 2591 return mPermissionGroups.containsKey(group) ? out : null; 2592 } 2593 } 2594 2595 @Override 2596 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2597 // reader 2598 synchronized (mPackages) { 2599 return PackageParser.generatePermissionGroupInfo( 2600 mPermissionGroups.get(name), flags); 2601 } 2602 } 2603 2604 @Override 2605 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2606 // reader 2607 synchronized (mPackages) { 2608 final int N = mPermissionGroups.size(); 2609 ArrayList<PermissionGroupInfo> out 2610 = new ArrayList<PermissionGroupInfo>(N); 2611 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2612 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2613 } 2614 return out; 2615 } 2616 } 2617 2618 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2619 int userId) { 2620 if (!sUserManager.exists(userId)) return null; 2621 PackageSetting ps = mSettings.mPackages.get(packageName); 2622 if (ps != null) { 2623 if (ps.pkg == null) { 2624 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2625 flags, userId); 2626 if (pInfo != null) { 2627 return pInfo.applicationInfo; 2628 } 2629 return null; 2630 } 2631 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2632 ps.readUserState(userId), userId); 2633 } 2634 return null; 2635 } 2636 2637 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2638 int userId) { 2639 if (!sUserManager.exists(userId)) return null; 2640 PackageSetting ps = mSettings.mPackages.get(packageName); 2641 if (ps != null) { 2642 PackageParser.Package pkg = ps.pkg; 2643 if (pkg == null) { 2644 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2645 return null; 2646 } 2647 // Only data remains, so we aren't worried about code paths 2648 pkg = new PackageParser.Package(packageName); 2649 pkg.applicationInfo.packageName = packageName; 2650 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2651 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2652 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2653 packageName, userId).getAbsolutePath(); 2654 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2655 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2656 } 2657 return generatePackageInfo(pkg, flags, userId); 2658 } 2659 return null; 2660 } 2661 2662 @Override 2663 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2664 if (!sUserManager.exists(userId)) return null; 2665 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2666 // writer 2667 synchronized (mPackages) { 2668 PackageParser.Package p = mPackages.get(packageName); 2669 if (DEBUG_PACKAGE_INFO) Log.v( 2670 TAG, "getApplicationInfo " + packageName 2671 + ": " + p); 2672 if (p != null) { 2673 PackageSetting ps = mSettings.mPackages.get(packageName); 2674 if (ps == null) return null; 2675 // Note: isEnabledLP() does not apply here - always return info 2676 return PackageParser.generateApplicationInfo( 2677 p, flags, ps.readUserState(userId), userId); 2678 } 2679 if ("android".equals(packageName)||"system".equals(packageName)) { 2680 return mAndroidApplication; 2681 } 2682 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2683 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2684 } 2685 } 2686 return null; 2687 } 2688 2689 @Override 2690 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2691 final IPackageDataObserver observer) { 2692 mContext.enforceCallingOrSelfPermission( 2693 android.Manifest.permission.CLEAR_APP_CACHE, null); 2694 // Queue up an async operation since clearing cache may take a little while. 2695 mHandler.post(new Runnable() { 2696 public void run() { 2697 mHandler.removeCallbacks(this); 2698 int retCode = -1; 2699 synchronized (mInstallLock) { 2700 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2701 if (retCode < 0) { 2702 Slog.w(TAG, "Couldn't clear application caches"); 2703 } 2704 } 2705 if (observer != null) { 2706 try { 2707 observer.onRemoveCompleted(null, (retCode >= 0)); 2708 } catch (RemoteException e) { 2709 Slog.w(TAG, "RemoveException when invoking call back"); 2710 } 2711 } 2712 } 2713 }); 2714 } 2715 2716 @Override 2717 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2718 final IntentSender pi) { 2719 mContext.enforceCallingOrSelfPermission( 2720 android.Manifest.permission.CLEAR_APP_CACHE, null); 2721 // Queue up an async operation since clearing cache may take a little while. 2722 mHandler.post(new Runnable() { 2723 public void run() { 2724 mHandler.removeCallbacks(this); 2725 int retCode = -1; 2726 synchronized (mInstallLock) { 2727 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2728 if (retCode < 0) { 2729 Slog.w(TAG, "Couldn't clear application caches"); 2730 } 2731 } 2732 if(pi != null) { 2733 try { 2734 // Callback via pending intent 2735 int code = (retCode >= 0) ? 1 : 0; 2736 pi.sendIntent(null, code, null, 2737 null, null); 2738 } catch (SendIntentException e1) { 2739 Slog.i(TAG, "Failed to send pending intent"); 2740 } 2741 } 2742 } 2743 }); 2744 } 2745 2746 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2747 synchronized (mInstallLock) { 2748 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2749 throw new IOException("Failed to free enough space"); 2750 } 2751 } 2752 } 2753 2754 @Override 2755 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2756 if (!sUserManager.exists(userId)) return null; 2757 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2758 synchronized (mPackages) { 2759 PackageParser.Activity a = mActivities.mActivities.get(component); 2760 2761 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2762 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2763 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2764 if (ps == null) return null; 2765 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2766 userId); 2767 } 2768 if (mResolveComponentName.equals(component)) { 2769 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2770 new PackageUserState(), userId); 2771 } 2772 } 2773 return null; 2774 } 2775 2776 @Override 2777 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2778 String resolvedType) { 2779 synchronized (mPackages) { 2780 PackageParser.Activity a = mActivities.mActivities.get(component); 2781 if (a == null) { 2782 return false; 2783 } 2784 for (int i=0; i<a.intents.size(); i++) { 2785 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2786 intent.getData(), intent.getCategories(), TAG) >= 0) { 2787 return true; 2788 } 2789 } 2790 return false; 2791 } 2792 } 2793 2794 @Override 2795 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2796 if (!sUserManager.exists(userId)) return null; 2797 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2798 synchronized (mPackages) { 2799 PackageParser.Activity a = mReceivers.mActivities.get(component); 2800 if (DEBUG_PACKAGE_INFO) Log.v( 2801 TAG, "getReceiverInfo " + component + ": " + a); 2802 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2803 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2804 if (ps == null) return null; 2805 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2806 userId); 2807 } 2808 } 2809 return null; 2810 } 2811 2812 @Override 2813 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2814 if (!sUserManager.exists(userId)) return null; 2815 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2816 synchronized (mPackages) { 2817 PackageParser.Service s = mServices.mServices.get(component); 2818 if (DEBUG_PACKAGE_INFO) Log.v( 2819 TAG, "getServiceInfo " + component + ": " + s); 2820 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2821 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2822 if (ps == null) return null; 2823 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2824 userId); 2825 } 2826 } 2827 return null; 2828 } 2829 2830 @Override 2831 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2832 if (!sUserManager.exists(userId)) return null; 2833 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2834 synchronized (mPackages) { 2835 PackageParser.Provider p = mProviders.mProviders.get(component); 2836 if (DEBUG_PACKAGE_INFO) Log.v( 2837 TAG, "getProviderInfo " + component + ": " + p); 2838 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2839 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2840 if (ps == null) return null; 2841 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2842 userId); 2843 } 2844 } 2845 return null; 2846 } 2847 2848 @Override 2849 public String[] getSystemSharedLibraryNames() { 2850 Set<String> libSet; 2851 synchronized (mPackages) { 2852 libSet = mSharedLibraries.keySet(); 2853 int size = libSet.size(); 2854 if (size > 0) { 2855 String[] libs = new String[size]; 2856 libSet.toArray(libs); 2857 return libs; 2858 } 2859 } 2860 return null; 2861 } 2862 2863 /** 2864 * @hide 2865 */ 2866 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2867 synchronized (mPackages) { 2868 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2869 if (lib != null && lib.apk != null) { 2870 return mPackages.get(lib.apk); 2871 } 2872 } 2873 return null; 2874 } 2875 2876 @Override 2877 public FeatureInfo[] getSystemAvailableFeatures() { 2878 Collection<FeatureInfo> featSet; 2879 synchronized (mPackages) { 2880 featSet = mAvailableFeatures.values(); 2881 int size = featSet.size(); 2882 if (size > 0) { 2883 FeatureInfo[] features = new FeatureInfo[size+1]; 2884 featSet.toArray(features); 2885 FeatureInfo fi = new FeatureInfo(); 2886 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2887 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2888 features[size] = fi; 2889 return features; 2890 } 2891 } 2892 return null; 2893 } 2894 2895 @Override 2896 public boolean hasSystemFeature(String name) { 2897 synchronized (mPackages) { 2898 return mAvailableFeatures.containsKey(name); 2899 } 2900 } 2901 2902 private void checkValidCaller(int uid, int userId) { 2903 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2904 return; 2905 2906 throw new SecurityException("Caller uid=" + uid 2907 + " is not privileged to communicate with user=" + userId); 2908 } 2909 2910 @Override 2911 public int checkPermission(String permName, String pkgName, int userId) { 2912 if (!sUserManager.exists(userId)) { 2913 return PackageManager.PERMISSION_DENIED; 2914 } 2915 2916 synchronized (mPackages) { 2917 final PackageParser.Package p = mPackages.get(pkgName); 2918 if (p != null && p.mExtras != null) { 2919 final PackageSetting ps = (PackageSetting) p.mExtras; 2920 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2921 return PackageManager.PERMISSION_GRANTED; 2922 } 2923 } 2924 } 2925 2926 return PackageManager.PERMISSION_DENIED; 2927 } 2928 2929 @Override 2930 public int checkUidPermission(String permName, int uid) { 2931 final int userId = UserHandle.getUserId(uid); 2932 2933 if (!sUserManager.exists(userId)) { 2934 return PackageManager.PERMISSION_DENIED; 2935 } 2936 2937 synchronized (mPackages) { 2938 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2939 if (obj != null) { 2940 final SettingBase ps = (SettingBase) obj; 2941 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2942 return PackageManager.PERMISSION_GRANTED; 2943 } 2944 } else { 2945 ArraySet<String> perms = mSystemPermissions.get(uid); 2946 if (perms != null && perms.contains(permName)) { 2947 return PackageManager.PERMISSION_GRANTED; 2948 } 2949 } 2950 } 2951 2952 return PackageManager.PERMISSION_DENIED; 2953 } 2954 2955 /** 2956 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2957 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2958 * @param checkShell TODO(yamasani): 2959 * @param message the message to log on security exception 2960 */ 2961 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2962 boolean checkShell, String message) { 2963 if (userId < 0) { 2964 throw new IllegalArgumentException("Invalid userId " + userId); 2965 } 2966 if (checkShell) { 2967 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2968 } 2969 if (userId == UserHandle.getUserId(callingUid)) return; 2970 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2971 if (requireFullPermission) { 2972 mContext.enforceCallingOrSelfPermission( 2973 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2974 } else { 2975 try { 2976 mContext.enforceCallingOrSelfPermission( 2977 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2978 } catch (SecurityException se) { 2979 mContext.enforceCallingOrSelfPermission( 2980 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2981 } 2982 } 2983 } 2984 } 2985 2986 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2987 if (callingUid == Process.SHELL_UID) { 2988 if (userHandle >= 0 2989 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2990 throw new SecurityException("Shell does not have permission to access user " 2991 + userHandle); 2992 } else if (userHandle < 0) { 2993 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2994 + Debug.getCallers(3)); 2995 } 2996 } 2997 } 2998 2999 private BasePermission findPermissionTreeLP(String permName) { 3000 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3001 if (permName.startsWith(bp.name) && 3002 permName.length() > bp.name.length() && 3003 permName.charAt(bp.name.length()) == '.') { 3004 return bp; 3005 } 3006 } 3007 return null; 3008 } 3009 3010 private BasePermission checkPermissionTreeLP(String permName) { 3011 if (permName != null) { 3012 BasePermission bp = findPermissionTreeLP(permName); 3013 if (bp != null) { 3014 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3015 return bp; 3016 } 3017 throw new SecurityException("Calling uid " 3018 + Binder.getCallingUid() 3019 + " is not allowed to add to permission tree " 3020 + bp.name + " owned by uid " + bp.uid); 3021 } 3022 } 3023 throw new SecurityException("No permission tree found for " + permName); 3024 } 3025 3026 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3027 if (s1 == null) { 3028 return s2 == null; 3029 } 3030 if (s2 == null) { 3031 return false; 3032 } 3033 if (s1.getClass() != s2.getClass()) { 3034 return false; 3035 } 3036 return s1.equals(s2); 3037 } 3038 3039 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3040 if (pi1.icon != pi2.icon) return false; 3041 if (pi1.logo != pi2.logo) return false; 3042 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3043 if (!compareStrings(pi1.name, pi2.name)) return false; 3044 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3045 // We'll take care of setting this one. 3046 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3047 // These are not currently stored in settings. 3048 //if (!compareStrings(pi1.group, pi2.group)) return false; 3049 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3050 //if (pi1.labelRes != pi2.labelRes) return false; 3051 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3052 return true; 3053 } 3054 3055 int permissionInfoFootprint(PermissionInfo info) { 3056 int size = info.name.length(); 3057 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3058 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3059 return size; 3060 } 3061 3062 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3063 int size = 0; 3064 for (BasePermission perm : mSettings.mPermissions.values()) { 3065 if (perm.uid == tree.uid) { 3066 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3067 } 3068 } 3069 return size; 3070 } 3071 3072 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3073 // We calculate the max size of permissions defined by this uid and throw 3074 // if that plus the size of 'info' would exceed our stated maximum. 3075 if (tree.uid != Process.SYSTEM_UID) { 3076 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3077 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3078 throw new SecurityException("Permission tree size cap exceeded"); 3079 } 3080 } 3081 } 3082 3083 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3084 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3085 throw new SecurityException("Label must be specified in permission"); 3086 } 3087 BasePermission tree = checkPermissionTreeLP(info.name); 3088 BasePermission bp = mSettings.mPermissions.get(info.name); 3089 boolean added = bp == null; 3090 boolean changed = true; 3091 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3092 if (added) { 3093 enforcePermissionCapLocked(info, tree); 3094 bp = new BasePermission(info.name, tree.sourcePackage, 3095 BasePermission.TYPE_DYNAMIC); 3096 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3097 throw new SecurityException( 3098 "Not allowed to modify non-dynamic permission " 3099 + info.name); 3100 } else { 3101 if (bp.protectionLevel == fixedLevel 3102 && bp.perm.owner.equals(tree.perm.owner) 3103 && bp.uid == tree.uid 3104 && comparePermissionInfos(bp.perm.info, info)) { 3105 changed = false; 3106 } 3107 } 3108 bp.protectionLevel = fixedLevel; 3109 info = new PermissionInfo(info); 3110 info.protectionLevel = fixedLevel; 3111 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3112 bp.perm.info.packageName = tree.perm.info.packageName; 3113 bp.uid = tree.uid; 3114 if (added) { 3115 mSettings.mPermissions.put(info.name, bp); 3116 } 3117 if (changed) { 3118 if (!async) { 3119 mSettings.writeLPr(); 3120 } else { 3121 scheduleWriteSettingsLocked(); 3122 } 3123 } 3124 return added; 3125 } 3126 3127 @Override 3128 public boolean addPermission(PermissionInfo info) { 3129 synchronized (mPackages) { 3130 return addPermissionLocked(info, false); 3131 } 3132 } 3133 3134 @Override 3135 public boolean addPermissionAsync(PermissionInfo info) { 3136 synchronized (mPackages) { 3137 return addPermissionLocked(info, true); 3138 } 3139 } 3140 3141 @Override 3142 public void removePermission(String name) { 3143 synchronized (mPackages) { 3144 checkPermissionTreeLP(name); 3145 BasePermission bp = mSettings.mPermissions.get(name); 3146 if (bp != null) { 3147 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3148 throw new SecurityException( 3149 "Not allowed to modify non-dynamic permission " 3150 + name); 3151 } 3152 mSettings.mPermissions.remove(name); 3153 mSettings.writeLPr(); 3154 } 3155 } 3156 } 3157 3158 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3159 BasePermission bp) { 3160 int index = pkg.requestedPermissions.indexOf(bp.name); 3161 if (index == -1) { 3162 throw new SecurityException("Package " + pkg.packageName 3163 + " has not requested permission " + bp.name); 3164 } 3165 if (!bp.isRuntime()) { 3166 throw new SecurityException("Permission " + bp.name 3167 + " is not a changeable permission type"); 3168 } 3169 } 3170 3171 @Override 3172 public void grantRuntimePermission(String packageName, String name, final int userId) { 3173 if (!sUserManager.exists(userId)) { 3174 Log.e(TAG, "No such user:" + userId); 3175 return; 3176 } 3177 3178 mContext.enforceCallingOrSelfPermission( 3179 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3180 "grantRuntimePermission"); 3181 3182 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3183 "grantRuntimePermission"); 3184 3185 final SettingBase sb; 3186 3187 synchronized (mPackages) { 3188 final PackageParser.Package pkg = mPackages.get(packageName); 3189 if (pkg == null) { 3190 throw new IllegalArgumentException("Unknown package: " + packageName); 3191 } 3192 3193 final BasePermission bp = mSettings.mPermissions.get(name); 3194 if (bp == null) { 3195 throw new IllegalArgumentException("Unknown permission: " + name); 3196 } 3197 3198 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3199 3200 sb = (SettingBase) pkg.mExtras; 3201 if (sb == null) { 3202 throw new IllegalArgumentException("Unknown package: " + packageName); 3203 } 3204 3205 final PermissionsState permissionsState = sb.getPermissionsState(); 3206 3207 final int flags = permissionsState.getPermissionFlags(name, userId); 3208 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3209 throw new SecurityException("Cannot grant system fixed permission: " 3210 + name + " for package: " + packageName); 3211 } 3212 3213 final int result = permissionsState.grantRuntimePermission(bp, userId); 3214 switch (result) { 3215 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3216 return; 3217 } 3218 3219 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3220 mHandler.post(new Runnable() { 3221 @Override 3222 public void run() { 3223 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3224 } 3225 }); 3226 } break; 3227 } 3228 3229 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3230 3231 // Not critical if that is lost - app has to request again. 3232 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3233 } 3234 } 3235 3236 @Override 3237 public void revokeRuntimePermission(String packageName, String name, int userId) { 3238 if (!sUserManager.exists(userId)) { 3239 Log.e(TAG, "No such user:" + userId); 3240 return; 3241 } 3242 3243 mContext.enforceCallingOrSelfPermission( 3244 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3245 "revokeRuntimePermission"); 3246 3247 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3248 "revokeRuntimePermission"); 3249 3250 final SettingBase sb; 3251 3252 synchronized (mPackages) { 3253 final PackageParser.Package pkg = mPackages.get(packageName); 3254 if (pkg == null) { 3255 throw new IllegalArgumentException("Unknown package: " + packageName); 3256 } 3257 3258 final BasePermission bp = mSettings.mPermissions.get(name); 3259 if (bp == null) { 3260 throw new IllegalArgumentException("Unknown permission: " + name); 3261 } 3262 3263 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3264 3265 sb = (SettingBase) pkg.mExtras; 3266 if (sb == null) { 3267 throw new IllegalArgumentException("Unknown package: " + packageName); 3268 } 3269 3270 final PermissionsState permissionsState = sb.getPermissionsState(); 3271 3272 final int flags = permissionsState.getPermissionFlags(name, userId); 3273 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3274 throw new SecurityException("Cannot revoke system fixed permission: " 3275 + name + " for package: " + packageName); 3276 } 3277 3278 if (permissionsState.revokeRuntimePermission(bp, userId) == 3279 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3280 return; 3281 } 3282 3283 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3284 3285 // Critical, after this call app should never have the permission. 3286 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3287 } 3288 3289 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3290 } 3291 3292 @Override 3293 public int getPermissionFlags(String name, String packageName, int userId) { 3294 if (!sUserManager.exists(userId)) { 3295 return 0; 3296 } 3297 3298 mContext.enforceCallingOrSelfPermission( 3299 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3300 "getPermissionFlags"); 3301 3302 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3303 "getPermissionFlags"); 3304 3305 synchronized (mPackages) { 3306 final PackageParser.Package pkg = mPackages.get(packageName); 3307 if (pkg == null) { 3308 throw new IllegalArgumentException("Unknown package: " + packageName); 3309 } 3310 3311 final BasePermission bp = mSettings.mPermissions.get(name); 3312 if (bp == null) { 3313 throw new IllegalArgumentException("Unknown permission: " + name); 3314 } 3315 3316 SettingBase sb = (SettingBase) pkg.mExtras; 3317 if (sb == null) { 3318 throw new IllegalArgumentException("Unknown package: " + packageName); 3319 } 3320 3321 PermissionsState permissionsState = sb.getPermissionsState(); 3322 return permissionsState.getPermissionFlags(name, userId); 3323 } 3324 } 3325 3326 @Override 3327 public void updatePermissionFlags(String name, String packageName, int flagMask, 3328 int flagValues, int userId) { 3329 if (!sUserManager.exists(userId)) { 3330 return; 3331 } 3332 3333 mContext.enforceCallingOrSelfPermission( 3334 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3335 "updatePermissionFlags"); 3336 3337 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3338 "updatePermissionFlags"); 3339 3340 // Only the system can change policy and system fixed flags. 3341 if (getCallingUid() != Process.SYSTEM_UID) { 3342 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3343 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3344 3345 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3346 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3347 } 3348 3349 synchronized (mPackages) { 3350 final PackageParser.Package pkg = mPackages.get(packageName); 3351 if (pkg == null) { 3352 throw new IllegalArgumentException("Unknown package: " + packageName); 3353 } 3354 3355 final BasePermission bp = mSettings.mPermissions.get(name); 3356 if (bp == null) { 3357 throw new IllegalArgumentException("Unknown permission: " + name); 3358 } 3359 3360 SettingBase sb = (SettingBase) pkg.mExtras; 3361 if (sb == null) { 3362 throw new IllegalArgumentException("Unknown package: " + packageName); 3363 } 3364 3365 PermissionsState permissionsState = sb.getPermissionsState(); 3366 3367 // Only the package manager can change flags for system component permissions. 3368 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3369 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3370 return; 3371 } 3372 3373 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3374 // Install and runtime permissions are stored in different places, 3375 // so figure out what permission changed and persist the change. 3376 if (permissionsState.getInstallPermissionState(name) != null) { 3377 scheduleWriteSettingsLocked(); 3378 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3379 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3380 } 3381 } 3382 } 3383 } 3384 3385 @Override 3386 public boolean shouldShowRequestPermissionRationale(String permissionName, 3387 String packageName, int userId) { 3388 if (UserHandle.getCallingUserId() != userId) { 3389 mContext.enforceCallingPermission( 3390 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3391 "canShowRequestPermissionRationale for user " + userId); 3392 } 3393 3394 final int uid = getPackageUid(packageName, userId); 3395 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3396 return false; 3397 } 3398 3399 if (checkPermission(permissionName, packageName, userId) 3400 == PackageManager.PERMISSION_GRANTED) { 3401 return false; 3402 } 3403 3404 final int flags; 3405 3406 final long identity = Binder.clearCallingIdentity(); 3407 try { 3408 flags = getPermissionFlags(permissionName, 3409 packageName, userId); 3410 } finally { 3411 Binder.restoreCallingIdentity(identity); 3412 } 3413 3414 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3415 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3416 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3417 3418 if ((flags & fixedFlags) != 0) { 3419 return false; 3420 } 3421 3422 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3423 } 3424 3425 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3426 BasePermission bp = mSettings.mPermissions.get(permission); 3427 if (bp == null) { 3428 throw new SecurityException("Missing " + permission + " permission"); 3429 } 3430 3431 SettingBase sb = (SettingBase) pkg.mExtras; 3432 PermissionsState permissionsState = sb.getPermissionsState(); 3433 3434 if (permissionsState.grantInstallPermission(bp) != 3435 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3436 scheduleWriteSettingsLocked(); 3437 } 3438 } 3439 3440 @Override 3441 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3442 mContext.enforceCallingOrSelfPermission( 3443 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3444 "addOnPermissionsChangeListener"); 3445 3446 synchronized (mPackages) { 3447 mOnPermissionChangeListeners.addListenerLocked(listener); 3448 } 3449 } 3450 3451 @Override 3452 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3453 synchronized (mPackages) { 3454 mOnPermissionChangeListeners.removeListenerLocked(listener); 3455 } 3456 } 3457 3458 @Override 3459 public boolean isProtectedBroadcast(String actionName) { 3460 synchronized (mPackages) { 3461 return mProtectedBroadcasts.contains(actionName); 3462 } 3463 } 3464 3465 @Override 3466 public int checkSignatures(String pkg1, String pkg2) { 3467 synchronized (mPackages) { 3468 final PackageParser.Package p1 = mPackages.get(pkg1); 3469 final PackageParser.Package p2 = mPackages.get(pkg2); 3470 if (p1 == null || p1.mExtras == null 3471 || p2 == null || p2.mExtras == null) { 3472 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3473 } 3474 return compareSignatures(p1.mSignatures, p2.mSignatures); 3475 } 3476 } 3477 3478 @Override 3479 public int checkUidSignatures(int uid1, int uid2) { 3480 // Map to base uids. 3481 uid1 = UserHandle.getAppId(uid1); 3482 uid2 = UserHandle.getAppId(uid2); 3483 // reader 3484 synchronized (mPackages) { 3485 Signature[] s1; 3486 Signature[] s2; 3487 Object obj = mSettings.getUserIdLPr(uid1); 3488 if (obj != null) { 3489 if (obj instanceof SharedUserSetting) { 3490 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3491 } else if (obj instanceof PackageSetting) { 3492 s1 = ((PackageSetting)obj).signatures.mSignatures; 3493 } else { 3494 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3495 } 3496 } else { 3497 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3498 } 3499 obj = mSettings.getUserIdLPr(uid2); 3500 if (obj != null) { 3501 if (obj instanceof SharedUserSetting) { 3502 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3503 } else if (obj instanceof PackageSetting) { 3504 s2 = ((PackageSetting)obj).signatures.mSignatures; 3505 } else { 3506 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3507 } 3508 } else { 3509 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3510 } 3511 return compareSignatures(s1, s2); 3512 } 3513 } 3514 3515 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3516 final long identity = Binder.clearCallingIdentity(); 3517 try { 3518 if (sb instanceof SharedUserSetting) { 3519 SharedUserSetting sus = (SharedUserSetting) sb; 3520 final int packageCount = sus.packages.size(); 3521 for (int i = 0; i < packageCount; i++) { 3522 PackageSetting susPs = sus.packages.valueAt(i); 3523 if (userId == UserHandle.USER_ALL) { 3524 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3525 } else { 3526 final int uid = UserHandle.getUid(userId, susPs.appId); 3527 killUid(uid, reason); 3528 } 3529 } 3530 } else if (sb instanceof PackageSetting) { 3531 PackageSetting ps = (PackageSetting) sb; 3532 if (userId == UserHandle.USER_ALL) { 3533 killApplication(ps.pkg.packageName, ps.appId, reason); 3534 } else { 3535 final int uid = UserHandle.getUid(userId, ps.appId); 3536 killUid(uid, reason); 3537 } 3538 } 3539 } finally { 3540 Binder.restoreCallingIdentity(identity); 3541 } 3542 } 3543 3544 private static void killUid(int uid, String reason) { 3545 IActivityManager am = ActivityManagerNative.getDefault(); 3546 if (am != null) { 3547 try { 3548 am.killUid(uid, reason); 3549 } catch (RemoteException e) { 3550 /* ignore - same process */ 3551 } 3552 } 3553 } 3554 3555 /** 3556 * Compares two sets of signatures. Returns: 3557 * <br /> 3558 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3559 * <br /> 3560 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3561 * <br /> 3562 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3563 * <br /> 3564 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3565 * <br /> 3566 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3567 */ 3568 static int compareSignatures(Signature[] s1, Signature[] s2) { 3569 if (s1 == null) { 3570 return s2 == null 3571 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3572 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3573 } 3574 3575 if (s2 == null) { 3576 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3577 } 3578 3579 if (s1.length != s2.length) { 3580 return PackageManager.SIGNATURE_NO_MATCH; 3581 } 3582 3583 // Since both signature sets are of size 1, we can compare without HashSets. 3584 if (s1.length == 1) { 3585 return s1[0].equals(s2[0]) ? 3586 PackageManager.SIGNATURE_MATCH : 3587 PackageManager.SIGNATURE_NO_MATCH; 3588 } 3589 3590 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3591 for (Signature sig : s1) { 3592 set1.add(sig); 3593 } 3594 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3595 for (Signature sig : s2) { 3596 set2.add(sig); 3597 } 3598 // Make sure s2 contains all signatures in s1. 3599 if (set1.equals(set2)) { 3600 return PackageManager.SIGNATURE_MATCH; 3601 } 3602 return PackageManager.SIGNATURE_NO_MATCH; 3603 } 3604 3605 /** 3606 * If the database version for this type of package (internal storage or 3607 * external storage) is less than the version where package signatures 3608 * were updated, return true. 3609 */ 3610 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3611 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3612 DatabaseVersion.SIGNATURE_END_ENTITY)) 3613 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3614 DatabaseVersion.SIGNATURE_END_ENTITY)); 3615 } 3616 3617 /** 3618 * Used for backward compatibility to make sure any packages with 3619 * certificate chains get upgraded to the new style. {@code existingSigs} 3620 * will be in the old format (since they were stored on disk from before the 3621 * system upgrade) and {@code scannedSigs} will be in the newer format. 3622 */ 3623 private int compareSignaturesCompat(PackageSignatures existingSigs, 3624 PackageParser.Package scannedPkg) { 3625 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3626 return PackageManager.SIGNATURE_NO_MATCH; 3627 } 3628 3629 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3630 for (Signature sig : existingSigs.mSignatures) { 3631 existingSet.add(sig); 3632 } 3633 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3634 for (Signature sig : scannedPkg.mSignatures) { 3635 try { 3636 Signature[] chainSignatures = sig.getChainSignatures(); 3637 for (Signature chainSig : chainSignatures) { 3638 scannedCompatSet.add(chainSig); 3639 } 3640 } catch (CertificateEncodingException e) { 3641 scannedCompatSet.add(sig); 3642 } 3643 } 3644 /* 3645 * Make sure the expanded scanned set contains all signatures in the 3646 * existing one. 3647 */ 3648 if (scannedCompatSet.equals(existingSet)) { 3649 // Migrate the old signatures to the new scheme. 3650 existingSigs.assignSignatures(scannedPkg.mSignatures); 3651 // The new KeySets will be re-added later in the scanning process. 3652 synchronized (mPackages) { 3653 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3654 } 3655 return PackageManager.SIGNATURE_MATCH; 3656 } 3657 return PackageManager.SIGNATURE_NO_MATCH; 3658 } 3659 3660 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3661 if (isExternal(scannedPkg)) { 3662 return mSettings.isExternalDatabaseVersionOlderThan( 3663 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3664 } else { 3665 return mSettings.isInternalDatabaseVersionOlderThan( 3666 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3667 } 3668 } 3669 3670 private int compareSignaturesRecover(PackageSignatures existingSigs, 3671 PackageParser.Package scannedPkg) { 3672 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3673 return PackageManager.SIGNATURE_NO_MATCH; 3674 } 3675 3676 String msg = null; 3677 try { 3678 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3679 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3680 + scannedPkg.packageName); 3681 return PackageManager.SIGNATURE_MATCH; 3682 } 3683 } catch (CertificateException e) { 3684 msg = e.getMessage(); 3685 } 3686 3687 logCriticalInfo(Log.INFO, 3688 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3689 return PackageManager.SIGNATURE_NO_MATCH; 3690 } 3691 3692 @Override 3693 public String[] getPackagesForUid(int uid) { 3694 uid = UserHandle.getAppId(uid); 3695 // reader 3696 synchronized (mPackages) { 3697 Object obj = mSettings.getUserIdLPr(uid); 3698 if (obj instanceof SharedUserSetting) { 3699 final SharedUserSetting sus = (SharedUserSetting) obj; 3700 final int N = sus.packages.size(); 3701 final String[] res = new String[N]; 3702 final Iterator<PackageSetting> it = sus.packages.iterator(); 3703 int i = 0; 3704 while (it.hasNext()) { 3705 res[i++] = it.next().name; 3706 } 3707 return res; 3708 } else if (obj instanceof PackageSetting) { 3709 final PackageSetting ps = (PackageSetting) obj; 3710 return new String[] { ps.name }; 3711 } 3712 } 3713 return null; 3714 } 3715 3716 @Override 3717 public String getNameForUid(int uid) { 3718 // reader 3719 synchronized (mPackages) { 3720 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3721 if (obj instanceof SharedUserSetting) { 3722 final SharedUserSetting sus = (SharedUserSetting) obj; 3723 return sus.name + ":" + sus.userId; 3724 } else if (obj instanceof PackageSetting) { 3725 final PackageSetting ps = (PackageSetting) obj; 3726 return ps.name; 3727 } 3728 } 3729 return null; 3730 } 3731 3732 @Override 3733 public int getUidForSharedUser(String sharedUserName) { 3734 if(sharedUserName == null) { 3735 return -1; 3736 } 3737 // reader 3738 synchronized (mPackages) { 3739 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3740 if (suid == null) { 3741 return -1; 3742 } 3743 return suid.userId; 3744 } 3745 } 3746 3747 @Override 3748 public int getFlagsForUid(int uid) { 3749 synchronized (mPackages) { 3750 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3751 if (obj instanceof SharedUserSetting) { 3752 final SharedUserSetting sus = (SharedUserSetting) obj; 3753 return sus.pkgFlags; 3754 } else if (obj instanceof PackageSetting) { 3755 final PackageSetting ps = (PackageSetting) obj; 3756 return ps.pkgFlags; 3757 } 3758 } 3759 return 0; 3760 } 3761 3762 @Override 3763 public int getPrivateFlagsForUid(int uid) { 3764 synchronized (mPackages) { 3765 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3766 if (obj instanceof SharedUserSetting) { 3767 final SharedUserSetting sus = (SharedUserSetting) obj; 3768 return sus.pkgPrivateFlags; 3769 } else if (obj instanceof PackageSetting) { 3770 final PackageSetting ps = (PackageSetting) obj; 3771 return ps.pkgPrivateFlags; 3772 } 3773 } 3774 return 0; 3775 } 3776 3777 @Override 3778 public boolean isUidPrivileged(int uid) { 3779 uid = UserHandle.getAppId(uid); 3780 // reader 3781 synchronized (mPackages) { 3782 Object obj = mSettings.getUserIdLPr(uid); 3783 if (obj instanceof SharedUserSetting) { 3784 final SharedUserSetting sus = (SharedUserSetting) obj; 3785 final Iterator<PackageSetting> it = sus.packages.iterator(); 3786 while (it.hasNext()) { 3787 if (it.next().isPrivileged()) { 3788 return true; 3789 } 3790 } 3791 } else if (obj instanceof PackageSetting) { 3792 final PackageSetting ps = (PackageSetting) obj; 3793 return ps.isPrivileged(); 3794 } 3795 } 3796 return false; 3797 } 3798 3799 @Override 3800 public String[] getAppOpPermissionPackages(String permissionName) { 3801 synchronized (mPackages) { 3802 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3803 if (pkgs == null) { 3804 return null; 3805 } 3806 return pkgs.toArray(new String[pkgs.size()]); 3807 } 3808 } 3809 3810 @Override 3811 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3812 int flags, int userId) { 3813 if (!sUserManager.exists(userId)) return null; 3814 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3815 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3816 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3817 } 3818 3819 @Override 3820 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3821 IntentFilter filter, int match, ComponentName activity) { 3822 final int userId = UserHandle.getCallingUserId(); 3823 if (DEBUG_PREFERRED) { 3824 Log.v(TAG, "setLastChosenActivity intent=" + intent 3825 + " resolvedType=" + resolvedType 3826 + " flags=" + flags 3827 + " filter=" + filter 3828 + " match=" + match 3829 + " activity=" + activity); 3830 filter.dump(new PrintStreamPrinter(System.out), " "); 3831 } 3832 intent.setComponent(null); 3833 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3834 // Find any earlier preferred or last chosen entries and nuke them 3835 findPreferredActivity(intent, resolvedType, 3836 flags, query, 0, false, true, false, userId); 3837 // Add the new activity as the last chosen for this filter 3838 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3839 "Setting last chosen"); 3840 } 3841 3842 @Override 3843 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3844 final int userId = UserHandle.getCallingUserId(); 3845 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3846 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3847 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3848 false, false, false, userId); 3849 } 3850 3851 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3852 int flags, List<ResolveInfo> query, int userId) { 3853 if (query != null) { 3854 final int N = query.size(); 3855 if (N == 1) { 3856 return query.get(0); 3857 } else if (N > 1) { 3858 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3859 // If there is more than one activity with the same priority, 3860 // then let the user decide between them. 3861 ResolveInfo r0 = query.get(0); 3862 ResolveInfo r1 = query.get(1); 3863 if (DEBUG_INTENT_MATCHING || debug) { 3864 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3865 + r1.activityInfo.name + "=" + r1.priority); 3866 } 3867 // If the first activity has a higher priority, or a different 3868 // default, then it is always desireable to pick it. 3869 if (r0.priority != r1.priority 3870 || r0.preferredOrder != r1.preferredOrder 3871 || r0.isDefault != r1.isDefault) { 3872 return query.get(0); 3873 } 3874 // If we have saved a preference for a preferred activity for 3875 // this Intent, use that. 3876 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3877 flags, query, r0.priority, true, false, debug, userId); 3878 if (ri != null) { 3879 return ri; 3880 } 3881 if (userId != 0) { 3882 ri = new ResolveInfo(mResolveInfo); 3883 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3884 ri.activityInfo.applicationInfo = new ApplicationInfo( 3885 ri.activityInfo.applicationInfo); 3886 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3887 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3888 return ri; 3889 } 3890 return mResolveInfo; 3891 } 3892 } 3893 return null; 3894 } 3895 3896 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3897 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3898 final int N = query.size(); 3899 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3900 .get(userId); 3901 // Get the list of persistent preferred activities that handle the intent 3902 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3903 List<PersistentPreferredActivity> pprefs = ppir != null 3904 ? ppir.queryIntent(intent, resolvedType, 3905 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3906 : null; 3907 if (pprefs != null && pprefs.size() > 0) { 3908 final int M = pprefs.size(); 3909 for (int i=0; i<M; i++) { 3910 final PersistentPreferredActivity ppa = pprefs.get(i); 3911 if (DEBUG_PREFERRED || debug) { 3912 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3913 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3914 + "\n component=" + ppa.mComponent); 3915 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3916 } 3917 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3918 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3919 if (DEBUG_PREFERRED || debug) { 3920 Slog.v(TAG, "Found persistent preferred activity:"); 3921 if (ai != null) { 3922 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3923 } else { 3924 Slog.v(TAG, " null"); 3925 } 3926 } 3927 if (ai == null) { 3928 // This previously registered persistent preferred activity 3929 // component is no longer known. Ignore it and do NOT remove it. 3930 continue; 3931 } 3932 for (int j=0; j<N; j++) { 3933 final ResolveInfo ri = query.get(j); 3934 if (!ri.activityInfo.applicationInfo.packageName 3935 .equals(ai.applicationInfo.packageName)) { 3936 continue; 3937 } 3938 if (!ri.activityInfo.name.equals(ai.name)) { 3939 continue; 3940 } 3941 // Found a persistent preference that can handle the intent. 3942 if (DEBUG_PREFERRED || debug) { 3943 Slog.v(TAG, "Returning persistent preferred activity: " + 3944 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3945 } 3946 return ri; 3947 } 3948 } 3949 } 3950 return null; 3951 } 3952 3953 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3954 List<ResolveInfo> query, int priority, boolean always, 3955 boolean removeMatches, boolean debug, int userId) { 3956 if (!sUserManager.exists(userId)) return null; 3957 // writer 3958 synchronized (mPackages) { 3959 if (intent.getSelector() != null) { 3960 intent = intent.getSelector(); 3961 } 3962 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3963 3964 // Try to find a matching persistent preferred activity. 3965 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3966 debug, userId); 3967 3968 // If a persistent preferred activity matched, use it. 3969 if (pri != null) { 3970 return pri; 3971 } 3972 3973 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3974 // Get the list of preferred activities that handle the intent 3975 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3976 List<PreferredActivity> prefs = pir != null 3977 ? pir.queryIntent(intent, resolvedType, 3978 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3979 : null; 3980 if (prefs != null && prefs.size() > 0) { 3981 boolean changed = false; 3982 try { 3983 // First figure out how good the original match set is. 3984 // We will only allow preferred activities that came 3985 // from the same match quality. 3986 int match = 0; 3987 3988 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3989 3990 final int N = query.size(); 3991 for (int j=0; j<N; j++) { 3992 final ResolveInfo ri = query.get(j); 3993 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3994 + ": 0x" + Integer.toHexString(match)); 3995 if (ri.match > match) { 3996 match = ri.match; 3997 } 3998 } 3999 4000 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4001 + Integer.toHexString(match)); 4002 4003 match &= IntentFilter.MATCH_CATEGORY_MASK; 4004 final int M = prefs.size(); 4005 for (int i=0; i<M; i++) { 4006 final PreferredActivity pa = prefs.get(i); 4007 if (DEBUG_PREFERRED || debug) { 4008 Slog.v(TAG, "Checking PreferredActivity ds=" 4009 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4010 + "\n component=" + pa.mPref.mComponent); 4011 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4012 } 4013 if (pa.mPref.mMatch != match) { 4014 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4015 + Integer.toHexString(pa.mPref.mMatch)); 4016 continue; 4017 } 4018 // If it's not an "always" type preferred activity and that's what we're 4019 // looking for, skip it. 4020 if (always && !pa.mPref.mAlways) { 4021 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4022 continue; 4023 } 4024 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4025 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4026 if (DEBUG_PREFERRED || debug) { 4027 Slog.v(TAG, "Found preferred activity:"); 4028 if (ai != null) { 4029 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4030 } else { 4031 Slog.v(TAG, " null"); 4032 } 4033 } 4034 if (ai == null) { 4035 // This previously registered preferred activity 4036 // component is no longer known. Most likely an update 4037 // to the app was installed and in the new version this 4038 // component no longer exists. Clean it up by removing 4039 // it from the preferred activities list, and skip it. 4040 Slog.w(TAG, "Removing dangling preferred activity: " 4041 + pa.mPref.mComponent); 4042 pir.removeFilter(pa); 4043 changed = true; 4044 continue; 4045 } 4046 for (int j=0; j<N; j++) { 4047 final ResolveInfo ri = query.get(j); 4048 if (!ri.activityInfo.applicationInfo.packageName 4049 .equals(ai.applicationInfo.packageName)) { 4050 continue; 4051 } 4052 if (!ri.activityInfo.name.equals(ai.name)) { 4053 continue; 4054 } 4055 4056 if (removeMatches) { 4057 pir.removeFilter(pa); 4058 changed = true; 4059 if (DEBUG_PREFERRED) { 4060 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4061 } 4062 break; 4063 } 4064 4065 // Okay we found a previously set preferred or last chosen app. 4066 // If the result set is different from when this 4067 // was created, we need to clear it and re-ask the 4068 // user their preference, if we're looking for an "always" type entry. 4069 if (always && !pa.mPref.sameSet(query)) { 4070 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4071 + intent + " type " + resolvedType); 4072 if (DEBUG_PREFERRED) { 4073 Slog.v(TAG, "Removing preferred activity since set changed " 4074 + pa.mPref.mComponent); 4075 } 4076 pir.removeFilter(pa); 4077 // Re-add the filter as a "last chosen" entry (!always) 4078 PreferredActivity lastChosen = new PreferredActivity( 4079 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4080 pir.addFilter(lastChosen); 4081 changed = true; 4082 return null; 4083 } 4084 4085 // Yay! Either the set matched or we're looking for the last chosen 4086 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4087 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4088 return ri; 4089 } 4090 } 4091 } finally { 4092 if (changed) { 4093 if (DEBUG_PREFERRED) { 4094 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4095 } 4096 scheduleWritePackageRestrictionsLocked(userId); 4097 } 4098 } 4099 } 4100 } 4101 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4102 return null; 4103 } 4104 4105 /* 4106 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4107 */ 4108 @Override 4109 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4110 int targetUserId) { 4111 mContext.enforceCallingOrSelfPermission( 4112 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4113 List<CrossProfileIntentFilter> matches = 4114 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4115 if (matches != null) { 4116 int size = matches.size(); 4117 for (int i = 0; i < size; i++) { 4118 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4119 } 4120 } 4121 return false; 4122 } 4123 4124 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4125 String resolvedType, int userId) { 4126 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4127 if (resolver != null) { 4128 return resolver.queryIntent(intent, resolvedType, false, userId); 4129 } 4130 return null; 4131 } 4132 4133 @Override 4134 public List<ResolveInfo> queryIntentActivities(Intent intent, 4135 String resolvedType, int flags, int userId) { 4136 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4137 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4138 ComponentName comp = intent.getComponent(); 4139 if (comp == null) { 4140 if (intent.getSelector() != null) { 4141 intent = intent.getSelector(); 4142 comp = intent.getComponent(); 4143 } 4144 } 4145 4146 if (comp != null) { 4147 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4148 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4149 if (ai != null) { 4150 final ResolveInfo ri = new ResolveInfo(); 4151 ri.activityInfo = ai; 4152 list.add(ri); 4153 } 4154 return list; 4155 } 4156 4157 // reader 4158 synchronized (mPackages) { 4159 final String pkgName = intent.getPackage(); 4160 if (pkgName == null) { 4161 List<CrossProfileIntentFilter> matchingFilters = 4162 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4163 // Check for results that need to skip the current profile. 4164 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4165 resolvedType, flags, userId); 4166 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4167 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4168 result.add(resolveInfo); 4169 return filterIfNotPrimaryUser(result, userId); 4170 } 4171 4172 // Check for results in the current profile. 4173 List<ResolveInfo> result = mActivities.queryIntent( 4174 intent, resolvedType, flags, userId); 4175 4176 // Check for cross profile results. 4177 resolveInfo = queryCrossProfileIntents( 4178 matchingFilters, intent, resolvedType, flags, userId); 4179 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4180 result.add(resolveInfo); 4181 Collections.sort(result, mResolvePrioritySorter); 4182 } 4183 result = filterIfNotPrimaryUser(result, userId); 4184 if (result.size() > 1 && hasWebURI(intent)) { 4185 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4186 } 4187 return result; 4188 } 4189 final PackageParser.Package pkg = mPackages.get(pkgName); 4190 if (pkg != null) { 4191 return filterIfNotPrimaryUser( 4192 mActivities.queryIntentForPackage( 4193 intent, resolvedType, flags, pkg.activities, userId), 4194 userId); 4195 } 4196 return new ArrayList<ResolveInfo>(); 4197 } 4198 } 4199 4200 private boolean isUserEnabled(int userId) { 4201 long callingId = Binder.clearCallingIdentity(); 4202 try { 4203 UserInfo userInfo = sUserManager.getUserInfo(userId); 4204 return userInfo != null && userInfo.isEnabled(); 4205 } finally { 4206 Binder.restoreCallingIdentity(callingId); 4207 } 4208 } 4209 4210 /** 4211 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4212 * 4213 * @return filtered list 4214 */ 4215 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4216 if (userId == UserHandle.USER_OWNER) { 4217 return resolveInfos; 4218 } 4219 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4220 ResolveInfo info = resolveInfos.get(i); 4221 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4222 resolveInfos.remove(i); 4223 } 4224 } 4225 return resolveInfos; 4226 } 4227 4228 private static boolean hasWebURI(Intent intent) { 4229 if (intent.getData() == null) { 4230 return false; 4231 } 4232 final String scheme = intent.getScheme(); 4233 if (TextUtils.isEmpty(scheme)) { 4234 return false; 4235 } 4236 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4237 } 4238 4239 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4240 int flags, List<ResolveInfo> candidates) { 4241 if (DEBUG_PREFERRED) { 4242 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4243 candidates.size()); 4244 } 4245 4246 final int userId = UserHandle.getCallingUserId(); 4247 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4248 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4249 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4250 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4251 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4252 4253 synchronized (mPackages) { 4254 final int count = candidates.size(); 4255 // First, try to use the domain prefered App. Partition the candidates into four lists: 4256 // one for the final results, one for the "do not use ever", one for "undefined status" 4257 // and finally one for "Browser App type". 4258 for (int n=0; n<count; n++) { 4259 ResolveInfo info = candidates.get(n); 4260 String packageName = info.activityInfo.packageName; 4261 PackageSetting ps = mSettings.mPackages.get(packageName); 4262 if (ps != null) { 4263 // Add to the special match all list (Browser use case) 4264 if (info.handleAllWebDataURI) { 4265 matchAllList.add(info); 4266 continue; 4267 } 4268 // Try to get the status from User settings first 4269 int status = getDomainVerificationStatusLPr(ps, userId); 4270 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4271 alwaysList.add(info); 4272 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4273 neverList.add(info); 4274 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4275 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4276 undefinedList.add(info); 4277 } 4278 } 4279 } 4280 // First try to add the "always" if there is any 4281 if (alwaysList.size() > 0) { 4282 result.addAll(alwaysList); 4283 } else { 4284 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4285 result.addAll(undefinedList); 4286 // Also add Browsers (all of them or only the default one) 4287 if ((flags & MATCH_ALL) != 0) { 4288 result.addAll(matchAllList); 4289 } else { 4290 // Try to add the Default Browser if we can 4291 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4292 UserHandle.myUserId()); 4293 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4294 boolean defaultBrowserFound = false; 4295 final int browserCount = matchAllList.size(); 4296 for (int n=0; n<browserCount; n++) { 4297 ResolveInfo browser = matchAllList.get(n); 4298 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4299 result.add(browser); 4300 defaultBrowserFound = true; 4301 break; 4302 } 4303 } 4304 if (!defaultBrowserFound) { 4305 result.addAll(matchAllList); 4306 } 4307 } else { 4308 result.addAll(matchAllList); 4309 } 4310 } 4311 4312 // If there is nothing selected, add all candidates and remove the ones that the User 4313 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4314 if (result.size() == 0) { 4315 result.addAll(candidates); 4316 result.removeAll(neverList); 4317 } 4318 } 4319 } 4320 if (DEBUG_PREFERRED) { 4321 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4322 result.size()); 4323 } 4324 return result; 4325 } 4326 4327 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4328 int status = ps.getDomainVerificationStatusForUser(userId); 4329 // if none available, get the master status 4330 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4331 if (ps.getIntentFilterVerificationInfo() != null) { 4332 status = ps.getIntentFilterVerificationInfo().getStatus(); 4333 } 4334 } 4335 return status; 4336 } 4337 4338 private ResolveInfo querySkipCurrentProfileIntents( 4339 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4340 int flags, int sourceUserId) { 4341 if (matchingFilters != null) { 4342 int size = matchingFilters.size(); 4343 for (int i = 0; i < size; i ++) { 4344 CrossProfileIntentFilter filter = matchingFilters.get(i); 4345 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4346 // Checking if there are activities in the target user that can handle the 4347 // intent. 4348 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4349 flags, sourceUserId); 4350 if (resolveInfo != null) { 4351 return resolveInfo; 4352 } 4353 } 4354 } 4355 } 4356 return null; 4357 } 4358 4359 // Return matching ResolveInfo if any for skip current profile intent filters. 4360 private ResolveInfo queryCrossProfileIntents( 4361 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4362 int flags, int sourceUserId) { 4363 if (matchingFilters != null) { 4364 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4365 // match the same intent. For performance reasons, it is better not to 4366 // run queryIntent twice for the same userId 4367 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4368 int size = matchingFilters.size(); 4369 for (int i = 0; i < size; i++) { 4370 CrossProfileIntentFilter filter = matchingFilters.get(i); 4371 int targetUserId = filter.getTargetUserId(); 4372 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4373 && !alreadyTriedUserIds.get(targetUserId)) { 4374 // Checking if there are activities in the target user that can handle the 4375 // intent. 4376 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4377 flags, sourceUserId); 4378 if (resolveInfo != null) return resolveInfo; 4379 alreadyTriedUserIds.put(targetUserId, true); 4380 } 4381 } 4382 } 4383 return null; 4384 } 4385 4386 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4387 String resolvedType, int flags, int sourceUserId) { 4388 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4389 resolvedType, flags, filter.getTargetUserId()); 4390 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4391 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4392 } 4393 return null; 4394 } 4395 4396 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4397 int sourceUserId, int targetUserId) { 4398 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4399 String className; 4400 if (targetUserId == UserHandle.USER_OWNER) { 4401 className = FORWARD_INTENT_TO_USER_OWNER; 4402 } else { 4403 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4404 } 4405 ComponentName forwardingActivityComponentName = new ComponentName( 4406 mAndroidApplication.packageName, className); 4407 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4408 sourceUserId); 4409 if (targetUserId == UserHandle.USER_OWNER) { 4410 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4411 forwardingResolveInfo.noResourceId = true; 4412 } 4413 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4414 forwardingResolveInfo.priority = 0; 4415 forwardingResolveInfo.preferredOrder = 0; 4416 forwardingResolveInfo.match = 0; 4417 forwardingResolveInfo.isDefault = true; 4418 forwardingResolveInfo.filter = filter; 4419 forwardingResolveInfo.targetUserId = targetUserId; 4420 return forwardingResolveInfo; 4421 } 4422 4423 @Override 4424 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4425 Intent[] specifics, String[] specificTypes, Intent intent, 4426 String resolvedType, int flags, int userId) { 4427 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4428 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4429 false, "query intent activity options"); 4430 final String resultsAction = intent.getAction(); 4431 4432 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4433 | PackageManager.GET_RESOLVED_FILTER, userId); 4434 4435 if (DEBUG_INTENT_MATCHING) { 4436 Log.v(TAG, "Query " + intent + ": " + results); 4437 } 4438 4439 int specificsPos = 0; 4440 int N; 4441 4442 // todo: note that the algorithm used here is O(N^2). This 4443 // isn't a problem in our current environment, but if we start running 4444 // into situations where we have more than 5 or 10 matches then this 4445 // should probably be changed to something smarter... 4446 4447 // First we go through and resolve each of the specific items 4448 // that were supplied, taking care of removing any corresponding 4449 // duplicate items in the generic resolve list. 4450 if (specifics != null) { 4451 for (int i=0; i<specifics.length; i++) { 4452 final Intent sintent = specifics[i]; 4453 if (sintent == null) { 4454 continue; 4455 } 4456 4457 if (DEBUG_INTENT_MATCHING) { 4458 Log.v(TAG, "Specific #" + i + ": " + sintent); 4459 } 4460 4461 String action = sintent.getAction(); 4462 if (resultsAction != null && resultsAction.equals(action)) { 4463 // If this action was explicitly requested, then don't 4464 // remove things that have it. 4465 action = null; 4466 } 4467 4468 ResolveInfo ri = null; 4469 ActivityInfo ai = null; 4470 4471 ComponentName comp = sintent.getComponent(); 4472 if (comp == null) { 4473 ri = resolveIntent( 4474 sintent, 4475 specificTypes != null ? specificTypes[i] : null, 4476 flags, userId); 4477 if (ri == null) { 4478 continue; 4479 } 4480 if (ri == mResolveInfo) { 4481 // ACK! Must do something better with this. 4482 } 4483 ai = ri.activityInfo; 4484 comp = new ComponentName(ai.applicationInfo.packageName, 4485 ai.name); 4486 } else { 4487 ai = getActivityInfo(comp, flags, userId); 4488 if (ai == null) { 4489 continue; 4490 } 4491 } 4492 4493 // Look for any generic query activities that are duplicates 4494 // of this specific one, and remove them from the results. 4495 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4496 N = results.size(); 4497 int j; 4498 for (j=specificsPos; j<N; j++) { 4499 ResolveInfo sri = results.get(j); 4500 if ((sri.activityInfo.name.equals(comp.getClassName()) 4501 && sri.activityInfo.applicationInfo.packageName.equals( 4502 comp.getPackageName())) 4503 || (action != null && sri.filter.matchAction(action))) { 4504 results.remove(j); 4505 if (DEBUG_INTENT_MATCHING) Log.v( 4506 TAG, "Removing duplicate item from " + j 4507 + " due to specific " + specificsPos); 4508 if (ri == null) { 4509 ri = sri; 4510 } 4511 j--; 4512 N--; 4513 } 4514 } 4515 4516 // Add this specific item to its proper place. 4517 if (ri == null) { 4518 ri = new ResolveInfo(); 4519 ri.activityInfo = ai; 4520 } 4521 results.add(specificsPos, ri); 4522 ri.specificIndex = i; 4523 specificsPos++; 4524 } 4525 } 4526 4527 // Now we go through the remaining generic results and remove any 4528 // duplicate actions that are found here. 4529 N = results.size(); 4530 for (int i=specificsPos; i<N-1; i++) { 4531 final ResolveInfo rii = results.get(i); 4532 if (rii.filter == null) { 4533 continue; 4534 } 4535 4536 // Iterate over all of the actions of this result's intent 4537 // filter... typically this should be just one. 4538 final Iterator<String> it = rii.filter.actionsIterator(); 4539 if (it == null) { 4540 continue; 4541 } 4542 while (it.hasNext()) { 4543 final String action = it.next(); 4544 if (resultsAction != null && resultsAction.equals(action)) { 4545 // If this action was explicitly requested, then don't 4546 // remove things that have it. 4547 continue; 4548 } 4549 for (int j=i+1; j<N; j++) { 4550 final ResolveInfo rij = results.get(j); 4551 if (rij.filter != null && rij.filter.hasAction(action)) { 4552 results.remove(j); 4553 if (DEBUG_INTENT_MATCHING) Log.v( 4554 TAG, "Removing duplicate item from " + j 4555 + " due to action " + action + " at " + i); 4556 j--; 4557 N--; 4558 } 4559 } 4560 } 4561 4562 // If the caller didn't request filter information, drop it now 4563 // so we don't have to marshall/unmarshall it. 4564 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4565 rii.filter = null; 4566 } 4567 } 4568 4569 // Filter out the caller activity if so requested. 4570 if (caller != null) { 4571 N = results.size(); 4572 for (int i=0; i<N; i++) { 4573 ActivityInfo ainfo = results.get(i).activityInfo; 4574 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4575 && caller.getClassName().equals(ainfo.name)) { 4576 results.remove(i); 4577 break; 4578 } 4579 } 4580 } 4581 4582 // If the caller didn't request filter information, 4583 // drop them now so we don't have to 4584 // marshall/unmarshall it. 4585 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4586 N = results.size(); 4587 for (int i=0; i<N; i++) { 4588 results.get(i).filter = null; 4589 } 4590 } 4591 4592 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4593 return results; 4594 } 4595 4596 @Override 4597 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4598 int userId) { 4599 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4600 ComponentName comp = intent.getComponent(); 4601 if (comp == null) { 4602 if (intent.getSelector() != null) { 4603 intent = intent.getSelector(); 4604 comp = intent.getComponent(); 4605 } 4606 } 4607 if (comp != null) { 4608 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4609 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4610 if (ai != null) { 4611 ResolveInfo ri = new ResolveInfo(); 4612 ri.activityInfo = ai; 4613 list.add(ri); 4614 } 4615 return list; 4616 } 4617 4618 // reader 4619 synchronized (mPackages) { 4620 String pkgName = intent.getPackage(); 4621 if (pkgName == null) { 4622 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4623 } 4624 final PackageParser.Package pkg = mPackages.get(pkgName); 4625 if (pkg != null) { 4626 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4627 userId); 4628 } 4629 return null; 4630 } 4631 } 4632 4633 @Override 4634 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4635 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4636 if (!sUserManager.exists(userId)) return null; 4637 if (query != null) { 4638 if (query.size() >= 1) { 4639 // If there is more than one service with the same priority, 4640 // just arbitrarily pick the first one. 4641 return query.get(0); 4642 } 4643 } 4644 return null; 4645 } 4646 4647 @Override 4648 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4649 int userId) { 4650 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4651 ComponentName comp = intent.getComponent(); 4652 if (comp == null) { 4653 if (intent.getSelector() != null) { 4654 intent = intent.getSelector(); 4655 comp = intent.getComponent(); 4656 } 4657 } 4658 if (comp != null) { 4659 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4660 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4661 if (si != null) { 4662 final ResolveInfo ri = new ResolveInfo(); 4663 ri.serviceInfo = si; 4664 list.add(ri); 4665 } 4666 return list; 4667 } 4668 4669 // reader 4670 synchronized (mPackages) { 4671 String pkgName = intent.getPackage(); 4672 if (pkgName == null) { 4673 return mServices.queryIntent(intent, resolvedType, flags, userId); 4674 } 4675 final PackageParser.Package pkg = mPackages.get(pkgName); 4676 if (pkg != null) { 4677 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4678 userId); 4679 } 4680 return null; 4681 } 4682 } 4683 4684 @Override 4685 public List<ResolveInfo> queryIntentContentProviders( 4686 Intent intent, String resolvedType, int flags, int userId) { 4687 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4688 ComponentName comp = intent.getComponent(); 4689 if (comp == null) { 4690 if (intent.getSelector() != null) { 4691 intent = intent.getSelector(); 4692 comp = intent.getComponent(); 4693 } 4694 } 4695 if (comp != null) { 4696 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4697 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4698 if (pi != null) { 4699 final ResolveInfo ri = new ResolveInfo(); 4700 ri.providerInfo = pi; 4701 list.add(ri); 4702 } 4703 return list; 4704 } 4705 4706 // reader 4707 synchronized (mPackages) { 4708 String pkgName = intent.getPackage(); 4709 if (pkgName == null) { 4710 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4711 } 4712 final PackageParser.Package pkg = mPackages.get(pkgName); 4713 if (pkg != null) { 4714 return mProviders.queryIntentForPackage( 4715 intent, resolvedType, flags, pkg.providers, userId); 4716 } 4717 return null; 4718 } 4719 } 4720 4721 @Override 4722 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4723 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4724 4725 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4726 4727 // writer 4728 synchronized (mPackages) { 4729 ArrayList<PackageInfo> list; 4730 if (listUninstalled) { 4731 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4732 for (PackageSetting ps : mSettings.mPackages.values()) { 4733 PackageInfo pi; 4734 if (ps.pkg != null) { 4735 pi = generatePackageInfo(ps.pkg, flags, userId); 4736 } else { 4737 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4738 } 4739 if (pi != null) { 4740 list.add(pi); 4741 } 4742 } 4743 } else { 4744 list = new ArrayList<PackageInfo>(mPackages.size()); 4745 for (PackageParser.Package p : mPackages.values()) { 4746 PackageInfo pi = generatePackageInfo(p, flags, userId); 4747 if (pi != null) { 4748 list.add(pi); 4749 } 4750 } 4751 } 4752 4753 return new ParceledListSlice<PackageInfo>(list); 4754 } 4755 } 4756 4757 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4758 String[] permissions, boolean[] tmp, int flags, int userId) { 4759 int numMatch = 0; 4760 final PermissionsState permissionsState = ps.getPermissionsState(); 4761 for (int i=0; i<permissions.length; i++) { 4762 final String permission = permissions[i]; 4763 if (permissionsState.hasPermission(permission, userId)) { 4764 tmp[i] = true; 4765 numMatch++; 4766 } else { 4767 tmp[i] = false; 4768 } 4769 } 4770 if (numMatch == 0) { 4771 return; 4772 } 4773 PackageInfo pi; 4774 if (ps.pkg != null) { 4775 pi = generatePackageInfo(ps.pkg, flags, userId); 4776 } else { 4777 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4778 } 4779 // The above might return null in cases of uninstalled apps or install-state 4780 // skew across users/profiles. 4781 if (pi != null) { 4782 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4783 if (numMatch == permissions.length) { 4784 pi.requestedPermissions = permissions; 4785 } else { 4786 pi.requestedPermissions = new String[numMatch]; 4787 numMatch = 0; 4788 for (int i=0; i<permissions.length; i++) { 4789 if (tmp[i]) { 4790 pi.requestedPermissions[numMatch] = permissions[i]; 4791 numMatch++; 4792 } 4793 } 4794 } 4795 } 4796 list.add(pi); 4797 } 4798 } 4799 4800 @Override 4801 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4802 String[] permissions, int flags, int userId) { 4803 if (!sUserManager.exists(userId)) return null; 4804 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4805 4806 // writer 4807 synchronized (mPackages) { 4808 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4809 boolean[] tmpBools = new boolean[permissions.length]; 4810 if (listUninstalled) { 4811 for (PackageSetting ps : mSettings.mPackages.values()) { 4812 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4813 } 4814 } else { 4815 for (PackageParser.Package pkg : mPackages.values()) { 4816 PackageSetting ps = (PackageSetting)pkg.mExtras; 4817 if (ps != null) { 4818 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4819 userId); 4820 } 4821 } 4822 } 4823 4824 return new ParceledListSlice<PackageInfo>(list); 4825 } 4826 } 4827 4828 @Override 4829 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4830 if (!sUserManager.exists(userId)) return null; 4831 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4832 4833 // writer 4834 synchronized (mPackages) { 4835 ArrayList<ApplicationInfo> list; 4836 if (listUninstalled) { 4837 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4838 for (PackageSetting ps : mSettings.mPackages.values()) { 4839 ApplicationInfo ai; 4840 if (ps.pkg != null) { 4841 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4842 ps.readUserState(userId), userId); 4843 } else { 4844 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4845 } 4846 if (ai != null) { 4847 list.add(ai); 4848 } 4849 } 4850 } else { 4851 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4852 for (PackageParser.Package p : mPackages.values()) { 4853 if (p.mExtras != null) { 4854 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4855 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4856 if (ai != null) { 4857 list.add(ai); 4858 } 4859 } 4860 } 4861 } 4862 4863 return new ParceledListSlice<ApplicationInfo>(list); 4864 } 4865 } 4866 4867 public List<ApplicationInfo> getPersistentApplications(int flags) { 4868 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4869 4870 // reader 4871 synchronized (mPackages) { 4872 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4873 final int userId = UserHandle.getCallingUserId(); 4874 while (i.hasNext()) { 4875 final PackageParser.Package p = i.next(); 4876 if (p.applicationInfo != null 4877 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4878 && (!mSafeMode || isSystemApp(p))) { 4879 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4880 if (ps != null) { 4881 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4882 ps.readUserState(userId), userId); 4883 if (ai != null) { 4884 finalList.add(ai); 4885 } 4886 } 4887 } 4888 } 4889 } 4890 4891 return finalList; 4892 } 4893 4894 @Override 4895 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4896 if (!sUserManager.exists(userId)) return null; 4897 // reader 4898 synchronized (mPackages) { 4899 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4900 PackageSetting ps = provider != null 4901 ? mSettings.mPackages.get(provider.owner.packageName) 4902 : null; 4903 return ps != null 4904 && mSettings.isEnabledLPr(provider.info, flags, userId) 4905 && (!mSafeMode || (provider.info.applicationInfo.flags 4906 &ApplicationInfo.FLAG_SYSTEM) != 0) 4907 ? PackageParser.generateProviderInfo(provider, flags, 4908 ps.readUserState(userId), userId) 4909 : null; 4910 } 4911 } 4912 4913 /** 4914 * @deprecated 4915 */ 4916 @Deprecated 4917 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4918 // reader 4919 synchronized (mPackages) { 4920 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4921 .entrySet().iterator(); 4922 final int userId = UserHandle.getCallingUserId(); 4923 while (i.hasNext()) { 4924 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4925 PackageParser.Provider p = entry.getValue(); 4926 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4927 4928 if (ps != null && p.syncable 4929 && (!mSafeMode || (p.info.applicationInfo.flags 4930 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4931 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4932 ps.readUserState(userId), userId); 4933 if (info != null) { 4934 outNames.add(entry.getKey()); 4935 outInfo.add(info); 4936 } 4937 } 4938 } 4939 } 4940 } 4941 4942 @Override 4943 public List<ProviderInfo> queryContentProviders(String processName, 4944 int uid, int flags) { 4945 ArrayList<ProviderInfo> finalList = null; 4946 // reader 4947 synchronized (mPackages) { 4948 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4949 final int userId = processName != null ? 4950 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4951 while (i.hasNext()) { 4952 final PackageParser.Provider p = i.next(); 4953 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4954 if (ps != null && p.info.authority != null 4955 && (processName == null 4956 || (p.info.processName.equals(processName) 4957 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4958 && mSettings.isEnabledLPr(p.info, flags, userId) 4959 && (!mSafeMode 4960 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4961 if (finalList == null) { 4962 finalList = new ArrayList<ProviderInfo>(3); 4963 } 4964 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4965 ps.readUserState(userId), userId); 4966 if (info != null) { 4967 finalList.add(info); 4968 } 4969 } 4970 } 4971 } 4972 4973 if (finalList != null) { 4974 Collections.sort(finalList, mProviderInitOrderSorter); 4975 } 4976 4977 return finalList; 4978 } 4979 4980 @Override 4981 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4982 int flags) { 4983 // reader 4984 synchronized (mPackages) { 4985 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4986 return PackageParser.generateInstrumentationInfo(i, flags); 4987 } 4988 } 4989 4990 @Override 4991 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4992 int flags) { 4993 ArrayList<InstrumentationInfo> finalList = 4994 new ArrayList<InstrumentationInfo>(); 4995 4996 // reader 4997 synchronized (mPackages) { 4998 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4999 while (i.hasNext()) { 5000 final PackageParser.Instrumentation p = i.next(); 5001 if (targetPackage == null 5002 || targetPackage.equals(p.info.targetPackage)) { 5003 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5004 flags); 5005 if (ii != null) { 5006 finalList.add(ii); 5007 } 5008 } 5009 } 5010 } 5011 5012 return finalList; 5013 } 5014 5015 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5016 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5017 if (overlays == null) { 5018 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5019 return; 5020 } 5021 for (PackageParser.Package opkg : overlays.values()) { 5022 // Not much to do if idmap fails: we already logged the error 5023 // and we certainly don't want to abort installation of pkg simply 5024 // because an overlay didn't fit properly. For these reasons, 5025 // ignore the return value of createIdmapForPackagePairLI. 5026 createIdmapForPackagePairLI(pkg, opkg); 5027 } 5028 } 5029 5030 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5031 PackageParser.Package opkg) { 5032 if (!opkg.mTrustedOverlay) { 5033 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5034 opkg.baseCodePath + ": overlay not trusted"); 5035 return false; 5036 } 5037 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5038 if (overlaySet == null) { 5039 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5040 opkg.baseCodePath + " but target package has no known overlays"); 5041 return false; 5042 } 5043 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5044 // TODO: generate idmap for split APKs 5045 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5046 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5047 + opkg.baseCodePath); 5048 return false; 5049 } 5050 PackageParser.Package[] overlayArray = 5051 overlaySet.values().toArray(new PackageParser.Package[0]); 5052 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5053 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5054 return p1.mOverlayPriority - p2.mOverlayPriority; 5055 } 5056 }; 5057 Arrays.sort(overlayArray, cmp); 5058 5059 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5060 int i = 0; 5061 for (PackageParser.Package p : overlayArray) { 5062 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5063 } 5064 return true; 5065 } 5066 5067 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5068 final File[] files = dir.listFiles(); 5069 if (ArrayUtils.isEmpty(files)) { 5070 Log.d(TAG, "No files in app dir " + dir); 5071 return; 5072 } 5073 5074 if (DEBUG_PACKAGE_SCANNING) { 5075 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5076 + " flags=0x" + Integer.toHexString(parseFlags)); 5077 } 5078 5079 for (File file : files) { 5080 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5081 && !PackageInstallerService.isStageName(file.getName()); 5082 if (!isPackage) { 5083 // Ignore entries which are not packages 5084 continue; 5085 } 5086 try { 5087 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5088 scanFlags, currentTime, null); 5089 } catch (PackageManagerException e) { 5090 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5091 5092 // Delete invalid userdata apps 5093 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5094 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5095 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5096 if (file.isDirectory()) { 5097 mInstaller.rmPackageDir(file.getAbsolutePath()); 5098 } else { 5099 file.delete(); 5100 } 5101 } 5102 } 5103 } 5104 } 5105 5106 private static File getSettingsProblemFile() { 5107 File dataDir = Environment.getDataDirectory(); 5108 File systemDir = new File(dataDir, "system"); 5109 File fname = new File(systemDir, "uiderrors.txt"); 5110 return fname; 5111 } 5112 5113 static void reportSettingsProblem(int priority, String msg) { 5114 logCriticalInfo(priority, msg); 5115 } 5116 5117 static void logCriticalInfo(int priority, String msg) { 5118 Slog.println(priority, TAG, msg); 5119 EventLogTags.writePmCriticalInfo(msg); 5120 try { 5121 File fname = getSettingsProblemFile(); 5122 FileOutputStream out = new FileOutputStream(fname, true); 5123 PrintWriter pw = new FastPrintWriter(out); 5124 SimpleDateFormat formatter = new SimpleDateFormat(); 5125 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5126 pw.println(dateString + ": " + msg); 5127 pw.close(); 5128 FileUtils.setPermissions( 5129 fname.toString(), 5130 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5131 -1, -1); 5132 } catch (java.io.IOException e) { 5133 } 5134 } 5135 5136 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5137 PackageParser.Package pkg, File srcFile, int parseFlags) 5138 throws PackageManagerException { 5139 if (ps != null 5140 && ps.codePath.equals(srcFile) 5141 && ps.timeStamp == srcFile.lastModified() 5142 && !isCompatSignatureUpdateNeeded(pkg) 5143 && !isRecoverSignatureUpdateNeeded(pkg)) { 5144 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5145 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5146 ArraySet<PublicKey> signingKs; 5147 synchronized (mPackages) { 5148 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5149 } 5150 if (ps.signatures.mSignatures != null 5151 && ps.signatures.mSignatures.length != 0 5152 && signingKs != null) { 5153 // Optimization: reuse the existing cached certificates 5154 // if the package appears to be unchanged. 5155 pkg.mSignatures = ps.signatures.mSignatures; 5156 pkg.mSigningKeys = signingKs; 5157 return; 5158 } 5159 5160 Slog.w(TAG, "PackageSetting for " + ps.name 5161 + " is missing signatures. Collecting certs again to recover them."); 5162 } else { 5163 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5164 } 5165 5166 try { 5167 pp.collectCertificates(pkg, parseFlags); 5168 pp.collectManifestDigest(pkg); 5169 } catch (PackageParserException e) { 5170 throw PackageManagerException.from(e); 5171 } 5172 } 5173 5174 /* 5175 * Scan a package and return the newly parsed package. 5176 * Returns null in case of errors and the error code is stored in mLastScanError 5177 */ 5178 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5179 long currentTime, UserHandle user) throws PackageManagerException { 5180 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5181 parseFlags |= mDefParseFlags; 5182 PackageParser pp = new PackageParser(); 5183 pp.setSeparateProcesses(mSeparateProcesses); 5184 pp.setOnlyCoreApps(mOnlyCore); 5185 pp.setDisplayMetrics(mMetrics); 5186 5187 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5188 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5189 } 5190 5191 final PackageParser.Package pkg; 5192 try { 5193 pkg = pp.parsePackage(scanFile, parseFlags); 5194 } catch (PackageParserException e) { 5195 throw PackageManagerException.from(e); 5196 } 5197 5198 PackageSetting ps = null; 5199 PackageSetting updatedPkg; 5200 // reader 5201 synchronized (mPackages) { 5202 // Look to see if we already know about this package. 5203 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5204 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5205 // This package has been renamed to its original name. Let's 5206 // use that. 5207 ps = mSettings.peekPackageLPr(oldName); 5208 } 5209 // If there was no original package, see one for the real package name. 5210 if (ps == null) { 5211 ps = mSettings.peekPackageLPr(pkg.packageName); 5212 } 5213 // Check to see if this package could be hiding/updating a system 5214 // package. Must look for it either under the original or real 5215 // package name depending on our state. 5216 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5217 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5218 } 5219 boolean updatedPkgBetter = false; 5220 // First check if this is a system package that may involve an update 5221 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5222 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5223 // it needs to drop FLAG_PRIVILEGED. 5224 if (locationIsPrivileged(scanFile)) { 5225 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5226 } else { 5227 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5228 } 5229 5230 if (ps != null && !ps.codePath.equals(scanFile)) { 5231 // The path has changed from what was last scanned... check the 5232 // version of the new path against what we have stored to determine 5233 // what to do. 5234 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5235 if (pkg.mVersionCode <= ps.versionCode) { 5236 // The system package has been updated and the code path does not match 5237 // Ignore entry. Skip it. 5238 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5239 + " ignored: updated version " + ps.versionCode 5240 + " better than this " + pkg.mVersionCode); 5241 if (!updatedPkg.codePath.equals(scanFile)) { 5242 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5243 + ps.name + " changing from " + updatedPkg.codePathString 5244 + " to " + scanFile); 5245 updatedPkg.codePath = scanFile; 5246 updatedPkg.codePathString = scanFile.toString(); 5247 updatedPkg.resourcePath = scanFile; 5248 updatedPkg.resourcePathString = scanFile.toString(); 5249 } 5250 updatedPkg.pkg = pkg; 5251 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5252 } else { 5253 // The current app on the system partition is better than 5254 // what we have updated to on the data partition; switch 5255 // back to the system partition version. 5256 // At this point, its safely assumed that package installation for 5257 // apps in system partition will go through. If not there won't be a working 5258 // version of the app 5259 // writer 5260 synchronized (mPackages) { 5261 // Just remove the loaded entries from package lists. 5262 mPackages.remove(ps.name); 5263 } 5264 5265 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5266 + " reverting from " + ps.codePathString 5267 + ": new version " + pkg.mVersionCode 5268 + " better than installed " + ps.versionCode); 5269 5270 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5271 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5272 synchronized (mInstallLock) { 5273 args.cleanUpResourcesLI(); 5274 } 5275 synchronized (mPackages) { 5276 mSettings.enableSystemPackageLPw(ps.name); 5277 } 5278 updatedPkgBetter = true; 5279 } 5280 } 5281 } 5282 5283 if (updatedPkg != null) { 5284 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5285 // initially 5286 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5287 5288 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5289 // flag set initially 5290 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5291 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5292 } 5293 } 5294 5295 // Verify certificates against what was last scanned 5296 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5297 5298 /* 5299 * A new system app appeared, but we already had a non-system one of the 5300 * same name installed earlier. 5301 */ 5302 boolean shouldHideSystemApp = false; 5303 if (updatedPkg == null && ps != null 5304 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5305 /* 5306 * Check to make sure the signatures match first. If they don't, 5307 * wipe the installed application and its data. 5308 */ 5309 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5310 != PackageManager.SIGNATURE_MATCH) { 5311 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5312 + " signatures don't match existing userdata copy; removing"); 5313 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5314 ps = null; 5315 } else { 5316 /* 5317 * If the newly-added system app is an older version than the 5318 * already installed version, hide it. It will be scanned later 5319 * and re-added like an update. 5320 */ 5321 if (pkg.mVersionCode <= ps.versionCode) { 5322 shouldHideSystemApp = true; 5323 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5324 + " but new version " + pkg.mVersionCode + " better than installed " 5325 + ps.versionCode + "; hiding system"); 5326 } else { 5327 /* 5328 * The newly found system app is a newer version that the 5329 * one previously installed. Simply remove the 5330 * already-installed application and replace it with our own 5331 * while keeping the application data. 5332 */ 5333 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5334 + " reverting from " + ps.codePathString + ": new version " 5335 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5336 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5337 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5338 synchronized (mInstallLock) { 5339 args.cleanUpResourcesLI(); 5340 } 5341 } 5342 } 5343 } 5344 5345 // The apk is forward locked (not public) if its code and resources 5346 // are kept in different files. (except for app in either system or 5347 // vendor path). 5348 // TODO grab this value from PackageSettings 5349 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5350 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5351 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5352 } 5353 } 5354 5355 // TODO: extend to support forward-locked splits 5356 String resourcePath = null; 5357 String baseResourcePath = null; 5358 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5359 if (ps != null && ps.resourcePathString != null) { 5360 resourcePath = ps.resourcePathString; 5361 baseResourcePath = ps.resourcePathString; 5362 } else { 5363 // Should not happen at all. Just log an error. 5364 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5365 } 5366 } else { 5367 resourcePath = pkg.codePath; 5368 baseResourcePath = pkg.baseCodePath; 5369 } 5370 5371 // Set application objects path explicitly. 5372 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5373 pkg.applicationInfo.setCodePath(pkg.codePath); 5374 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5375 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5376 pkg.applicationInfo.setResourcePath(resourcePath); 5377 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5378 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5379 5380 // Note that we invoke the following method only if we are about to unpack an application 5381 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5382 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5383 5384 /* 5385 * If the system app should be overridden by a previously installed 5386 * data, hide the system app now and let the /data/app scan pick it up 5387 * again. 5388 */ 5389 if (shouldHideSystemApp) { 5390 synchronized (mPackages) { 5391 /* 5392 * We have to grant systems permissions before we hide, because 5393 * grantPermissions will assume the package update is trying to 5394 * expand its permissions. 5395 */ 5396 grantPermissionsLPw(pkg, true, pkg.packageName); 5397 mSettings.disableSystemPackageLPw(pkg.packageName); 5398 } 5399 } 5400 5401 return scannedPkg; 5402 } 5403 5404 private static String fixProcessName(String defProcessName, 5405 String processName, int uid) { 5406 if (processName == null) { 5407 return defProcessName; 5408 } 5409 return processName; 5410 } 5411 5412 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5413 throws PackageManagerException { 5414 if (pkgSetting.signatures.mSignatures != null) { 5415 // Already existing package. Make sure signatures match 5416 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5417 == PackageManager.SIGNATURE_MATCH; 5418 if (!match) { 5419 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5420 == PackageManager.SIGNATURE_MATCH; 5421 } 5422 if (!match) { 5423 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5424 == PackageManager.SIGNATURE_MATCH; 5425 } 5426 if (!match) { 5427 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5428 + pkg.packageName + " signatures do not match the " 5429 + "previously installed version; ignoring!"); 5430 } 5431 } 5432 5433 // Check for shared user signatures 5434 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5435 // Already existing package. Make sure signatures match 5436 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5437 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5438 if (!match) { 5439 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5440 == PackageManager.SIGNATURE_MATCH; 5441 } 5442 if (!match) { 5443 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5444 == PackageManager.SIGNATURE_MATCH; 5445 } 5446 if (!match) { 5447 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5448 "Package " + pkg.packageName 5449 + " has no signatures that match those in shared user " 5450 + pkgSetting.sharedUser.name + "; ignoring!"); 5451 } 5452 } 5453 } 5454 5455 /** 5456 * Enforces that only the system UID or root's UID can call a method exposed 5457 * via Binder. 5458 * 5459 * @param message used as message if SecurityException is thrown 5460 * @throws SecurityException if the caller is not system or root 5461 */ 5462 private static final void enforceSystemOrRoot(String message) { 5463 final int uid = Binder.getCallingUid(); 5464 if (uid != Process.SYSTEM_UID && uid != 0) { 5465 throw new SecurityException(message); 5466 } 5467 } 5468 5469 @Override 5470 public void performBootDexOpt() { 5471 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5472 5473 // Before everything else, see whether we need to fstrim. 5474 try { 5475 IMountService ms = PackageHelper.getMountService(); 5476 if (ms != null) { 5477 final boolean isUpgrade = isUpgrade(); 5478 boolean doTrim = isUpgrade; 5479 if (doTrim) { 5480 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5481 } else { 5482 final long interval = android.provider.Settings.Global.getLong( 5483 mContext.getContentResolver(), 5484 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5485 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5486 if (interval > 0) { 5487 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5488 if (timeSinceLast > interval) { 5489 doTrim = true; 5490 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5491 + "; running immediately"); 5492 } 5493 } 5494 } 5495 if (doTrim) { 5496 if (!isFirstBoot()) { 5497 try { 5498 ActivityManagerNative.getDefault().showBootMessage( 5499 mContext.getResources().getString( 5500 R.string.android_upgrading_fstrim), true); 5501 } catch (RemoteException e) { 5502 } 5503 } 5504 ms.runMaintenance(); 5505 } 5506 } else { 5507 Slog.e(TAG, "Mount service unavailable!"); 5508 } 5509 } catch (RemoteException e) { 5510 // Can't happen; MountService is local 5511 } 5512 5513 final ArraySet<PackageParser.Package> pkgs; 5514 synchronized (mPackages) { 5515 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5516 } 5517 5518 if (pkgs != null) { 5519 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5520 // in case the device runs out of space. 5521 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5522 // Give priority to core apps. 5523 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5524 PackageParser.Package pkg = it.next(); 5525 if (pkg.coreApp) { 5526 if (DEBUG_DEXOPT) { 5527 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5528 } 5529 sortedPkgs.add(pkg); 5530 it.remove(); 5531 } 5532 } 5533 // Give priority to system apps that listen for pre boot complete. 5534 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5535 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5536 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5537 PackageParser.Package pkg = it.next(); 5538 if (pkgNames.contains(pkg.packageName)) { 5539 if (DEBUG_DEXOPT) { 5540 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5541 } 5542 sortedPkgs.add(pkg); 5543 it.remove(); 5544 } 5545 } 5546 // Give priority to system apps. 5547 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5548 PackageParser.Package pkg = it.next(); 5549 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5550 if (DEBUG_DEXOPT) { 5551 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5552 } 5553 sortedPkgs.add(pkg); 5554 it.remove(); 5555 } 5556 } 5557 // Give priority to updated system apps. 5558 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5559 PackageParser.Package pkg = it.next(); 5560 if (pkg.isUpdatedSystemApp()) { 5561 if (DEBUG_DEXOPT) { 5562 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5563 } 5564 sortedPkgs.add(pkg); 5565 it.remove(); 5566 } 5567 } 5568 // Give priority to apps that listen for boot complete. 5569 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5570 pkgNames = getPackageNamesForIntent(intent); 5571 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5572 PackageParser.Package pkg = it.next(); 5573 if (pkgNames.contains(pkg.packageName)) { 5574 if (DEBUG_DEXOPT) { 5575 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5576 } 5577 sortedPkgs.add(pkg); 5578 it.remove(); 5579 } 5580 } 5581 // Filter out packages that aren't recently used. 5582 filterRecentlyUsedApps(pkgs); 5583 // Add all remaining apps. 5584 for (PackageParser.Package pkg : pkgs) { 5585 if (DEBUG_DEXOPT) { 5586 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5587 } 5588 sortedPkgs.add(pkg); 5589 } 5590 5591 // If we want to be lazy, filter everything that wasn't recently used. 5592 if (mLazyDexOpt) { 5593 filterRecentlyUsedApps(sortedPkgs); 5594 } 5595 5596 int i = 0; 5597 int total = sortedPkgs.size(); 5598 File dataDir = Environment.getDataDirectory(); 5599 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5600 if (lowThreshold == 0) { 5601 throw new IllegalStateException("Invalid low memory threshold"); 5602 } 5603 for (PackageParser.Package pkg : sortedPkgs) { 5604 long usableSpace = dataDir.getUsableSpace(); 5605 if (usableSpace < lowThreshold) { 5606 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5607 break; 5608 } 5609 performBootDexOpt(pkg, ++i, total); 5610 } 5611 } 5612 } 5613 5614 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5615 // Filter out packages that aren't recently used. 5616 // 5617 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5618 // should do a full dexopt. 5619 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5620 int total = pkgs.size(); 5621 int skipped = 0; 5622 long now = System.currentTimeMillis(); 5623 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5624 PackageParser.Package pkg = i.next(); 5625 long then = pkg.mLastPackageUsageTimeInMills; 5626 if (then + mDexOptLRUThresholdInMills < now) { 5627 if (DEBUG_DEXOPT) { 5628 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5629 ((then == 0) ? "never" : new Date(then))); 5630 } 5631 i.remove(); 5632 skipped++; 5633 } 5634 } 5635 if (DEBUG_DEXOPT) { 5636 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5637 } 5638 } 5639 } 5640 5641 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5642 List<ResolveInfo> ris = null; 5643 try { 5644 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5645 intent, null, 0, UserHandle.USER_OWNER); 5646 } catch (RemoteException e) { 5647 } 5648 ArraySet<String> pkgNames = new ArraySet<String>(); 5649 if (ris != null) { 5650 for (ResolveInfo ri : ris) { 5651 pkgNames.add(ri.activityInfo.packageName); 5652 } 5653 } 5654 return pkgNames; 5655 } 5656 5657 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5658 if (DEBUG_DEXOPT) { 5659 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5660 } 5661 if (!isFirstBoot()) { 5662 try { 5663 ActivityManagerNative.getDefault().showBootMessage( 5664 mContext.getResources().getString(R.string.android_upgrading_apk, 5665 curr, total), true); 5666 } catch (RemoteException e) { 5667 } 5668 } 5669 PackageParser.Package p = pkg; 5670 synchronized (mInstallLock) { 5671 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5672 false /* force dex */, false /* defer */, true /* include dependencies */); 5673 } 5674 } 5675 5676 @Override 5677 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5678 return performDexOpt(packageName, instructionSet, false); 5679 } 5680 5681 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5682 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5683 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5684 if (!dexopt && !updateUsage) { 5685 // We aren't going to dexopt or update usage, so bail early. 5686 return false; 5687 } 5688 PackageParser.Package p; 5689 final String targetInstructionSet; 5690 synchronized (mPackages) { 5691 p = mPackages.get(packageName); 5692 if (p == null) { 5693 return false; 5694 } 5695 if (updateUsage) { 5696 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5697 } 5698 mPackageUsage.write(false); 5699 if (!dexopt) { 5700 // We aren't going to dexopt, so bail early. 5701 return false; 5702 } 5703 5704 targetInstructionSet = instructionSet != null ? instructionSet : 5705 getPrimaryInstructionSet(p.applicationInfo); 5706 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5707 return false; 5708 } 5709 } 5710 5711 synchronized (mInstallLock) { 5712 final String[] instructionSets = new String[] { targetInstructionSet }; 5713 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5714 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5715 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5716 } 5717 } 5718 5719 public ArraySet<String> getPackagesThatNeedDexOpt() { 5720 ArraySet<String> pkgs = null; 5721 synchronized (mPackages) { 5722 for (PackageParser.Package p : mPackages.values()) { 5723 if (DEBUG_DEXOPT) { 5724 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5725 } 5726 if (!p.mDexOptPerformed.isEmpty()) { 5727 continue; 5728 } 5729 if (pkgs == null) { 5730 pkgs = new ArraySet<String>(); 5731 } 5732 pkgs.add(p.packageName); 5733 } 5734 } 5735 return pkgs; 5736 } 5737 5738 public void shutdown() { 5739 mPackageUsage.write(true); 5740 } 5741 5742 @Override 5743 public void forceDexOpt(String packageName) { 5744 enforceSystemOrRoot("forceDexOpt"); 5745 5746 PackageParser.Package pkg; 5747 synchronized (mPackages) { 5748 pkg = mPackages.get(packageName); 5749 if (pkg == null) { 5750 throw new IllegalArgumentException("Missing package: " + packageName); 5751 } 5752 } 5753 5754 synchronized (mInstallLock) { 5755 final String[] instructionSets = new String[] { 5756 getPrimaryInstructionSet(pkg.applicationInfo) }; 5757 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5758 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5759 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5760 throw new IllegalStateException("Failed to dexopt: " + res); 5761 } 5762 } 5763 } 5764 5765 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5766 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5767 Slog.w(TAG, "Unable to update from " + oldPkg.name 5768 + " to " + newPkg.packageName 5769 + ": old package not in system partition"); 5770 return false; 5771 } else if (mPackages.get(oldPkg.name) != null) { 5772 Slog.w(TAG, "Unable to update from " + oldPkg.name 5773 + " to " + newPkg.packageName 5774 + ": old package still exists"); 5775 return false; 5776 } 5777 return true; 5778 } 5779 5780 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5781 int[] users = sUserManager.getUserIds(); 5782 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5783 if (res < 0) { 5784 return res; 5785 } 5786 for (int user : users) { 5787 if (user != 0) { 5788 res = mInstaller.createUserData(volumeUuid, packageName, 5789 UserHandle.getUid(user, uid), user, seinfo); 5790 if (res < 0) { 5791 return res; 5792 } 5793 } 5794 } 5795 return res; 5796 } 5797 5798 private int removeDataDirsLI(String volumeUuid, String packageName) { 5799 int[] users = sUserManager.getUserIds(); 5800 int res = 0; 5801 for (int user : users) { 5802 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5803 if (resInner < 0) { 5804 res = resInner; 5805 } 5806 } 5807 5808 return res; 5809 } 5810 5811 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5812 int[] users = sUserManager.getUserIds(); 5813 int res = 0; 5814 for (int user : users) { 5815 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5816 if (resInner < 0) { 5817 res = resInner; 5818 } 5819 } 5820 return res; 5821 } 5822 5823 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5824 PackageParser.Package changingLib) { 5825 if (file.path != null) { 5826 usesLibraryFiles.add(file.path); 5827 return; 5828 } 5829 PackageParser.Package p = mPackages.get(file.apk); 5830 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5831 // If we are doing this while in the middle of updating a library apk, 5832 // then we need to make sure to use that new apk for determining the 5833 // dependencies here. (We haven't yet finished committing the new apk 5834 // to the package manager state.) 5835 if (p == null || p.packageName.equals(changingLib.packageName)) { 5836 p = changingLib; 5837 } 5838 } 5839 if (p != null) { 5840 usesLibraryFiles.addAll(p.getAllCodePaths()); 5841 } 5842 } 5843 5844 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5845 PackageParser.Package changingLib) throws PackageManagerException { 5846 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5847 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5848 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5849 for (int i=0; i<N; i++) { 5850 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5851 if (file == null) { 5852 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5853 "Package " + pkg.packageName + " requires unavailable shared library " 5854 + pkg.usesLibraries.get(i) + "; failing!"); 5855 } 5856 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5857 } 5858 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5859 for (int i=0; i<N; i++) { 5860 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5861 if (file == null) { 5862 Slog.w(TAG, "Package " + pkg.packageName 5863 + " desires unavailable shared library " 5864 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5865 } else { 5866 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5867 } 5868 } 5869 N = usesLibraryFiles.size(); 5870 if (N > 0) { 5871 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5872 } else { 5873 pkg.usesLibraryFiles = null; 5874 } 5875 } 5876 } 5877 5878 private static boolean hasString(List<String> list, List<String> which) { 5879 if (list == null) { 5880 return false; 5881 } 5882 for (int i=list.size()-1; i>=0; i--) { 5883 for (int j=which.size()-1; j>=0; j--) { 5884 if (which.get(j).equals(list.get(i))) { 5885 return true; 5886 } 5887 } 5888 } 5889 return false; 5890 } 5891 5892 private void updateAllSharedLibrariesLPw() { 5893 for (PackageParser.Package pkg : mPackages.values()) { 5894 try { 5895 updateSharedLibrariesLPw(pkg, null); 5896 } catch (PackageManagerException e) { 5897 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5898 } 5899 } 5900 } 5901 5902 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5903 PackageParser.Package changingPkg) { 5904 ArrayList<PackageParser.Package> res = null; 5905 for (PackageParser.Package pkg : mPackages.values()) { 5906 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5907 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5908 if (res == null) { 5909 res = new ArrayList<PackageParser.Package>(); 5910 } 5911 res.add(pkg); 5912 try { 5913 updateSharedLibrariesLPw(pkg, changingPkg); 5914 } catch (PackageManagerException e) { 5915 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5916 } 5917 } 5918 } 5919 return res; 5920 } 5921 5922 /** 5923 * Derive the value of the {@code cpuAbiOverride} based on the provided 5924 * value and an optional stored value from the package settings. 5925 */ 5926 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5927 String cpuAbiOverride = null; 5928 5929 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5930 cpuAbiOverride = null; 5931 } else if (abiOverride != null) { 5932 cpuAbiOverride = abiOverride; 5933 } else if (settings != null) { 5934 cpuAbiOverride = settings.cpuAbiOverrideString; 5935 } 5936 5937 return cpuAbiOverride; 5938 } 5939 5940 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5941 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5942 boolean success = false; 5943 try { 5944 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5945 currentTime, user); 5946 success = true; 5947 return res; 5948 } finally { 5949 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5950 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5951 } 5952 } 5953 } 5954 5955 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5956 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5957 final File scanFile = new File(pkg.codePath); 5958 if (pkg.applicationInfo.getCodePath() == null || 5959 pkg.applicationInfo.getResourcePath() == null) { 5960 // Bail out. The resource and code paths haven't been set. 5961 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5962 "Code and resource paths haven't been set correctly"); 5963 } 5964 5965 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5966 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5967 } else { 5968 // Only allow system apps to be flagged as core apps. 5969 pkg.coreApp = false; 5970 } 5971 5972 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5973 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5974 } 5975 5976 if (mCustomResolverComponentName != null && 5977 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5978 setUpCustomResolverActivity(pkg); 5979 } 5980 5981 if (pkg.packageName.equals("android")) { 5982 synchronized (mPackages) { 5983 if (mAndroidApplication != null) { 5984 Slog.w(TAG, "*************************************************"); 5985 Slog.w(TAG, "Core android package being redefined. Skipping."); 5986 Slog.w(TAG, " file=" + scanFile); 5987 Slog.w(TAG, "*************************************************"); 5988 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5989 "Core android package being redefined. Skipping."); 5990 } 5991 5992 // Set up information for our fall-back user intent resolution activity. 5993 mPlatformPackage = pkg; 5994 pkg.mVersionCode = mSdkVersion; 5995 mAndroidApplication = pkg.applicationInfo; 5996 5997 if (!mResolverReplaced) { 5998 mResolveActivity.applicationInfo = mAndroidApplication; 5999 mResolveActivity.name = ResolverActivity.class.getName(); 6000 mResolveActivity.packageName = mAndroidApplication.packageName; 6001 mResolveActivity.processName = "system:ui"; 6002 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6003 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6004 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6005 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6006 mResolveActivity.exported = true; 6007 mResolveActivity.enabled = true; 6008 mResolveInfo.activityInfo = mResolveActivity; 6009 mResolveInfo.priority = 0; 6010 mResolveInfo.preferredOrder = 0; 6011 mResolveInfo.match = 0; 6012 mResolveComponentName = new ComponentName( 6013 mAndroidApplication.packageName, mResolveActivity.name); 6014 } 6015 } 6016 } 6017 6018 if (DEBUG_PACKAGE_SCANNING) { 6019 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6020 Log.d(TAG, "Scanning package " + pkg.packageName); 6021 } 6022 6023 if (mPackages.containsKey(pkg.packageName) 6024 || mSharedLibraries.containsKey(pkg.packageName)) { 6025 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6026 "Application package " + pkg.packageName 6027 + " already installed. Skipping duplicate."); 6028 } 6029 6030 // If we're only installing presumed-existing packages, require that the 6031 // scanned APK is both already known and at the path previously established 6032 // for it. Previously unknown packages we pick up normally, but if we have an 6033 // a priori expectation about this package's install presence, enforce it. 6034 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6035 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6036 if (known != null) { 6037 if (DEBUG_PACKAGE_SCANNING) { 6038 Log.d(TAG, "Examining " + pkg.codePath 6039 + " and requiring known paths " + known.codePathString 6040 + " & " + known.resourcePathString); 6041 } 6042 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6043 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6044 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6045 "Application package " + pkg.packageName 6046 + " found at " + pkg.applicationInfo.getCodePath() 6047 + " but expected at " + known.codePathString + "; ignoring."); 6048 } 6049 } 6050 } 6051 6052 // Initialize package source and resource directories 6053 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6054 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6055 6056 SharedUserSetting suid = null; 6057 PackageSetting pkgSetting = null; 6058 6059 if (!isSystemApp(pkg)) { 6060 // Only system apps can use these features. 6061 pkg.mOriginalPackages = null; 6062 pkg.mRealPackage = null; 6063 pkg.mAdoptPermissions = null; 6064 } 6065 6066 // writer 6067 synchronized (mPackages) { 6068 if (pkg.mSharedUserId != null) { 6069 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6070 if (suid == null) { 6071 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6072 "Creating application package " + pkg.packageName 6073 + " for shared user failed"); 6074 } 6075 if (DEBUG_PACKAGE_SCANNING) { 6076 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6077 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6078 + "): packages=" + suid.packages); 6079 } 6080 } 6081 6082 // Check if we are renaming from an original package name. 6083 PackageSetting origPackage = null; 6084 String realName = null; 6085 if (pkg.mOriginalPackages != null) { 6086 // This package may need to be renamed to a previously 6087 // installed name. Let's check on that... 6088 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6089 if (pkg.mOriginalPackages.contains(renamed)) { 6090 // This package had originally been installed as the 6091 // original name, and we have already taken care of 6092 // transitioning to the new one. Just update the new 6093 // one to continue using the old name. 6094 realName = pkg.mRealPackage; 6095 if (!pkg.packageName.equals(renamed)) { 6096 // Callers into this function may have already taken 6097 // care of renaming the package; only do it here if 6098 // it is not already done. 6099 pkg.setPackageName(renamed); 6100 } 6101 6102 } else { 6103 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6104 if ((origPackage = mSettings.peekPackageLPr( 6105 pkg.mOriginalPackages.get(i))) != null) { 6106 // We do have the package already installed under its 6107 // original name... should we use it? 6108 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6109 // New package is not compatible with original. 6110 origPackage = null; 6111 continue; 6112 } else if (origPackage.sharedUser != null) { 6113 // Make sure uid is compatible between packages. 6114 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6115 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6116 + " to " + pkg.packageName + ": old uid " 6117 + origPackage.sharedUser.name 6118 + " differs from " + pkg.mSharedUserId); 6119 origPackage = null; 6120 continue; 6121 } 6122 } else { 6123 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6124 + pkg.packageName + " to old name " + origPackage.name); 6125 } 6126 break; 6127 } 6128 } 6129 } 6130 } 6131 6132 if (mTransferedPackages.contains(pkg.packageName)) { 6133 Slog.w(TAG, "Package " + pkg.packageName 6134 + " was transferred to another, but its .apk remains"); 6135 } 6136 6137 // Just create the setting, don't add it yet. For already existing packages 6138 // the PkgSetting exists already and doesn't have to be created. 6139 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6140 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6141 pkg.applicationInfo.primaryCpuAbi, 6142 pkg.applicationInfo.secondaryCpuAbi, 6143 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6144 user, false); 6145 if (pkgSetting == null) { 6146 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6147 "Creating application package " + pkg.packageName + " failed"); 6148 } 6149 6150 if (pkgSetting.origPackage != null) { 6151 // If we are first transitioning from an original package, 6152 // fix up the new package's name now. We need to do this after 6153 // looking up the package under its new name, so getPackageLP 6154 // can take care of fiddling things correctly. 6155 pkg.setPackageName(origPackage.name); 6156 6157 // File a report about this. 6158 String msg = "New package " + pkgSetting.realName 6159 + " renamed to replace old package " + pkgSetting.name; 6160 reportSettingsProblem(Log.WARN, msg); 6161 6162 // Make a note of it. 6163 mTransferedPackages.add(origPackage.name); 6164 6165 // No longer need to retain this. 6166 pkgSetting.origPackage = null; 6167 } 6168 6169 if (realName != null) { 6170 // Make a note of it. 6171 mTransferedPackages.add(pkg.packageName); 6172 } 6173 6174 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6175 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6176 } 6177 6178 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6179 // Check all shared libraries and map to their actual file path. 6180 // We only do this here for apps not on a system dir, because those 6181 // are the only ones that can fail an install due to this. We 6182 // will take care of the system apps by updating all of their 6183 // library paths after the scan is done. 6184 updateSharedLibrariesLPw(pkg, null); 6185 } 6186 6187 if (mFoundPolicyFile) { 6188 SELinuxMMAC.assignSeinfoValue(pkg); 6189 } 6190 6191 pkg.applicationInfo.uid = pkgSetting.appId; 6192 pkg.mExtras = pkgSetting; 6193 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6194 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6195 // We just determined the app is signed correctly, so bring 6196 // over the latest parsed certs. 6197 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6198 } else { 6199 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6200 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6201 "Package " + pkg.packageName + " upgrade keys do not match the " 6202 + "previously installed version"); 6203 } else { 6204 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6205 String msg = "System package " + pkg.packageName 6206 + " signature changed; retaining data."; 6207 reportSettingsProblem(Log.WARN, msg); 6208 } 6209 } 6210 } else { 6211 try { 6212 verifySignaturesLP(pkgSetting, pkg); 6213 // We just determined the app is signed correctly, so bring 6214 // over the latest parsed certs. 6215 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6216 } catch (PackageManagerException e) { 6217 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6218 throw e; 6219 } 6220 // The signature has changed, but this package is in the system 6221 // image... let's recover! 6222 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6223 // However... if this package is part of a shared user, but it 6224 // doesn't match the signature of the shared user, let's fail. 6225 // What this means is that you can't change the signatures 6226 // associated with an overall shared user, which doesn't seem all 6227 // that unreasonable. 6228 if (pkgSetting.sharedUser != null) { 6229 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6230 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6231 throw new PackageManagerException( 6232 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6233 "Signature mismatch for shared user : " 6234 + pkgSetting.sharedUser); 6235 } 6236 } 6237 // File a report about this. 6238 String msg = "System package " + pkg.packageName 6239 + " signature changed; retaining data."; 6240 reportSettingsProblem(Log.WARN, msg); 6241 } 6242 } 6243 // Verify that this new package doesn't have any content providers 6244 // that conflict with existing packages. Only do this if the 6245 // package isn't already installed, since we don't want to break 6246 // things that are installed. 6247 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6248 final int N = pkg.providers.size(); 6249 int i; 6250 for (i=0; i<N; i++) { 6251 PackageParser.Provider p = pkg.providers.get(i); 6252 if (p.info.authority != null) { 6253 String names[] = p.info.authority.split(";"); 6254 for (int j = 0; j < names.length; j++) { 6255 if (mProvidersByAuthority.containsKey(names[j])) { 6256 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6257 final String otherPackageName = 6258 ((other != null && other.getComponentName() != null) ? 6259 other.getComponentName().getPackageName() : "?"); 6260 throw new PackageManagerException( 6261 INSTALL_FAILED_CONFLICTING_PROVIDER, 6262 "Can't install because provider name " + names[j] 6263 + " (in package " + pkg.applicationInfo.packageName 6264 + ") is already used by " + otherPackageName); 6265 } 6266 } 6267 } 6268 } 6269 } 6270 6271 if (pkg.mAdoptPermissions != null) { 6272 // This package wants to adopt ownership of permissions from 6273 // another package. 6274 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6275 final String origName = pkg.mAdoptPermissions.get(i); 6276 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6277 if (orig != null) { 6278 if (verifyPackageUpdateLPr(orig, pkg)) { 6279 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6280 + pkg.packageName); 6281 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6282 } 6283 } 6284 } 6285 } 6286 } 6287 6288 final String pkgName = pkg.packageName; 6289 6290 final long scanFileTime = scanFile.lastModified(); 6291 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6292 pkg.applicationInfo.processName = fixProcessName( 6293 pkg.applicationInfo.packageName, 6294 pkg.applicationInfo.processName, 6295 pkg.applicationInfo.uid); 6296 6297 File dataPath; 6298 if (mPlatformPackage == pkg) { 6299 // The system package is special. 6300 dataPath = new File(Environment.getDataDirectory(), "system"); 6301 6302 pkg.applicationInfo.dataDir = dataPath.getPath(); 6303 6304 } else { 6305 // This is a normal package, need to make its data directory. 6306 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6307 UserHandle.USER_OWNER); 6308 6309 boolean uidError = false; 6310 if (dataPath.exists()) { 6311 int currentUid = 0; 6312 try { 6313 StructStat stat = Os.stat(dataPath.getPath()); 6314 currentUid = stat.st_uid; 6315 } catch (ErrnoException e) { 6316 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6317 } 6318 6319 // If we have mismatched owners for the data path, we have a problem. 6320 if (currentUid != pkg.applicationInfo.uid) { 6321 boolean recovered = false; 6322 if (currentUid == 0) { 6323 // The directory somehow became owned by root. Wow. 6324 // This is probably because the system was stopped while 6325 // installd was in the middle of messing with its libs 6326 // directory. Ask installd to fix that. 6327 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6328 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6329 if (ret >= 0) { 6330 recovered = true; 6331 String msg = "Package " + pkg.packageName 6332 + " unexpectedly changed to uid 0; recovered to " + 6333 + pkg.applicationInfo.uid; 6334 reportSettingsProblem(Log.WARN, msg); 6335 } 6336 } 6337 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6338 || (scanFlags&SCAN_BOOTING) != 0)) { 6339 // If this is a system app, we can at least delete its 6340 // current data so the application will still work. 6341 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6342 if (ret >= 0) { 6343 // TODO: Kill the processes first 6344 // Old data gone! 6345 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6346 ? "System package " : "Third party package "; 6347 String msg = prefix + pkg.packageName 6348 + " has changed from uid: " 6349 + currentUid + " to " 6350 + pkg.applicationInfo.uid + "; old data erased"; 6351 reportSettingsProblem(Log.WARN, msg); 6352 recovered = true; 6353 6354 // And now re-install the app. 6355 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6356 pkg.applicationInfo.seinfo); 6357 if (ret == -1) { 6358 // Ack should not happen! 6359 msg = prefix + pkg.packageName 6360 + " could not have data directory re-created after delete."; 6361 reportSettingsProblem(Log.WARN, msg); 6362 throw new PackageManagerException( 6363 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6364 } 6365 } 6366 if (!recovered) { 6367 mHasSystemUidErrors = true; 6368 } 6369 } else if (!recovered) { 6370 // If we allow this install to proceed, we will be broken. 6371 // Abort, abort! 6372 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6373 "scanPackageLI"); 6374 } 6375 if (!recovered) { 6376 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6377 + pkg.applicationInfo.uid + "/fs_" 6378 + currentUid; 6379 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6380 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6381 String msg = "Package " + pkg.packageName 6382 + " has mismatched uid: " 6383 + currentUid + " on disk, " 6384 + pkg.applicationInfo.uid + " in settings"; 6385 // writer 6386 synchronized (mPackages) { 6387 mSettings.mReadMessages.append(msg); 6388 mSettings.mReadMessages.append('\n'); 6389 uidError = true; 6390 if (!pkgSetting.uidError) { 6391 reportSettingsProblem(Log.ERROR, msg); 6392 } 6393 } 6394 } 6395 } 6396 pkg.applicationInfo.dataDir = dataPath.getPath(); 6397 if (mShouldRestoreconData) { 6398 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6399 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6400 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6401 } 6402 } else { 6403 if (DEBUG_PACKAGE_SCANNING) { 6404 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6405 Log.v(TAG, "Want this data dir: " + dataPath); 6406 } 6407 //invoke installer to do the actual installation 6408 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6409 pkg.applicationInfo.seinfo); 6410 if (ret < 0) { 6411 // Error from installer 6412 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6413 "Unable to create data dirs [errorCode=" + ret + "]"); 6414 } 6415 6416 if (dataPath.exists()) { 6417 pkg.applicationInfo.dataDir = dataPath.getPath(); 6418 } else { 6419 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6420 pkg.applicationInfo.dataDir = null; 6421 } 6422 } 6423 6424 pkgSetting.uidError = uidError; 6425 } 6426 6427 final String path = scanFile.getPath(); 6428 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6429 6430 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6431 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6432 6433 // Some system apps still use directory structure for native libraries 6434 // in which case we might end up not detecting abi solely based on apk 6435 // structure. Try to detect abi based on directory structure. 6436 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6437 pkg.applicationInfo.primaryCpuAbi == null) { 6438 setBundledAppAbisAndRoots(pkg, pkgSetting); 6439 setNativeLibraryPaths(pkg); 6440 } 6441 6442 } else { 6443 if ((scanFlags & SCAN_MOVE) != 0) { 6444 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6445 // but we already have this packages package info in the PackageSetting. We just 6446 // use that and derive the native library path based on the new codepath. 6447 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6448 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6449 } 6450 6451 // Set native library paths again. For moves, the path will be updated based on the 6452 // ABIs we've determined above. For non-moves, the path will be updated based on the 6453 // ABIs we determined during compilation, but the path will depend on the final 6454 // package path (after the rename away from the stage path). 6455 setNativeLibraryPaths(pkg); 6456 } 6457 6458 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6459 final int[] userIds = sUserManager.getUserIds(); 6460 synchronized (mInstallLock) { 6461 // Create a native library symlink only if we have native libraries 6462 // and if the native libraries are 32 bit libraries. We do not provide 6463 // this symlink for 64 bit libraries. 6464 if (pkg.applicationInfo.primaryCpuAbi != null && 6465 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6466 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6467 for (int userId : userIds) { 6468 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6469 nativeLibPath, userId) < 0) { 6470 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6471 "Failed linking native library dir (user=" + userId + ")"); 6472 } 6473 } 6474 } 6475 } 6476 6477 // This is a special case for the "system" package, where the ABI is 6478 // dictated by the zygote configuration (and init.rc). We should keep track 6479 // of this ABI so that we can deal with "normal" applications that run under 6480 // the same UID correctly. 6481 if (mPlatformPackage == pkg) { 6482 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6483 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6484 } 6485 6486 // If there's a mismatch between the abi-override in the package setting 6487 // and the abiOverride specified for the install. Warn about this because we 6488 // would've already compiled the app without taking the package setting into 6489 // account. 6490 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6491 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6492 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6493 " for package: " + pkg.packageName); 6494 } 6495 } 6496 6497 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6498 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6499 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6500 6501 // Copy the derived override back to the parsed package, so that we can 6502 // update the package settings accordingly. 6503 pkg.cpuAbiOverride = cpuAbiOverride; 6504 6505 if (DEBUG_ABI_SELECTION) { 6506 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6507 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6508 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6509 } 6510 6511 // Push the derived path down into PackageSettings so we know what to 6512 // clean up at uninstall time. 6513 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6514 6515 if (DEBUG_ABI_SELECTION) { 6516 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6517 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6518 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6519 } 6520 6521 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6522 // We don't do this here during boot because we can do it all 6523 // at once after scanning all existing packages. 6524 // 6525 // We also do this *before* we perform dexopt on this package, so that 6526 // we can avoid redundant dexopts, and also to make sure we've got the 6527 // code and package path correct. 6528 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6529 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6530 } 6531 6532 if ((scanFlags & SCAN_NO_DEX) == 0) { 6533 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6534 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6535 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6536 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6537 } 6538 } 6539 if (mFactoryTest && pkg.requestedPermissions.contains( 6540 android.Manifest.permission.FACTORY_TEST)) { 6541 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6542 } 6543 6544 ArrayList<PackageParser.Package> clientLibPkgs = null; 6545 6546 // writer 6547 synchronized (mPackages) { 6548 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6549 // Only system apps can add new shared libraries. 6550 if (pkg.libraryNames != null) { 6551 for (int i=0; i<pkg.libraryNames.size(); i++) { 6552 String name = pkg.libraryNames.get(i); 6553 boolean allowed = false; 6554 if (pkg.isUpdatedSystemApp()) { 6555 // New library entries can only be added through the 6556 // system image. This is important to get rid of a lot 6557 // of nasty edge cases: for example if we allowed a non- 6558 // system update of the app to add a library, then uninstalling 6559 // the update would make the library go away, and assumptions 6560 // we made such as through app install filtering would now 6561 // have allowed apps on the device which aren't compatible 6562 // with it. Better to just have the restriction here, be 6563 // conservative, and create many fewer cases that can negatively 6564 // impact the user experience. 6565 final PackageSetting sysPs = mSettings 6566 .getDisabledSystemPkgLPr(pkg.packageName); 6567 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6568 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6569 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6570 allowed = true; 6571 allowed = true; 6572 break; 6573 } 6574 } 6575 } 6576 } else { 6577 allowed = true; 6578 } 6579 if (allowed) { 6580 if (!mSharedLibraries.containsKey(name)) { 6581 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6582 } else if (!name.equals(pkg.packageName)) { 6583 Slog.w(TAG, "Package " + pkg.packageName + " library " 6584 + name + " already exists; skipping"); 6585 } 6586 } else { 6587 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6588 + name + " that is not declared on system image; skipping"); 6589 } 6590 } 6591 if ((scanFlags&SCAN_BOOTING) == 0) { 6592 // If we are not booting, we need to update any applications 6593 // that are clients of our shared library. If we are booting, 6594 // this will all be done once the scan is complete. 6595 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6596 } 6597 } 6598 } 6599 } 6600 6601 // We also need to dexopt any apps that are dependent on this library. Note that 6602 // if these fail, we should abort the install since installing the library will 6603 // result in some apps being broken. 6604 if (clientLibPkgs != null) { 6605 if ((scanFlags & SCAN_NO_DEX) == 0) { 6606 for (int i = 0; i < clientLibPkgs.size(); i++) { 6607 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6608 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6609 null /* instruction sets */, forceDex, 6610 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6611 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6612 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6613 "scanPackageLI failed to dexopt clientLibPkgs"); 6614 } 6615 } 6616 } 6617 } 6618 6619 // Also need to kill any apps that are dependent on the library. 6620 if (clientLibPkgs != null) { 6621 for (int i=0; i<clientLibPkgs.size(); i++) { 6622 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6623 killApplication(clientPkg.applicationInfo.packageName, 6624 clientPkg.applicationInfo.uid, "update lib"); 6625 } 6626 } 6627 6628 // Make sure we're not adding any bogus keyset info 6629 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6630 ksms.assertScannedPackageValid(pkg); 6631 6632 // writer 6633 synchronized (mPackages) { 6634 // We don't expect installation to fail beyond this point 6635 6636 // Add the new setting to mSettings 6637 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6638 // Add the new setting to mPackages 6639 mPackages.put(pkg.applicationInfo.packageName, pkg); 6640 // Make sure we don't accidentally delete its data. 6641 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6642 while (iter.hasNext()) { 6643 PackageCleanItem item = iter.next(); 6644 if (pkgName.equals(item.packageName)) { 6645 iter.remove(); 6646 } 6647 } 6648 6649 // Take care of first install / last update times. 6650 if (currentTime != 0) { 6651 if (pkgSetting.firstInstallTime == 0) { 6652 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6653 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6654 pkgSetting.lastUpdateTime = currentTime; 6655 } 6656 } else if (pkgSetting.firstInstallTime == 0) { 6657 // We need *something*. Take time time stamp of the file. 6658 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6659 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6660 if (scanFileTime != pkgSetting.timeStamp) { 6661 // A package on the system image has changed; consider this 6662 // to be an update. 6663 pkgSetting.lastUpdateTime = scanFileTime; 6664 } 6665 } 6666 6667 // Add the package's KeySets to the global KeySetManagerService 6668 ksms.addScannedPackageLPw(pkg); 6669 6670 int N = pkg.providers.size(); 6671 StringBuilder r = null; 6672 int i; 6673 for (i=0; i<N; i++) { 6674 PackageParser.Provider p = pkg.providers.get(i); 6675 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6676 p.info.processName, pkg.applicationInfo.uid); 6677 mProviders.addProvider(p); 6678 p.syncable = p.info.isSyncable; 6679 if (p.info.authority != null) { 6680 String names[] = p.info.authority.split(";"); 6681 p.info.authority = null; 6682 for (int j = 0; j < names.length; j++) { 6683 if (j == 1 && p.syncable) { 6684 // We only want the first authority for a provider to possibly be 6685 // syncable, so if we already added this provider using a different 6686 // authority clear the syncable flag. We copy the provider before 6687 // changing it because the mProviders object contains a reference 6688 // to a provider that we don't want to change. 6689 // Only do this for the second authority since the resulting provider 6690 // object can be the same for all future authorities for this provider. 6691 p = new PackageParser.Provider(p); 6692 p.syncable = false; 6693 } 6694 if (!mProvidersByAuthority.containsKey(names[j])) { 6695 mProvidersByAuthority.put(names[j], p); 6696 if (p.info.authority == null) { 6697 p.info.authority = names[j]; 6698 } else { 6699 p.info.authority = p.info.authority + ";" + names[j]; 6700 } 6701 if (DEBUG_PACKAGE_SCANNING) { 6702 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6703 Log.d(TAG, "Registered content provider: " + names[j] 6704 + ", className = " + p.info.name + ", isSyncable = " 6705 + p.info.isSyncable); 6706 } 6707 } else { 6708 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6709 Slog.w(TAG, "Skipping provider name " + names[j] + 6710 " (in package " + pkg.applicationInfo.packageName + 6711 "): name already used by " 6712 + ((other != null && other.getComponentName() != null) 6713 ? other.getComponentName().getPackageName() : "?")); 6714 } 6715 } 6716 } 6717 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6718 if (r == null) { 6719 r = new StringBuilder(256); 6720 } else { 6721 r.append(' '); 6722 } 6723 r.append(p.info.name); 6724 } 6725 } 6726 if (r != null) { 6727 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6728 } 6729 6730 N = pkg.services.size(); 6731 r = null; 6732 for (i=0; i<N; i++) { 6733 PackageParser.Service s = pkg.services.get(i); 6734 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6735 s.info.processName, pkg.applicationInfo.uid); 6736 mServices.addService(s); 6737 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6738 if (r == null) { 6739 r = new StringBuilder(256); 6740 } else { 6741 r.append(' '); 6742 } 6743 r.append(s.info.name); 6744 } 6745 } 6746 if (r != null) { 6747 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6748 } 6749 6750 N = pkg.receivers.size(); 6751 r = null; 6752 for (i=0; i<N; i++) { 6753 PackageParser.Activity a = pkg.receivers.get(i); 6754 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6755 a.info.processName, pkg.applicationInfo.uid); 6756 mReceivers.addActivity(a, "receiver"); 6757 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6758 if (r == null) { 6759 r = new StringBuilder(256); 6760 } else { 6761 r.append(' '); 6762 } 6763 r.append(a.info.name); 6764 } 6765 } 6766 if (r != null) { 6767 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6768 } 6769 6770 N = pkg.activities.size(); 6771 r = null; 6772 for (i=0; i<N; i++) { 6773 PackageParser.Activity a = pkg.activities.get(i); 6774 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6775 a.info.processName, pkg.applicationInfo.uid); 6776 mActivities.addActivity(a, "activity"); 6777 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6778 if (r == null) { 6779 r = new StringBuilder(256); 6780 } else { 6781 r.append(' '); 6782 } 6783 r.append(a.info.name); 6784 } 6785 } 6786 if (r != null) { 6787 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6788 } 6789 6790 N = pkg.permissionGroups.size(); 6791 r = null; 6792 for (i=0; i<N; i++) { 6793 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6794 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6795 if (cur == null) { 6796 mPermissionGroups.put(pg.info.name, pg); 6797 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6798 if (r == null) { 6799 r = new StringBuilder(256); 6800 } else { 6801 r.append(' '); 6802 } 6803 r.append(pg.info.name); 6804 } 6805 } else { 6806 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6807 + pg.info.packageName + " ignored: original from " 6808 + cur.info.packageName); 6809 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6810 if (r == null) { 6811 r = new StringBuilder(256); 6812 } else { 6813 r.append(' '); 6814 } 6815 r.append("DUP:"); 6816 r.append(pg.info.name); 6817 } 6818 } 6819 } 6820 if (r != null) { 6821 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6822 } 6823 6824 N = pkg.permissions.size(); 6825 r = null; 6826 for (i=0; i<N; i++) { 6827 PackageParser.Permission p = pkg.permissions.get(i); 6828 6829 // Now that permission groups have a special meaning, we ignore permission 6830 // groups for legacy apps to prevent unexpected behavior. In particular, 6831 // permissions for one app being granted to someone just becuase they happen 6832 // to be in a group defined by another app (before this had no implications). 6833 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6834 p.group = mPermissionGroups.get(p.info.group); 6835 // Warn for a permission in an unknown group. 6836 if (p.info.group != null && p.group == null) { 6837 Slog.w(TAG, "Permission " + p.info.name + " from package " 6838 + p.info.packageName + " in an unknown group " + p.info.group); 6839 } 6840 } 6841 6842 ArrayMap<String, BasePermission> permissionMap = 6843 p.tree ? mSettings.mPermissionTrees 6844 : mSettings.mPermissions; 6845 BasePermission bp = permissionMap.get(p.info.name); 6846 6847 // Allow system apps to redefine non-system permissions 6848 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6849 final boolean currentOwnerIsSystem = (bp.perm != null 6850 && isSystemApp(bp.perm.owner)); 6851 if (isSystemApp(p.owner)) { 6852 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6853 // It's a built-in permission and no owner, take ownership now 6854 bp.packageSetting = pkgSetting; 6855 bp.perm = p; 6856 bp.uid = pkg.applicationInfo.uid; 6857 bp.sourcePackage = p.info.packageName; 6858 } else if (!currentOwnerIsSystem) { 6859 String msg = "New decl " + p.owner + " of permission " 6860 + p.info.name + " is system; overriding " + bp.sourcePackage; 6861 reportSettingsProblem(Log.WARN, msg); 6862 bp = null; 6863 } 6864 } 6865 } 6866 6867 if (bp == null) { 6868 bp = new BasePermission(p.info.name, p.info.packageName, 6869 BasePermission.TYPE_NORMAL); 6870 permissionMap.put(p.info.name, bp); 6871 } 6872 6873 if (bp.perm == null) { 6874 if (bp.sourcePackage == null 6875 || bp.sourcePackage.equals(p.info.packageName)) { 6876 BasePermission tree = findPermissionTreeLP(p.info.name); 6877 if (tree == null 6878 || tree.sourcePackage.equals(p.info.packageName)) { 6879 bp.packageSetting = pkgSetting; 6880 bp.perm = p; 6881 bp.uid = pkg.applicationInfo.uid; 6882 bp.sourcePackage = p.info.packageName; 6883 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6884 if (r == null) { 6885 r = new StringBuilder(256); 6886 } else { 6887 r.append(' '); 6888 } 6889 r.append(p.info.name); 6890 } 6891 } else { 6892 Slog.w(TAG, "Permission " + p.info.name + " from package " 6893 + p.info.packageName + " ignored: base tree " 6894 + tree.name + " is from package " 6895 + tree.sourcePackage); 6896 } 6897 } else { 6898 Slog.w(TAG, "Permission " + p.info.name + " from package " 6899 + p.info.packageName + " ignored: original from " 6900 + bp.sourcePackage); 6901 } 6902 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6903 if (r == null) { 6904 r = new StringBuilder(256); 6905 } else { 6906 r.append(' '); 6907 } 6908 r.append("DUP:"); 6909 r.append(p.info.name); 6910 } 6911 if (bp.perm == p) { 6912 bp.protectionLevel = p.info.protectionLevel; 6913 } 6914 } 6915 6916 if (r != null) { 6917 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6918 } 6919 6920 N = pkg.instrumentation.size(); 6921 r = null; 6922 for (i=0; i<N; i++) { 6923 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6924 a.info.packageName = pkg.applicationInfo.packageName; 6925 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6926 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6927 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6928 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6929 a.info.dataDir = pkg.applicationInfo.dataDir; 6930 6931 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6932 // need other information about the application, like the ABI and what not ? 6933 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6934 mInstrumentation.put(a.getComponentName(), a); 6935 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6936 if (r == null) { 6937 r = new StringBuilder(256); 6938 } else { 6939 r.append(' '); 6940 } 6941 r.append(a.info.name); 6942 } 6943 } 6944 if (r != null) { 6945 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6946 } 6947 6948 if (pkg.protectedBroadcasts != null) { 6949 N = pkg.protectedBroadcasts.size(); 6950 for (i=0; i<N; i++) { 6951 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6952 } 6953 } 6954 6955 pkgSetting.setTimeStamp(scanFileTime); 6956 6957 // Create idmap files for pairs of (packages, overlay packages). 6958 // Note: "android", ie framework-res.apk, is handled by native layers. 6959 if (pkg.mOverlayTarget != null) { 6960 // This is an overlay package. 6961 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6962 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6963 mOverlays.put(pkg.mOverlayTarget, 6964 new ArrayMap<String, PackageParser.Package>()); 6965 } 6966 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6967 map.put(pkg.packageName, pkg); 6968 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6969 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6970 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6971 "scanPackageLI failed to createIdmap"); 6972 } 6973 } 6974 } else if (mOverlays.containsKey(pkg.packageName) && 6975 !pkg.packageName.equals("android")) { 6976 // This is a regular package, with one or more known overlay packages. 6977 createIdmapsForPackageLI(pkg); 6978 } 6979 } 6980 6981 return pkg; 6982 } 6983 6984 /** 6985 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6986 * is derived purely on the basis of the contents of {@code scanFile} and 6987 * {@code cpuAbiOverride}. 6988 * 6989 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6990 */ 6991 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6992 String cpuAbiOverride, boolean extractLibs) 6993 throws PackageManagerException { 6994 // TODO: We can probably be smarter about this stuff. For installed apps, 6995 // we can calculate this information at install time once and for all. For 6996 // system apps, we can probably assume that this information doesn't change 6997 // after the first boot scan. As things stand, we do lots of unnecessary work. 6998 6999 // Give ourselves some initial paths; we'll come back for another 7000 // pass once we've determined ABI below. 7001 setNativeLibraryPaths(pkg); 7002 7003 // We would never need to extract libs for forward-locked and external packages, 7004 // since the container service will do it for us. We shouldn't attempt to 7005 // extract libs from system app when it was not updated. 7006 if (pkg.isForwardLocked() || isExternal(pkg) || 7007 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7008 extractLibs = false; 7009 } 7010 7011 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7012 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7013 7014 NativeLibraryHelper.Handle handle = null; 7015 try { 7016 handle = NativeLibraryHelper.Handle.create(scanFile); 7017 // TODO(multiArch): This can be null for apps that didn't go through the 7018 // usual installation process. We can calculate it again, like we 7019 // do during install time. 7020 // 7021 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7022 // unnecessary. 7023 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7024 7025 // Null out the abis so that they can be recalculated. 7026 pkg.applicationInfo.primaryCpuAbi = null; 7027 pkg.applicationInfo.secondaryCpuAbi = null; 7028 if (isMultiArch(pkg.applicationInfo)) { 7029 // Warn if we've set an abiOverride for multi-lib packages.. 7030 // By definition, we need to copy both 32 and 64 bit libraries for 7031 // such packages. 7032 if (pkg.cpuAbiOverride != null 7033 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7034 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7035 } 7036 7037 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7038 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7039 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7040 if (extractLibs) { 7041 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7042 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7043 useIsaSpecificSubdirs); 7044 } else { 7045 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7046 } 7047 } 7048 7049 maybeThrowExceptionForMultiArchCopy( 7050 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7051 7052 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7053 if (extractLibs) { 7054 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7055 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7056 useIsaSpecificSubdirs); 7057 } else { 7058 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7059 } 7060 } 7061 7062 maybeThrowExceptionForMultiArchCopy( 7063 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7064 7065 if (abi64 >= 0) { 7066 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7067 } 7068 7069 if (abi32 >= 0) { 7070 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7071 if (abi64 >= 0) { 7072 pkg.applicationInfo.secondaryCpuAbi = abi; 7073 } else { 7074 pkg.applicationInfo.primaryCpuAbi = abi; 7075 } 7076 } 7077 } else { 7078 String[] abiList = (cpuAbiOverride != null) ? 7079 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7080 7081 // Enable gross and lame hacks for apps that are built with old 7082 // SDK tools. We must scan their APKs for renderscript bitcode and 7083 // not launch them if it's present. Don't bother checking on devices 7084 // that don't have 64 bit support. 7085 boolean needsRenderScriptOverride = false; 7086 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7087 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7088 abiList = Build.SUPPORTED_32_BIT_ABIS; 7089 needsRenderScriptOverride = true; 7090 } 7091 7092 final int copyRet; 7093 if (extractLibs) { 7094 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7095 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7096 } else { 7097 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7098 } 7099 7100 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7101 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7102 "Error unpackaging native libs for app, errorCode=" + copyRet); 7103 } 7104 7105 if (copyRet >= 0) { 7106 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7107 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7108 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7109 } else if (needsRenderScriptOverride) { 7110 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7111 } 7112 } 7113 } catch (IOException ioe) { 7114 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7115 } finally { 7116 IoUtils.closeQuietly(handle); 7117 } 7118 7119 // Now that we've calculated the ABIs and determined if it's an internal app, 7120 // we will go ahead and populate the nativeLibraryPath. 7121 setNativeLibraryPaths(pkg); 7122 } 7123 7124 /** 7125 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7126 * i.e, so that all packages can be run inside a single process if required. 7127 * 7128 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7129 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7130 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7131 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7132 * updating a package that belongs to a shared user. 7133 * 7134 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7135 * adds unnecessary complexity. 7136 */ 7137 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7138 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7139 String requiredInstructionSet = null; 7140 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7141 requiredInstructionSet = VMRuntime.getInstructionSet( 7142 scannedPackage.applicationInfo.primaryCpuAbi); 7143 } 7144 7145 PackageSetting requirer = null; 7146 for (PackageSetting ps : packagesForUser) { 7147 // If packagesForUser contains scannedPackage, we skip it. This will happen 7148 // when scannedPackage is an update of an existing package. Without this check, 7149 // we will never be able to change the ABI of any package belonging to a shared 7150 // user, even if it's compatible with other packages. 7151 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7152 if (ps.primaryCpuAbiString == null) { 7153 continue; 7154 } 7155 7156 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7157 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7158 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7159 // this but there's not much we can do. 7160 String errorMessage = "Instruction set mismatch, " 7161 + ((requirer == null) ? "[caller]" : requirer) 7162 + " requires " + requiredInstructionSet + " whereas " + ps 7163 + " requires " + instructionSet; 7164 Slog.w(TAG, errorMessage); 7165 } 7166 7167 if (requiredInstructionSet == null) { 7168 requiredInstructionSet = instructionSet; 7169 requirer = ps; 7170 } 7171 } 7172 } 7173 7174 if (requiredInstructionSet != null) { 7175 String adjustedAbi; 7176 if (requirer != null) { 7177 // requirer != null implies that either scannedPackage was null or that scannedPackage 7178 // did not require an ABI, in which case we have to adjust scannedPackage to match 7179 // the ABI of the set (which is the same as requirer's ABI) 7180 adjustedAbi = requirer.primaryCpuAbiString; 7181 if (scannedPackage != null) { 7182 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7183 } 7184 } else { 7185 // requirer == null implies that we're updating all ABIs in the set to 7186 // match scannedPackage. 7187 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7188 } 7189 7190 for (PackageSetting ps : packagesForUser) { 7191 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7192 if (ps.primaryCpuAbiString != null) { 7193 continue; 7194 } 7195 7196 ps.primaryCpuAbiString = adjustedAbi; 7197 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7198 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7199 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7200 7201 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7202 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7203 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7204 ps.primaryCpuAbiString = null; 7205 ps.pkg.applicationInfo.primaryCpuAbi = null; 7206 return; 7207 } else { 7208 mInstaller.rmdex(ps.codePathString, 7209 getDexCodeInstructionSet(getPreferredInstructionSet())); 7210 } 7211 } 7212 } 7213 } 7214 } 7215 } 7216 7217 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7218 synchronized (mPackages) { 7219 mResolverReplaced = true; 7220 // Set up information for custom user intent resolution activity. 7221 mResolveActivity.applicationInfo = pkg.applicationInfo; 7222 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7223 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7224 mResolveActivity.processName = pkg.applicationInfo.packageName; 7225 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7226 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7227 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7228 mResolveActivity.theme = 0; 7229 mResolveActivity.exported = true; 7230 mResolveActivity.enabled = true; 7231 mResolveInfo.activityInfo = mResolveActivity; 7232 mResolveInfo.priority = 0; 7233 mResolveInfo.preferredOrder = 0; 7234 mResolveInfo.match = 0; 7235 mResolveComponentName = mCustomResolverComponentName; 7236 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7237 mResolveComponentName); 7238 } 7239 } 7240 7241 private static String calculateBundledApkRoot(final String codePathString) { 7242 final File codePath = new File(codePathString); 7243 final File codeRoot; 7244 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7245 codeRoot = Environment.getRootDirectory(); 7246 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7247 codeRoot = Environment.getOemDirectory(); 7248 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7249 codeRoot = Environment.getVendorDirectory(); 7250 } else { 7251 // Unrecognized code path; take its top real segment as the apk root: 7252 // e.g. /something/app/blah.apk => /something 7253 try { 7254 File f = codePath.getCanonicalFile(); 7255 File parent = f.getParentFile(); // non-null because codePath is a file 7256 File tmp; 7257 while ((tmp = parent.getParentFile()) != null) { 7258 f = parent; 7259 parent = tmp; 7260 } 7261 codeRoot = f; 7262 Slog.w(TAG, "Unrecognized code path " 7263 + codePath + " - using " + codeRoot); 7264 } catch (IOException e) { 7265 // Can't canonicalize the code path -- shenanigans? 7266 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7267 return Environment.getRootDirectory().getPath(); 7268 } 7269 } 7270 return codeRoot.getPath(); 7271 } 7272 7273 /** 7274 * Derive and set the location of native libraries for the given package, 7275 * which varies depending on where and how the package was installed. 7276 */ 7277 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7278 final ApplicationInfo info = pkg.applicationInfo; 7279 final String codePath = pkg.codePath; 7280 final File codeFile = new File(codePath); 7281 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7282 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7283 7284 info.nativeLibraryRootDir = null; 7285 info.nativeLibraryRootRequiresIsa = false; 7286 info.nativeLibraryDir = null; 7287 info.secondaryNativeLibraryDir = null; 7288 7289 if (isApkFile(codeFile)) { 7290 // Monolithic install 7291 if (bundledApp) { 7292 // If "/system/lib64/apkname" exists, assume that is the per-package 7293 // native library directory to use; otherwise use "/system/lib/apkname". 7294 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7295 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7296 getPrimaryInstructionSet(info)); 7297 7298 // This is a bundled system app so choose the path based on the ABI. 7299 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7300 // is just the default path. 7301 final String apkName = deriveCodePathName(codePath); 7302 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7303 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7304 apkName).getAbsolutePath(); 7305 7306 if (info.secondaryCpuAbi != null) { 7307 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7308 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7309 secondaryLibDir, apkName).getAbsolutePath(); 7310 } 7311 } else if (asecApp) { 7312 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7313 .getAbsolutePath(); 7314 } else { 7315 final String apkName = deriveCodePathName(codePath); 7316 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7317 .getAbsolutePath(); 7318 } 7319 7320 info.nativeLibraryRootRequiresIsa = false; 7321 info.nativeLibraryDir = info.nativeLibraryRootDir; 7322 } else { 7323 // Cluster install 7324 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7325 info.nativeLibraryRootRequiresIsa = true; 7326 7327 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7328 getPrimaryInstructionSet(info)).getAbsolutePath(); 7329 7330 if (info.secondaryCpuAbi != null) { 7331 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7332 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7333 } 7334 } 7335 } 7336 7337 /** 7338 * Calculate the abis and roots for a bundled app. These can uniquely 7339 * be determined from the contents of the system partition, i.e whether 7340 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7341 * of this information, and instead assume that the system was built 7342 * sensibly. 7343 */ 7344 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7345 PackageSetting pkgSetting) { 7346 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7347 7348 // If "/system/lib64/apkname" exists, assume that is the per-package 7349 // native library directory to use; otherwise use "/system/lib/apkname". 7350 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7351 setBundledAppAbi(pkg, apkRoot, apkName); 7352 // pkgSetting might be null during rescan following uninstall of updates 7353 // to a bundled app, so accommodate that possibility. The settings in 7354 // that case will be established later from the parsed package. 7355 // 7356 // If the settings aren't null, sync them up with what we've just derived. 7357 // note that apkRoot isn't stored in the package settings. 7358 if (pkgSetting != null) { 7359 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7360 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7361 } 7362 } 7363 7364 /** 7365 * Deduces the ABI of a bundled app and sets the relevant fields on the 7366 * parsed pkg object. 7367 * 7368 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7369 * under which system libraries are installed. 7370 * @param apkName the name of the installed package. 7371 */ 7372 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7373 final File codeFile = new File(pkg.codePath); 7374 7375 final boolean has64BitLibs; 7376 final boolean has32BitLibs; 7377 if (isApkFile(codeFile)) { 7378 // Monolithic install 7379 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7380 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7381 } else { 7382 // Cluster install 7383 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7384 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7385 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7386 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7387 has64BitLibs = (new File(rootDir, isa)).exists(); 7388 } else { 7389 has64BitLibs = false; 7390 } 7391 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7392 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7393 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7394 has32BitLibs = (new File(rootDir, isa)).exists(); 7395 } else { 7396 has32BitLibs = false; 7397 } 7398 } 7399 7400 if (has64BitLibs && !has32BitLibs) { 7401 // The package has 64 bit libs, but not 32 bit libs. Its primary 7402 // ABI should be 64 bit. We can safely assume here that the bundled 7403 // native libraries correspond to the most preferred ABI in the list. 7404 7405 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7406 pkg.applicationInfo.secondaryCpuAbi = null; 7407 } else if (has32BitLibs && !has64BitLibs) { 7408 // The package has 32 bit libs but not 64 bit libs. Its primary 7409 // ABI should be 32 bit. 7410 7411 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7412 pkg.applicationInfo.secondaryCpuAbi = null; 7413 } else if (has32BitLibs && has64BitLibs) { 7414 // The application has both 64 and 32 bit bundled libraries. We check 7415 // here that the app declares multiArch support, and warn if it doesn't. 7416 // 7417 // We will be lenient here and record both ABIs. The primary will be the 7418 // ABI that's higher on the list, i.e, a device that's configured to prefer 7419 // 64 bit apps will see a 64 bit primary ABI, 7420 7421 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7422 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7423 } 7424 7425 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7426 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7427 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7428 } else { 7429 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7430 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7431 } 7432 } else { 7433 pkg.applicationInfo.primaryCpuAbi = null; 7434 pkg.applicationInfo.secondaryCpuAbi = null; 7435 } 7436 } 7437 7438 private void killApplication(String pkgName, int appId, String reason) { 7439 // Request the ActivityManager to kill the process(only for existing packages) 7440 // so that we do not end up in a confused state while the user is still using the older 7441 // version of the application while the new one gets installed. 7442 IActivityManager am = ActivityManagerNative.getDefault(); 7443 if (am != null) { 7444 try { 7445 am.killApplicationWithAppId(pkgName, appId, reason); 7446 } catch (RemoteException e) { 7447 } 7448 } 7449 } 7450 7451 void removePackageLI(PackageSetting ps, boolean chatty) { 7452 if (DEBUG_INSTALL) { 7453 if (chatty) 7454 Log.d(TAG, "Removing package " + ps.name); 7455 } 7456 7457 // writer 7458 synchronized (mPackages) { 7459 mPackages.remove(ps.name); 7460 final PackageParser.Package pkg = ps.pkg; 7461 if (pkg != null) { 7462 cleanPackageDataStructuresLILPw(pkg, chatty); 7463 } 7464 } 7465 } 7466 7467 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7468 if (DEBUG_INSTALL) { 7469 if (chatty) 7470 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7471 } 7472 7473 // writer 7474 synchronized (mPackages) { 7475 mPackages.remove(pkg.applicationInfo.packageName); 7476 cleanPackageDataStructuresLILPw(pkg, chatty); 7477 } 7478 } 7479 7480 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7481 int N = pkg.providers.size(); 7482 StringBuilder r = null; 7483 int i; 7484 for (i=0; i<N; i++) { 7485 PackageParser.Provider p = pkg.providers.get(i); 7486 mProviders.removeProvider(p); 7487 if (p.info.authority == null) { 7488 7489 /* There was another ContentProvider with this authority when 7490 * this app was installed so this authority is null, 7491 * Ignore it as we don't have to unregister the provider. 7492 */ 7493 continue; 7494 } 7495 String names[] = p.info.authority.split(";"); 7496 for (int j = 0; j < names.length; j++) { 7497 if (mProvidersByAuthority.get(names[j]) == p) { 7498 mProvidersByAuthority.remove(names[j]); 7499 if (DEBUG_REMOVE) { 7500 if (chatty) 7501 Log.d(TAG, "Unregistered content provider: " + names[j] 7502 + ", className = " + p.info.name + ", isSyncable = " 7503 + p.info.isSyncable); 7504 } 7505 } 7506 } 7507 if (DEBUG_REMOVE && chatty) { 7508 if (r == null) { 7509 r = new StringBuilder(256); 7510 } else { 7511 r.append(' '); 7512 } 7513 r.append(p.info.name); 7514 } 7515 } 7516 if (r != null) { 7517 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7518 } 7519 7520 N = pkg.services.size(); 7521 r = null; 7522 for (i=0; i<N; i++) { 7523 PackageParser.Service s = pkg.services.get(i); 7524 mServices.removeService(s); 7525 if (chatty) { 7526 if (r == null) { 7527 r = new StringBuilder(256); 7528 } else { 7529 r.append(' '); 7530 } 7531 r.append(s.info.name); 7532 } 7533 } 7534 if (r != null) { 7535 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7536 } 7537 7538 N = pkg.receivers.size(); 7539 r = null; 7540 for (i=0; i<N; i++) { 7541 PackageParser.Activity a = pkg.receivers.get(i); 7542 mReceivers.removeActivity(a, "receiver"); 7543 if (DEBUG_REMOVE && chatty) { 7544 if (r == null) { 7545 r = new StringBuilder(256); 7546 } else { 7547 r.append(' '); 7548 } 7549 r.append(a.info.name); 7550 } 7551 } 7552 if (r != null) { 7553 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7554 } 7555 7556 N = pkg.activities.size(); 7557 r = null; 7558 for (i=0; i<N; i++) { 7559 PackageParser.Activity a = pkg.activities.get(i); 7560 mActivities.removeActivity(a, "activity"); 7561 if (DEBUG_REMOVE && chatty) { 7562 if (r == null) { 7563 r = new StringBuilder(256); 7564 } else { 7565 r.append(' '); 7566 } 7567 r.append(a.info.name); 7568 } 7569 } 7570 if (r != null) { 7571 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7572 } 7573 7574 N = pkg.permissions.size(); 7575 r = null; 7576 for (i=0; i<N; i++) { 7577 PackageParser.Permission p = pkg.permissions.get(i); 7578 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7579 if (bp == null) { 7580 bp = mSettings.mPermissionTrees.get(p.info.name); 7581 } 7582 if (bp != null && bp.perm == p) { 7583 bp.perm = null; 7584 if (DEBUG_REMOVE && chatty) { 7585 if (r == null) { 7586 r = new StringBuilder(256); 7587 } else { 7588 r.append(' '); 7589 } 7590 r.append(p.info.name); 7591 } 7592 } 7593 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7594 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7595 if (appOpPerms != null) { 7596 appOpPerms.remove(pkg.packageName); 7597 } 7598 } 7599 } 7600 if (r != null) { 7601 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7602 } 7603 7604 N = pkg.requestedPermissions.size(); 7605 r = null; 7606 for (i=0; i<N; i++) { 7607 String perm = pkg.requestedPermissions.get(i); 7608 BasePermission bp = mSettings.mPermissions.get(perm); 7609 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7610 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7611 if (appOpPerms != null) { 7612 appOpPerms.remove(pkg.packageName); 7613 if (appOpPerms.isEmpty()) { 7614 mAppOpPermissionPackages.remove(perm); 7615 } 7616 } 7617 } 7618 } 7619 if (r != null) { 7620 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7621 } 7622 7623 N = pkg.instrumentation.size(); 7624 r = null; 7625 for (i=0; i<N; i++) { 7626 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7627 mInstrumentation.remove(a.getComponentName()); 7628 if (DEBUG_REMOVE && chatty) { 7629 if (r == null) { 7630 r = new StringBuilder(256); 7631 } else { 7632 r.append(' '); 7633 } 7634 r.append(a.info.name); 7635 } 7636 } 7637 if (r != null) { 7638 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7639 } 7640 7641 r = null; 7642 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7643 // Only system apps can hold shared libraries. 7644 if (pkg.libraryNames != null) { 7645 for (i=0; i<pkg.libraryNames.size(); i++) { 7646 String name = pkg.libraryNames.get(i); 7647 SharedLibraryEntry cur = mSharedLibraries.get(name); 7648 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7649 mSharedLibraries.remove(name); 7650 if (DEBUG_REMOVE && chatty) { 7651 if (r == null) { 7652 r = new StringBuilder(256); 7653 } else { 7654 r.append(' '); 7655 } 7656 r.append(name); 7657 } 7658 } 7659 } 7660 } 7661 } 7662 if (r != null) { 7663 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7664 } 7665 } 7666 7667 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7668 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7669 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7670 return true; 7671 } 7672 } 7673 return false; 7674 } 7675 7676 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7677 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7678 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7679 7680 private void updatePermissionsLPw(String changingPkg, 7681 PackageParser.Package pkgInfo, int flags) { 7682 // Make sure there are no dangling permission trees. 7683 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7684 while (it.hasNext()) { 7685 final BasePermission bp = it.next(); 7686 if (bp.packageSetting == null) { 7687 // We may not yet have parsed the package, so just see if 7688 // we still know about its settings. 7689 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7690 } 7691 if (bp.packageSetting == null) { 7692 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7693 + " from package " + bp.sourcePackage); 7694 it.remove(); 7695 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7696 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7697 Slog.i(TAG, "Removing old permission tree: " + bp.name 7698 + " from package " + bp.sourcePackage); 7699 flags |= UPDATE_PERMISSIONS_ALL; 7700 it.remove(); 7701 } 7702 } 7703 } 7704 7705 // Make sure all dynamic permissions have been assigned to a package, 7706 // and make sure there are no dangling permissions. 7707 it = mSettings.mPermissions.values().iterator(); 7708 while (it.hasNext()) { 7709 final BasePermission bp = it.next(); 7710 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7711 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7712 + bp.name + " pkg=" + bp.sourcePackage 7713 + " info=" + bp.pendingInfo); 7714 if (bp.packageSetting == null && bp.pendingInfo != null) { 7715 final BasePermission tree = findPermissionTreeLP(bp.name); 7716 if (tree != null && tree.perm != null) { 7717 bp.packageSetting = tree.packageSetting; 7718 bp.perm = new PackageParser.Permission(tree.perm.owner, 7719 new PermissionInfo(bp.pendingInfo)); 7720 bp.perm.info.packageName = tree.perm.info.packageName; 7721 bp.perm.info.name = bp.name; 7722 bp.uid = tree.uid; 7723 } 7724 } 7725 } 7726 if (bp.packageSetting == null) { 7727 // We may not yet have parsed the package, so just see if 7728 // we still know about its settings. 7729 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7730 } 7731 if (bp.packageSetting == null) { 7732 Slog.w(TAG, "Removing dangling permission: " + bp.name 7733 + " from package " + bp.sourcePackage); 7734 it.remove(); 7735 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7736 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7737 Slog.i(TAG, "Removing old permission: " + bp.name 7738 + " from package " + bp.sourcePackage); 7739 flags |= UPDATE_PERMISSIONS_ALL; 7740 it.remove(); 7741 } 7742 } 7743 } 7744 7745 // Now update the permissions for all packages, in particular 7746 // replace the granted permissions of the system packages. 7747 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7748 for (PackageParser.Package pkg : mPackages.values()) { 7749 if (pkg != pkgInfo) { 7750 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7751 changingPkg); 7752 } 7753 } 7754 } 7755 7756 if (pkgInfo != null) { 7757 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7758 } 7759 } 7760 7761 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7762 String packageOfInterest) { 7763 // IMPORTANT: There are two types of permissions: install and runtime. 7764 // Install time permissions are granted when the app is installed to 7765 // all device users and users added in the future. Runtime permissions 7766 // are granted at runtime explicitly to specific users. Normal and signature 7767 // protected permissions are install time permissions. Dangerous permissions 7768 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7769 // otherwise they are runtime permissions. This function does not manage 7770 // runtime permissions except for the case an app targeting Lollipop MR1 7771 // being upgraded to target a newer SDK, in which case dangerous permissions 7772 // are transformed from install time to runtime ones. 7773 7774 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7775 if (ps == null) { 7776 return; 7777 } 7778 7779 PermissionsState permissionsState = ps.getPermissionsState(); 7780 PermissionsState origPermissions = permissionsState; 7781 7782 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7783 7784 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7785 7786 boolean changedInstallPermission = false; 7787 7788 if (replace) { 7789 ps.installPermissionsFixed = false; 7790 if (!ps.isSharedUser()) { 7791 origPermissions = new PermissionsState(permissionsState); 7792 permissionsState.reset(); 7793 } 7794 } 7795 7796 permissionsState.setGlobalGids(mGlobalGids); 7797 7798 final int N = pkg.requestedPermissions.size(); 7799 for (int i=0; i<N; i++) { 7800 final String name = pkg.requestedPermissions.get(i); 7801 final BasePermission bp = mSettings.mPermissions.get(name); 7802 7803 if (DEBUG_INSTALL) { 7804 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7805 } 7806 7807 if (bp == null || bp.packageSetting == null) { 7808 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7809 Slog.w(TAG, "Unknown permission " + name 7810 + " in package " + pkg.packageName); 7811 } 7812 continue; 7813 } 7814 7815 final String perm = bp.name; 7816 boolean allowedSig = false; 7817 int grant = GRANT_DENIED; 7818 7819 // Keep track of app op permissions. 7820 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7821 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7822 if (pkgs == null) { 7823 pkgs = new ArraySet<>(); 7824 mAppOpPermissionPackages.put(bp.name, pkgs); 7825 } 7826 pkgs.add(pkg.packageName); 7827 } 7828 7829 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7830 switch (level) { 7831 case PermissionInfo.PROTECTION_NORMAL: { 7832 // For all apps normal permissions are install time ones. 7833 grant = GRANT_INSTALL; 7834 } break; 7835 7836 case PermissionInfo.PROTECTION_DANGEROUS: { 7837 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7838 // For legacy apps dangerous permissions are install time ones. 7839 grant = GRANT_INSTALL_LEGACY; 7840 } else if (origPermissions.hasInstallPermission(bp.name)) { 7841 // For legacy apps that became modern, install becomes runtime. 7842 grant = GRANT_UPGRADE; 7843 } else { 7844 // For modern apps keep runtime permissions unchanged. 7845 grant = GRANT_RUNTIME; 7846 } 7847 } break; 7848 7849 case PermissionInfo.PROTECTION_SIGNATURE: { 7850 // For all apps signature permissions are install time ones. 7851 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7852 if (allowedSig) { 7853 grant = GRANT_INSTALL; 7854 } 7855 } break; 7856 } 7857 7858 if (DEBUG_INSTALL) { 7859 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7860 } 7861 7862 if (grant != GRANT_DENIED) { 7863 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7864 // If this is an existing, non-system package, then 7865 // we can't add any new permissions to it. 7866 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7867 // Except... if this is a permission that was added 7868 // to the platform (note: need to only do this when 7869 // updating the platform). 7870 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7871 grant = GRANT_DENIED; 7872 } 7873 } 7874 } 7875 7876 switch (grant) { 7877 case GRANT_INSTALL: { 7878 // Revoke this as runtime permission to handle the case of 7879 // a runtime permission being downgraded to an install one. 7880 for (int userId : UserManagerService.getInstance().getUserIds()) { 7881 if (origPermissions.getRuntimePermissionState( 7882 bp.name, userId) != null) { 7883 // Revoke the runtime permission and clear the flags. 7884 origPermissions.revokeRuntimePermission(bp, userId); 7885 origPermissions.updatePermissionFlags(bp, userId, 7886 PackageManager.MASK_PERMISSION_FLAGS, 0); 7887 // If we revoked a permission permission, we have to write. 7888 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7889 changedRuntimePermissionUserIds, userId); 7890 } 7891 } 7892 // Grant an install permission. 7893 if (permissionsState.grantInstallPermission(bp) != 7894 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7895 changedInstallPermission = true; 7896 } 7897 } break; 7898 7899 case GRANT_INSTALL_LEGACY: { 7900 // Grant an install permission. 7901 if (permissionsState.grantInstallPermission(bp) != 7902 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7903 changedInstallPermission = true; 7904 } 7905 } break; 7906 7907 case GRANT_RUNTIME: { 7908 // Grant previously granted runtime permissions. 7909 for (int userId : UserManagerService.getInstance().getUserIds()) { 7910 PermissionState permissionState = origPermissions 7911 .getRuntimePermissionState(bp.name, userId); 7912 final int flags = permissionState != null 7913 ? permissionState.getFlags() : 0; 7914 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7915 if (permissionsState.grantRuntimePermission(bp, userId) == 7916 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7917 // If we cannot put the permission as it was, we have to write. 7918 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7919 changedRuntimePermissionUserIds, userId); 7920 } 7921 } 7922 // Propagate the permission flags. 7923 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 7924 } 7925 } break; 7926 7927 case GRANT_UPGRADE: { 7928 // Grant runtime permissions for a previously held install permission. 7929 PermissionState permissionState = origPermissions 7930 .getInstallPermissionState(bp.name); 7931 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7932 7933 if (origPermissions.revokeInstallPermission(bp) 7934 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 7935 // We will be transferring the permission flags, so clear them. 7936 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7937 PackageManager.MASK_PERMISSION_FLAGS, 0); 7938 changedInstallPermission = true; 7939 } 7940 7941 // If the permission is not to be promoted to runtime we ignore it and 7942 // also its other flags as they are not applicable to install permissions. 7943 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7944 for (int userId : currentUserIds) { 7945 if (permissionsState.grantRuntimePermission(bp, userId) != 7946 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7947 // Transfer the permission flags. 7948 permissionsState.updatePermissionFlags(bp, userId, 7949 flags, flags); 7950 // If we granted the permission, we have to write. 7951 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7952 changedRuntimePermissionUserIds, userId); 7953 } 7954 } 7955 } 7956 } break; 7957 7958 default: { 7959 if (packageOfInterest == null 7960 || packageOfInterest.equals(pkg.packageName)) { 7961 Slog.w(TAG, "Not granting permission " + perm 7962 + " to package " + pkg.packageName 7963 + " because it was previously installed without"); 7964 } 7965 } break; 7966 } 7967 } else { 7968 if (permissionsState.revokeInstallPermission(bp) != 7969 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7970 // Also drop the permission flags. 7971 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7972 PackageManager.MASK_PERMISSION_FLAGS, 0); 7973 changedInstallPermission = true; 7974 Slog.i(TAG, "Un-granting permission " + perm 7975 + " from package " + pkg.packageName 7976 + " (protectionLevel=" + bp.protectionLevel 7977 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7978 + ")"); 7979 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7980 // Don't print warning for app op permissions, since it is fine for them 7981 // not to be granted, there is a UI for the user to decide. 7982 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7983 Slog.w(TAG, "Not granting permission " + perm 7984 + " to package " + pkg.packageName 7985 + " (protectionLevel=" + bp.protectionLevel 7986 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7987 + ")"); 7988 } 7989 } 7990 } 7991 } 7992 7993 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7994 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7995 // This is the first that we have heard about this package, so the 7996 // permissions we have now selected are fixed until explicitly 7997 // changed. 7998 ps.installPermissionsFixed = true; 7999 } 8000 8001 // Persist the runtime permissions state for users with changes. 8002 for (int userId : changedRuntimePermissionUserIds) { 8003 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8004 } 8005 } 8006 8007 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8008 boolean allowed = false; 8009 final int NP = PackageParser.NEW_PERMISSIONS.length; 8010 for (int ip=0; ip<NP; ip++) { 8011 final PackageParser.NewPermissionInfo npi 8012 = PackageParser.NEW_PERMISSIONS[ip]; 8013 if (npi.name.equals(perm) 8014 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8015 allowed = true; 8016 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8017 + pkg.packageName); 8018 break; 8019 } 8020 } 8021 return allowed; 8022 } 8023 8024 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8025 BasePermission bp, PermissionsState origPermissions) { 8026 boolean allowed; 8027 allowed = (compareSignatures( 8028 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8029 == PackageManager.SIGNATURE_MATCH) 8030 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8031 == PackageManager.SIGNATURE_MATCH); 8032 if (!allowed && (bp.protectionLevel 8033 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8034 if (isSystemApp(pkg)) { 8035 // For updated system applications, a system permission 8036 // is granted only if it had been defined by the original application. 8037 if (pkg.isUpdatedSystemApp()) { 8038 final PackageSetting sysPs = mSettings 8039 .getDisabledSystemPkgLPr(pkg.packageName); 8040 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8041 // If the original was granted this permission, we take 8042 // that grant decision as read and propagate it to the 8043 // update. 8044 if (sysPs.isPrivileged()) { 8045 allowed = true; 8046 } 8047 } else { 8048 // The system apk may have been updated with an older 8049 // version of the one on the data partition, but which 8050 // granted a new system permission that it didn't have 8051 // before. In this case we do want to allow the app to 8052 // now get the new permission if the ancestral apk is 8053 // privileged to get it. 8054 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8055 for (int j=0; 8056 j<sysPs.pkg.requestedPermissions.size(); j++) { 8057 if (perm.equals( 8058 sysPs.pkg.requestedPermissions.get(j))) { 8059 allowed = true; 8060 break; 8061 } 8062 } 8063 } 8064 } 8065 } else { 8066 allowed = isPrivilegedApp(pkg); 8067 } 8068 } 8069 } 8070 if (!allowed && (bp.protectionLevel 8071 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8072 // For development permissions, a development permission 8073 // is granted only if it was already granted. 8074 allowed = origPermissions.hasInstallPermission(perm); 8075 } 8076 return allowed; 8077 } 8078 8079 final class ActivityIntentResolver 8080 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8081 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8082 boolean defaultOnly, int userId) { 8083 if (!sUserManager.exists(userId)) return null; 8084 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8085 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8086 } 8087 8088 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8089 int userId) { 8090 if (!sUserManager.exists(userId)) return null; 8091 mFlags = flags; 8092 return super.queryIntent(intent, resolvedType, 8093 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8094 } 8095 8096 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8097 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8098 if (!sUserManager.exists(userId)) return null; 8099 if (packageActivities == null) { 8100 return null; 8101 } 8102 mFlags = flags; 8103 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8104 final int N = packageActivities.size(); 8105 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8106 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8107 8108 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8109 for (int i = 0; i < N; ++i) { 8110 intentFilters = packageActivities.get(i).intents; 8111 if (intentFilters != null && intentFilters.size() > 0) { 8112 PackageParser.ActivityIntentInfo[] array = 8113 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8114 intentFilters.toArray(array); 8115 listCut.add(array); 8116 } 8117 } 8118 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8119 } 8120 8121 public final void addActivity(PackageParser.Activity a, String type) { 8122 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8123 mActivities.put(a.getComponentName(), a); 8124 if (DEBUG_SHOW_INFO) 8125 Log.v( 8126 TAG, " " + type + " " + 8127 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8128 if (DEBUG_SHOW_INFO) 8129 Log.v(TAG, " Class=" + a.info.name); 8130 final int NI = a.intents.size(); 8131 for (int j=0; j<NI; j++) { 8132 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8133 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8134 intent.setPriority(0); 8135 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8136 + a.className + " with priority > 0, forcing to 0"); 8137 } 8138 if (DEBUG_SHOW_INFO) { 8139 Log.v(TAG, " IntentFilter:"); 8140 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8141 } 8142 if (!intent.debugCheck()) { 8143 Log.w(TAG, "==> For Activity " + a.info.name); 8144 } 8145 addFilter(intent); 8146 } 8147 } 8148 8149 public final void removeActivity(PackageParser.Activity a, String type) { 8150 mActivities.remove(a.getComponentName()); 8151 if (DEBUG_SHOW_INFO) { 8152 Log.v(TAG, " " + type + " " 8153 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8154 : a.info.name) + ":"); 8155 Log.v(TAG, " Class=" + a.info.name); 8156 } 8157 final int NI = a.intents.size(); 8158 for (int j=0; j<NI; j++) { 8159 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8160 if (DEBUG_SHOW_INFO) { 8161 Log.v(TAG, " IntentFilter:"); 8162 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8163 } 8164 removeFilter(intent); 8165 } 8166 } 8167 8168 @Override 8169 protected boolean allowFilterResult( 8170 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8171 ActivityInfo filterAi = filter.activity.info; 8172 for (int i=dest.size()-1; i>=0; i--) { 8173 ActivityInfo destAi = dest.get(i).activityInfo; 8174 if (destAi.name == filterAi.name 8175 && destAi.packageName == filterAi.packageName) { 8176 return false; 8177 } 8178 } 8179 return true; 8180 } 8181 8182 @Override 8183 protected ActivityIntentInfo[] newArray(int size) { 8184 return new ActivityIntentInfo[size]; 8185 } 8186 8187 @Override 8188 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8189 if (!sUserManager.exists(userId)) return true; 8190 PackageParser.Package p = filter.activity.owner; 8191 if (p != null) { 8192 PackageSetting ps = (PackageSetting)p.mExtras; 8193 if (ps != null) { 8194 // System apps are never considered stopped for purposes of 8195 // filtering, because there may be no way for the user to 8196 // actually re-launch them. 8197 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8198 && ps.getStopped(userId); 8199 } 8200 } 8201 return false; 8202 } 8203 8204 @Override 8205 protected boolean isPackageForFilter(String packageName, 8206 PackageParser.ActivityIntentInfo info) { 8207 return packageName.equals(info.activity.owner.packageName); 8208 } 8209 8210 @Override 8211 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8212 int match, int userId) { 8213 if (!sUserManager.exists(userId)) return null; 8214 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8215 return null; 8216 } 8217 final PackageParser.Activity activity = info.activity; 8218 if (mSafeMode && (activity.info.applicationInfo.flags 8219 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8220 return null; 8221 } 8222 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8223 if (ps == null) { 8224 return null; 8225 } 8226 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8227 ps.readUserState(userId), userId); 8228 if (ai == null) { 8229 return null; 8230 } 8231 final ResolveInfo res = new ResolveInfo(); 8232 res.activityInfo = ai; 8233 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8234 res.filter = info; 8235 } 8236 if (info != null) { 8237 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8238 } 8239 res.priority = info.getPriority(); 8240 res.preferredOrder = activity.owner.mPreferredOrder; 8241 //System.out.println("Result: " + res.activityInfo.className + 8242 // " = " + res.priority); 8243 res.match = match; 8244 res.isDefault = info.hasDefault; 8245 res.labelRes = info.labelRes; 8246 res.nonLocalizedLabel = info.nonLocalizedLabel; 8247 if (userNeedsBadging(userId)) { 8248 res.noResourceId = true; 8249 } else { 8250 res.icon = info.icon; 8251 } 8252 res.iconResourceId = info.icon; 8253 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8254 return res; 8255 } 8256 8257 @Override 8258 protected void sortResults(List<ResolveInfo> results) { 8259 Collections.sort(results, mResolvePrioritySorter); 8260 } 8261 8262 @Override 8263 protected void dumpFilter(PrintWriter out, String prefix, 8264 PackageParser.ActivityIntentInfo filter) { 8265 out.print(prefix); out.print( 8266 Integer.toHexString(System.identityHashCode(filter.activity))); 8267 out.print(' '); 8268 filter.activity.printComponentShortName(out); 8269 out.print(" filter "); 8270 out.println(Integer.toHexString(System.identityHashCode(filter))); 8271 } 8272 8273 @Override 8274 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8275 return filter.activity; 8276 } 8277 8278 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8279 PackageParser.Activity activity = (PackageParser.Activity)label; 8280 out.print(prefix); out.print( 8281 Integer.toHexString(System.identityHashCode(activity))); 8282 out.print(' '); 8283 activity.printComponentShortName(out); 8284 if (count > 1) { 8285 out.print(" ("); out.print(count); out.print(" filters)"); 8286 } 8287 out.println(); 8288 } 8289 8290// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8291// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8292// final List<ResolveInfo> retList = Lists.newArrayList(); 8293// while (i.hasNext()) { 8294// final ResolveInfo resolveInfo = i.next(); 8295// if (isEnabledLP(resolveInfo.activityInfo)) { 8296// retList.add(resolveInfo); 8297// } 8298// } 8299// return retList; 8300// } 8301 8302 // Keys are String (activity class name), values are Activity. 8303 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8304 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8305 private int mFlags; 8306 } 8307 8308 private final class ServiceIntentResolver 8309 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8310 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8311 boolean defaultOnly, int userId) { 8312 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8313 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8314 } 8315 8316 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8317 int userId) { 8318 if (!sUserManager.exists(userId)) return null; 8319 mFlags = flags; 8320 return super.queryIntent(intent, resolvedType, 8321 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8322 } 8323 8324 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8325 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8326 if (!sUserManager.exists(userId)) return null; 8327 if (packageServices == null) { 8328 return null; 8329 } 8330 mFlags = flags; 8331 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8332 final int N = packageServices.size(); 8333 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8334 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8335 8336 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8337 for (int i = 0; i < N; ++i) { 8338 intentFilters = packageServices.get(i).intents; 8339 if (intentFilters != null && intentFilters.size() > 0) { 8340 PackageParser.ServiceIntentInfo[] array = 8341 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8342 intentFilters.toArray(array); 8343 listCut.add(array); 8344 } 8345 } 8346 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8347 } 8348 8349 public final void addService(PackageParser.Service s) { 8350 mServices.put(s.getComponentName(), s); 8351 if (DEBUG_SHOW_INFO) { 8352 Log.v(TAG, " " 8353 + (s.info.nonLocalizedLabel != null 8354 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8355 Log.v(TAG, " Class=" + s.info.name); 8356 } 8357 final int NI = s.intents.size(); 8358 int j; 8359 for (j=0; j<NI; j++) { 8360 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8361 if (DEBUG_SHOW_INFO) { 8362 Log.v(TAG, " IntentFilter:"); 8363 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8364 } 8365 if (!intent.debugCheck()) { 8366 Log.w(TAG, "==> For Service " + s.info.name); 8367 } 8368 addFilter(intent); 8369 } 8370 } 8371 8372 public final void removeService(PackageParser.Service s) { 8373 mServices.remove(s.getComponentName()); 8374 if (DEBUG_SHOW_INFO) { 8375 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8376 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8377 Log.v(TAG, " Class=" + s.info.name); 8378 } 8379 final int NI = s.intents.size(); 8380 int j; 8381 for (j=0; j<NI; j++) { 8382 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8383 if (DEBUG_SHOW_INFO) { 8384 Log.v(TAG, " IntentFilter:"); 8385 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8386 } 8387 removeFilter(intent); 8388 } 8389 } 8390 8391 @Override 8392 protected boolean allowFilterResult( 8393 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8394 ServiceInfo filterSi = filter.service.info; 8395 for (int i=dest.size()-1; i>=0; i--) { 8396 ServiceInfo destAi = dest.get(i).serviceInfo; 8397 if (destAi.name == filterSi.name 8398 && destAi.packageName == filterSi.packageName) { 8399 return false; 8400 } 8401 } 8402 return true; 8403 } 8404 8405 @Override 8406 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8407 return new PackageParser.ServiceIntentInfo[size]; 8408 } 8409 8410 @Override 8411 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8412 if (!sUserManager.exists(userId)) return true; 8413 PackageParser.Package p = filter.service.owner; 8414 if (p != null) { 8415 PackageSetting ps = (PackageSetting)p.mExtras; 8416 if (ps != null) { 8417 // System apps are never considered stopped for purposes of 8418 // filtering, because there may be no way for the user to 8419 // actually re-launch them. 8420 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8421 && ps.getStopped(userId); 8422 } 8423 } 8424 return false; 8425 } 8426 8427 @Override 8428 protected boolean isPackageForFilter(String packageName, 8429 PackageParser.ServiceIntentInfo info) { 8430 return packageName.equals(info.service.owner.packageName); 8431 } 8432 8433 @Override 8434 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8435 int match, int userId) { 8436 if (!sUserManager.exists(userId)) return null; 8437 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8438 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8439 return null; 8440 } 8441 final PackageParser.Service service = info.service; 8442 if (mSafeMode && (service.info.applicationInfo.flags 8443 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8444 return null; 8445 } 8446 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8447 if (ps == null) { 8448 return null; 8449 } 8450 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8451 ps.readUserState(userId), userId); 8452 if (si == null) { 8453 return null; 8454 } 8455 final ResolveInfo res = new ResolveInfo(); 8456 res.serviceInfo = si; 8457 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8458 res.filter = filter; 8459 } 8460 res.priority = info.getPriority(); 8461 res.preferredOrder = service.owner.mPreferredOrder; 8462 res.match = match; 8463 res.isDefault = info.hasDefault; 8464 res.labelRes = info.labelRes; 8465 res.nonLocalizedLabel = info.nonLocalizedLabel; 8466 res.icon = info.icon; 8467 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8468 return res; 8469 } 8470 8471 @Override 8472 protected void sortResults(List<ResolveInfo> results) { 8473 Collections.sort(results, mResolvePrioritySorter); 8474 } 8475 8476 @Override 8477 protected void dumpFilter(PrintWriter out, String prefix, 8478 PackageParser.ServiceIntentInfo filter) { 8479 out.print(prefix); out.print( 8480 Integer.toHexString(System.identityHashCode(filter.service))); 8481 out.print(' '); 8482 filter.service.printComponentShortName(out); 8483 out.print(" filter "); 8484 out.println(Integer.toHexString(System.identityHashCode(filter))); 8485 } 8486 8487 @Override 8488 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8489 return filter.service; 8490 } 8491 8492 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8493 PackageParser.Service service = (PackageParser.Service)label; 8494 out.print(prefix); out.print( 8495 Integer.toHexString(System.identityHashCode(service))); 8496 out.print(' '); 8497 service.printComponentShortName(out); 8498 if (count > 1) { 8499 out.print(" ("); out.print(count); out.print(" filters)"); 8500 } 8501 out.println(); 8502 } 8503 8504// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8505// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8506// final List<ResolveInfo> retList = Lists.newArrayList(); 8507// while (i.hasNext()) { 8508// final ResolveInfo resolveInfo = (ResolveInfo) i; 8509// if (isEnabledLP(resolveInfo.serviceInfo)) { 8510// retList.add(resolveInfo); 8511// } 8512// } 8513// return retList; 8514// } 8515 8516 // Keys are String (activity class name), values are Activity. 8517 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8518 = new ArrayMap<ComponentName, PackageParser.Service>(); 8519 private int mFlags; 8520 }; 8521 8522 private final class ProviderIntentResolver 8523 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8524 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8525 boolean defaultOnly, int userId) { 8526 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8527 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8528 } 8529 8530 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8531 int userId) { 8532 if (!sUserManager.exists(userId)) 8533 return null; 8534 mFlags = flags; 8535 return super.queryIntent(intent, resolvedType, 8536 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8537 } 8538 8539 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8540 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8541 if (!sUserManager.exists(userId)) 8542 return null; 8543 if (packageProviders == null) { 8544 return null; 8545 } 8546 mFlags = flags; 8547 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8548 final int N = packageProviders.size(); 8549 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8550 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8551 8552 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8553 for (int i = 0; i < N; ++i) { 8554 intentFilters = packageProviders.get(i).intents; 8555 if (intentFilters != null && intentFilters.size() > 0) { 8556 PackageParser.ProviderIntentInfo[] array = 8557 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8558 intentFilters.toArray(array); 8559 listCut.add(array); 8560 } 8561 } 8562 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8563 } 8564 8565 public final void addProvider(PackageParser.Provider p) { 8566 if (mProviders.containsKey(p.getComponentName())) { 8567 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8568 return; 8569 } 8570 8571 mProviders.put(p.getComponentName(), p); 8572 if (DEBUG_SHOW_INFO) { 8573 Log.v(TAG, " " 8574 + (p.info.nonLocalizedLabel != null 8575 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8576 Log.v(TAG, " Class=" + p.info.name); 8577 } 8578 final int NI = p.intents.size(); 8579 int j; 8580 for (j = 0; j < NI; j++) { 8581 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8582 if (DEBUG_SHOW_INFO) { 8583 Log.v(TAG, " IntentFilter:"); 8584 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8585 } 8586 if (!intent.debugCheck()) { 8587 Log.w(TAG, "==> For Provider " + p.info.name); 8588 } 8589 addFilter(intent); 8590 } 8591 } 8592 8593 public final void removeProvider(PackageParser.Provider p) { 8594 mProviders.remove(p.getComponentName()); 8595 if (DEBUG_SHOW_INFO) { 8596 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8597 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8598 Log.v(TAG, " Class=" + p.info.name); 8599 } 8600 final int NI = p.intents.size(); 8601 int j; 8602 for (j = 0; j < NI; j++) { 8603 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8604 if (DEBUG_SHOW_INFO) { 8605 Log.v(TAG, " IntentFilter:"); 8606 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8607 } 8608 removeFilter(intent); 8609 } 8610 } 8611 8612 @Override 8613 protected boolean allowFilterResult( 8614 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8615 ProviderInfo filterPi = filter.provider.info; 8616 for (int i = dest.size() - 1; i >= 0; i--) { 8617 ProviderInfo destPi = dest.get(i).providerInfo; 8618 if (destPi.name == filterPi.name 8619 && destPi.packageName == filterPi.packageName) { 8620 return false; 8621 } 8622 } 8623 return true; 8624 } 8625 8626 @Override 8627 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8628 return new PackageParser.ProviderIntentInfo[size]; 8629 } 8630 8631 @Override 8632 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8633 if (!sUserManager.exists(userId)) 8634 return true; 8635 PackageParser.Package p = filter.provider.owner; 8636 if (p != null) { 8637 PackageSetting ps = (PackageSetting) p.mExtras; 8638 if (ps != null) { 8639 // System apps are never considered stopped for purposes of 8640 // filtering, because there may be no way for the user to 8641 // actually re-launch them. 8642 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8643 && ps.getStopped(userId); 8644 } 8645 } 8646 return false; 8647 } 8648 8649 @Override 8650 protected boolean isPackageForFilter(String packageName, 8651 PackageParser.ProviderIntentInfo info) { 8652 return packageName.equals(info.provider.owner.packageName); 8653 } 8654 8655 @Override 8656 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8657 int match, int userId) { 8658 if (!sUserManager.exists(userId)) 8659 return null; 8660 final PackageParser.ProviderIntentInfo info = filter; 8661 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8662 return null; 8663 } 8664 final PackageParser.Provider provider = info.provider; 8665 if (mSafeMode && (provider.info.applicationInfo.flags 8666 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8667 return null; 8668 } 8669 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8670 if (ps == null) { 8671 return null; 8672 } 8673 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8674 ps.readUserState(userId), userId); 8675 if (pi == null) { 8676 return null; 8677 } 8678 final ResolveInfo res = new ResolveInfo(); 8679 res.providerInfo = pi; 8680 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8681 res.filter = filter; 8682 } 8683 res.priority = info.getPriority(); 8684 res.preferredOrder = provider.owner.mPreferredOrder; 8685 res.match = match; 8686 res.isDefault = info.hasDefault; 8687 res.labelRes = info.labelRes; 8688 res.nonLocalizedLabel = info.nonLocalizedLabel; 8689 res.icon = info.icon; 8690 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8691 return res; 8692 } 8693 8694 @Override 8695 protected void sortResults(List<ResolveInfo> results) { 8696 Collections.sort(results, mResolvePrioritySorter); 8697 } 8698 8699 @Override 8700 protected void dumpFilter(PrintWriter out, String prefix, 8701 PackageParser.ProviderIntentInfo filter) { 8702 out.print(prefix); 8703 out.print( 8704 Integer.toHexString(System.identityHashCode(filter.provider))); 8705 out.print(' '); 8706 filter.provider.printComponentShortName(out); 8707 out.print(" filter "); 8708 out.println(Integer.toHexString(System.identityHashCode(filter))); 8709 } 8710 8711 @Override 8712 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8713 return filter.provider; 8714 } 8715 8716 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8717 PackageParser.Provider provider = (PackageParser.Provider)label; 8718 out.print(prefix); out.print( 8719 Integer.toHexString(System.identityHashCode(provider))); 8720 out.print(' '); 8721 provider.printComponentShortName(out); 8722 if (count > 1) { 8723 out.print(" ("); out.print(count); out.print(" filters)"); 8724 } 8725 out.println(); 8726 } 8727 8728 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8729 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8730 private int mFlags; 8731 }; 8732 8733 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8734 new Comparator<ResolveInfo>() { 8735 public int compare(ResolveInfo r1, ResolveInfo r2) { 8736 int v1 = r1.priority; 8737 int v2 = r2.priority; 8738 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8739 if (v1 != v2) { 8740 return (v1 > v2) ? -1 : 1; 8741 } 8742 v1 = r1.preferredOrder; 8743 v2 = r2.preferredOrder; 8744 if (v1 != v2) { 8745 return (v1 > v2) ? -1 : 1; 8746 } 8747 if (r1.isDefault != r2.isDefault) { 8748 return r1.isDefault ? -1 : 1; 8749 } 8750 v1 = r1.match; 8751 v2 = r2.match; 8752 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8753 if (v1 != v2) { 8754 return (v1 > v2) ? -1 : 1; 8755 } 8756 if (r1.system != r2.system) { 8757 return r1.system ? -1 : 1; 8758 } 8759 return 0; 8760 } 8761 }; 8762 8763 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8764 new Comparator<ProviderInfo>() { 8765 public int compare(ProviderInfo p1, ProviderInfo p2) { 8766 final int v1 = p1.initOrder; 8767 final int v2 = p2.initOrder; 8768 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8769 } 8770 }; 8771 8772 final void sendPackageBroadcast(final String action, final String pkg, 8773 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8774 final int[] userIds) { 8775 mHandler.post(new Runnable() { 8776 @Override 8777 public void run() { 8778 try { 8779 final IActivityManager am = ActivityManagerNative.getDefault(); 8780 if (am == null) return; 8781 final int[] resolvedUserIds; 8782 if (userIds == null) { 8783 resolvedUserIds = am.getRunningUserIds(); 8784 } else { 8785 resolvedUserIds = userIds; 8786 } 8787 for (int id : resolvedUserIds) { 8788 final Intent intent = new Intent(action, 8789 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8790 if (extras != null) { 8791 intent.putExtras(extras); 8792 } 8793 if (targetPkg != null) { 8794 intent.setPackage(targetPkg); 8795 } 8796 // Modify the UID when posting to other users 8797 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8798 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8799 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8800 intent.putExtra(Intent.EXTRA_UID, uid); 8801 } 8802 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8803 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8804 if (DEBUG_BROADCASTS) { 8805 RuntimeException here = new RuntimeException("here"); 8806 here.fillInStackTrace(); 8807 Slog.d(TAG, "Sending to user " + id + ": " 8808 + intent.toShortString(false, true, false, false) 8809 + " " + intent.getExtras(), here); 8810 } 8811 am.broadcastIntent(null, intent, null, finishedReceiver, 8812 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8813 null, finishedReceiver != null, false, id); 8814 } 8815 } catch (RemoteException ex) { 8816 } 8817 } 8818 }); 8819 } 8820 8821 /** 8822 * Check if the external storage media is available. This is true if there 8823 * is a mounted external storage medium or if the external storage is 8824 * emulated. 8825 */ 8826 private boolean isExternalMediaAvailable() { 8827 return mMediaMounted || Environment.isExternalStorageEmulated(); 8828 } 8829 8830 @Override 8831 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8832 // writer 8833 synchronized (mPackages) { 8834 if (!isExternalMediaAvailable()) { 8835 // If the external storage is no longer mounted at this point, 8836 // the caller may not have been able to delete all of this 8837 // packages files and can not delete any more. Bail. 8838 return null; 8839 } 8840 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8841 if (lastPackage != null) { 8842 pkgs.remove(lastPackage); 8843 } 8844 if (pkgs.size() > 0) { 8845 return pkgs.get(0); 8846 } 8847 } 8848 return null; 8849 } 8850 8851 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8852 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8853 userId, andCode ? 1 : 0, packageName); 8854 if (mSystemReady) { 8855 msg.sendToTarget(); 8856 } else { 8857 if (mPostSystemReadyMessages == null) { 8858 mPostSystemReadyMessages = new ArrayList<>(); 8859 } 8860 mPostSystemReadyMessages.add(msg); 8861 } 8862 } 8863 8864 void startCleaningPackages() { 8865 // reader 8866 synchronized (mPackages) { 8867 if (!isExternalMediaAvailable()) { 8868 return; 8869 } 8870 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8871 return; 8872 } 8873 } 8874 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8875 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8876 IActivityManager am = ActivityManagerNative.getDefault(); 8877 if (am != null) { 8878 try { 8879 am.startService(null, intent, null, UserHandle.USER_OWNER); 8880 } catch (RemoteException e) { 8881 } 8882 } 8883 } 8884 8885 @Override 8886 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8887 int installFlags, String installerPackageName, VerificationParams verificationParams, 8888 String packageAbiOverride) { 8889 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8890 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8891 } 8892 8893 @Override 8894 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8895 int installFlags, String installerPackageName, VerificationParams verificationParams, 8896 String packageAbiOverride, int userId) { 8897 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8898 8899 final int callingUid = Binder.getCallingUid(); 8900 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8901 8902 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8903 try { 8904 if (observer != null) { 8905 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8906 } 8907 } catch (RemoteException re) { 8908 } 8909 return; 8910 } 8911 8912 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8913 installFlags |= PackageManager.INSTALL_FROM_ADB; 8914 8915 } else { 8916 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8917 // about installerPackageName. 8918 8919 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8920 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8921 } 8922 8923 UserHandle user; 8924 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8925 user = UserHandle.ALL; 8926 } else { 8927 user = new UserHandle(userId); 8928 } 8929 8930 // Only system components can circumvent runtime permissions when installing. 8931 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8932 && mContext.checkCallingOrSelfPermission(Manifest.permission 8933 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8934 throw new SecurityException("You need the " 8935 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8936 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8937 } 8938 8939 verificationParams.setInstallerUid(callingUid); 8940 8941 final File originFile = new File(originPath); 8942 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8943 8944 final Message msg = mHandler.obtainMessage(INIT_COPY); 8945 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8946 null, verificationParams, user, packageAbiOverride); 8947 mHandler.sendMessage(msg); 8948 } 8949 8950 void installStage(String packageName, File stagedDir, String stagedCid, 8951 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8952 String installerPackageName, int installerUid, UserHandle user) { 8953 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8954 params.referrerUri, installerUid, null); 8955 8956 final OriginInfo origin; 8957 if (stagedDir != null) { 8958 origin = OriginInfo.fromStagedFile(stagedDir); 8959 } else { 8960 origin = OriginInfo.fromStagedContainer(stagedCid); 8961 } 8962 8963 final Message msg = mHandler.obtainMessage(INIT_COPY); 8964 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8965 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8966 mHandler.sendMessage(msg); 8967 } 8968 8969 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8970 Bundle extras = new Bundle(1); 8971 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8972 8973 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8974 packageName, extras, null, null, new int[] {userId}); 8975 try { 8976 IActivityManager am = ActivityManagerNative.getDefault(); 8977 final boolean isSystem = 8978 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8979 if (isSystem && am.isUserRunning(userId, false)) { 8980 // The just-installed/enabled app is bundled on the system, so presumed 8981 // to be able to run automatically without needing an explicit launch. 8982 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8983 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8984 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8985 .setPackage(packageName); 8986 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8987 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 8988 } 8989 } catch (RemoteException e) { 8990 // shouldn't happen 8991 Slog.w(TAG, "Unable to bootstrap installed package", e); 8992 } 8993 } 8994 8995 @Override 8996 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8997 int userId) { 8998 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8999 PackageSetting pkgSetting; 9000 final int uid = Binder.getCallingUid(); 9001 enforceCrossUserPermission(uid, userId, true, true, 9002 "setApplicationHiddenSetting for user " + userId); 9003 9004 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9005 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9006 return false; 9007 } 9008 9009 long callingId = Binder.clearCallingIdentity(); 9010 try { 9011 boolean sendAdded = false; 9012 boolean sendRemoved = false; 9013 // writer 9014 synchronized (mPackages) { 9015 pkgSetting = mSettings.mPackages.get(packageName); 9016 if (pkgSetting == null) { 9017 return false; 9018 } 9019 if (pkgSetting.getHidden(userId) != hidden) { 9020 pkgSetting.setHidden(hidden, userId); 9021 mSettings.writePackageRestrictionsLPr(userId); 9022 if (hidden) { 9023 sendRemoved = true; 9024 } else { 9025 sendAdded = true; 9026 } 9027 } 9028 } 9029 if (sendAdded) { 9030 sendPackageAddedForUser(packageName, pkgSetting, userId); 9031 return true; 9032 } 9033 if (sendRemoved) { 9034 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9035 "hiding pkg"); 9036 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9037 } 9038 } finally { 9039 Binder.restoreCallingIdentity(callingId); 9040 } 9041 return false; 9042 } 9043 9044 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9045 int userId) { 9046 final PackageRemovedInfo info = new PackageRemovedInfo(); 9047 info.removedPackage = packageName; 9048 info.removedUsers = new int[] {userId}; 9049 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9050 info.sendBroadcast(false, false, false); 9051 } 9052 9053 /** 9054 * Returns true if application is not found or there was an error. Otherwise it returns 9055 * the hidden state of the package for the given user. 9056 */ 9057 @Override 9058 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9059 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9060 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9061 false, "getApplicationHidden for user " + userId); 9062 PackageSetting pkgSetting; 9063 long callingId = Binder.clearCallingIdentity(); 9064 try { 9065 // writer 9066 synchronized (mPackages) { 9067 pkgSetting = mSettings.mPackages.get(packageName); 9068 if (pkgSetting == null) { 9069 return true; 9070 } 9071 return pkgSetting.getHidden(userId); 9072 } 9073 } finally { 9074 Binder.restoreCallingIdentity(callingId); 9075 } 9076 } 9077 9078 /** 9079 * @hide 9080 */ 9081 @Override 9082 public int installExistingPackageAsUser(String packageName, int userId) { 9083 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9084 null); 9085 PackageSetting pkgSetting; 9086 final int uid = Binder.getCallingUid(); 9087 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9088 + userId); 9089 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9090 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9091 } 9092 9093 long callingId = Binder.clearCallingIdentity(); 9094 try { 9095 boolean sendAdded = false; 9096 9097 // writer 9098 synchronized (mPackages) { 9099 pkgSetting = mSettings.mPackages.get(packageName); 9100 if (pkgSetting == null) { 9101 return PackageManager.INSTALL_FAILED_INVALID_URI; 9102 } 9103 if (!pkgSetting.getInstalled(userId)) { 9104 pkgSetting.setInstalled(true, userId); 9105 pkgSetting.setHidden(false, userId); 9106 mSettings.writePackageRestrictionsLPr(userId); 9107 sendAdded = true; 9108 } 9109 } 9110 9111 if (sendAdded) { 9112 sendPackageAddedForUser(packageName, pkgSetting, userId); 9113 } 9114 } finally { 9115 Binder.restoreCallingIdentity(callingId); 9116 } 9117 9118 return PackageManager.INSTALL_SUCCEEDED; 9119 } 9120 9121 boolean isUserRestricted(int userId, String restrictionKey) { 9122 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9123 if (restrictions.getBoolean(restrictionKey, false)) { 9124 Log.w(TAG, "User is restricted: " + restrictionKey); 9125 return true; 9126 } 9127 return false; 9128 } 9129 9130 @Override 9131 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9132 mContext.enforceCallingOrSelfPermission( 9133 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9134 "Only package verification agents can verify applications"); 9135 9136 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9137 final PackageVerificationResponse response = new PackageVerificationResponse( 9138 verificationCode, Binder.getCallingUid()); 9139 msg.arg1 = id; 9140 msg.obj = response; 9141 mHandler.sendMessage(msg); 9142 } 9143 9144 @Override 9145 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9146 long millisecondsToDelay) { 9147 mContext.enforceCallingOrSelfPermission( 9148 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9149 "Only package verification agents can extend verification timeouts"); 9150 9151 final PackageVerificationState state = mPendingVerification.get(id); 9152 final PackageVerificationResponse response = new PackageVerificationResponse( 9153 verificationCodeAtTimeout, Binder.getCallingUid()); 9154 9155 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9156 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9157 } 9158 if (millisecondsToDelay < 0) { 9159 millisecondsToDelay = 0; 9160 } 9161 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9162 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9163 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9164 } 9165 9166 if ((state != null) && !state.timeoutExtended()) { 9167 state.extendTimeout(); 9168 9169 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9170 msg.arg1 = id; 9171 msg.obj = response; 9172 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9173 } 9174 } 9175 9176 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9177 int verificationCode, UserHandle user) { 9178 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9179 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9180 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9181 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9182 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9183 9184 mContext.sendBroadcastAsUser(intent, user, 9185 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9186 } 9187 9188 private ComponentName matchComponentForVerifier(String packageName, 9189 List<ResolveInfo> receivers) { 9190 ActivityInfo targetReceiver = null; 9191 9192 final int NR = receivers.size(); 9193 for (int i = 0; i < NR; i++) { 9194 final ResolveInfo info = receivers.get(i); 9195 if (info.activityInfo == null) { 9196 continue; 9197 } 9198 9199 if (packageName.equals(info.activityInfo.packageName)) { 9200 targetReceiver = info.activityInfo; 9201 break; 9202 } 9203 } 9204 9205 if (targetReceiver == null) { 9206 return null; 9207 } 9208 9209 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9210 } 9211 9212 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9213 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9214 if (pkgInfo.verifiers.length == 0) { 9215 return null; 9216 } 9217 9218 final int N = pkgInfo.verifiers.length; 9219 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9220 for (int i = 0; i < N; i++) { 9221 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9222 9223 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9224 receivers); 9225 if (comp == null) { 9226 continue; 9227 } 9228 9229 final int verifierUid = getUidForVerifier(verifierInfo); 9230 if (verifierUid == -1) { 9231 continue; 9232 } 9233 9234 if (DEBUG_VERIFY) { 9235 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9236 + " with the correct signature"); 9237 } 9238 sufficientVerifiers.add(comp); 9239 verificationState.addSufficientVerifier(verifierUid); 9240 } 9241 9242 return sufficientVerifiers; 9243 } 9244 9245 private int getUidForVerifier(VerifierInfo verifierInfo) { 9246 synchronized (mPackages) { 9247 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9248 if (pkg == null) { 9249 return -1; 9250 } else if (pkg.mSignatures.length != 1) { 9251 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9252 + " has more than one signature; ignoring"); 9253 return -1; 9254 } 9255 9256 /* 9257 * If the public key of the package's signature does not match 9258 * our expected public key, then this is a different package and 9259 * we should skip. 9260 */ 9261 9262 final byte[] expectedPublicKey; 9263 try { 9264 final Signature verifierSig = pkg.mSignatures[0]; 9265 final PublicKey publicKey = verifierSig.getPublicKey(); 9266 expectedPublicKey = publicKey.getEncoded(); 9267 } catch (CertificateException e) { 9268 return -1; 9269 } 9270 9271 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9272 9273 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9274 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9275 + " does not have the expected public key; ignoring"); 9276 return -1; 9277 } 9278 9279 return pkg.applicationInfo.uid; 9280 } 9281 } 9282 9283 @Override 9284 public void finishPackageInstall(int token) { 9285 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9286 9287 if (DEBUG_INSTALL) { 9288 Slog.v(TAG, "BM finishing package install for " + token); 9289 } 9290 9291 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9292 mHandler.sendMessage(msg); 9293 } 9294 9295 /** 9296 * Get the verification agent timeout. 9297 * 9298 * @return verification timeout in milliseconds 9299 */ 9300 private long getVerificationTimeout() { 9301 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9302 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9303 DEFAULT_VERIFICATION_TIMEOUT); 9304 } 9305 9306 /** 9307 * Get the default verification agent response code. 9308 * 9309 * @return default verification response code 9310 */ 9311 private int getDefaultVerificationResponse() { 9312 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9313 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9314 DEFAULT_VERIFICATION_RESPONSE); 9315 } 9316 9317 /** 9318 * Check whether or not package verification has been enabled. 9319 * 9320 * @return true if verification should be performed 9321 */ 9322 private boolean isVerificationEnabled(int userId, int installFlags) { 9323 if (!DEFAULT_VERIFY_ENABLE) { 9324 return false; 9325 } 9326 9327 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9328 9329 // Check if installing from ADB 9330 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9331 // Do not run verification in a test harness environment 9332 if (ActivityManager.isRunningInTestHarness()) { 9333 return false; 9334 } 9335 if (ensureVerifyAppsEnabled) { 9336 return true; 9337 } 9338 // Check if the developer does not want package verification for ADB installs 9339 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9340 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9341 return false; 9342 } 9343 } 9344 9345 if (ensureVerifyAppsEnabled) { 9346 return true; 9347 } 9348 9349 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9350 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9351 } 9352 9353 @Override 9354 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9355 throws RemoteException { 9356 mContext.enforceCallingOrSelfPermission( 9357 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9358 "Only intentfilter verification agents can verify applications"); 9359 9360 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9361 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9362 Binder.getCallingUid(), verificationCode, failedDomains); 9363 msg.arg1 = id; 9364 msg.obj = response; 9365 mHandler.sendMessage(msg); 9366 } 9367 9368 @Override 9369 public int getIntentVerificationStatus(String packageName, int userId) { 9370 synchronized (mPackages) { 9371 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9372 } 9373 } 9374 9375 @Override 9376 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9377 boolean result = false; 9378 synchronized (mPackages) { 9379 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9380 } 9381 if (result) { 9382 scheduleWritePackageRestrictionsLocked(userId); 9383 } 9384 return result; 9385 } 9386 9387 @Override 9388 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9389 synchronized (mPackages) { 9390 return mSettings.getIntentFilterVerificationsLPr(packageName); 9391 } 9392 } 9393 9394 @Override 9395 public List<IntentFilter> getAllIntentFilters(String packageName) { 9396 if (TextUtils.isEmpty(packageName)) { 9397 return Collections.<IntentFilter>emptyList(); 9398 } 9399 synchronized (mPackages) { 9400 PackageParser.Package pkg = mPackages.get(packageName); 9401 if (pkg == null || pkg.activities == null) { 9402 return Collections.<IntentFilter>emptyList(); 9403 } 9404 final int count = pkg.activities.size(); 9405 ArrayList<IntentFilter> result = new ArrayList<>(); 9406 for (int n=0; n<count; n++) { 9407 PackageParser.Activity activity = pkg.activities.get(n); 9408 if (activity.intents != null || activity.intents.size() > 0) { 9409 result.addAll(activity.intents); 9410 } 9411 } 9412 return result; 9413 } 9414 } 9415 9416 @Override 9417 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9418 synchronized (mPackages) { 9419 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9420 if (packageName != null) { 9421 result |= updateIntentVerificationStatus(packageName, 9422 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9423 UserHandle.myUserId()); 9424 } 9425 return result; 9426 } 9427 } 9428 9429 @Override 9430 public String getDefaultBrowserPackageName(int userId) { 9431 synchronized (mPackages) { 9432 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9433 } 9434 } 9435 9436 /** 9437 * Get the "allow unknown sources" setting. 9438 * 9439 * @return the current "allow unknown sources" setting 9440 */ 9441 private int getUnknownSourcesSettings() { 9442 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9443 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9444 -1); 9445 } 9446 9447 @Override 9448 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9449 final int uid = Binder.getCallingUid(); 9450 // writer 9451 synchronized (mPackages) { 9452 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9453 if (targetPackageSetting == null) { 9454 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9455 } 9456 9457 PackageSetting installerPackageSetting; 9458 if (installerPackageName != null) { 9459 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9460 if (installerPackageSetting == null) { 9461 throw new IllegalArgumentException("Unknown installer package: " 9462 + installerPackageName); 9463 } 9464 } else { 9465 installerPackageSetting = null; 9466 } 9467 9468 Signature[] callerSignature; 9469 Object obj = mSettings.getUserIdLPr(uid); 9470 if (obj != null) { 9471 if (obj instanceof SharedUserSetting) { 9472 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9473 } else if (obj instanceof PackageSetting) { 9474 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9475 } else { 9476 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9477 } 9478 } else { 9479 throw new SecurityException("Unknown calling uid " + uid); 9480 } 9481 9482 // Verify: can't set installerPackageName to a package that is 9483 // not signed with the same cert as the caller. 9484 if (installerPackageSetting != null) { 9485 if (compareSignatures(callerSignature, 9486 installerPackageSetting.signatures.mSignatures) 9487 != PackageManager.SIGNATURE_MATCH) { 9488 throw new SecurityException( 9489 "Caller does not have same cert as new installer package " 9490 + installerPackageName); 9491 } 9492 } 9493 9494 // Verify: if target already has an installer package, it must 9495 // be signed with the same cert as the caller. 9496 if (targetPackageSetting.installerPackageName != null) { 9497 PackageSetting setting = mSettings.mPackages.get( 9498 targetPackageSetting.installerPackageName); 9499 // If the currently set package isn't valid, then it's always 9500 // okay to change it. 9501 if (setting != null) { 9502 if (compareSignatures(callerSignature, 9503 setting.signatures.mSignatures) 9504 != PackageManager.SIGNATURE_MATCH) { 9505 throw new SecurityException( 9506 "Caller does not have same cert as old installer package " 9507 + targetPackageSetting.installerPackageName); 9508 } 9509 } 9510 } 9511 9512 // Okay! 9513 targetPackageSetting.installerPackageName = installerPackageName; 9514 scheduleWriteSettingsLocked(); 9515 } 9516 } 9517 9518 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9519 // Queue up an async operation since the package installation may take a little while. 9520 mHandler.post(new Runnable() { 9521 public void run() { 9522 mHandler.removeCallbacks(this); 9523 // Result object to be returned 9524 PackageInstalledInfo res = new PackageInstalledInfo(); 9525 res.returnCode = currentStatus; 9526 res.uid = -1; 9527 res.pkg = null; 9528 res.removedInfo = new PackageRemovedInfo(); 9529 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9530 args.doPreInstall(res.returnCode); 9531 synchronized (mInstallLock) { 9532 installPackageLI(args, res); 9533 } 9534 args.doPostInstall(res.returnCode, res.uid); 9535 } 9536 9537 // A restore should be performed at this point if (a) the install 9538 // succeeded, (b) the operation is not an update, and (c) the new 9539 // package has not opted out of backup participation. 9540 final boolean update = res.removedInfo.removedPackage != null; 9541 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9542 boolean doRestore = !update 9543 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9544 9545 // Set up the post-install work request bookkeeping. This will be used 9546 // and cleaned up by the post-install event handling regardless of whether 9547 // there's a restore pass performed. Token values are >= 1. 9548 int token; 9549 if (mNextInstallToken < 0) mNextInstallToken = 1; 9550 token = mNextInstallToken++; 9551 9552 PostInstallData data = new PostInstallData(args, res); 9553 mRunningInstalls.put(token, data); 9554 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9555 9556 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9557 // Pass responsibility to the Backup Manager. It will perform a 9558 // restore if appropriate, then pass responsibility back to the 9559 // Package Manager to run the post-install observer callbacks 9560 // and broadcasts. 9561 IBackupManager bm = IBackupManager.Stub.asInterface( 9562 ServiceManager.getService(Context.BACKUP_SERVICE)); 9563 if (bm != null) { 9564 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9565 + " to BM for possible restore"); 9566 try { 9567 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9568 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9569 } else { 9570 doRestore = false; 9571 } 9572 } catch (RemoteException e) { 9573 // can't happen; the backup manager is local 9574 } catch (Exception e) { 9575 Slog.e(TAG, "Exception trying to enqueue restore", e); 9576 doRestore = false; 9577 } 9578 } else { 9579 Slog.e(TAG, "Backup Manager not found!"); 9580 doRestore = false; 9581 } 9582 } 9583 9584 if (!doRestore) { 9585 // No restore possible, or the Backup Manager was mysteriously not 9586 // available -- just fire the post-install work request directly. 9587 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9588 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9589 mHandler.sendMessage(msg); 9590 } 9591 } 9592 }); 9593 } 9594 9595 private abstract class HandlerParams { 9596 private static final int MAX_RETRIES = 4; 9597 9598 /** 9599 * Number of times startCopy() has been attempted and had a non-fatal 9600 * error. 9601 */ 9602 private int mRetries = 0; 9603 9604 /** User handle for the user requesting the information or installation. */ 9605 private final UserHandle mUser; 9606 9607 HandlerParams(UserHandle user) { 9608 mUser = user; 9609 } 9610 9611 UserHandle getUser() { 9612 return mUser; 9613 } 9614 9615 final boolean startCopy() { 9616 boolean res; 9617 try { 9618 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9619 9620 if (++mRetries > MAX_RETRIES) { 9621 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9622 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9623 handleServiceError(); 9624 return false; 9625 } else { 9626 handleStartCopy(); 9627 res = true; 9628 } 9629 } catch (RemoteException e) { 9630 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9631 mHandler.sendEmptyMessage(MCS_RECONNECT); 9632 res = false; 9633 } 9634 handleReturnCode(); 9635 return res; 9636 } 9637 9638 final void serviceError() { 9639 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9640 handleServiceError(); 9641 handleReturnCode(); 9642 } 9643 9644 abstract void handleStartCopy() throws RemoteException; 9645 abstract void handleServiceError(); 9646 abstract void handleReturnCode(); 9647 } 9648 9649 class MeasureParams extends HandlerParams { 9650 private final PackageStats mStats; 9651 private boolean mSuccess; 9652 9653 private final IPackageStatsObserver mObserver; 9654 9655 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9656 super(new UserHandle(stats.userHandle)); 9657 mObserver = observer; 9658 mStats = stats; 9659 } 9660 9661 @Override 9662 public String toString() { 9663 return "MeasureParams{" 9664 + Integer.toHexString(System.identityHashCode(this)) 9665 + " " + mStats.packageName + "}"; 9666 } 9667 9668 @Override 9669 void handleStartCopy() throws RemoteException { 9670 synchronized (mInstallLock) { 9671 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9672 } 9673 9674 if (mSuccess) { 9675 final boolean mounted; 9676 if (Environment.isExternalStorageEmulated()) { 9677 mounted = true; 9678 } else { 9679 final String status = Environment.getExternalStorageState(); 9680 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9681 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9682 } 9683 9684 if (mounted) { 9685 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9686 9687 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9688 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9689 9690 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9691 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9692 9693 // Always subtract cache size, since it's a subdirectory 9694 mStats.externalDataSize -= mStats.externalCacheSize; 9695 9696 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9697 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9698 9699 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9700 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9701 } 9702 } 9703 } 9704 9705 @Override 9706 void handleReturnCode() { 9707 if (mObserver != null) { 9708 try { 9709 mObserver.onGetStatsCompleted(mStats, mSuccess); 9710 } catch (RemoteException e) { 9711 Slog.i(TAG, "Observer no longer exists."); 9712 } 9713 } 9714 } 9715 9716 @Override 9717 void handleServiceError() { 9718 Slog.e(TAG, "Could not measure application " + mStats.packageName 9719 + " external storage"); 9720 } 9721 } 9722 9723 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9724 throws RemoteException { 9725 long result = 0; 9726 for (File path : paths) { 9727 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9728 } 9729 return result; 9730 } 9731 9732 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9733 for (File path : paths) { 9734 try { 9735 mcs.clearDirectory(path.getAbsolutePath()); 9736 } catch (RemoteException e) { 9737 } 9738 } 9739 } 9740 9741 static class OriginInfo { 9742 /** 9743 * Location where install is coming from, before it has been 9744 * copied/renamed into place. This could be a single monolithic APK 9745 * file, or a cluster directory. This location may be untrusted. 9746 */ 9747 final File file; 9748 final String cid; 9749 9750 /** 9751 * Flag indicating that {@link #file} or {@link #cid} has already been 9752 * staged, meaning downstream users don't need to defensively copy the 9753 * contents. 9754 */ 9755 final boolean staged; 9756 9757 /** 9758 * Flag indicating that {@link #file} or {@link #cid} is an already 9759 * installed app that is being moved. 9760 */ 9761 final boolean existing; 9762 9763 final String resolvedPath; 9764 final File resolvedFile; 9765 9766 static OriginInfo fromNothing() { 9767 return new OriginInfo(null, null, false, false); 9768 } 9769 9770 static OriginInfo fromUntrustedFile(File file) { 9771 return new OriginInfo(file, null, false, false); 9772 } 9773 9774 static OriginInfo fromExistingFile(File file) { 9775 return new OriginInfo(file, null, false, true); 9776 } 9777 9778 static OriginInfo fromStagedFile(File file) { 9779 return new OriginInfo(file, null, true, false); 9780 } 9781 9782 static OriginInfo fromStagedContainer(String cid) { 9783 return new OriginInfo(null, cid, true, false); 9784 } 9785 9786 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9787 this.file = file; 9788 this.cid = cid; 9789 this.staged = staged; 9790 this.existing = existing; 9791 9792 if (cid != null) { 9793 resolvedPath = PackageHelper.getSdDir(cid); 9794 resolvedFile = new File(resolvedPath); 9795 } else if (file != null) { 9796 resolvedPath = file.getAbsolutePath(); 9797 resolvedFile = file; 9798 } else { 9799 resolvedPath = null; 9800 resolvedFile = null; 9801 } 9802 } 9803 } 9804 9805 class MoveInfo { 9806 final int moveId; 9807 final String fromUuid; 9808 final String toUuid; 9809 final String packageName; 9810 final String dataAppName; 9811 final int appId; 9812 final String seinfo; 9813 9814 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9815 String dataAppName, int appId, String seinfo) { 9816 this.moveId = moveId; 9817 this.fromUuid = fromUuid; 9818 this.toUuid = toUuid; 9819 this.packageName = packageName; 9820 this.dataAppName = dataAppName; 9821 this.appId = appId; 9822 this.seinfo = seinfo; 9823 } 9824 } 9825 9826 class InstallParams extends HandlerParams { 9827 final OriginInfo origin; 9828 final MoveInfo move; 9829 final IPackageInstallObserver2 observer; 9830 int installFlags; 9831 final String installerPackageName; 9832 final String volumeUuid; 9833 final VerificationParams verificationParams; 9834 private InstallArgs mArgs; 9835 private int mRet; 9836 final String packageAbiOverride; 9837 9838 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9839 int installFlags, String installerPackageName, String volumeUuid, 9840 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9841 super(user); 9842 this.origin = origin; 9843 this.move = move; 9844 this.observer = observer; 9845 this.installFlags = installFlags; 9846 this.installerPackageName = installerPackageName; 9847 this.volumeUuid = volumeUuid; 9848 this.verificationParams = verificationParams; 9849 this.packageAbiOverride = packageAbiOverride; 9850 } 9851 9852 @Override 9853 public String toString() { 9854 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9855 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9856 } 9857 9858 public ManifestDigest getManifestDigest() { 9859 if (verificationParams == null) { 9860 return null; 9861 } 9862 return verificationParams.getManifestDigest(); 9863 } 9864 9865 private int installLocationPolicy(PackageInfoLite pkgLite) { 9866 String packageName = pkgLite.packageName; 9867 int installLocation = pkgLite.installLocation; 9868 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9869 // reader 9870 synchronized (mPackages) { 9871 PackageParser.Package pkg = mPackages.get(packageName); 9872 if (pkg != null) { 9873 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9874 // Check for downgrading. 9875 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9876 try { 9877 checkDowngrade(pkg, pkgLite); 9878 } catch (PackageManagerException e) { 9879 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9880 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9881 } 9882 } 9883 // Check for updated system application. 9884 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9885 if (onSd) { 9886 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9887 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9888 } 9889 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9890 } else { 9891 if (onSd) { 9892 // Install flag overrides everything. 9893 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9894 } 9895 // If current upgrade specifies particular preference 9896 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9897 // Application explicitly specified internal. 9898 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9899 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9900 // App explictly prefers external. Let policy decide 9901 } else { 9902 // Prefer previous location 9903 if (isExternal(pkg)) { 9904 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9905 } 9906 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9907 } 9908 } 9909 } else { 9910 // Invalid install. Return error code 9911 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9912 } 9913 } 9914 } 9915 // All the special cases have been taken care of. 9916 // Return result based on recommended install location. 9917 if (onSd) { 9918 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9919 } 9920 return pkgLite.recommendedInstallLocation; 9921 } 9922 9923 /* 9924 * Invoke remote method to get package information and install 9925 * location values. Override install location based on default 9926 * policy if needed and then create install arguments based 9927 * on the install location. 9928 */ 9929 public void handleStartCopy() throws RemoteException { 9930 int ret = PackageManager.INSTALL_SUCCEEDED; 9931 9932 // If we're already staged, we've firmly committed to an install location 9933 if (origin.staged) { 9934 if (origin.file != null) { 9935 installFlags |= PackageManager.INSTALL_INTERNAL; 9936 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9937 } else if (origin.cid != null) { 9938 installFlags |= PackageManager.INSTALL_EXTERNAL; 9939 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9940 } else { 9941 throw new IllegalStateException("Invalid stage location"); 9942 } 9943 } 9944 9945 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9946 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9947 9948 PackageInfoLite pkgLite = null; 9949 9950 if (onInt && onSd) { 9951 // Check if both bits are set. 9952 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9953 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9954 } else { 9955 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9956 packageAbiOverride); 9957 9958 /* 9959 * If we have too little free space, try to free cache 9960 * before giving up. 9961 */ 9962 if (!origin.staged && pkgLite.recommendedInstallLocation 9963 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9964 // TODO: focus freeing disk space on the target device 9965 final StorageManager storage = StorageManager.from(mContext); 9966 final long lowThreshold = storage.getStorageLowBytes( 9967 Environment.getDataDirectory()); 9968 9969 final long sizeBytes = mContainerService.calculateInstalledSize( 9970 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9971 9972 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9973 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9974 installFlags, packageAbiOverride); 9975 } 9976 9977 /* 9978 * The cache free must have deleted the file we 9979 * downloaded to install. 9980 * 9981 * TODO: fix the "freeCache" call to not delete 9982 * the file we care about. 9983 */ 9984 if (pkgLite.recommendedInstallLocation 9985 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9986 pkgLite.recommendedInstallLocation 9987 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9988 } 9989 } 9990 } 9991 9992 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9993 int loc = pkgLite.recommendedInstallLocation; 9994 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9995 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9996 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9997 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9998 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9999 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10000 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10001 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10002 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10003 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10004 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10005 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10006 } else { 10007 // Override with defaults if needed. 10008 loc = installLocationPolicy(pkgLite); 10009 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10010 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10011 } else if (!onSd && !onInt) { 10012 // Override install location with flags 10013 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10014 // Set the flag to install on external media. 10015 installFlags |= PackageManager.INSTALL_EXTERNAL; 10016 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10017 } else { 10018 // Make sure the flag for installing on external 10019 // media is unset 10020 installFlags |= PackageManager.INSTALL_INTERNAL; 10021 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10022 } 10023 } 10024 } 10025 } 10026 10027 final InstallArgs args = createInstallArgs(this); 10028 mArgs = args; 10029 10030 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10031 /* 10032 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10033 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10034 */ 10035 int userIdentifier = getUser().getIdentifier(); 10036 if (userIdentifier == UserHandle.USER_ALL 10037 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10038 userIdentifier = UserHandle.USER_OWNER; 10039 } 10040 10041 /* 10042 * Determine if we have any installed package verifiers. If we 10043 * do, then we'll defer to them to verify the packages. 10044 */ 10045 final int requiredUid = mRequiredVerifierPackage == null ? -1 10046 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10047 if (!origin.existing && requiredUid != -1 10048 && isVerificationEnabled(userIdentifier, installFlags)) { 10049 final Intent verification = new Intent( 10050 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10051 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10052 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10053 PACKAGE_MIME_TYPE); 10054 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10055 10056 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10057 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10058 0 /* TODO: Which userId? */); 10059 10060 if (DEBUG_VERIFY) { 10061 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10062 + verification.toString() + " with " + pkgLite.verifiers.length 10063 + " optional verifiers"); 10064 } 10065 10066 final int verificationId = mPendingVerificationToken++; 10067 10068 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10069 10070 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10071 installerPackageName); 10072 10073 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10074 installFlags); 10075 10076 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10077 pkgLite.packageName); 10078 10079 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10080 pkgLite.versionCode); 10081 10082 if (verificationParams != null) { 10083 if (verificationParams.getVerificationURI() != null) { 10084 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10085 verificationParams.getVerificationURI()); 10086 } 10087 if (verificationParams.getOriginatingURI() != null) { 10088 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10089 verificationParams.getOriginatingURI()); 10090 } 10091 if (verificationParams.getReferrer() != null) { 10092 verification.putExtra(Intent.EXTRA_REFERRER, 10093 verificationParams.getReferrer()); 10094 } 10095 if (verificationParams.getOriginatingUid() >= 0) { 10096 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10097 verificationParams.getOriginatingUid()); 10098 } 10099 if (verificationParams.getInstallerUid() >= 0) { 10100 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10101 verificationParams.getInstallerUid()); 10102 } 10103 } 10104 10105 final PackageVerificationState verificationState = new PackageVerificationState( 10106 requiredUid, args); 10107 10108 mPendingVerification.append(verificationId, verificationState); 10109 10110 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10111 receivers, verificationState); 10112 10113 /* 10114 * If any sufficient verifiers were listed in the package 10115 * manifest, attempt to ask them. 10116 */ 10117 if (sufficientVerifiers != null) { 10118 final int N = sufficientVerifiers.size(); 10119 if (N == 0) { 10120 Slog.i(TAG, "Additional verifiers required, but none installed."); 10121 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10122 } else { 10123 for (int i = 0; i < N; i++) { 10124 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10125 10126 final Intent sufficientIntent = new Intent(verification); 10127 sufficientIntent.setComponent(verifierComponent); 10128 10129 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10130 } 10131 } 10132 } 10133 10134 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10135 mRequiredVerifierPackage, receivers); 10136 if (ret == PackageManager.INSTALL_SUCCEEDED 10137 && mRequiredVerifierPackage != null) { 10138 /* 10139 * Send the intent to the required verification agent, 10140 * but only start the verification timeout after the 10141 * target BroadcastReceivers have run. 10142 */ 10143 verification.setComponent(requiredVerifierComponent); 10144 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10145 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10146 new BroadcastReceiver() { 10147 @Override 10148 public void onReceive(Context context, Intent intent) { 10149 final Message msg = mHandler 10150 .obtainMessage(CHECK_PENDING_VERIFICATION); 10151 msg.arg1 = verificationId; 10152 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10153 } 10154 }, null, 0, null, null); 10155 10156 /* 10157 * We don't want the copy to proceed until verification 10158 * succeeds, so null out this field. 10159 */ 10160 mArgs = null; 10161 } 10162 } else { 10163 /* 10164 * No package verification is enabled, so immediately start 10165 * the remote call to initiate copy using temporary file. 10166 */ 10167 ret = args.copyApk(mContainerService, true); 10168 } 10169 } 10170 10171 mRet = ret; 10172 } 10173 10174 @Override 10175 void handleReturnCode() { 10176 // If mArgs is null, then MCS couldn't be reached. When it 10177 // reconnects, it will try again to install. At that point, this 10178 // will succeed. 10179 if (mArgs != null) { 10180 processPendingInstall(mArgs, mRet); 10181 } 10182 } 10183 10184 @Override 10185 void handleServiceError() { 10186 mArgs = createInstallArgs(this); 10187 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10188 } 10189 10190 public boolean isForwardLocked() { 10191 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10192 } 10193 } 10194 10195 /** 10196 * Used during creation of InstallArgs 10197 * 10198 * @param installFlags package installation flags 10199 * @return true if should be installed on external storage 10200 */ 10201 private static boolean installOnExternalAsec(int installFlags) { 10202 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10203 return false; 10204 } 10205 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10206 return true; 10207 } 10208 return false; 10209 } 10210 10211 /** 10212 * Used during creation of InstallArgs 10213 * 10214 * @param installFlags package installation flags 10215 * @return true if should be installed as forward locked 10216 */ 10217 private static boolean installForwardLocked(int installFlags) { 10218 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10219 } 10220 10221 private InstallArgs createInstallArgs(InstallParams params) { 10222 if (params.move != null) { 10223 return new MoveInstallArgs(params); 10224 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10225 return new AsecInstallArgs(params); 10226 } else { 10227 return new FileInstallArgs(params); 10228 } 10229 } 10230 10231 /** 10232 * Create args that describe an existing installed package. Typically used 10233 * when cleaning up old installs, or used as a move source. 10234 */ 10235 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10236 String resourcePath, String[] instructionSets) { 10237 final boolean isInAsec; 10238 if (installOnExternalAsec(installFlags)) { 10239 /* Apps on SD card are always in ASEC containers. */ 10240 isInAsec = true; 10241 } else if (installForwardLocked(installFlags) 10242 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10243 /* 10244 * Forward-locked apps are only in ASEC containers if they're the 10245 * new style 10246 */ 10247 isInAsec = true; 10248 } else { 10249 isInAsec = false; 10250 } 10251 10252 if (isInAsec) { 10253 return new AsecInstallArgs(codePath, instructionSets, 10254 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10255 } else { 10256 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10257 } 10258 } 10259 10260 static abstract class InstallArgs { 10261 /** @see InstallParams#origin */ 10262 final OriginInfo origin; 10263 /** @see InstallParams#move */ 10264 final MoveInfo move; 10265 10266 final IPackageInstallObserver2 observer; 10267 // Always refers to PackageManager flags only 10268 final int installFlags; 10269 final String installerPackageName; 10270 final String volumeUuid; 10271 final ManifestDigest manifestDigest; 10272 final UserHandle user; 10273 final String abiOverride; 10274 10275 // The list of instruction sets supported by this app. This is currently 10276 // only used during the rmdex() phase to clean up resources. We can get rid of this 10277 // if we move dex files under the common app path. 10278 /* nullable */ String[] instructionSets; 10279 10280 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10281 int installFlags, String installerPackageName, String volumeUuid, 10282 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10283 String abiOverride) { 10284 this.origin = origin; 10285 this.move = move; 10286 this.installFlags = installFlags; 10287 this.observer = observer; 10288 this.installerPackageName = installerPackageName; 10289 this.volumeUuid = volumeUuid; 10290 this.manifestDigest = manifestDigest; 10291 this.user = user; 10292 this.instructionSets = instructionSets; 10293 this.abiOverride = abiOverride; 10294 } 10295 10296 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10297 abstract int doPreInstall(int status); 10298 10299 /** 10300 * Rename package into final resting place. All paths on the given 10301 * scanned package should be updated to reflect the rename. 10302 */ 10303 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10304 abstract int doPostInstall(int status, int uid); 10305 10306 /** @see PackageSettingBase#codePathString */ 10307 abstract String getCodePath(); 10308 /** @see PackageSettingBase#resourcePathString */ 10309 abstract String getResourcePath(); 10310 10311 // Need installer lock especially for dex file removal. 10312 abstract void cleanUpResourcesLI(); 10313 abstract boolean doPostDeleteLI(boolean delete); 10314 10315 /** 10316 * Called before the source arguments are copied. This is used mostly 10317 * for MoveParams when it needs to read the source file to put it in the 10318 * destination. 10319 */ 10320 int doPreCopy() { 10321 return PackageManager.INSTALL_SUCCEEDED; 10322 } 10323 10324 /** 10325 * Called after the source arguments are copied. This is used mostly for 10326 * MoveParams when it needs to read the source file to put it in the 10327 * destination. 10328 * 10329 * @return 10330 */ 10331 int doPostCopy(int uid) { 10332 return PackageManager.INSTALL_SUCCEEDED; 10333 } 10334 10335 protected boolean isFwdLocked() { 10336 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10337 } 10338 10339 protected boolean isExternalAsec() { 10340 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10341 } 10342 10343 UserHandle getUser() { 10344 return user; 10345 } 10346 } 10347 10348 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10349 if (!allCodePaths.isEmpty()) { 10350 if (instructionSets == null) { 10351 throw new IllegalStateException("instructionSet == null"); 10352 } 10353 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10354 for (String codePath : allCodePaths) { 10355 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10356 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10357 if (retCode < 0) { 10358 Slog.w(TAG, "Couldn't remove dex file for package: " 10359 + " at location " + codePath + ", retcode=" + retCode); 10360 // we don't consider this to be a failure of the core package deletion 10361 } 10362 } 10363 } 10364 } 10365 } 10366 10367 /** 10368 * Logic to handle installation of non-ASEC applications, including copying 10369 * and renaming logic. 10370 */ 10371 class FileInstallArgs extends InstallArgs { 10372 private File codeFile; 10373 private File resourceFile; 10374 10375 // Example topology: 10376 // /data/app/com.example/base.apk 10377 // /data/app/com.example/split_foo.apk 10378 // /data/app/com.example/lib/arm/libfoo.so 10379 // /data/app/com.example/lib/arm64/libfoo.so 10380 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10381 10382 /** New install */ 10383 FileInstallArgs(InstallParams params) { 10384 super(params.origin, params.move, params.observer, params.installFlags, 10385 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10386 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10387 if (isFwdLocked()) { 10388 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10389 } 10390 } 10391 10392 /** Existing install */ 10393 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10394 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10395 null); 10396 this.codeFile = (codePath != null) ? new File(codePath) : null; 10397 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10398 } 10399 10400 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10401 if (origin.staged) { 10402 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10403 codeFile = origin.file; 10404 resourceFile = origin.file; 10405 return PackageManager.INSTALL_SUCCEEDED; 10406 } 10407 10408 try { 10409 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10410 codeFile = tempDir; 10411 resourceFile = tempDir; 10412 } catch (IOException e) { 10413 Slog.w(TAG, "Failed to create copy file: " + e); 10414 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10415 } 10416 10417 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10418 @Override 10419 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10420 if (!FileUtils.isValidExtFilename(name)) { 10421 throw new IllegalArgumentException("Invalid filename: " + name); 10422 } 10423 try { 10424 final File file = new File(codeFile, name); 10425 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10426 O_RDWR | O_CREAT, 0644); 10427 Os.chmod(file.getAbsolutePath(), 0644); 10428 return new ParcelFileDescriptor(fd); 10429 } catch (ErrnoException e) { 10430 throw new RemoteException("Failed to open: " + e.getMessage()); 10431 } 10432 } 10433 }; 10434 10435 int ret = PackageManager.INSTALL_SUCCEEDED; 10436 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10437 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10438 Slog.e(TAG, "Failed to copy package"); 10439 return ret; 10440 } 10441 10442 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10443 NativeLibraryHelper.Handle handle = null; 10444 try { 10445 handle = NativeLibraryHelper.Handle.create(codeFile); 10446 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10447 abiOverride); 10448 } catch (IOException e) { 10449 Slog.e(TAG, "Copying native libraries failed", e); 10450 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10451 } finally { 10452 IoUtils.closeQuietly(handle); 10453 } 10454 10455 return ret; 10456 } 10457 10458 int doPreInstall(int status) { 10459 if (status != PackageManager.INSTALL_SUCCEEDED) { 10460 cleanUp(); 10461 } 10462 return status; 10463 } 10464 10465 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10466 if (status != PackageManager.INSTALL_SUCCEEDED) { 10467 cleanUp(); 10468 return false; 10469 } 10470 10471 final File targetDir = codeFile.getParentFile(); 10472 final File beforeCodeFile = codeFile; 10473 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10474 10475 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10476 try { 10477 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10478 } catch (ErrnoException e) { 10479 Slog.w(TAG, "Failed to rename", e); 10480 return false; 10481 } 10482 10483 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10484 Slog.w(TAG, "Failed to restorecon"); 10485 return false; 10486 } 10487 10488 // Reflect the rename internally 10489 codeFile = afterCodeFile; 10490 resourceFile = afterCodeFile; 10491 10492 // Reflect the rename in scanned details 10493 pkg.codePath = afterCodeFile.getAbsolutePath(); 10494 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10495 pkg.baseCodePath); 10496 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10497 pkg.splitCodePaths); 10498 10499 // Reflect the rename in app info 10500 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10501 pkg.applicationInfo.setCodePath(pkg.codePath); 10502 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10503 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10504 pkg.applicationInfo.setResourcePath(pkg.codePath); 10505 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10506 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10507 10508 return true; 10509 } 10510 10511 int doPostInstall(int status, int uid) { 10512 if (status != PackageManager.INSTALL_SUCCEEDED) { 10513 cleanUp(); 10514 } 10515 return status; 10516 } 10517 10518 @Override 10519 String getCodePath() { 10520 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10521 } 10522 10523 @Override 10524 String getResourcePath() { 10525 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10526 } 10527 10528 private boolean cleanUp() { 10529 if (codeFile == null || !codeFile.exists()) { 10530 return false; 10531 } 10532 10533 if (codeFile.isDirectory()) { 10534 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10535 } else { 10536 codeFile.delete(); 10537 } 10538 10539 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10540 resourceFile.delete(); 10541 } 10542 10543 return true; 10544 } 10545 10546 void cleanUpResourcesLI() { 10547 // Try enumerating all code paths before deleting 10548 List<String> allCodePaths = Collections.EMPTY_LIST; 10549 if (codeFile != null && codeFile.exists()) { 10550 try { 10551 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10552 allCodePaths = pkg.getAllCodePaths(); 10553 } catch (PackageParserException e) { 10554 // Ignored; we tried our best 10555 } 10556 } 10557 10558 cleanUp(); 10559 removeDexFiles(allCodePaths, instructionSets); 10560 } 10561 10562 boolean doPostDeleteLI(boolean delete) { 10563 // XXX err, shouldn't we respect the delete flag? 10564 cleanUpResourcesLI(); 10565 return true; 10566 } 10567 } 10568 10569 private boolean isAsecExternal(String cid) { 10570 final String asecPath = PackageHelper.getSdFilesystem(cid); 10571 return !asecPath.startsWith(mAsecInternalPath); 10572 } 10573 10574 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10575 PackageManagerException { 10576 if (copyRet < 0) { 10577 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10578 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10579 throw new PackageManagerException(copyRet, message); 10580 } 10581 } 10582 } 10583 10584 /** 10585 * Extract the MountService "container ID" from the full code path of an 10586 * .apk. 10587 */ 10588 static String cidFromCodePath(String fullCodePath) { 10589 int eidx = fullCodePath.lastIndexOf("/"); 10590 String subStr1 = fullCodePath.substring(0, eidx); 10591 int sidx = subStr1.lastIndexOf("/"); 10592 return subStr1.substring(sidx+1, eidx); 10593 } 10594 10595 /** 10596 * Logic to handle installation of ASEC applications, including copying and 10597 * renaming logic. 10598 */ 10599 class AsecInstallArgs extends InstallArgs { 10600 static final String RES_FILE_NAME = "pkg.apk"; 10601 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10602 10603 String cid; 10604 String packagePath; 10605 String resourcePath; 10606 10607 /** New install */ 10608 AsecInstallArgs(InstallParams params) { 10609 super(params.origin, params.move, params.observer, params.installFlags, 10610 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10611 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10612 } 10613 10614 /** Existing install */ 10615 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10616 boolean isExternal, boolean isForwardLocked) { 10617 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10618 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10619 instructionSets, null); 10620 // Hackily pretend we're still looking at a full code path 10621 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10622 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10623 } 10624 10625 // Extract cid from fullCodePath 10626 int eidx = fullCodePath.lastIndexOf("/"); 10627 String subStr1 = fullCodePath.substring(0, eidx); 10628 int sidx = subStr1.lastIndexOf("/"); 10629 cid = subStr1.substring(sidx+1, eidx); 10630 setMountPath(subStr1); 10631 } 10632 10633 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10634 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10635 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10636 instructionSets, null); 10637 this.cid = cid; 10638 setMountPath(PackageHelper.getSdDir(cid)); 10639 } 10640 10641 void createCopyFile() { 10642 cid = mInstallerService.allocateExternalStageCidLegacy(); 10643 } 10644 10645 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10646 if (origin.staged) { 10647 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10648 cid = origin.cid; 10649 setMountPath(PackageHelper.getSdDir(cid)); 10650 return PackageManager.INSTALL_SUCCEEDED; 10651 } 10652 10653 if (temp) { 10654 createCopyFile(); 10655 } else { 10656 /* 10657 * Pre-emptively destroy the container since it's destroyed if 10658 * copying fails due to it existing anyway. 10659 */ 10660 PackageHelper.destroySdDir(cid); 10661 } 10662 10663 final String newMountPath = imcs.copyPackageToContainer( 10664 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10665 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10666 10667 if (newMountPath != null) { 10668 setMountPath(newMountPath); 10669 return PackageManager.INSTALL_SUCCEEDED; 10670 } else { 10671 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10672 } 10673 } 10674 10675 @Override 10676 String getCodePath() { 10677 return packagePath; 10678 } 10679 10680 @Override 10681 String getResourcePath() { 10682 return resourcePath; 10683 } 10684 10685 int doPreInstall(int status) { 10686 if (status != PackageManager.INSTALL_SUCCEEDED) { 10687 // Destroy container 10688 PackageHelper.destroySdDir(cid); 10689 } else { 10690 boolean mounted = PackageHelper.isContainerMounted(cid); 10691 if (!mounted) { 10692 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10693 Process.SYSTEM_UID); 10694 if (newMountPath != null) { 10695 setMountPath(newMountPath); 10696 } else { 10697 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10698 } 10699 } 10700 } 10701 return status; 10702 } 10703 10704 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10705 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10706 String newMountPath = null; 10707 if (PackageHelper.isContainerMounted(cid)) { 10708 // Unmount the container 10709 if (!PackageHelper.unMountSdDir(cid)) { 10710 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10711 return false; 10712 } 10713 } 10714 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10715 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10716 " which might be stale. Will try to clean up."); 10717 // Clean up the stale container and proceed to recreate. 10718 if (!PackageHelper.destroySdDir(newCacheId)) { 10719 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10720 return false; 10721 } 10722 // Successfully cleaned up stale container. Try to rename again. 10723 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10724 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10725 + " inspite of cleaning it up."); 10726 return false; 10727 } 10728 } 10729 if (!PackageHelper.isContainerMounted(newCacheId)) { 10730 Slog.w(TAG, "Mounting container " + newCacheId); 10731 newMountPath = PackageHelper.mountSdDir(newCacheId, 10732 getEncryptKey(), Process.SYSTEM_UID); 10733 } else { 10734 newMountPath = PackageHelper.getSdDir(newCacheId); 10735 } 10736 if (newMountPath == null) { 10737 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10738 return false; 10739 } 10740 Log.i(TAG, "Succesfully renamed " + cid + 10741 " to " + newCacheId + 10742 " at new path: " + newMountPath); 10743 cid = newCacheId; 10744 10745 final File beforeCodeFile = new File(packagePath); 10746 setMountPath(newMountPath); 10747 final File afterCodeFile = new File(packagePath); 10748 10749 // Reflect the rename in scanned details 10750 pkg.codePath = afterCodeFile.getAbsolutePath(); 10751 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10752 pkg.baseCodePath); 10753 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10754 pkg.splitCodePaths); 10755 10756 // Reflect the rename in app info 10757 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10758 pkg.applicationInfo.setCodePath(pkg.codePath); 10759 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10760 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10761 pkg.applicationInfo.setResourcePath(pkg.codePath); 10762 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10763 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10764 10765 return true; 10766 } 10767 10768 private void setMountPath(String mountPath) { 10769 final File mountFile = new File(mountPath); 10770 10771 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10772 if (monolithicFile.exists()) { 10773 packagePath = monolithicFile.getAbsolutePath(); 10774 if (isFwdLocked()) { 10775 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10776 } else { 10777 resourcePath = packagePath; 10778 } 10779 } else { 10780 packagePath = mountFile.getAbsolutePath(); 10781 resourcePath = packagePath; 10782 } 10783 } 10784 10785 int doPostInstall(int status, int uid) { 10786 if (status != PackageManager.INSTALL_SUCCEEDED) { 10787 cleanUp(); 10788 } else { 10789 final int groupOwner; 10790 final String protectedFile; 10791 if (isFwdLocked()) { 10792 groupOwner = UserHandle.getSharedAppGid(uid); 10793 protectedFile = RES_FILE_NAME; 10794 } else { 10795 groupOwner = -1; 10796 protectedFile = null; 10797 } 10798 10799 if (uid < Process.FIRST_APPLICATION_UID 10800 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10801 Slog.e(TAG, "Failed to finalize " + cid); 10802 PackageHelper.destroySdDir(cid); 10803 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10804 } 10805 10806 boolean mounted = PackageHelper.isContainerMounted(cid); 10807 if (!mounted) { 10808 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10809 } 10810 } 10811 return status; 10812 } 10813 10814 private void cleanUp() { 10815 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10816 10817 // Destroy secure container 10818 PackageHelper.destroySdDir(cid); 10819 } 10820 10821 private List<String> getAllCodePaths() { 10822 final File codeFile = new File(getCodePath()); 10823 if (codeFile != null && codeFile.exists()) { 10824 try { 10825 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10826 return pkg.getAllCodePaths(); 10827 } catch (PackageParserException e) { 10828 // Ignored; we tried our best 10829 } 10830 } 10831 return Collections.EMPTY_LIST; 10832 } 10833 10834 void cleanUpResourcesLI() { 10835 // Enumerate all code paths before deleting 10836 cleanUpResourcesLI(getAllCodePaths()); 10837 } 10838 10839 private void cleanUpResourcesLI(List<String> allCodePaths) { 10840 cleanUp(); 10841 removeDexFiles(allCodePaths, instructionSets); 10842 } 10843 10844 String getPackageName() { 10845 return getAsecPackageName(cid); 10846 } 10847 10848 boolean doPostDeleteLI(boolean delete) { 10849 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10850 final List<String> allCodePaths = getAllCodePaths(); 10851 boolean mounted = PackageHelper.isContainerMounted(cid); 10852 if (mounted) { 10853 // Unmount first 10854 if (PackageHelper.unMountSdDir(cid)) { 10855 mounted = false; 10856 } 10857 } 10858 if (!mounted && delete) { 10859 cleanUpResourcesLI(allCodePaths); 10860 } 10861 return !mounted; 10862 } 10863 10864 @Override 10865 int doPreCopy() { 10866 if (isFwdLocked()) { 10867 if (!PackageHelper.fixSdPermissions(cid, 10868 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10869 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10870 } 10871 } 10872 10873 return PackageManager.INSTALL_SUCCEEDED; 10874 } 10875 10876 @Override 10877 int doPostCopy(int uid) { 10878 if (isFwdLocked()) { 10879 if (uid < Process.FIRST_APPLICATION_UID 10880 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10881 RES_FILE_NAME)) { 10882 Slog.e(TAG, "Failed to finalize " + cid); 10883 PackageHelper.destroySdDir(cid); 10884 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10885 } 10886 } 10887 10888 return PackageManager.INSTALL_SUCCEEDED; 10889 } 10890 } 10891 10892 /** 10893 * Logic to handle movement of existing installed applications. 10894 */ 10895 class MoveInstallArgs extends InstallArgs { 10896 private File codeFile; 10897 private File resourceFile; 10898 10899 /** New install */ 10900 MoveInstallArgs(InstallParams params) { 10901 super(params.origin, params.move, params.observer, params.installFlags, 10902 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10903 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10904 } 10905 10906 int copyApk(IMediaContainerService imcs, boolean temp) { 10907 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10908 + move.fromUuid + " to " + move.toUuid); 10909 synchronized (mInstaller) { 10910 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10911 move.dataAppName, move.appId, move.seinfo) != 0) { 10912 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10913 } 10914 } 10915 10916 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10917 resourceFile = codeFile; 10918 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10919 10920 return PackageManager.INSTALL_SUCCEEDED; 10921 } 10922 10923 int doPreInstall(int status) { 10924 if (status != PackageManager.INSTALL_SUCCEEDED) { 10925 cleanUp(); 10926 } 10927 return status; 10928 } 10929 10930 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10931 if (status != PackageManager.INSTALL_SUCCEEDED) { 10932 cleanUp(); 10933 return false; 10934 } 10935 10936 // Reflect the move in app info 10937 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10938 pkg.applicationInfo.setCodePath(pkg.codePath); 10939 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10940 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10941 pkg.applicationInfo.setResourcePath(pkg.codePath); 10942 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10943 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10944 10945 return true; 10946 } 10947 10948 int doPostInstall(int status, int uid) { 10949 if (status != PackageManager.INSTALL_SUCCEEDED) { 10950 cleanUp(); 10951 } 10952 return status; 10953 } 10954 10955 @Override 10956 String getCodePath() { 10957 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10958 } 10959 10960 @Override 10961 String getResourcePath() { 10962 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10963 } 10964 10965 private boolean cleanUp() { 10966 if (codeFile == null || !codeFile.exists()) { 10967 return false; 10968 } 10969 10970 if (codeFile.isDirectory()) { 10971 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10972 } else { 10973 codeFile.delete(); 10974 } 10975 10976 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10977 resourceFile.delete(); 10978 } 10979 10980 return true; 10981 } 10982 10983 void cleanUpResourcesLI() { 10984 cleanUp(); 10985 } 10986 10987 boolean doPostDeleteLI(boolean delete) { 10988 // XXX err, shouldn't we respect the delete flag? 10989 cleanUpResourcesLI(); 10990 return true; 10991 } 10992 } 10993 10994 static String getAsecPackageName(String packageCid) { 10995 int idx = packageCid.lastIndexOf("-"); 10996 if (idx == -1) { 10997 return packageCid; 10998 } 10999 return packageCid.substring(0, idx); 11000 } 11001 11002 // Utility method used to create code paths based on package name and available index. 11003 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11004 String idxStr = ""; 11005 int idx = 1; 11006 // Fall back to default value of idx=1 if prefix is not 11007 // part of oldCodePath 11008 if (oldCodePath != null) { 11009 String subStr = oldCodePath; 11010 // Drop the suffix right away 11011 if (suffix != null && subStr.endsWith(suffix)) { 11012 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11013 } 11014 // If oldCodePath already contains prefix find out the 11015 // ending index to either increment or decrement. 11016 int sidx = subStr.lastIndexOf(prefix); 11017 if (sidx != -1) { 11018 subStr = subStr.substring(sidx + prefix.length()); 11019 if (subStr != null) { 11020 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11021 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11022 } 11023 try { 11024 idx = Integer.parseInt(subStr); 11025 if (idx <= 1) { 11026 idx++; 11027 } else { 11028 idx--; 11029 } 11030 } catch(NumberFormatException e) { 11031 } 11032 } 11033 } 11034 } 11035 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11036 return prefix + idxStr; 11037 } 11038 11039 private File getNextCodePath(File targetDir, String packageName) { 11040 int suffix = 1; 11041 File result; 11042 do { 11043 result = new File(targetDir, packageName + "-" + suffix); 11044 suffix++; 11045 } while (result.exists()); 11046 return result; 11047 } 11048 11049 // Utility method that returns the relative package path with respect 11050 // to the installation directory. Like say for /data/data/com.test-1.apk 11051 // string com.test-1 is returned. 11052 static String deriveCodePathName(String codePath) { 11053 if (codePath == null) { 11054 return null; 11055 } 11056 final File codeFile = new File(codePath); 11057 final String name = codeFile.getName(); 11058 if (codeFile.isDirectory()) { 11059 return name; 11060 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11061 final int lastDot = name.lastIndexOf('.'); 11062 return name.substring(0, lastDot); 11063 } else { 11064 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11065 return null; 11066 } 11067 } 11068 11069 class PackageInstalledInfo { 11070 String name; 11071 int uid; 11072 // The set of users that originally had this package installed. 11073 int[] origUsers; 11074 // The set of users that now have this package installed. 11075 int[] newUsers; 11076 PackageParser.Package pkg; 11077 int returnCode; 11078 String returnMsg; 11079 PackageRemovedInfo removedInfo; 11080 11081 public void setError(int code, String msg) { 11082 returnCode = code; 11083 returnMsg = msg; 11084 Slog.w(TAG, msg); 11085 } 11086 11087 public void setError(String msg, PackageParserException e) { 11088 returnCode = e.error; 11089 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11090 Slog.w(TAG, msg, e); 11091 } 11092 11093 public void setError(String msg, PackageManagerException e) { 11094 returnCode = e.error; 11095 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11096 Slog.w(TAG, msg, e); 11097 } 11098 11099 // In some error cases we want to convey more info back to the observer 11100 String origPackage; 11101 String origPermission; 11102 } 11103 11104 /* 11105 * Install a non-existing package. 11106 */ 11107 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11108 UserHandle user, String installerPackageName, String volumeUuid, 11109 PackageInstalledInfo res) { 11110 // Remember this for later, in case we need to rollback this install 11111 String pkgName = pkg.packageName; 11112 11113 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11114 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11115 UserHandle.USER_OWNER).exists(); 11116 synchronized(mPackages) { 11117 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11118 // A package with the same name is already installed, though 11119 // it has been renamed to an older name. The package we 11120 // are trying to install should be installed as an update to 11121 // the existing one, but that has not been requested, so bail. 11122 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11123 + " without first uninstalling package running as " 11124 + mSettings.mRenamedPackages.get(pkgName)); 11125 return; 11126 } 11127 if (mPackages.containsKey(pkgName)) { 11128 // Don't allow installation over an existing package with the same name. 11129 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11130 + " without first uninstalling."); 11131 return; 11132 } 11133 } 11134 11135 try { 11136 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11137 System.currentTimeMillis(), user); 11138 11139 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11140 // delete the partially installed application. the data directory will have to be 11141 // restored if it was already existing 11142 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11143 // remove package from internal structures. Note that we want deletePackageX to 11144 // delete the package data and cache directories that it created in 11145 // scanPackageLocked, unless those directories existed before we even tried to 11146 // install. 11147 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11148 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11149 res.removedInfo, true); 11150 } 11151 11152 } catch (PackageManagerException e) { 11153 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11154 } 11155 } 11156 11157 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11158 // Can't rotate keys during boot or if sharedUser. 11159 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11160 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11161 return false; 11162 } 11163 // app is using upgradeKeySets; make sure all are valid 11164 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11165 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11166 for (int i = 0; i < upgradeKeySets.length; i++) { 11167 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11168 Slog.wtf(TAG, "Package " 11169 + (oldPs.name != null ? oldPs.name : "<null>") 11170 + " contains upgrade-key-set reference to unknown key-set: " 11171 + upgradeKeySets[i] 11172 + " reverting to signatures check."); 11173 return false; 11174 } 11175 } 11176 return true; 11177 } 11178 11179 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11180 // Upgrade keysets are being used. Determine if new package has a superset of the 11181 // required keys. 11182 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11183 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11184 for (int i = 0; i < upgradeKeySets.length; i++) { 11185 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11186 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11187 return true; 11188 } 11189 } 11190 return false; 11191 } 11192 11193 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11194 UserHandle user, String installerPackageName, String volumeUuid, 11195 PackageInstalledInfo res) { 11196 final PackageParser.Package oldPackage; 11197 final String pkgName = pkg.packageName; 11198 final int[] allUsers; 11199 final boolean[] perUserInstalled; 11200 final boolean weFroze; 11201 11202 // First find the old package info and check signatures 11203 synchronized(mPackages) { 11204 oldPackage = mPackages.get(pkgName); 11205 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11206 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11207 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11208 if(!checkUpgradeKeySetLP(ps, pkg)) { 11209 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11210 "New package not signed by keys specified by upgrade-keysets: " 11211 + pkgName); 11212 return; 11213 } 11214 } else { 11215 // default to original signature matching 11216 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11217 != PackageManager.SIGNATURE_MATCH) { 11218 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11219 "New package has a different signature: " + pkgName); 11220 return; 11221 } 11222 } 11223 11224 // In case of rollback, remember per-user/profile install state 11225 allUsers = sUserManager.getUserIds(); 11226 perUserInstalled = new boolean[allUsers.length]; 11227 for (int i = 0; i < allUsers.length; i++) { 11228 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11229 } 11230 11231 // Mark the app as frozen to prevent launching during the upgrade 11232 // process, and then kill all running instances 11233 if (!ps.frozen) { 11234 ps.frozen = true; 11235 weFroze = true; 11236 } else { 11237 weFroze = false; 11238 } 11239 } 11240 11241 // Now that we're guarded by frozen state, kill app during upgrade 11242 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11243 11244 try { 11245 boolean sysPkg = (isSystemApp(oldPackage)); 11246 if (sysPkg) { 11247 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11248 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11249 } else { 11250 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11251 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11252 } 11253 } finally { 11254 // Regardless of success or failure of upgrade steps above, always 11255 // unfreeze the package if we froze it 11256 if (weFroze) { 11257 unfreezePackage(pkgName); 11258 } 11259 } 11260 } 11261 11262 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11263 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11264 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11265 String volumeUuid, PackageInstalledInfo res) { 11266 String pkgName = deletedPackage.packageName; 11267 boolean deletedPkg = true; 11268 boolean updatedSettings = false; 11269 11270 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11271 + deletedPackage); 11272 long origUpdateTime; 11273 if (pkg.mExtras != null) { 11274 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11275 } else { 11276 origUpdateTime = 0; 11277 } 11278 11279 // First delete the existing package while retaining the data directory 11280 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11281 res.removedInfo, true)) { 11282 // If the existing package wasn't successfully deleted 11283 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11284 deletedPkg = false; 11285 } else { 11286 // Successfully deleted the old package; proceed with replace. 11287 11288 // If deleted package lived in a container, give users a chance to 11289 // relinquish resources before killing. 11290 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11291 if (DEBUG_INSTALL) { 11292 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11293 } 11294 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11295 final ArrayList<String> pkgList = new ArrayList<String>(1); 11296 pkgList.add(deletedPackage.applicationInfo.packageName); 11297 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11298 } 11299 11300 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11301 try { 11302 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11303 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11304 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11305 perUserInstalled, res, user); 11306 updatedSettings = true; 11307 } catch (PackageManagerException e) { 11308 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11309 } 11310 } 11311 11312 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11313 // remove package from internal structures. Note that we want deletePackageX to 11314 // delete the package data and cache directories that it created in 11315 // scanPackageLocked, unless those directories existed before we even tried to 11316 // install. 11317 if(updatedSettings) { 11318 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11319 deletePackageLI( 11320 pkgName, null, true, allUsers, perUserInstalled, 11321 PackageManager.DELETE_KEEP_DATA, 11322 res.removedInfo, true); 11323 } 11324 // Since we failed to install the new package we need to restore the old 11325 // package that we deleted. 11326 if (deletedPkg) { 11327 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11328 File restoreFile = new File(deletedPackage.codePath); 11329 // Parse old package 11330 boolean oldExternal = isExternal(deletedPackage); 11331 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11332 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11333 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11334 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11335 try { 11336 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11337 } catch (PackageManagerException e) { 11338 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11339 + e.getMessage()); 11340 return; 11341 } 11342 // Restore of old package succeeded. Update permissions. 11343 // writer 11344 synchronized (mPackages) { 11345 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11346 UPDATE_PERMISSIONS_ALL); 11347 // can downgrade to reader 11348 mSettings.writeLPr(); 11349 } 11350 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11351 } 11352 } 11353 } 11354 11355 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11356 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11357 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11358 String volumeUuid, PackageInstalledInfo res) { 11359 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11360 + ", old=" + deletedPackage); 11361 boolean disabledSystem = false; 11362 boolean updatedSettings = false; 11363 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11364 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11365 != 0) { 11366 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11367 } 11368 String packageName = deletedPackage.packageName; 11369 if (packageName == null) { 11370 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11371 "Attempt to delete null packageName."); 11372 return; 11373 } 11374 PackageParser.Package oldPkg; 11375 PackageSetting oldPkgSetting; 11376 // reader 11377 synchronized (mPackages) { 11378 oldPkg = mPackages.get(packageName); 11379 oldPkgSetting = mSettings.mPackages.get(packageName); 11380 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11381 (oldPkgSetting == null)) { 11382 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11383 "Couldn't find package:" + packageName + " information"); 11384 return; 11385 } 11386 } 11387 11388 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11389 res.removedInfo.removedPackage = packageName; 11390 // Remove existing system package 11391 removePackageLI(oldPkgSetting, true); 11392 // writer 11393 synchronized (mPackages) { 11394 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11395 if (!disabledSystem && deletedPackage != null) { 11396 // We didn't need to disable the .apk as a current system package, 11397 // which means we are replacing another update that is already 11398 // installed. We need to make sure to delete the older one's .apk. 11399 res.removedInfo.args = createInstallArgsForExisting(0, 11400 deletedPackage.applicationInfo.getCodePath(), 11401 deletedPackage.applicationInfo.getResourcePath(), 11402 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11403 } else { 11404 res.removedInfo.args = null; 11405 } 11406 } 11407 11408 // Successfully disabled the old package. Now proceed with re-installation 11409 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11410 11411 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11412 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11413 11414 PackageParser.Package newPackage = null; 11415 try { 11416 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11417 if (newPackage.mExtras != null) { 11418 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11419 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11420 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11421 11422 // is the update attempting to change shared user? that isn't going to work... 11423 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11424 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11425 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11426 + " to " + newPkgSetting.sharedUser); 11427 updatedSettings = true; 11428 } 11429 } 11430 11431 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11432 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11433 perUserInstalled, res, user); 11434 updatedSettings = true; 11435 } 11436 11437 } catch (PackageManagerException e) { 11438 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11439 } 11440 11441 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11442 // Re installation failed. Restore old information 11443 // Remove new pkg information 11444 if (newPackage != null) { 11445 removeInstalledPackageLI(newPackage, true); 11446 } 11447 // Add back the old system package 11448 try { 11449 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11450 } catch (PackageManagerException e) { 11451 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11452 } 11453 // Restore the old system information in Settings 11454 synchronized (mPackages) { 11455 if (disabledSystem) { 11456 mSettings.enableSystemPackageLPw(packageName); 11457 } 11458 if (updatedSettings) { 11459 mSettings.setInstallerPackageName(packageName, 11460 oldPkgSetting.installerPackageName); 11461 } 11462 mSettings.writeLPr(); 11463 } 11464 } 11465 } 11466 11467 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11468 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11469 UserHandle user) { 11470 String pkgName = newPackage.packageName; 11471 synchronized (mPackages) { 11472 //write settings. the installStatus will be incomplete at this stage. 11473 //note that the new package setting would have already been 11474 //added to mPackages. It hasn't been persisted yet. 11475 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11476 mSettings.writeLPr(); 11477 } 11478 11479 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11480 11481 synchronized (mPackages) { 11482 updatePermissionsLPw(newPackage.packageName, newPackage, 11483 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11484 ? UPDATE_PERMISSIONS_ALL : 0)); 11485 // For system-bundled packages, we assume that installing an upgraded version 11486 // of the package implies that the user actually wants to run that new code, 11487 // so we enable the package. 11488 PackageSetting ps = mSettings.mPackages.get(pkgName); 11489 if (ps != null) { 11490 if (isSystemApp(newPackage)) { 11491 // NB: implicit assumption that system package upgrades apply to all users 11492 if (DEBUG_INSTALL) { 11493 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11494 } 11495 if (res.origUsers != null) { 11496 for (int userHandle : res.origUsers) { 11497 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11498 userHandle, installerPackageName); 11499 } 11500 } 11501 // Also convey the prior install/uninstall state 11502 if (allUsers != null && perUserInstalled != null) { 11503 for (int i = 0; i < allUsers.length; i++) { 11504 if (DEBUG_INSTALL) { 11505 Slog.d(TAG, " user " + allUsers[i] 11506 + " => " + perUserInstalled[i]); 11507 } 11508 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11509 } 11510 // these install state changes will be persisted in the 11511 // upcoming call to mSettings.writeLPr(). 11512 } 11513 } 11514 // It's implied that when a user requests installation, they want the app to be 11515 // installed and enabled. 11516 int userId = user.getIdentifier(); 11517 if (userId != UserHandle.USER_ALL) { 11518 ps.setInstalled(true, userId); 11519 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11520 } 11521 } 11522 res.name = pkgName; 11523 res.uid = newPackage.applicationInfo.uid; 11524 res.pkg = newPackage; 11525 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11526 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11527 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11528 //to update install status 11529 mSettings.writeLPr(); 11530 } 11531 } 11532 11533 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11534 final int installFlags = args.installFlags; 11535 final String installerPackageName = args.installerPackageName; 11536 final String volumeUuid = args.volumeUuid; 11537 final File tmpPackageFile = new File(args.getCodePath()); 11538 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11539 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11540 || (args.volumeUuid != null)); 11541 boolean replace = false; 11542 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11543 // Result object to be returned 11544 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11545 11546 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11547 // Retrieve PackageSettings and parse package 11548 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11549 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11550 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11551 PackageParser pp = new PackageParser(); 11552 pp.setSeparateProcesses(mSeparateProcesses); 11553 pp.setDisplayMetrics(mMetrics); 11554 11555 final PackageParser.Package pkg; 11556 try { 11557 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11558 } catch (PackageParserException e) { 11559 res.setError("Failed parse during installPackageLI", e); 11560 return; 11561 } 11562 11563 // Mark that we have an install time CPU ABI override. 11564 pkg.cpuAbiOverride = args.abiOverride; 11565 11566 String pkgName = res.name = pkg.packageName; 11567 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11568 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11569 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11570 return; 11571 } 11572 } 11573 11574 try { 11575 pp.collectCertificates(pkg, parseFlags); 11576 pp.collectManifestDigest(pkg); 11577 } catch (PackageParserException e) { 11578 res.setError("Failed collect during installPackageLI", e); 11579 return; 11580 } 11581 11582 /* If the installer passed in a manifest digest, compare it now. */ 11583 if (args.manifestDigest != null) { 11584 if (DEBUG_INSTALL) { 11585 final String parsedManifest = pkg.manifestDigest == null ? "null" 11586 : pkg.manifestDigest.toString(); 11587 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11588 + parsedManifest); 11589 } 11590 11591 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11592 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11593 return; 11594 } 11595 } else if (DEBUG_INSTALL) { 11596 final String parsedManifest = pkg.manifestDigest == null 11597 ? "null" : pkg.manifestDigest.toString(); 11598 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11599 } 11600 11601 // Get rid of all references to package scan path via parser. 11602 pp = null; 11603 String oldCodePath = null; 11604 boolean systemApp = false; 11605 synchronized (mPackages) { 11606 // Check if installing already existing package 11607 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11608 String oldName = mSettings.mRenamedPackages.get(pkgName); 11609 if (pkg.mOriginalPackages != null 11610 && pkg.mOriginalPackages.contains(oldName) 11611 && mPackages.containsKey(oldName)) { 11612 // This package is derived from an original package, 11613 // and this device has been updating from that original 11614 // name. We must continue using the original name, so 11615 // rename the new package here. 11616 pkg.setPackageName(oldName); 11617 pkgName = pkg.packageName; 11618 replace = true; 11619 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11620 + oldName + " pkgName=" + pkgName); 11621 } else if (mPackages.containsKey(pkgName)) { 11622 // This package, under its official name, already exists 11623 // on the device; we should replace it. 11624 replace = true; 11625 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11626 } 11627 11628 // Prevent apps opting out from runtime permissions 11629 if (replace) { 11630 PackageParser.Package oldPackage = mPackages.get(pkgName); 11631 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11632 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11633 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11634 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11635 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11636 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11637 + " doesn't support runtime permissions but the old" 11638 + " target SDK " + oldTargetSdk + " does."); 11639 return; 11640 } 11641 } 11642 } 11643 11644 PackageSetting ps = mSettings.mPackages.get(pkgName); 11645 if (ps != null) { 11646 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11647 11648 // Quick sanity check that we're signed correctly if updating; 11649 // we'll check this again later when scanning, but we want to 11650 // bail early here before tripping over redefined permissions. 11651 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11652 if (!checkUpgradeKeySetLP(ps, pkg)) { 11653 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11654 + pkg.packageName + " upgrade keys do not match the " 11655 + "previously installed version"); 11656 return; 11657 } 11658 } else { 11659 try { 11660 verifySignaturesLP(ps, pkg); 11661 } catch (PackageManagerException e) { 11662 res.setError(e.error, e.getMessage()); 11663 return; 11664 } 11665 } 11666 11667 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11668 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11669 systemApp = (ps.pkg.applicationInfo.flags & 11670 ApplicationInfo.FLAG_SYSTEM) != 0; 11671 } 11672 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11673 } 11674 11675 // Check whether the newly-scanned package wants to define an already-defined perm 11676 int N = pkg.permissions.size(); 11677 for (int i = N-1; i >= 0; i--) { 11678 PackageParser.Permission perm = pkg.permissions.get(i); 11679 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11680 if (bp != null) { 11681 // If the defining package is signed with our cert, it's okay. This 11682 // also includes the "updating the same package" case, of course. 11683 // "updating same package" could also involve key-rotation. 11684 final boolean sigsOk; 11685 if (bp.sourcePackage.equals(pkg.packageName) 11686 && (bp.packageSetting instanceof PackageSetting) 11687 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11688 scanFlags))) { 11689 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11690 } else { 11691 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11692 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11693 } 11694 if (!sigsOk) { 11695 // If the owning package is the system itself, we log but allow 11696 // install to proceed; we fail the install on all other permission 11697 // redefinitions. 11698 if (!bp.sourcePackage.equals("android")) { 11699 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11700 + pkg.packageName + " attempting to redeclare permission " 11701 + perm.info.name + " already owned by " + bp.sourcePackage); 11702 res.origPermission = perm.info.name; 11703 res.origPackage = bp.sourcePackage; 11704 return; 11705 } else { 11706 Slog.w(TAG, "Package " + pkg.packageName 11707 + " attempting to redeclare system permission " 11708 + perm.info.name + "; ignoring new declaration"); 11709 pkg.permissions.remove(i); 11710 } 11711 } 11712 } 11713 } 11714 11715 } 11716 11717 if (systemApp && onExternal) { 11718 // Disable updates to system apps on sdcard 11719 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11720 "Cannot install updates to system apps on sdcard"); 11721 return; 11722 } 11723 11724 if (args.move != null) { 11725 // We did an in-place move, so dex is ready to roll 11726 scanFlags |= SCAN_NO_DEX; 11727 scanFlags |= SCAN_MOVE; 11728 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11729 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11730 scanFlags |= SCAN_NO_DEX; 11731 11732 try { 11733 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11734 true /* extract libs */); 11735 } catch (PackageManagerException pme) { 11736 Slog.e(TAG, "Error deriving application ABI", pme); 11737 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11738 return; 11739 } 11740 11741 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11742 int result = mPackageDexOptimizer 11743 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11744 false /* defer */, false /* inclDependencies */); 11745 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11746 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11747 return; 11748 } 11749 } 11750 11751 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11752 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11753 return; 11754 } 11755 11756 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11757 11758 if (replace) { 11759 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11760 installerPackageName, volumeUuid, res); 11761 } else { 11762 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11763 args.user, installerPackageName, volumeUuid, res); 11764 } 11765 synchronized (mPackages) { 11766 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11767 if (ps != null) { 11768 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11769 } 11770 } 11771 } 11772 11773 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11774 if (mIntentFilterVerifierComponent == null) { 11775 Slog.w(TAG, "No IntentFilter verification will not be done as " 11776 + "there is no IntentFilterVerifier available!"); 11777 return; 11778 } 11779 11780 final int verifierUid = getPackageUid( 11781 mIntentFilterVerifierComponent.getPackageName(), 11782 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11783 11784 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11785 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11786 msg.obj = pkg; 11787 msg.arg1 = userId; 11788 msg.arg2 = verifierUid; 11789 11790 mHandler.sendMessage(msg); 11791 } 11792 11793 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11794 PackageParser.Package pkg) { 11795 int size = pkg.activities.size(); 11796 if (size == 0) { 11797 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11798 "No activity, so no need to verify any IntentFilter!"); 11799 return; 11800 } 11801 11802 final boolean hasDomainURLs = hasDomainURLs(pkg); 11803 if (!hasDomainURLs) { 11804 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11805 "No domain URLs, so no need to verify any IntentFilter!"); 11806 return; 11807 } 11808 11809 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11810 + " if any IntentFilter from the " + size 11811 + " Activities needs verification ..."); 11812 11813 final int verificationId = mIntentFilterVerificationToken++; 11814 int count = 0; 11815 final String packageName = pkg.packageName; 11816 boolean needToVerify = false; 11817 11818 synchronized (mPackages) { 11819 // If any filters need to be verified, then all need to be. 11820 for (PackageParser.Activity a : pkg.activities) { 11821 for (ActivityIntentInfo filter : a.intents) { 11822 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 11823 if (DEBUG_DOMAIN_VERIFICATION) { 11824 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 11825 } 11826 needToVerify = true; 11827 break; 11828 } 11829 } 11830 } 11831 if (needToVerify) { 11832 for (PackageParser.Activity a : pkg.activities) { 11833 for (ActivityIntentInfo filter : a.intents) { 11834 boolean needsFilterVerification = filter.hasWebDataURI(); 11835 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11836 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11837 "Verification needed for IntentFilter:" + filter.toString()); 11838 mIntentFilterVerifier.addOneIntentFilterVerification( 11839 verifierUid, userId, verificationId, filter, packageName); 11840 count++; 11841 } 11842 } 11843 } 11844 } 11845 } 11846 11847 if (count > 0) { 11848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 11849 + " IntentFilter verification" + (count > 1 ? "s" : "") 11850 + " for userId:" + userId); 11851 mIntentFilterVerifier.startVerifications(userId); 11852 } else { 11853 if (DEBUG_DOMAIN_VERIFICATION) { 11854 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 11855 } 11856 } 11857 } 11858 11859 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11860 final ComponentName cn = filter.activity.getComponentName(); 11861 final String packageName = cn.getPackageName(); 11862 11863 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11864 packageName); 11865 if (ivi == null) { 11866 return true; 11867 } 11868 int status = ivi.getStatus(); 11869 switch (status) { 11870 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11871 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11872 return true; 11873 11874 default: 11875 // Nothing to do 11876 return false; 11877 } 11878 } 11879 11880 private static boolean isMultiArch(PackageSetting ps) { 11881 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11882 } 11883 11884 private static boolean isMultiArch(ApplicationInfo info) { 11885 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11886 } 11887 11888 private static boolean isExternal(PackageParser.Package pkg) { 11889 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11890 } 11891 11892 private static boolean isExternal(PackageSetting ps) { 11893 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11894 } 11895 11896 private static boolean isExternal(ApplicationInfo info) { 11897 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11898 } 11899 11900 private static boolean isSystemApp(PackageParser.Package pkg) { 11901 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11902 } 11903 11904 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11905 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11906 } 11907 11908 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11909 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11910 } 11911 11912 private static boolean isSystemApp(PackageSetting ps) { 11913 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11914 } 11915 11916 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11917 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11918 } 11919 11920 private int packageFlagsToInstallFlags(PackageSetting ps) { 11921 int installFlags = 0; 11922 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11923 // This existing package was an external ASEC install when we have 11924 // the external flag without a UUID 11925 installFlags |= PackageManager.INSTALL_EXTERNAL; 11926 } 11927 if (ps.isForwardLocked()) { 11928 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11929 } 11930 return installFlags; 11931 } 11932 11933 private void deleteTempPackageFiles() { 11934 final FilenameFilter filter = new FilenameFilter() { 11935 public boolean accept(File dir, String name) { 11936 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11937 } 11938 }; 11939 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11940 file.delete(); 11941 } 11942 } 11943 11944 @Override 11945 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11946 int flags) { 11947 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11948 flags); 11949 } 11950 11951 @Override 11952 public void deletePackage(final String packageName, 11953 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11954 mContext.enforceCallingOrSelfPermission( 11955 android.Manifest.permission.DELETE_PACKAGES, null); 11956 final int uid = Binder.getCallingUid(); 11957 if (UserHandle.getUserId(uid) != userId) { 11958 mContext.enforceCallingPermission( 11959 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11960 "deletePackage for user " + userId); 11961 } 11962 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11963 try { 11964 observer.onPackageDeleted(packageName, 11965 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11966 } catch (RemoteException re) { 11967 } 11968 return; 11969 } 11970 11971 boolean uninstallBlocked = false; 11972 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11973 int[] users = sUserManager.getUserIds(); 11974 for (int i = 0; i < users.length; ++i) { 11975 if (getBlockUninstallForUser(packageName, users[i])) { 11976 uninstallBlocked = true; 11977 break; 11978 } 11979 } 11980 } else { 11981 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11982 } 11983 if (uninstallBlocked) { 11984 try { 11985 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11986 null); 11987 } catch (RemoteException re) { 11988 } 11989 return; 11990 } 11991 11992 if (DEBUG_REMOVE) { 11993 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11994 } 11995 // Queue up an async operation since the package deletion may take a little while. 11996 mHandler.post(new Runnable() { 11997 public void run() { 11998 mHandler.removeCallbacks(this); 11999 final int returnCode = deletePackageX(packageName, userId, flags); 12000 if (observer != null) { 12001 try { 12002 observer.onPackageDeleted(packageName, returnCode, null); 12003 } catch (RemoteException e) { 12004 Log.i(TAG, "Observer no longer exists."); 12005 } //end catch 12006 } //end if 12007 } //end run 12008 }); 12009 } 12010 12011 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12012 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12013 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12014 try { 12015 if (dpm != null) { 12016 if (dpm.isDeviceOwner(packageName)) { 12017 return true; 12018 } 12019 int[] users; 12020 if (userId == UserHandle.USER_ALL) { 12021 users = sUserManager.getUserIds(); 12022 } else { 12023 users = new int[]{userId}; 12024 } 12025 for (int i = 0; i < users.length; ++i) { 12026 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12027 return true; 12028 } 12029 } 12030 } 12031 } catch (RemoteException e) { 12032 } 12033 return false; 12034 } 12035 12036 /** 12037 * This method is an internal method that could be get invoked either 12038 * to delete an installed package or to clean up a failed installation. 12039 * After deleting an installed package, a broadcast is sent to notify any 12040 * listeners that the package has been installed. For cleaning up a failed 12041 * installation, the broadcast is not necessary since the package's 12042 * installation wouldn't have sent the initial broadcast either 12043 * The key steps in deleting a package are 12044 * deleting the package information in internal structures like mPackages, 12045 * deleting the packages base directories through installd 12046 * updating mSettings to reflect current status 12047 * persisting settings for later use 12048 * sending a broadcast if necessary 12049 */ 12050 private int deletePackageX(String packageName, int userId, int flags) { 12051 final PackageRemovedInfo info = new PackageRemovedInfo(); 12052 final boolean res; 12053 12054 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12055 ? UserHandle.ALL : new UserHandle(userId); 12056 12057 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12058 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12059 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12060 } 12061 12062 boolean removedForAllUsers = false; 12063 boolean systemUpdate = false; 12064 12065 // for the uninstall-updates case and restricted profiles, remember the per- 12066 // userhandle installed state 12067 int[] allUsers; 12068 boolean[] perUserInstalled; 12069 synchronized (mPackages) { 12070 PackageSetting ps = mSettings.mPackages.get(packageName); 12071 allUsers = sUserManager.getUserIds(); 12072 perUserInstalled = new boolean[allUsers.length]; 12073 for (int i = 0; i < allUsers.length; i++) { 12074 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12075 } 12076 } 12077 12078 synchronized (mInstallLock) { 12079 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12080 res = deletePackageLI(packageName, removeForUser, 12081 true, allUsers, perUserInstalled, 12082 flags | REMOVE_CHATTY, info, true); 12083 systemUpdate = info.isRemovedPackageSystemUpdate; 12084 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12085 removedForAllUsers = true; 12086 } 12087 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12088 + " removedForAllUsers=" + removedForAllUsers); 12089 } 12090 12091 if (res) { 12092 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12093 12094 // If the removed package was a system update, the old system package 12095 // was re-enabled; we need to broadcast this information 12096 if (systemUpdate) { 12097 Bundle extras = new Bundle(1); 12098 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12099 ? info.removedAppId : info.uid); 12100 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12101 12102 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12103 extras, null, null, null); 12104 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12105 extras, null, null, null); 12106 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12107 null, packageName, null, null); 12108 } 12109 } 12110 // Force a gc here. 12111 Runtime.getRuntime().gc(); 12112 // Delete the resources here after sending the broadcast to let 12113 // other processes clean up before deleting resources. 12114 if (info.args != null) { 12115 synchronized (mInstallLock) { 12116 info.args.doPostDeleteLI(true); 12117 } 12118 } 12119 12120 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12121 } 12122 12123 class PackageRemovedInfo { 12124 String removedPackage; 12125 int uid = -1; 12126 int removedAppId = -1; 12127 int[] removedUsers = null; 12128 boolean isRemovedPackageSystemUpdate = false; 12129 // Clean up resources deleted packages. 12130 InstallArgs args = null; 12131 12132 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12133 Bundle extras = new Bundle(1); 12134 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12135 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12136 if (replacing) { 12137 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12138 } 12139 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12140 if (removedPackage != null) { 12141 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12142 extras, null, null, removedUsers); 12143 if (fullRemove && !replacing) { 12144 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12145 extras, null, null, removedUsers); 12146 } 12147 } 12148 if (removedAppId >= 0) { 12149 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12150 removedUsers); 12151 } 12152 } 12153 } 12154 12155 /* 12156 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12157 * flag is not set, the data directory is removed as well. 12158 * make sure this flag is set for partially installed apps. If not its meaningless to 12159 * delete a partially installed application. 12160 */ 12161 private void removePackageDataLI(PackageSetting ps, 12162 int[] allUserHandles, boolean[] perUserInstalled, 12163 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12164 String packageName = ps.name; 12165 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12166 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12167 // Retrieve object to delete permissions for shared user later on 12168 final PackageSetting deletedPs; 12169 // reader 12170 synchronized (mPackages) { 12171 deletedPs = mSettings.mPackages.get(packageName); 12172 if (outInfo != null) { 12173 outInfo.removedPackage = packageName; 12174 outInfo.removedUsers = deletedPs != null 12175 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12176 : null; 12177 } 12178 } 12179 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12180 removeDataDirsLI(ps.volumeUuid, packageName); 12181 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12182 } 12183 // writer 12184 synchronized (mPackages) { 12185 if (deletedPs != null) { 12186 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12187 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12188 clearDefaultBrowserIfNeeded(packageName); 12189 if (outInfo != null) { 12190 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12191 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12192 } 12193 updatePermissionsLPw(deletedPs.name, null, 0); 12194 if (deletedPs.sharedUser != null) { 12195 // Remove permissions associated with package. Since runtime 12196 // permissions are per user we have to kill the removed package 12197 // or packages running under the shared user of the removed 12198 // package if revoking the permissions requested only by the removed 12199 // package is successful and this causes a change in gids. 12200 for (int userId : UserManagerService.getInstance().getUserIds()) { 12201 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12202 userId); 12203 if (userIdToKill == UserHandle.USER_ALL 12204 || userIdToKill >= UserHandle.USER_OWNER) { 12205 // If gids changed for this user, kill all affected packages. 12206 mHandler.post(new Runnable() { 12207 @Override 12208 public void run() { 12209 // This has to happen with no lock held. 12210 killSettingPackagesForUser(deletedPs, userIdToKill, 12211 KILL_APP_REASON_GIDS_CHANGED); 12212 } 12213 }); 12214 break; 12215 } 12216 } 12217 } 12218 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12219 } 12220 // make sure to preserve per-user disabled state if this removal was just 12221 // a downgrade of a system app to the factory package 12222 if (allUserHandles != null && perUserInstalled != null) { 12223 if (DEBUG_REMOVE) { 12224 Slog.d(TAG, "Propagating install state across downgrade"); 12225 } 12226 for (int i = 0; i < allUserHandles.length; i++) { 12227 if (DEBUG_REMOVE) { 12228 Slog.d(TAG, " user " + allUserHandles[i] 12229 + " => " + perUserInstalled[i]); 12230 } 12231 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12232 } 12233 } 12234 } 12235 // can downgrade to reader 12236 if (writeSettings) { 12237 // Save settings now 12238 mSettings.writeLPr(); 12239 } 12240 } 12241 if (outInfo != null) { 12242 // A user ID was deleted here. Go through all users and remove it 12243 // from KeyStore. 12244 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12245 } 12246 } 12247 12248 static boolean locationIsPrivileged(File path) { 12249 try { 12250 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12251 .getCanonicalPath(); 12252 return path.getCanonicalPath().startsWith(privilegedAppDir); 12253 } catch (IOException e) { 12254 Slog.e(TAG, "Unable to access code path " + path); 12255 } 12256 return false; 12257 } 12258 12259 /* 12260 * Tries to delete system package. 12261 */ 12262 private boolean deleteSystemPackageLI(PackageSetting newPs, 12263 int[] allUserHandles, boolean[] perUserInstalled, 12264 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12265 final boolean applyUserRestrictions 12266 = (allUserHandles != null) && (perUserInstalled != null); 12267 PackageSetting disabledPs = null; 12268 // Confirm if the system package has been updated 12269 // An updated system app can be deleted. This will also have to restore 12270 // the system pkg from system partition 12271 // reader 12272 synchronized (mPackages) { 12273 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12274 } 12275 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12276 + " disabledPs=" + disabledPs); 12277 if (disabledPs == null) { 12278 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12279 return false; 12280 } else if (DEBUG_REMOVE) { 12281 Slog.d(TAG, "Deleting system pkg from data partition"); 12282 } 12283 if (DEBUG_REMOVE) { 12284 if (applyUserRestrictions) { 12285 Slog.d(TAG, "Remembering install states:"); 12286 for (int i = 0; i < allUserHandles.length; i++) { 12287 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12288 } 12289 } 12290 } 12291 // Delete the updated package 12292 outInfo.isRemovedPackageSystemUpdate = true; 12293 if (disabledPs.versionCode < newPs.versionCode) { 12294 // Delete data for downgrades 12295 flags &= ~PackageManager.DELETE_KEEP_DATA; 12296 } else { 12297 // Preserve data by setting flag 12298 flags |= PackageManager.DELETE_KEEP_DATA; 12299 } 12300 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12301 allUserHandles, perUserInstalled, outInfo, writeSettings); 12302 if (!ret) { 12303 return false; 12304 } 12305 // writer 12306 synchronized (mPackages) { 12307 // Reinstate the old system package 12308 mSettings.enableSystemPackageLPw(newPs.name); 12309 // Remove any native libraries from the upgraded package. 12310 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12311 } 12312 // Install the system package 12313 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12314 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12315 if (locationIsPrivileged(disabledPs.codePath)) { 12316 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12317 } 12318 12319 final PackageParser.Package newPkg; 12320 try { 12321 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12322 } catch (PackageManagerException e) { 12323 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12324 return false; 12325 } 12326 12327 // writer 12328 synchronized (mPackages) { 12329 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12330 updatePermissionsLPw(newPkg.packageName, newPkg, 12331 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12332 if (applyUserRestrictions) { 12333 if (DEBUG_REMOVE) { 12334 Slog.d(TAG, "Propagating install state across reinstall"); 12335 } 12336 for (int i = 0; i < allUserHandles.length; i++) { 12337 if (DEBUG_REMOVE) { 12338 Slog.d(TAG, " user " + allUserHandles[i] 12339 + " => " + perUserInstalled[i]); 12340 } 12341 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12342 } 12343 // Regardless of writeSettings we need to ensure that this restriction 12344 // state propagation is persisted 12345 mSettings.writeAllUsersPackageRestrictionsLPr(); 12346 } 12347 // can downgrade to reader here 12348 if (writeSettings) { 12349 mSettings.writeLPr(); 12350 } 12351 } 12352 return true; 12353 } 12354 12355 private boolean deleteInstalledPackageLI(PackageSetting ps, 12356 boolean deleteCodeAndResources, int flags, 12357 int[] allUserHandles, boolean[] perUserInstalled, 12358 PackageRemovedInfo outInfo, boolean writeSettings) { 12359 if (outInfo != null) { 12360 outInfo.uid = ps.appId; 12361 } 12362 12363 // Delete package data from internal structures and also remove data if flag is set 12364 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12365 12366 // Delete application code and resources 12367 if (deleteCodeAndResources && (outInfo != null)) { 12368 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12369 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12370 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12371 } 12372 return true; 12373 } 12374 12375 @Override 12376 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12377 int userId) { 12378 mContext.enforceCallingOrSelfPermission( 12379 android.Manifest.permission.DELETE_PACKAGES, null); 12380 synchronized (mPackages) { 12381 PackageSetting ps = mSettings.mPackages.get(packageName); 12382 if (ps == null) { 12383 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12384 return false; 12385 } 12386 if (!ps.getInstalled(userId)) { 12387 // Can't block uninstall for an app that is not installed or enabled. 12388 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12389 return false; 12390 } 12391 ps.setBlockUninstall(blockUninstall, userId); 12392 mSettings.writePackageRestrictionsLPr(userId); 12393 } 12394 return true; 12395 } 12396 12397 @Override 12398 public boolean getBlockUninstallForUser(String packageName, int userId) { 12399 synchronized (mPackages) { 12400 PackageSetting ps = mSettings.mPackages.get(packageName); 12401 if (ps == null) { 12402 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12403 return false; 12404 } 12405 return ps.getBlockUninstall(userId); 12406 } 12407 } 12408 12409 /* 12410 * This method handles package deletion in general 12411 */ 12412 private boolean deletePackageLI(String packageName, UserHandle user, 12413 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12414 int flags, PackageRemovedInfo outInfo, 12415 boolean writeSettings) { 12416 if (packageName == null) { 12417 Slog.w(TAG, "Attempt to delete null packageName."); 12418 return false; 12419 } 12420 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12421 PackageSetting ps; 12422 boolean dataOnly = false; 12423 int removeUser = -1; 12424 int appId = -1; 12425 synchronized (mPackages) { 12426 ps = mSettings.mPackages.get(packageName); 12427 if (ps == null) { 12428 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12429 return false; 12430 } 12431 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12432 && user.getIdentifier() != UserHandle.USER_ALL) { 12433 // The caller is asking that the package only be deleted for a single 12434 // user. To do this, we just mark its uninstalled state and delete 12435 // its data. If this is a system app, we only allow this to happen if 12436 // they have set the special DELETE_SYSTEM_APP which requests different 12437 // semantics than normal for uninstalling system apps. 12438 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12439 ps.setUserState(user.getIdentifier(), 12440 COMPONENT_ENABLED_STATE_DEFAULT, 12441 false, //installed 12442 true, //stopped 12443 true, //notLaunched 12444 false, //hidden 12445 null, null, null, 12446 false, // blockUninstall 12447 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12448 if (!isSystemApp(ps)) { 12449 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12450 // Other user still have this package installed, so all 12451 // we need to do is clear this user's data and save that 12452 // it is uninstalled. 12453 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12454 removeUser = user.getIdentifier(); 12455 appId = ps.appId; 12456 scheduleWritePackageRestrictionsLocked(removeUser); 12457 } else { 12458 // We need to set it back to 'installed' so the uninstall 12459 // broadcasts will be sent correctly. 12460 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12461 ps.setInstalled(true, user.getIdentifier()); 12462 } 12463 } else { 12464 // This is a system app, so we assume that the 12465 // other users still have this package installed, so all 12466 // we need to do is clear this user's data and save that 12467 // it is uninstalled. 12468 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12469 removeUser = user.getIdentifier(); 12470 appId = ps.appId; 12471 scheduleWritePackageRestrictionsLocked(removeUser); 12472 } 12473 } 12474 } 12475 12476 if (removeUser >= 0) { 12477 // From above, we determined that we are deleting this only 12478 // for a single user. Continue the work here. 12479 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12480 if (outInfo != null) { 12481 outInfo.removedPackage = packageName; 12482 outInfo.removedAppId = appId; 12483 outInfo.removedUsers = new int[] {removeUser}; 12484 } 12485 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12486 removeKeystoreDataIfNeeded(removeUser, appId); 12487 schedulePackageCleaning(packageName, removeUser, false); 12488 synchronized (mPackages) { 12489 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12490 scheduleWritePackageRestrictionsLocked(removeUser); 12491 } 12492 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12493 removeUser); 12494 } 12495 return true; 12496 } 12497 12498 if (dataOnly) { 12499 // Delete application data first 12500 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12501 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12502 return true; 12503 } 12504 12505 boolean ret = false; 12506 if (isSystemApp(ps)) { 12507 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12508 // When an updated system application is deleted we delete the existing resources as well and 12509 // fall back to existing code in system partition 12510 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12511 flags, outInfo, writeSettings); 12512 } else { 12513 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12514 // Kill application pre-emptively especially for apps on sd. 12515 killApplication(packageName, ps.appId, "uninstall pkg"); 12516 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12517 allUserHandles, perUserInstalled, 12518 outInfo, writeSettings); 12519 } 12520 12521 return ret; 12522 } 12523 12524 private final class ClearStorageConnection implements ServiceConnection { 12525 IMediaContainerService mContainerService; 12526 12527 @Override 12528 public void onServiceConnected(ComponentName name, IBinder service) { 12529 synchronized (this) { 12530 mContainerService = IMediaContainerService.Stub.asInterface(service); 12531 notifyAll(); 12532 } 12533 } 12534 12535 @Override 12536 public void onServiceDisconnected(ComponentName name) { 12537 } 12538 } 12539 12540 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12541 final boolean mounted; 12542 if (Environment.isExternalStorageEmulated()) { 12543 mounted = true; 12544 } else { 12545 final String status = Environment.getExternalStorageState(); 12546 12547 mounted = status.equals(Environment.MEDIA_MOUNTED) 12548 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12549 } 12550 12551 if (!mounted) { 12552 return; 12553 } 12554 12555 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12556 int[] users; 12557 if (userId == UserHandle.USER_ALL) { 12558 users = sUserManager.getUserIds(); 12559 } else { 12560 users = new int[] { userId }; 12561 } 12562 final ClearStorageConnection conn = new ClearStorageConnection(); 12563 if (mContext.bindServiceAsUser( 12564 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12565 try { 12566 for (int curUser : users) { 12567 long timeout = SystemClock.uptimeMillis() + 5000; 12568 synchronized (conn) { 12569 long now = SystemClock.uptimeMillis(); 12570 while (conn.mContainerService == null && now < timeout) { 12571 try { 12572 conn.wait(timeout - now); 12573 } catch (InterruptedException e) { 12574 } 12575 } 12576 } 12577 if (conn.mContainerService == null) { 12578 return; 12579 } 12580 12581 final UserEnvironment userEnv = new UserEnvironment(curUser); 12582 clearDirectory(conn.mContainerService, 12583 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12584 if (allData) { 12585 clearDirectory(conn.mContainerService, 12586 userEnv.buildExternalStorageAppDataDirs(packageName)); 12587 clearDirectory(conn.mContainerService, 12588 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12589 } 12590 } 12591 } finally { 12592 mContext.unbindService(conn); 12593 } 12594 } 12595 } 12596 12597 @Override 12598 public void clearApplicationUserData(final String packageName, 12599 final IPackageDataObserver observer, final int userId) { 12600 mContext.enforceCallingOrSelfPermission( 12601 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12602 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12603 // Queue up an async operation since the package deletion may take a little while. 12604 mHandler.post(new Runnable() { 12605 public void run() { 12606 mHandler.removeCallbacks(this); 12607 final boolean succeeded; 12608 synchronized (mInstallLock) { 12609 succeeded = clearApplicationUserDataLI(packageName, userId); 12610 } 12611 clearExternalStorageDataSync(packageName, userId, true); 12612 if (succeeded) { 12613 // invoke DeviceStorageMonitor's update method to clear any notifications 12614 DeviceStorageMonitorInternal 12615 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12616 if (dsm != null) { 12617 dsm.checkMemory(); 12618 } 12619 } 12620 if(observer != null) { 12621 try { 12622 observer.onRemoveCompleted(packageName, succeeded); 12623 } catch (RemoteException e) { 12624 Log.i(TAG, "Observer no longer exists."); 12625 } 12626 } //end if observer 12627 } //end run 12628 }); 12629 } 12630 12631 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12632 if (packageName == null) { 12633 Slog.w(TAG, "Attempt to delete null packageName."); 12634 return false; 12635 } 12636 12637 // Try finding details about the requested package 12638 PackageParser.Package pkg; 12639 synchronized (mPackages) { 12640 pkg = mPackages.get(packageName); 12641 if (pkg == null) { 12642 final PackageSetting ps = mSettings.mPackages.get(packageName); 12643 if (ps != null) { 12644 pkg = ps.pkg; 12645 } 12646 } 12647 12648 if (pkg == null) { 12649 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12650 return false; 12651 } 12652 12653 PackageSetting ps = (PackageSetting) pkg.mExtras; 12654 PermissionsState permissionsState = ps.getPermissionsState(); 12655 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12656 } 12657 12658 // Always delete data directories for package, even if we found no other 12659 // record of app. This helps users recover from UID mismatches without 12660 // resorting to a full data wipe. 12661 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12662 if (retCode < 0) { 12663 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12664 return false; 12665 } 12666 12667 final int appId = pkg.applicationInfo.uid; 12668 removeKeystoreDataIfNeeded(userId, appId); 12669 12670 // Create a native library symlink only if we have native libraries 12671 // and if the native libraries are 32 bit libraries. We do not provide 12672 // this symlink for 64 bit libraries. 12673 if (pkg.applicationInfo.primaryCpuAbi != null && 12674 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12675 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12676 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12677 nativeLibPath, userId) < 0) { 12678 Slog.w(TAG, "Failed linking native library dir"); 12679 return false; 12680 } 12681 } 12682 12683 return true; 12684 } 12685 12686 12687 /** 12688 * Revokes granted runtime permissions and clears resettable flags 12689 * which are flags that can be set by a user interaction. 12690 * 12691 * @param permissionsState The permission state to reset. 12692 * @param userId The device user for which to do a reset. 12693 */ 12694 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12695 PermissionsState permissionsState, int userId) { 12696 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12697 | PackageManager.FLAG_PERMISSION_USER_FIXED 12698 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12699 12700 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 12701 } 12702 12703 /** 12704 * Revokes granted runtime permissions and clears all flags. 12705 * 12706 * @param permissionsState The permission state to reset. 12707 * @param userId The device user for which to do a reset. 12708 */ 12709 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 12710 PermissionsState permissionsState, int userId) { 12711 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 12712 PackageManager.MASK_PERMISSION_FLAGS); 12713 } 12714 12715 /** 12716 * Revokes granted runtime permissions and clears certain flags. 12717 * 12718 * @param permissionsState The permission state to reset. 12719 * @param userId The device user for which to do a reset. 12720 * @param flags The flags that is going to be reset. 12721 */ 12722 private void revokeRuntimePermissionsAndClearFlagsLocked( 12723 PermissionsState permissionsState, int userId, int flags) { 12724 boolean needsWrite = false; 12725 12726 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12727 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12728 if (bp != null) { 12729 permissionsState.revokeRuntimePermission(bp, userId); 12730 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 12731 needsWrite = true; 12732 } 12733 } 12734 12735 // Ensure default permissions are never cleared. 12736 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 12737 12738 if (needsWrite) { 12739 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12740 } 12741 } 12742 12743 /** 12744 * Remove entries from the keystore daemon. Will only remove it if the 12745 * {@code appId} is valid. 12746 */ 12747 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12748 if (appId < 0) { 12749 return; 12750 } 12751 12752 final KeyStore keyStore = KeyStore.getInstance(); 12753 if (keyStore != null) { 12754 if (userId == UserHandle.USER_ALL) { 12755 for (final int individual : sUserManager.getUserIds()) { 12756 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12757 } 12758 } else { 12759 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12760 } 12761 } else { 12762 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12763 } 12764 } 12765 12766 @Override 12767 public void deleteApplicationCacheFiles(final String packageName, 12768 final IPackageDataObserver observer) { 12769 mContext.enforceCallingOrSelfPermission( 12770 android.Manifest.permission.DELETE_CACHE_FILES, null); 12771 // Queue up an async operation since the package deletion may take a little while. 12772 final int userId = UserHandle.getCallingUserId(); 12773 mHandler.post(new Runnable() { 12774 public void run() { 12775 mHandler.removeCallbacks(this); 12776 final boolean succeded; 12777 synchronized (mInstallLock) { 12778 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12779 } 12780 clearExternalStorageDataSync(packageName, userId, false); 12781 if (observer != null) { 12782 try { 12783 observer.onRemoveCompleted(packageName, succeded); 12784 } catch (RemoteException e) { 12785 Log.i(TAG, "Observer no longer exists."); 12786 } 12787 } //end if observer 12788 } //end run 12789 }); 12790 } 12791 12792 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12793 if (packageName == null) { 12794 Slog.w(TAG, "Attempt to delete null packageName."); 12795 return false; 12796 } 12797 PackageParser.Package p; 12798 synchronized (mPackages) { 12799 p = mPackages.get(packageName); 12800 } 12801 if (p == null) { 12802 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12803 return false; 12804 } 12805 final ApplicationInfo applicationInfo = p.applicationInfo; 12806 if (applicationInfo == null) { 12807 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12808 return false; 12809 } 12810 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12811 if (retCode < 0) { 12812 Slog.w(TAG, "Couldn't remove cache files for package: " 12813 + packageName + " u" + userId); 12814 return false; 12815 } 12816 return true; 12817 } 12818 12819 @Override 12820 public void getPackageSizeInfo(final String packageName, int userHandle, 12821 final IPackageStatsObserver observer) { 12822 mContext.enforceCallingOrSelfPermission( 12823 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12824 if (packageName == null) { 12825 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12826 } 12827 12828 PackageStats stats = new PackageStats(packageName, userHandle); 12829 12830 /* 12831 * Queue up an async operation since the package measurement may take a 12832 * little while. 12833 */ 12834 Message msg = mHandler.obtainMessage(INIT_COPY); 12835 msg.obj = new MeasureParams(stats, observer); 12836 mHandler.sendMessage(msg); 12837 } 12838 12839 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12840 PackageStats pStats) { 12841 if (packageName == null) { 12842 Slog.w(TAG, "Attempt to get size of null packageName."); 12843 return false; 12844 } 12845 PackageParser.Package p; 12846 boolean dataOnly = false; 12847 String libDirRoot = null; 12848 String asecPath = null; 12849 PackageSetting ps = null; 12850 synchronized (mPackages) { 12851 p = mPackages.get(packageName); 12852 ps = mSettings.mPackages.get(packageName); 12853 if(p == null) { 12854 dataOnly = true; 12855 if((ps == null) || (ps.pkg == null)) { 12856 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12857 return false; 12858 } 12859 p = ps.pkg; 12860 } 12861 if (ps != null) { 12862 libDirRoot = ps.legacyNativeLibraryPathString; 12863 } 12864 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12865 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12866 if (secureContainerId != null) { 12867 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12868 } 12869 } 12870 } 12871 String publicSrcDir = null; 12872 if(!dataOnly) { 12873 final ApplicationInfo applicationInfo = p.applicationInfo; 12874 if (applicationInfo == null) { 12875 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12876 return false; 12877 } 12878 if (p.isForwardLocked()) { 12879 publicSrcDir = applicationInfo.getBaseResourcePath(); 12880 } 12881 } 12882 // TODO: extend to measure size of split APKs 12883 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12884 // not just the first level. 12885 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12886 // just the primary. 12887 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12888 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12889 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12890 if (res < 0) { 12891 return false; 12892 } 12893 12894 // Fix-up for forward-locked applications in ASEC containers. 12895 if (!isExternal(p)) { 12896 pStats.codeSize += pStats.externalCodeSize; 12897 pStats.externalCodeSize = 0L; 12898 } 12899 12900 return true; 12901 } 12902 12903 12904 @Override 12905 public void addPackageToPreferred(String packageName) { 12906 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12907 } 12908 12909 @Override 12910 public void removePackageFromPreferred(String packageName) { 12911 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12912 } 12913 12914 @Override 12915 public List<PackageInfo> getPreferredPackages(int flags) { 12916 return new ArrayList<PackageInfo>(); 12917 } 12918 12919 private int getUidTargetSdkVersionLockedLPr(int uid) { 12920 Object obj = mSettings.getUserIdLPr(uid); 12921 if (obj instanceof SharedUserSetting) { 12922 final SharedUserSetting sus = (SharedUserSetting) obj; 12923 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12924 final Iterator<PackageSetting> it = sus.packages.iterator(); 12925 while (it.hasNext()) { 12926 final PackageSetting ps = it.next(); 12927 if (ps.pkg != null) { 12928 int v = ps.pkg.applicationInfo.targetSdkVersion; 12929 if (v < vers) vers = v; 12930 } 12931 } 12932 return vers; 12933 } else if (obj instanceof PackageSetting) { 12934 final PackageSetting ps = (PackageSetting) obj; 12935 if (ps.pkg != null) { 12936 return ps.pkg.applicationInfo.targetSdkVersion; 12937 } 12938 } 12939 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12940 } 12941 12942 @Override 12943 public void addPreferredActivity(IntentFilter filter, int match, 12944 ComponentName[] set, ComponentName activity, int userId) { 12945 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12946 "Adding preferred"); 12947 } 12948 12949 private void addPreferredActivityInternal(IntentFilter filter, int match, 12950 ComponentName[] set, ComponentName activity, boolean always, int userId, 12951 String opname) { 12952 // writer 12953 int callingUid = Binder.getCallingUid(); 12954 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12955 if (filter.countActions() == 0) { 12956 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12957 return; 12958 } 12959 synchronized (mPackages) { 12960 if (mContext.checkCallingOrSelfPermission( 12961 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12962 != PackageManager.PERMISSION_GRANTED) { 12963 if (getUidTargetSdkVersionLockedLPr(callingUid) 12964 < Build.VERSION_CODES.FROYO) { 12965 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12966 + callingUid); 12967 return; 12968 } 12969 mContext.enforceCallingOrSelfPermission( 12970 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12971 } 12972 12973 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12974 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12975 + userId + ":"); 12976 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12977 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12978 scheduleWritePackageRestrictionsLocked(userId); 12979 } 12980 } 12981 12982 @Override 12983 public void replacePreferredActivity(IntentFilter filter, int match, 12984 ComponentName[] set, ComponentName activity, int userId) { 12985 if (filter.countActions() != 1) { 12986 throw new IllegalArgumentException( 12987 "replacePreferredActivity expects filter to have only 1 action."); 12988 } 12989 if (filter.countDataAuthorities() != 0 12990 || filter.countDataPaths() != 0 12991 || filter.countDataSchemes() > 1 12992 || filter.countDataTypes() != 0) { 12993 throw new IllegalArgumentException( 12994 "replacePreferredActivity expects filter to have no data authorities, " + 12995 "paths, or types; and at most one scheme."); 12996 } 12997 12998 final int callingUid = Binder.getCallingUid(); 12999 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13000 synchronized (mPackages) { 13001 if (mContext.checkCallingOrSelfPermission( 13002 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13003 != PackageManager.PERMISSION_GRANTED) { 13004 if (getUidTargetSdkVersionLockedLPr(callingUid) 13005 < Build.VERSION_CODES.FROYO) { 13006 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13007 + Binder.getCallingUid()); 13008 return; 13009 } 13010 mContext.enforceCallingOrSelfPermission( 13011 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13012 } 13013 13014 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13015 if (pir != null) { 13016 // Get all of the existing entries that exactly match this filter. 13017 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13018 if (existing != null && existing.size() == 1) { 13019 PreferredActivity cur = existing.get(0); 13020 if (DEBUG_PREFERRED) { 13021 Slog.i(TAG, "Checking replace of preferred:"); 13022 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13023 if (!cur.mPref.mAlways) { 13024 Slog.i(TAG, " -- CUR; not mAlways!"); 13025 } else { 13026 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13027 Slog.i(TAG, " -- CUR: mSet=" 13028 + Arrays.toString(cur.mPref.mSetComponents)); 13029 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13030 Slog.i(TAG, " -- NEW: mMatch=" 13031 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13032 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13033 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13034 } 13035 } 13036 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13037 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13038 && cur.mPref.sameSet(set)) { 13039 // Setting the preferred activity to what it happens to be already 13040 if (DEBUG_PREFERRED) { 13041 Slog.i(TAG, "Replacing with same preferred activity " 13042 + cur.mPref.mShortComponent + " for user " 13043 + userId + ":"); 13044 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13045 } 13046 return; 13047 } 13048 } 13049 13050 if (existing != null) { 13051 if (DEBUG_PREFERRED) { 13052 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13053 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13054 } 13055 for (int i = 0; i < existing.size(); i++) { 13056 PreferredActivity pa = existing.get(i); 13057 if (DEBUG_PREFERRED) { 13058 Slog.i(TAG, "Removing existing preferred activity " 13059 + pa.mPref.mComponent + ":"); 13060 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13061 } 13062 pir.removeFilter(pa); 13063 } 13064 } 13065 } 13066 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13067 "Replacing preferred"); 13068 } 13069 } 13070 13071 @Override 13072 public void clearPackagePreferredActivities(String packageName) { 13073 final int uid = Binder.getCallingUid(); 13074 // writer 13075 synchronized (mPackages) { 13076 PackageParser.Package pkg = mPackages.get(packageName); 13077 if (pkg == null || pkg.applicationInfo.uid != uid) { 13078 if (mContext.checkCallingOrSelfPermission( 13079 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13080 != PackageManager.PERMISSION_GRANTED) { 13081 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13082 < Build.VERSION_CODES.FROYO) { 13083 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13084 + Binder.getCallingUid()); 13085 return; 13086 } 13087 mContext.enforceCallingOrSelfPermission( 13088 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13089 } 13090 } 13091 13092 int user = UserHandle.getCallingUserId(); 13093 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13094 scheduleWritePackageRestrictionsLocked(user); 13095 } 13096 } 13097 } 13098 13099 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13100 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13101 ArrayList<PreferredActivity> removed = null; 13102 boolean changed = false; 13103 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13104 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13105 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13106 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13107 continue; 13108 } 13109 Iterator<PreferredActivity> it = pir.filterIterator(); 13110 while (it.hasNext()) { 13111 PreferredActivity pa = it.next(); 13112 // Mark entry for removal only if it matches the package name 13113 // and the entry is of type "always". 13114 if (packageName == null || 13115 (pa.mPref.mComponent.getPackageName().equals(packageName) 13116 && pa.mPref.mAlways)) { 13117 if (removed == null) { 13118 removed = new ArrayList<PreferredActivity>(); 13119 } 13120 removed.add(pa); 13121 } 13122 } 13123 if (removed != null) { 13124 for (int j=0; j<removed.size(); j++) { 13125 PreferredActivity pa = removed.get(j); 13126 pir.removeFilter(pa); 13127 } 13128 changed = true; 13129 } 13130 } 13131 return changed; 13132 } 13133 13134 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13135 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13136 if (userId == UserHandle.USER_ALL) { 13137 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13138 sUserManager.getUserIds())) { 13139 for (int oneUserId : sUserManager.getUserIds()) { 13140 scheduleWritePackageRestrictionsLocked(oneUserId); 13141 } 13142 } 13143 } else { 13144 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13145 scheduleWritePackageRestrictionsLocked(userId); 13146 } 13147 } 13148 } 13149 13150 13151 void clearDefaultBrowserIfNeeded(String packageName) { 13152 for (int oneUserId : sUserManager.getUserIds()) { 13153 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13154 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13155 if (packageName.equals(defaultBrowserPackageName)) { 13156 setDefaultBrowserPackageName(null, oneUserId); 13157 } 13158 } 13159 } 13160 13161 @Override 13162 public void resetPreferredActivities(int userId) { 13163 /* TODO: Actually use userId. Why is it being passed in? */ 13164 mContext.enforceCallingOrSelfPermission( 13165 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13166 // writer 13167 synchronized (mPackages) { 13168 int user = UserHandle.getCallingUserId(); 13169 clearPackagePreferredActivitiesLPw(null, user); 13170 mSettings.readDefaultPreferredAppsLPw(this, user); 13171 scheduleWritePackageRestrictionsLocked(user); 13172 } 13173 } 13174 13175 @Override 13176 public int getPreferredActivities(List<IntentFilter> outFilters, 13177 List<ComponentName> outActivities, String packageName) { 13178 13179 int num = 0; 13180 final int userId = UserHandle.getCallingUserId(); 13181 // reader 13182 synchronized (mPackages) { 13183 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13184 if (pir != null) { 13185 final Iterator<PreferredActivity> it = pir.filterIterator(); 13186 while (it.hasNext()) { 13187 final PreferredActivity pa = it.next(); 13188 if (packageName == null 13189 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13190 && pa.mPref.mAlways)) { 13191 if (outFilters != null) { 13192 outFilters.add(new IntentFilter(pa)); 13193 } 13194 if (outActivities != null) { 13195 outActivities.add(pa.mPref.mComponent); 13196 } 13197 } 13198 } 13199 } 13200 } 13201 13202 return num; 13203 } 13204 13205 @Override 13206 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13207 int userId) { 13208 int callingUid = Binder.getCallingUid(); 13209 if (callingUid != Process.SYSTEM_UID) { 13210 throw new SecurityException( 13211 "addPersistentPreferredActivity can only be run by the system"); 13212 } 13213 if (filter.countActions() == 0) { 13214 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13215 return; 13216 } 13217 synchronized (mPackages) { 13218 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13219 " :"); 13220 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13221 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13222 new PersistentPreferredActivity(filter, activity)); 13223 scheduleWritePackageRestrictionsLocked(userId); 13224 } 13225 } 13226 13227 @Override 13228 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13229 int callingUid = Binder.getCallingUid(); 13230 if (callingUid != Process.SYSTEM_UID) { 13231 throw new SecurityException( 13232 "clearPackagePersistentPreferredActivities can only be run by the system"); 13233 } 13234 ArrayList<PersistentPreferredActivity> removed = null; 13235 boolean changed = false; 13236 synchronized (mPackages) { 13237 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13238 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13239 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13240 .valueAt(i); 13241 if (userId != thisUserId) { 13242 continue; 13243 } 13244 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13245 while (it.hasNext()) { 13246 PersistentPreferredActivity ppa = it.next(); 13247 // Mark entry for removal only if it matches the package name. 13248 if (ppa.mComponent.getPackageName().equals(packageName)) { 13249 if (removed == null) { 13250 removed = new ArrayList<PersistentPreferredActivity>(); 13251 } 13252 removed.add(ppa); 13253 } 13254 } 13255 if (removed != null) { 13256 for (int j=0; j<removed.size(); j++) { 13257 PersistentPreferredActivity ppa = removed.get(j); 13258 ppir.removeFilter(ppa); 13259 } 13260 changed = true; 13261 } 13262 } 13263 13264 if (changed) { 13265 scheduleWritePackageRestrictionsLocked(userId); 13266 } 13267 } 13268 } 13269 13270 /** 13271 * Non-Binder method, support for the backup/restore mechanism: write the 13272 * full set of preferred activities in its canonical XML format. Returns true 13273 * on success; false otherwise. 13274 */ 13275 @Override 13276 public byte[] getPreferredActivityBackup(int userId) { 13277 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13278 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13279 } 13280 13281 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13282 try { 13283 final XmlSerializer serializer = new FastXmlSerializer(); 13284 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13285 serializer.startDocument(null, true); 13286 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13287 13288 synchronized (mPackages) { 13289 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13290 } 13291 13292 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13293 serializer.endDocument(); 13294 serializer.flush(); 13295 } catch (Exception e) { 13296 if (DEBUG_BACKUP) { 13297 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13298 } 13299 return null; 13300 } 13301 13302 return dataStream.toByteArray(); 13303 } 13304 13305 @Override 13306 public void restorePreferredActivities(byte[] backup, int userId) { 13307 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13308 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13309 } 13310 13311 try { 13312 final XmlPullParser parser = Xml.newPullParser(); 13313 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13314 13315 int type; 13316 while ((type = parser.next()) != XmlPullParser.START_TAG 13317 && type != XmlPullParser.END_DOCUMENT) { 13318 } 13319 if (type != XmlPullParser.START_TAG) { 13320 // oops didn't find a start tag?! 13321 if (DEBUG_BACKUP) { 13322 Slog.e(TAG, "Didn't find start tag during restore"); 13323 } 13324 return; 13325 } 13326 13327 // this is supposed to be TAG_PREFERRED_BACKUP 13328 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13329 if (DEBUG_BACKUP) { 13330 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13331 } 13332 return; 13333 } 13334 13335 // skip interfering stuff, then we're aligned with the backing implementation 13336 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13337 synchronized (mPackages) { 13338 mSettings.readPreferredActivitiesLPw(parser, userId); 13339 } 13340 } catch (Exception e) { 13341 if (DEBUG_BACKUP) { 13342 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13343 } 13344 } 13345 } 13346 13347 @Override 13348 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13349 int sourceUserId, int targetUserId, int flags) { 13350 mContext.enforceCallingOrSelfPermission( 13351 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13352 int callingUid = Binder.getCallingUid(); 13353 enforceOwnerRights(ownerPackage, callingUid); 13354 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13355 if (intentFilter.countActions() == 0) { 13356 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13357 return; 13358 } 13359 synchronized (mPackages) { 13360 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13361 ownerPackage, targetUserId, flags); 13362 CrossProfileIntentResolver resolver = 13363 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13364 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13365 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13366 if (existing != null) { 13367 int size = existing.size(); 13368 for (int i = 0; i < size; i++) { 13369 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13370 return; 13371 } 13372 } 13373 } 13374 resolver.addFilter(newFilter); 13375 scheduleWritePackageRestrictionsLocked(sourceUserId); 13376 } 13377 } 13378 13379 @Override 13380 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13381 mContext.enforceCallingOrSelfPermission( 13382 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13383 int callingUid = Binder.getCallingUid(); 13384 enforceOwnerRights(ownerPackage, callingUid); 13385 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13386 synchronized (mPackages) { 13387 CrossProfileIntentResolver resolver = 13388 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13389 ArraySet<CrossProfileIntentFilter> set = 13390 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13391 for (CrossProfileIntentFilter filter : set) { 13392 if (filter.getOwnerPackage().equals(ownerPackage)) { 13393 resolver.removeFilter(filter); 13394 } 13395 } 13396 scheduleWritePackageRestrictionsLocked(sourceUserId); 13397 } 13398 } 13399 13400 // Enforcing that callingUid is owning pkg on userId 13401 private void enforceOwnerRights(String pkg, int callingUid) { 13402 // The system owns everything. 13403 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13404 return; 13405 } 13406 int callingUserId = UserHandle.getUserId(callingUid); 13407 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13408 if (pi == null) { 13409 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13410 + callingUserId); 13411 } 13412 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13413 throw new SecurityException("Calling uid " + callingUid 13414 + " does not own package " + pkg); 13415 } 13416 } 13417 13418 @Override 13419 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13420 Intent intent = new Intent(Intent.ACTION_MAIN); 13421 intent.addCategory(Intent.CATEGORY_HOME); 13422 13423 final int callingUserId = UserHandle.getCallingUserId(); 13424 List<ResolveInfo> list = queryIntentActivities(intent, null, 13425 PackageManager.GET_META_DATA, callingUserId); 13426 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13427 true, false, false, callingUserId); 13428 13429 allHomeCandidates.clear(); 13430 if (list != null) { 13431 for (ResolveInfo ri : list) { 13432 allHomeCandidates.add(ri); 13433 } 13434 } 13435 return (preferred == null || preferred.activityInfo == null) 13436 ? null 13437 : new ComponentName(preferred.activityInfo.packageName, 13438 preferred.activityInfo.name); 13439 } 13440 13441 @Override 13442 public void setApplicationEnabledSetting(String appPackageName, 13443 int newState, int flags, int userId, String callingPackage) { 13444 if (!sUserManager.exists(userId)) return; 13445 if (callingPackage == null) { 13446 callingPackage = Integer.toString(Binder.getCallingUid()); 13447 } 13448 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13449 } 13450 13451 @Override 13452 public void setComponentEnabledSetting(ComponentName componentName, 13453 int newState, int flags, int userId) { 13454 if (!sUserManager.exists(userId)) return; 13455 setEnabledSetting(componentName.getPackageName(), 13456 componentName.getClassName(), newState, flags, userId, null); 13457 } 13458 13459 private void setEnabledSetting(final String packageName, String className, int newState, 13460 final int flags, int userId, String callingPackage) { 13461 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13462 || newState == COMPONENT_ENABLED_STATE_ENABLED 13463 || newState == COMPONENT_ENABLED_STATE_DISABLED 13464 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13465 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13466 throw new IllegalArgumentException("Invalid new component state: " 13467 + newState); 13468 } 13469 PackageSetting pkgSetting; 13470 final int uid = Binder.getCallingUid(); 13471 final int permission = mContext.checkCallingOrSelfPermission( 13472 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13473 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13474 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13475 boolean sendNow = false; 13476 boolean isApp = (className == null); 13477 String componentName = isApp ? packageName : className; 13478 int packageUid = -1; 13479 ArrayList<String> components; 13480 13481 // writer 13482 synchronized (mPackages) { 13483 pkgSetting = mSettings.mPackages.get(packageName); 13484 if (pkgSetting == null) { 13485 if (className == null) { 13486 throw new IllegalArgumentException( 13487 "Unknown package: " + packageName); 13488 } 13489 throw new IllegalArgumentException( 13490 "Unknown component: " + packageName 13491 + "/" + className); 13492 } 13493 // Allow root and verify that userId is not being specified by a different user 13494 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13495 throw new SecurityException( 13496 "Permission Denial: attempt to change component state from pid=" 13497 + Binder.getCallingPid() 13498 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13499 } 13500 if (className == null) { 13501 // We're dealing with an application/package level state change 13502 if (pkgSetting.getEnabled(userId) == newState) { 13503 // Nothing to do 13504 return; 13505 } 13506 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13507 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13508 // Don't care about who enables an app. 13509 callingPackage = null; 13510 } 13511 pkgSetting.setEnabled(newState, userId, callingPackage); 13512 // pkgSetting.pkg.mSetEnabled = newState; 13513 } else { 13514 // We're dealing with a component level state change 13515 // First, verify that this is a valid class name. 13516 PackageParser.Package pkg = pkgSetting.pkg; 13517 if (pkg == null || !pkg.hasComponentClassName(className)) { 13518 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13519 throw new IllegalArgumentException("Component class " + className 13520 + " does not exist in " + packageName); 13521 } else { 13522 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13523 + className + " does not exist in " + packageName); 13524 } 13525 } 13526 switch (newState) { 13527 case COMPONENT_ENABLED_STATE_ENABLED: 13528 if (!pkgSetting.enableComponentLPw(className, userId)) { 13529 return; 13530 } 13531 break; 13532 case COMPONENT_ENABLED_STATE_DISABLED: 13533 if (!pkgSetting.disableComponentLPw(className, userId)) { 13534 return; 13535 } 13536 break; 13537 case COMPONENT_ENABLED_STATE_DEFAULT: 13538 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13539 return; 13540 } 13541 break; 13542 default: 13543 Slog.e(TAG, "Invalid new component state: " + newState); 13544 return; 13545 } 13546 } 13547 scheduleWritePackageRestrictionsLocked(userId); 13548 components = mPendingBroadcasts.get(userId, packageName); 13549 final boolean newPackage = components == null; 13550 if (newPackage) { 13551 components = new ArrayList<String>(); 13552 } 13553 if (!components.contains(componentName)) { 13554 components.add(componentName); 13555 } 13556 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13557 sendNow = true; 13558 // Purge entry from pending broadcast list if another one exists already 13559 // since we are sending one right away. 13560 mPendingBroadcasts.remove(userId, packageName); 13561 } else { 13562 if (newPackage) { 13563 mPendingBroadcasts.put(userId, packageName, components); 13564 } 13565 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13566 // Schedule a message 13567 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13568 } 13569 } 13570 } 13571 13572 long callingId = Binder.clearCallingIdentity(); 13573 try { 13574 if (sendNow) { 13575 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13576 sendPackageChangedBroadcast(packageName, 13577 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13578 } 13579 } finally { 13580 Binder.restoreCallingIdentity(callingId); 13581 } 13582 } 13583 13584 private void sendPackageChangedBroadcast(String packageName, 13585 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13586 if (DEBUG_INSTALL) 13587 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13588 + componentNames); 13589 Bundle extras = new Bundle(4); 13590 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13591 String nameList[] = new String[componentNames.size()]; 13592 componentNames.toArray(nameList); 13593 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13594 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13595 extras.putInt(Intent.EXTRA_UID, packageUid); 13596 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13597 new int[] {UserHandle.getUserId(packageUid)}); 13598 } 13599 13600 @Override 13601 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13602 if (!sUserManager.exists(userId)) return; 13603 final int uid = Binder.getCallingUid(); 13604 final int permission = mContext.checkCallingOrSelfPermission( 13605 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13606 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13607 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13608 // writer 13609 synchronized (mPackages) { 13610 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13611 allowedByPermission, uid, userId)) { 13612 scheduleWritePackageRestrictionsLocked(userId); 13613 } 13614 } 13615 } 13616 13617 @Override 13618 public String getInstallerPackageName(String packageName) { 13619 // reader 13620 synchronized (mPackages) { 13621 return mSettings.getInstallerPackageNameLPr(packageName); 13622 } 13623 } 13624 13625 @Override 13626 public int getApplicationEnabledSetting(String packageName, int userId) { 13627 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13628 int uid = Binder.getCallingUid(); 13629 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13630 // reader 13631 synchronized (mPackages) { 13632 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13633 } 13634 } 13635 13636 @Override 13637 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13638 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13639 int uid = Binder.getCallingUid(); 13640 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13641 // reader 13642 synchronized (mPackages) { 13643 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13644 } 13645 } 13646 13647 @Override 13648 public void enterSafeMode() { 13649 enforceSystemOrRoot("Only the system can request entering safe mode"); 13650 13651 if (!mSystemReady) { 13652 mSafeMode = true; 13653 } 13654 } 13655 13656 @Override 13657 public void systemReady() { 13658 mSystemReady = true; 13659 13660 // Read the compatibilty setting when the system is ready. 13661 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13662 mContext.getContentResolver(), 13663 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13664 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13665 if (DEBUG_SETTINGS) { 13666 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13667 } 13668 13669 synchronized (mPackages) { 13670 // Verify that all of the preferred activity components actually 13671 // exist. It is possible for applications to be updated and at 13672 // that point remove a previously declared activity component that 13673 // had been set as a preferred activity. We try to clean this up 13674 // the next time we encounter that preferred activity, but it is 13675 // possible for the user flow to never be able to return to that 13676 // situation so here we do a sanity check to make sure we haven't 13677 // left any junk around. 13678 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13679 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13680 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13681 removed.clear(); 13682 for (PreferredActivity pa : pir.filterSet()) { 13683 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13684 removed.add(pa); 13685 } 13686 } 13687 if (removed.size() > 0) { 13688 for (int r=0; r<removed.size(); r++) { 13689 PreferredActivity pa = removed.get(r); 13690 Slog.w(TAG, "Removing dangling preferred activity: " 13691 + pa.mPref.mComponent); 13692 pir.removeFilter(pa); 13693 } 13694 mSettings.writePackageRestrictionsLPr( 13695 mSettings.mPreferredActivities.keyAt(i)); 13696 } 13697 } 13698 } 13699 sUserManager.systemReady(); 13700 13701 // If we upgraded grant all default permissions before kicking off. 13702 if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) { 13703 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 13704 for (int userId : UserManagerService.getInstance().getUserIds()) { 13705 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13706 } 13707 } 13708 13709 // Kick off any messages waiting for system ready 13710 if (mPostSystemReadyMessages != null) { 13711 for (Message msg : mPostSystemReadyMessages) { 13712 msg.sendToTarget(); 13713 } 13714 mPostSystemReadyMessages = null; 13715 } 13716 13717 // Watch for external volumes that come and go over time 13718 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13719 storage.registerListener(mStorageListener); 13720 13721 mInstallerService.systemReady(); 13722 mPackageDexOptimizer.systemReady(); 13723 } 13724 13725 @Override 13726 public boolean isSafeMode() { 13727 return mSafeMode; 13728 } 13729 13730 @Override 13731 public boolean hasSystemUidErrors() { 13732 return mHasSystemUidErrors; 13733 } 13734 13735 static String arrayToString(int[] array) { 13736 StringBuffer buf = new StringBuffer(128); 13737 buf.append('['); 13738 if (array != null) { 13739 for (int i=0; i<array.length; i++) { 13740 if (i > 0) buf.append(", "); 13741 buf.append(array[i]); 13742 } 13743 } 13744 buf.append(']'); 13745 return buf.toString(); 13746 } 13747 13748 static class DumpState { 13749 public static final int DUMP_LIBS = 1 << 0; 13750 public static final int DUMP_FEATURES = 1 << 1; 13751 public static final int DUMP_RESOLVERS = 1 << 2; 13752 public static final int DUMP_PERMISSIONS = 1 << 3; 13753 public static final int DUMP_PACKAGES = 1 << 4; 13754 public static final int DUMP_SHARED_USERS = 1 << 5; 13755 public static final int DUMP_MESSAGES = 1 << 6; 13756 public static final int DUMP_PROVIDERS = 1 << 7; 13757 public static final int DUMP_VERIFIERS = 1 << 8; 13758 public static final int DUMP_PREFERRED = 1 << 9; 13759 public static final int DUMP_PREFERRED_XML = 1 << 10; 13760 public static final int DUMP_KEYSETS = 1 << 11; 13761 public static final int DUMP_VERSION = 1 << 12; 13762 public static final int DUMP_INSTALLS = 1 << 13; 13763 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13764 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13765 13766 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13767 13768 private int mTypes; 13769 13770 private int mOptions; 13771 13772 private boolean mTitlePrinted; 13773 13774 private SharedUserSetting mSharedUser; 13775 13776 public boolean isDumping(int type) { 13777 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13778 return true; 13779 } 13780 13781 return (mTypes & type) != 0; 13782 } 13783 13784 public void setDump(int type) { 13785 mTypes |= type; 13786 } 13787 13788 public boolean isOptionEnabled(int option) { 13789 return (mOptions & option) != 0; 13790 } 13791 13792 public void setOptionEnabled(int option) { 13793 mOptions |= option; 13794 } 13795 13796 public boolean onTitlePrinted() { 13797 final boolean printed = mTitlePrinted; 13798 mTitlePrinted = true; 13799 return printed; 13800 } 13801 13802 public boolean getTitlePrinted() { 13803 return mTitlePrinted; 13804 } 13805 13806 public void setTitlePrinted(boolean enabled) { 13807 mTitlePrinted = enabled; 13808 } 13809 13810 public SharedUserSetting getSharedUser() { 13811 return mSharedUser; 13812 } 13813 13814 public void setSharedUser(SharedUserSetting user) { 13815 mSharedUser = user; 13816 } 13817 } 13818 13819 @Override 13820 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13821 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13822 != PackageManager.PERMISSION_GRANTED) { 13823 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13824 + Binder.getCallingPid() 13825 + ", uid=" + Binder.getCallingUid() 13826 + " without permission " 13827 + android.Manifest.permission.DUMP); 13828 return; 13829 } 13830 13831 DumpState dumpState = new DumpState(); 13832 boolean fullPreferred = false; 13833 boolean checkin = false; 13834 13835 String packageName = null; 13836 13837 int opti = 0; 13838 while (opti < args.length) { 13839 String opt = args[opti]; 13840 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13841 break; 13842 } 13843 opti++; 13844 13845 if ("-a".equals(opt)) { 13846 // Right now we only know how to print all. 13847 } else if ("-h".equals(opt)) { 13848 pw.println("Package manager dump options:"); 13849 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13850 pw.println(" --checkin: dump for a checkin"); 13851 pw.println(" -f: print details of intent filters"); 13852 pw.println(" -h: print this help"); 13853 pw.println(" cmd may be one of:"); 13854 pw.println(" l[ibraries]: list known shared libraries"); 13855 pw.println(" f[ibraries]: list device features"); 13856 pw.println(" k[eysets]: print known keysets"); 13857 pw.println(" r[esolvers]: dump intent resolvers"); 13858 pw.println(" perm[issions]: dump permissions"); 13859 pw.println(" pref[erred]: print preferred package settings"); 13860 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13861 pw.println(" prov[iders]: dump content providers"); 13862 pw.println(" p[ackages]: dump installed packages"); 13863 pw.println(" s[hared-users]: dump shared user IDs"); 13864 pw.println(" m[essages]: print collected runtime messages"); 13865 pw.println(" v[erifiers]: print package verifier info"); 13866 pw.println(" version: print database version info"); 13867 pw.println(" write: write current settings now"); 13868 pw.println(" <package.name>: info about given package"); 13869 pw.println(" installs: details about install sessions"); 13870 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13871 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13872 return; 13873 } else if ("--checkin".equals(opt)) { 13874 checkin = true; 13875 } else if ("-f".equals(opt)) { 13876 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13877 } else { 13878 pw.println("Unknown argument: " + opt + "; use -h for help"); 13879 } 13880 } 13881 13882 // Is the caller requesting to dump a particular piece of data? 13883 if (opti < args.length) { 13884 String cmd = args[opti]; 13885 opti++; 13886 // Is this a package name? 13887 if ("android".equals(cmd) || cmd.contains(".")) { 13888 packageName = cmd; 13889 // When dumping a single package, we always dump all of its 13890 // filter information since the amount of data will be reasonable. 13891 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13892 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13893 dumpState.setDump(DumpState.DUMP_LIBS); 13894 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13895 dumpState.setDump(DumpState.DUMP_FEATURES); 13896 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13897 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13898 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13899 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13900 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13901 dumpState.setDump(DumpState.DUMP_PREFERRED); 13902 } else if ("preferred-xml".equals(cmd)) { 13903 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13904 if (opti < args.length && "--full".equals(args[opti])) { 13905 fullPreferred = true; 13906 opti++; 13907 } 13908 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13909 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13910 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13911 dumpState.setDump(DumpState.DUMP_PACKAGES); 13912 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13913 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13914 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13915 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13916 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13917 dumpState.setDump(DumpState.DUMP_MESSAGES); 13918 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13919 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13920 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13921 || "intent-filter-verifiers".equals(cmd)) { 13922 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13923 } else if ("version".equals(cmd)) { 13924 dumpState.setDump(DumpState.DUMP_VERSION); 13925 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13926 dumpState.setDump(DumpState.DUMP_KEYSETS); 13927 } else if ("installs".equals(cmd)) { 13928 dumpState.setDump(DumpState.DUMP_INSTALLS); 13929 } else if ("write".equals(cmd)) { 13930 synchronized (mPackages) { 13931 mSettings.writeLPr(); 13932 pw.println("Settings written."); 13933 return; 13934 } 13935 } 13936 } 13937 13938 if (checkin) { 13939 pw.println("vers,1"); 13940 } 13941 13942 // reader 13943 synchronized (mPackages) { 13944 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13945 if (!checkin) { 13946 if (dumpState.onTitlePrinted()) 13947 pw.println(); 13948 pw.println("Database versions:"); 13949 pw.print(" SDK Version:"); 13950 pw.print(" internal="); 13951 pw.print(mSettings.mInternalSdkPlatform); 13952 pw.print(" external="); 13953 pw.println(mSettings.mExternalSdkPlatform); 13954 pw.print(" DB Version:"); 13955 pw.print(" internal="); 13956 pw.print(mSettings.mInternalDatabaseVersion); 13957 pw.print(" external="); 13958 pw.println(mSettings.mExternalDatabaseVersion); 13959 } 13960 } 13961 13962 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13963 if (!checkin) { 13964 if (dumpState.onTitlePrinted()) 13965 pw.println(); 13966 pw.println("Verifiers:"); 13967 pw.print(" Required: "); 13968 pw.print(mRequiredVerifierPackage); 13969 pw.print(" (uid="); 13970 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13971 pw.println(")"); 13972 } else if (mRequiredVerifierPackage != null) { 13973 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13974 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13975 } 13976 } 13977 13978 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13979 packageName == null) { 13980 if (mIntentFilterVerifierComponent != null) { 13981 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13982 if (!checkin) { 13983 if (dumpState.onTitlePrinted()) 13984 pw.println(); 13985 pw.println("Intent Filter Verifier:"); 13986 pw.print(" Using: "); 13987 pw.print(verifierPackageName); 13988 pw.print(" (uid="); 13989 pw.print(getPackageUid(verifierPackageName, 0)); 13990 pw.println(")"); 13991 } else if (verifierPackageName != null) { 13992 pw.print("ifv,"); pw.print(verifierPackageName); 13993 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13994 } 13995 } else { 13996 pw.println(); 13997 pw.println("No Intent Filter Verifier available!"); 13998 } 13999 } 14000 14001 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14002 boolean printedHeader = false; 14003 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14004 while (it.hasNext()) { 14005 String name = it.next(); 14006 SharedLibraryEntry ent = mSharedLibraries.get(name); 14007 if (!checkin) { 14008 if (!printedHeader) { 14009 if (dumpState.onTitlePrinted()) 14010 pw.println(); 14011 pw.println("Libraries:"); 14012 printedHeader = true; 14013 } 14014 pw.print(" "); 14015 } else { 14016 pw.print("lib,"); 14017 } 14018 pw.print(name); 14019 if (!checkin) { 14020 pw.print(" -> "); 14021 } 14022 if (ent.path != null) { 14023 if (!checkin) { 14024 pw.print("(jar) "); 14025 pw.print(ent.path); 14026 } else { 14027 pw.print(",jar,"); 14028 pw.print(ent.path); 14029 } 14030 } else { 14031 if (!checkin) { 14032 pw.print("(apk) "); 14033 pw.print(ent.apk); 14034 } else { 14035 pw.print(",apk,"); 14036 pw.print(ent.apk); 14037 } 14038 } 14039 pw.println(); 14040 } 14041 } 14042 14043 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14044 if (dumpState.onTitlePrinted()) 14045 pw.println(); 14046 if (!checkin) { 14047 pw.println("Features:"); 14048 } 14049 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14050 while (it.hasNext()) { 14051 String name = it.next(); 14052 if (!checkin) { 14053 pw.print(" "); 14054 } else { 14055 pw.print("feat,"); 14056 } 14057 pw.println(name); 14058 } 14059 } 14060 14061 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14062 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14063 : "Activity Resolver Table:", " ", packageName, 14064 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14065 dumpState.setTitlePrinted(true); 14066 } 14067 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14068 : "Receiver Resolver Table:", " ", packageName, 14069 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14070 dumpState.setTitlePrinted(true); 14071 } 14072 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14073 : "Service Resolver Table:", " ", packageName, 14074 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14075 dumpState.setTitlePrinted(true); 14076 } 14077 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14078 : "Provider Resolver Table:", " ", packageName, 14079 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14080 dumpState.setTitlePrinted(true); 14081 } 14082 } 14083 14084 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14085 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14086 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14087 int user = mSettings.mPreferredActivities.keyAt(i); 14088 if (pir.dump(pw, 14089 dumpState.getTitlePrinted() 14090 ? "\nPreferred Activities User " + user + ":" 14091 : "Preferred Activities User " + user + ":", " ", 14092 packageName, true, false)) { 14093 dumpState.setTitlePrinted(true); 14094 } 14095 } 14096 } 14097 14098 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14099 pw.flush(); 14100 FileOutputStream fout = new FileOutputStream(fd); 14101 BufferedOutputStream str = new BufferedOutputStream(fout); 14102 XmlSerializer serializer = new FastXmlSerializer(); 14103 try { 14104 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14105 serializer.startDocument(null, true); 14106 serializer.setFeature( 14107 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14108 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14109 serializer.endDocument(); 14110 serializer.flush(); 14111 } catch (IllegalArgumentException e) { 14112 pw.println("Failed writing: " + e); 14113 } catch (IllegalStateException e) { 14114 pw.println("Failed writing: " + e); 14115 } catch (IOException e) { 14116 pw.println("Failed writing: " + e); 14117 } 14118 } 14119 14120 if (!checkin 14121 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14122 && packageName == null) { 14123 pw.println(); 14124 int count = mSettings.mPackages.size(); 14125 if (count == 0) { 14126 pw.println("No domain preferred apps!"); 14127 pw.println(); 14128 } else { 14129 final String prefix = " "; 14130 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14131 if (allPackageSettings.size() == 0) { 14132 pw.println("No domain preferred apps!"); 14133 pw.println(); 14134 } else { 14135 pw.println("Domain preferred apps status:"); 14136 pw.println(); 14137 count = 0; 14138 for (PackageSetting ps : allPackageSettings) { 14139 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14140 if (ivi == null || ivi.getPackageName() == null) continue; 14141 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14142 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14143 pw.println(prefix + "Status: " + ivi.getStatusString()); 14144 pw.println(); 14145 count++; 14146 } 14147 if (count == 0) { 14148 pw.println(prefix + "No domain preferred app status!"); 14149 pw.println(); 14150 } 14151 for (int userId : sUserManager.getUserIds()) { 14152 pw.println("Domain preferred apps for User " + userId + ":"); 14153 pw.println(); 14154 count = 0; 14155 for (PackageSetting ps : allPackageSettings) { 14156 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14157 if (ivi == null || ivi.getPackageName() == null) { 14158 continue; 14159 } 14160 final int status = ps.getDomainVerificationStatusForUser(userId); 14161 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14162 continue; 14163 } 14164 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14165 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14166 String statusStr = IntentFilterVerificationInfo. 14167 getStatusStringFromValue(status); 14168 pw.println(prefix + "Status: " + statusStr); 14169 pw.println(); 14170 count++; 14171 } 14172 if (count == 0) { 14173 pw.println(prefix + "No domain preferred apps!"); 14174 pw.println(); 14175 } 14176 } 14177 } 14178 } 14179 } 14180 14181 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14182 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14183 if (packageName == null) { 14184 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14185 if (iperm == 0) { 14186 if (dumpState.onTitlePrinted()) 14187 pw.println(); 14188 pw.println("AppOp Permissions:"); 14189 } 14190 pw.print(" AppOp Permission "); 14191 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14192 pw.println(":"); 14193 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14194 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14195 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14196 } 14197 } 14198 } 14199 } 14200 14201 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14202 boolean printedSomething = false; 14203 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14204 if (packageName != null && !packageName.equals(p.info.packageName)) { 14205 continue; 14206 } 14207 if (!printedSomething) { 14208 if (dumpState.onTitlePrinted()) 14209 pw.println(); 14210 pw.println("Registered ContentProviders:"); 14211 printedSomething = true; 14212 } 14213 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14214 pw.print(" "); pw.println(p.toString()); 14215 } 14216 printedSomething = false; 14217 for (Map.Entry<String, PackageParser.Provider> entry : 14218 mProvidersByAuthority.entrySet()) { 14219 PackageParser.Provider p = entry.getValue(); 14220 if (packageName != null && !packageName.equals(p.info.packageName)) { 14221 continue; 14222 } 14223 if (!printedSomething) { 14224 if (dumpState.onTitlePrinted()) 14225 pw.println(); 14226 pw.println("ContentProvider Authorities:"); 14227 printedSomething = true; 14228 } 14229 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14230 pw.print(" "); pw.println(p.toString()); 14231 if (p.info != null && p.info.applicationInfo != null) { 14232 final String appInfo = p.info.applicationInfo.toString(); 14233 pw.print(" applicationInfo="); pw.println(appInfo); 14234 } 14235 } 14236 } 14237 14238 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14239 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14240 } 14241 14242 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14243 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14244 } 14245 14246 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14247 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14248 } 14249 14250 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14251 // XXX should handle packageName != null by dumping only install data that 14252 // the given package is involved with. 14253 if (dumpState.onTitlePrinted()) pw.println(); 14254 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14255 } 14256 14257 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14258 if (dumpState.onTitlePrinted()) pw.println(); 14259 mSettings.dumpReadMessagesLPr(pw, dumpState); 14260 14261 pw.println(); 14262 pw.println("Package warning messages:"); 14263 BufferedReader in = null; 14264 String line = null; 14265 try { 14266 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14267 while ((line = in.readLine()) != null) { 14268 if (line.contains("ignored: updated version")) continue; 14269 pw.println(line); 14270 } 14271 } catch (IOException ignored) { 14272 } finally { 14273 IoUtils.closeQuietly(in); 14274 } 14275 } 14276 14277 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14278 BufferedReader in = null; 14279 String line = null; 14280 try { 14281 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14282 while ((line = in.readLine()) != null) { 14283 if (line.contains("ignored: updated version")) continue; 14284 pw.print("msg,"); 14285 pw.println(line); 14286 } 14287 } catch (IOException ignored) { 14288 } finally { 14289 IoUtils.closeQuietly(in); 14290 } 14291 } 14292 } 14293 } 14294 14295 // ------- apps on sdcard specific code ------- 14296 static final boolean DEBUG_SD_INSTALL = false; 14297 14298 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14299 14300 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14301 14302 private boolean mMediaMounted = false; 14303 14304 static String getEncryptKey() { 14305 try { 14306 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14307 SD_ENCRYPTION_KEYSTORE_NAME); 14308 if (sdEncKey == null) { 14309 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14310 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14311 if (sdEncKey == null) { 14312 Slog.e(TAG, "Failed to create encryption keys"); 14313 return null; 14314 } 14315 } 14316 return sdEncKey; 14317 } catch (NoSuchAlgorithmException nsae) { 14318 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14319 return null; 14320 } catch (IOException ioe) { 14321 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14322 return null; 14323 } 14324 } 14325 14326 /* 14327 * Update media status on PackageManager. 14328 */ 14329 @Override 14330 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14331 int callingUid = Binder.getCallingUid(); 14332 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14333 throw new SecurityException("Media status can only be updated by the system"); 14334 } 14335 // reader; this apparently protects mMediaMounted, but should probably 14336 // be a different lock in that case. 14337 synchronized (mPackages) { 14338 Log.i(TAG, "Updating external media status from " 14339 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14340 + (mediaStatus ? "mounted" : "unmounted")); 14341 if (DEBUG_SD_INSTALL) 14342 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14343 + ", mMediaMounted=" + mMediaMounted); 14344 if (mediaStatus == mMediaMounted) { 14345 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14346 : 0, -1); 14347 mHandler.sendMessage(msg); 14348 return; 14349 } 14350 mMediaMounted = mediaStatus; 14351 } 14352 // Queue up an async operation since the package installation may take a 14353 // little while. 14354 mHandler.post(new Runnable() { 14355 public void run() { 14356 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14357 } 14358 }); 14359 } 14360 14361 /** 14362 * Called by MountService when the initial ASECs to scan are available. 14363 * Should block until all the ASEC containers are finished being scanned. 14364 */ 14365 public void scanAvailableAsecs() { 14366 updateExternalMediaStatusInner(true, false, false); 14367 if (mShouldRestoreconData) { 14368 SELinuxMMAC.setRestoreconDone(); 14369 mShouldRestoreconData = false; 14370 } 14371 } 14372 14373 /* 14374 * Collect information of applications on external media, map them against 14375 * existing containers and update information based on current mount status. 14376 * Please note that we always have to report status if reportStatus has been 14377 * set to true especially when unloading packages. 14378 */ 14379 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14380 boolean externalStorage) { 14381 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14382 int[] uidArr = EmptyArray.INT; 14383 14384 final String[] list = PackageHelper.getSecureContainerList(); 14385 if (ArrayUtils.isEmpty(list)) { 14386 Log.i(TAG, "No secure containers found"); 14387 } else { 14388 // Process list of secure containers and categorize them 14389 // as active or stale based on their package internal state. 14390 14391 // reader 14392 synchronized (mPackages) { 14393 for (String cid : list) { 14394 // Leave stages untouched for now; installer service owns them 14395 if (PackageInstallerService.isStageName(cid)) continue; 14396 14397 if (DEBUG_SD_INSTALL) 14398 Log.i(TAG, "Processing container " + cid); 14399 String pkgName = getAsecPackageName(cid); 14400 if (pkgName == null) { 14401 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14402 continue; 14403 } 14404 if (DEBUG_SD_INSTALL) 14405 Log.i(TAG, "Looking for pkg : " + pkgName); 14406 14407 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14408 if (ps == null) { 14409 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14410 continue; 14411 } 14412 14413 /* 14414 * Skip packages that are not external if we're unmounting 14415 * external storage. 14416 */ 14417 if (externalStorage && !isMounted && !isExternal(ps)) { 14418 continue; 14419 } 14420 14421 final AsecInstallArgs args = new AsecInstallArgs(cid, 14422 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14423 // The package status is changed only if the code path 14424 // matches between settings and the container id. 14425 if (ps.codePathString != null 14426 && ps.codePathString.startsWith(args.getCodePath())) { 14427 if (DEBUG_SD_INSTALL) { 14428 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14429 + " at code path: " + ps.codePathString); 14430 } 14431 14432 // We do have a valid package installed on sdcard 14433 processCids.put(args, ps.codePathString); 14434 final int uid = ps.appId; 14435 if (uid != -1) { 14436 uidArr = ArrayUtils.appendInt(uidArr, uid); 14437 } 14438 } else { 14439 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14440 + ps.codePathString); 14441 } 14442 } 14443 } 14444 14445 Arrays.sort(uidArr); 14446 } 14447 14448 // Process packages with valid entries. 14449 if (isMounted) { 14450 if (DEBUG_SD_INSTALL) 14451 Log.i(TAG, "Loading packages"); 14452 loadMediaPackages(processCids, uidArr); 14453 startCleaningPackages(); 14454 mInstallerService.onSecureContainersAvailable(); 14455 } else { 14456 if (DEBUG_SD_INSTALL) 14457 Log.i(TAG, "Unloading packages"); 14458 unloadMediaPackages(processCids, uidArr, reportStatus); 14459 } 14460 } 14461 14462 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14463 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14464 final int size = infos.size(); 14465 final String[] packageNames = new String[size]; 14466 final int[] packageUids = new int[size]; 14467 for (int i = 0; i < size; i++) { 14468 final ApplicationInfo info = infos.get(i); 14469 packageNames[i] = info.packageName; 14470 packageUids[i] = info.uid; 14471 } 14472 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14473 finishedReceiver); 14474 } 14475 14476 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14477 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14478 sendResourcesChangedBroadcast(mediaStatus, replacing, 14479 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14480 } 14481 14482 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14483 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14484 int size = pkgList.length; 14485 if (size > 0) { 14486 // Send broadcasts here 14487 Bundle extras = new Bundle(); 14488 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14489 if (uidArr != null) { 14490 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14491 } 14492 if (replacing) { 14493 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14494 } 14495 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14496 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14497 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14498 } 14499 } 14500 14501 /* 14502 * Look at potentially valid container ids from processCids If package 14503 * information doesn't match the one on record or package scanning fails, 14504 * the cid is added to list of removeCids. We currently don't delete stale 14505 * containers. 14506 */ 14507 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14508 ArrayList<String> pkgList = new ArrayList<String>(); 14509 Set<AsecInstallArgs> keys = processCids.keySet(); 14510 14511 for (AsecInstallArgs args : keys) { 14512 String codePath = processCids.get(args); 14513 if (DEBUG_SD_INSTALL) 14514 Log.i(TAG, "Loading container : " + args.cid); 14515 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14516 try { 14517 // Make sure there are no container errors first. 14518 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14519 Slog.e(TAG, "Failed to mount cid : " + args.cid 14520 + " when installing from sdcard"); 14521 continue; 14522 } 14523 // Check code path here. 14524 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14525 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14526 + " does not match one in settings " + codePath); 14527 continue; 14528 } 14529 // Parse package 14530 int parseFlags = mDefParseFlags; 14531 if (args.isExternalAsec()) { 14532 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14533 } 14534 if (args.isFwdLocked()) { 14535 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14536 } 14537 14538 synchronized (mInstallLock) { 14539 PackageParser.Package pkg = null; 14540 try { 14541 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14542 } catch (PackageManagerException e) { 14543 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14544 } 14545 // Scan the package 14546 if (pkg != null) { 14547 /* 14548 * TODO why is the lock being held? doPostInstall is 14549 * called in other places without the lock. This needs 14550 * to be straightened out. 14551 */ 14552 // writer 14553 synchronized (mPackages) { 14554 retCode = PackageManager.INSTALL_SUCCEEDED; 14555 pkgList.add(pkg.packageName); 14556 // Post process args 14557 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14558 pkg.applicationInfo.uid); 14559 } 14560 } else { 14561 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14562 } 14563 } 14564 14565 } finally { 14566 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14567 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14568 } 14569 } 14570 } 14571 // writer 14572 synchronized (mPackages) { 14573 // If the platform SDK has changed since the last time we booted, 14574 // we need to re-grant app permission to catch any new ones that 14575 // appear. This is really a hack, and means that apps can in some 14576 // cases get permissions that the user didn't initially explicitly 14577 // allow... it would be nice to have some better way to handle 14578 // this situation. 14579 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14580 if (regrantPermissions) 14581 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14582 + mSdkVersion + "; regranting permissions for external storage"); 14583 mSettings.mExternalSdkPlatform = mSdkVersion; 14584 14585 // Make sure group IDs have been assigned, and any permission 14586 // changes in other apps are accounted for 14587 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14588 | (regrantPermissions 14589 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14590 : 0)); 14591 14592 mSettings.updateExternalDatabaseVersion(); 14593 14594 // can downgrade to reader 14595 // Persist settings 14596 mSettings.writeLPr(); 14597 } 14598 // Send a broadcast to let everyone know we are done processing 14599 if (pkgList.size() > 0) { 14600 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14601 } 14602 } 14603 14604 /* 14605 * Utility method to unload a list of specified containers 14606 */ 14607 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14608 // Just unmount all valid containers. 14609 for (AsecInstallArgs arg : cidArgs) { 14610 synchronized (mInstallLock) { 14611 arg.doPostDeleteLI(false); 14612 } 14613 } 14614 } 14615 14616 /* 14617 * Unload packages mounted on external media. This involves deleting package 14618 * data from internal structures, sending broadcasts about diabled packages, 14619 * gc'ing to free up references, unmounting all secure containers 14620 * corresponding to packages on external media, and posting a 14621 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14622 * that we always have to post this message if status has been requested no 14623 * matter what. 14624 */ 14625 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14626 final boolean reportStatus) { 14627 if (DEBUG_SD_INSTALL) 14628 Log.i(TAG, "unloading media packages"); 14629 ArrayList<String> pkgList = new ArrayList<String>(); 14630 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14631 final Set<AsecInstallArgs> keys = processCids.keySet(); 14632 for (AsecInstallArgs args : keys) { 14633 String pkgName = args.getPackageName(); 14634 if (DEBUG_SD_INSTALL) 14635 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14636 // Delete package internally 14637 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14638 synchronized (mInstallLock) { 14639 boolean res = deletePackageLI(pkgName, null, false, null, null, 14640 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14641 if (res) { 14642 pkgList.add(pkgName); 14643 } else { 14644 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14645 failedList.add(args); 14646 } 14647 } 14648 } 14649 14650 // reader 14651 synchronized (mPackages) { 14652 // We didn't update the settings after removing each package; 14653 // write them now for all packages. 14654 mSettings.writeLPr(); 14655 } 14656 14657 // We have to absolutely send UPDATED_MEDIA_STATUS only 14658 // after confirming that all the receivers processed the ordered 14659 // broadcast when packages get disabled, force a gc to clean things up. 14660 // and unload all the containers. 14661 if (pkgList.size() > 0) { 14662 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14663 new IIntentReceiver.Stub() { 14664 public void performReceive(Intent intent, int resultCode, String data, 14665 Bundle extras, boolean ordered, boolean sticky, 14666 int sendingUser) throws RemoteException { 14667 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14668 reportStatus ? 1 : 0, 1, keys); 14669 mHandler.sendMessage(msg); 14670 } 14671 }); 14672 } else { 14673 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14674 keys); 14675 mHandler.sendMessage(msg); 14676 } 14677 } 14678 14679 private void loadPrivatePackages(VolumeInfo vol) { 14680 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14681 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14682 synchronized (mInstallLock) { 14683 synchronized (mPackages) { 14684 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14685 for (PackageSetting ps : packages) { 14686 final PackageParser.Package pkg; 14687 try { 14688 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14689 loaded.add(pkg.applicationInfo); 14690 } catch (PackageManagerException e) { 14691 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14692 } 14693 } 14694 14695 // TODO: regrant any permissions that changed based since original install 14696 14697 mSettings.writeLPr(); 14698 } 14699 } 14700 14701 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14702 sendResourcesChangedBroadcast(true, false, loaded, null); 14703 } 14704 14705 private void unloadPrivatePackages(VolumeInfo vol) { 14706 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14707 synchronized (mInstallLock) { 14708 synchronized (mPackages) { 14709 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14710 for (PackageSetting ps : packages) { 14711 if (ps.pkg == null) continue; 14712 14713 final ApplicationInfo info = ps.pkg.applicationInfo; 14714 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14715 if (deletePackageLI(ps.name, null, false, null, null, 14716 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14717 unloaded.add(info); 14718 } else { 14719 Slog.w(TAG, "Failed to unload " + ps.codePath); 14720 } 14721 } 14722 14723 mSettings.writeLPr(); 14724 } 14725 } 14726 14727 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14728 sendResourcesChangedBroadcast(false, false, unloaded, null); 14729 } 14730 14731 private void unfreezePackage(String packageName) { 14732 synchronized (mPackages) { 14733 final PackageSetting ps = mSettings.mPackages.get(packageName); 14734 if (ps != null) { 14735 ps.frozen = false; 14736 } 14737 } 14738 } 14739 14740 @Override 14741 public int movePackage(final String packageName, final String volumeUuid) { 14742 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14743 14744 final int moveId = mNextMoveId.getAndIncrement(); 14745 try { 14746 movePackageInternal(packageName, volumeUuid, moveId); 14747 } catch (PackageManagerException e) { 14748 Slog.w(TAG, "Failed to move " + packageName, e); 14749 mMoveCallbacks.notifyStatusChanged(moveId, 14750 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14751 } 14752 return moveId; 14753 } 14754 14755 private void movePackageInternal(final String packageName, final String volumeUuid, 14756 final int moveId) throws PackageManagerException { 14757 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14758 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14759 final PackageManager pm = mContext.getPackageManager(); 14760 14761 final boolean currentAsec; 14762 final String currentVolumeUuid; 14763 final File codeFile; 14764 final String installerPackageName; 14765 final String packageAbiOverride; 14766 final int appId; 14767 final String seinfo; 14768 final String label; 14769 14770 // reader 14771 synchronized (mPackages) { 14772 final PackageParser.Package pkg = mPackages.get(packageName); 14773 final PackageSetting ps = mSettings.mPackages.get(packageName); 14774 if (pkg == null || ps == null) { 14775 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14776 } 14777 14778 if (pkg.applicationInfo.isSystemApp()) { 14779 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14780 "Cannot move system application"); 14781 } 14782 14783 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14784 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14785 "Package already moved to " + volumeUuid); 14786 } 14787 14788 final File probe = new File(pkg.codePath); 14789 final File probeOat = new File(probe, "oat"); 14790 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14791 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14792 "Move only supported for modern cluster style installs"); 14793 } 14794 14795 if (ps.frozen) { 14796 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14797 "Failed to move already frozen package"); 14798 } 14799 ps.frozen = true; 14800 14801 currentAsec = pkg.applicationInfo.isForwardLocked() 14802 || pkg.applicationInfo.isExternalAsec(); 14803 currentVolumeUuid = ps.volumeUuid; 14804 codeFile = new File(pkg.codePath); 14805 installerPackageName = ps.installerPackageName; 14806 packageAbiOverride = ps.cpuAbiOverrideString; 14807 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14808 seinfo = pkg.applicationInfo.seinfo; 14809 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14810 } 14811 14812 // Now that we're guarded by frozen state, kill app during move 14813 killApplication(packageName, appId, "move pkg"); 14814 14815 final Bundle extras = new Bundle(); 14816 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14817 extras.putString(Intent.EXTRA_TITLE, label); 14818 mMoveCallbacks.notifyCreated(moveId, extras); 14819 14820 int installFlags; 14821 final boolean moveCompleteApp; 14822 final File measurePath; 14823 14824 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14825 installFlags = INSTALL_INTERNAL; 14826 moveCompleteApp = !currentAsec; 14827 measurePath = Environment.getDataAppDirectory(volumeUuid); 14828 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14829 installFlags = INSTALL_EXTERNAL; 14830 moveCompleteApp = false; 14831 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14832 } else { 14833 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14834 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14835 || !volume.isMountedWritable()) { 14836 unfreezePackage(packageName); 14837 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14838 "Move location not mounted private volume"); 14839 } 14840 14841 Preconditions.checkState(!currentAsec); 14842 14843 installFlags = INSTALL_INTERNAL; 14844 moveCompleteApp = true; 14845 measurePath = Environment.getDataAppDirectory(volumeUuid); 14846 } 14847 14848 final PackageStats stats = new PackageStats(null, -1); 14849 synchronized (mInstaller) { 14850 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14851 unfreezePackage(packageName); 14852 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14853 "Failed to measure package size"); 14854 } 14855 } 14856 14857 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14858 + stats.dataSize); 14859 14860 final long startFreeBytes = measurePath.getFreeSpace(); 14861 final long sizeBytes; 14862 if (moveCompleteApp) { 14863 sizeBytes = stats.codeSize + stats.dataSize; 14864 } else { 14865 sizeBytes = stats.codeSize; 14866 } 14867 14868 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14869 unfreezePackage(packageName); 14870 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14871 "Not enough free space to move"); 14872 } 14873 14874 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14875 14876 final CountDownLatch installedLatch = new CountDownLatch(1); 14877 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14878 @Override 14879 public void onUserActionRequired(Intent intent) throws RemoteException { 14880 throw new IllegalStateException(); 14881 } 14882 14883 @Override 14884 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14885 Bundle extras) throws RemoteException { 14886 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14887 + PackageManager.installStatusToString(returnCode, msg)); 14888 14889 installedLatch.countDown(); 14890 14891 // Regardless of success or failure of the move operation, 14892 // always unfreeze the package 14893 unfreezePackage(packageName); 14894 14895 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14896 switch (status) { 14897 case PackageInstaller.STATUS_SUCCESS: 14898 mMoveCallbacks.notifyStatusChanged(moveId, 14899 PackageManager.MOVE_SUCCEEDED); 14900 break; 14901 case PackageInstaller.STATUS_FAILURE_STORAGE: 14902 mMoveCallbacks.notifyStatusChanged(moveId, 14903 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14904 break; 14905 default: 14906 mMoveCallbacks.notifyStatusChanged(moveId, 14907 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14908 break; 14909 } 14910 } 14911 }; 14912 14913 final MoveInfo move; 14914 if (moveCompleteApp) { 14915 // Kick off a thread to report progress estimates 14916 new Thread() { 14917 @Override 14918 public void run() { 14919 while (true) { 14920 try { 14921 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14922 break; 14923 } 14924 } catch (InterruptedException ignored) { 14925 } 14926 14927 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14928 final int progress = 10 + (int) MathUtils.constrain( 14929 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14930 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14931 } 14932 } 14933 }.start(); 14934 14935 final String dataAppName = codeFile.getName(); 14936 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14937 dataAppName, appId, seinfo); 14938 } else { 14939 move = null; 14940 } 14941 14942 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14943 14944 final Message msg = mHandler.obtainMessage(INIT_COPY); 14945 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14946 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14947 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14948 mHandler.sendMessage(msg); 14949 } 14950 14951 @Override 14952 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14953 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14954 14955 final int realMoveId = mNextMoveId.getAndIncrement(); 14956 final Bundle extras = new Bundle(); 14957 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14958 mMoveCallbacks.notifyCreated(realMoveId, extras); 14959 14960 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14961 @Override 14962 public void onCreated(int moveId, Bundle extras) { 14963 // Ignored 14964 } 14965 14966 @Override 14967 public void onStatusChanged(int moveId, int status, long estMillis) { 14968 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14969 } 14970 }; 14971 14972 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14973 storage.setPrimaryStorageUuid(volumeUuid, callback); 14974 return realMoveId; 14975 } 14976 14977 @Override 14978 public int getMoveStatus(int moveId) { 14979 mContext.enforceCallingOrSelfPermission( 14980 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14981 return mMoveCallbacks.mLastStatus.get(moveId); 14982 } 14983 14984 @Override 14985 public void registerMoveCallback(IPackageMoveObserver callback) { 14986 mContext.enforceCallingOrSelfPermission( 14987 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14988 mMoveCallbacks.register(callback); 14989 } 14990 14991 @Override 14992 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14993 mContext.enforceCallingOrSelfPermission( 14994 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14995 mMoveCallbacks.unregister(callback); 14996 } 14997 14998 @Override 14999 public boolean setInstallLocation(int loc) { 15000 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15001 null); 15002 if (getInstallLocation() == loc) { 15003 return true; 15004 } 15005 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15006 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15007 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15008 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15009 return true; 15010 } 15011 return false; 15012 } 15013 15014 @Override 15015 public int getInstallLocation() { 15016 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15017 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15018 PackageHelper.APP_INSTALL_AUTO); 15019 } 15020 15021 /** Called by UserManagerService */ 15022 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15023 mDirtyUsers.remove(userHandle); 15024 mSettings.removeUserLPw(userHandle); 15025 mPendingBroadcasts.remove(userHandle); 15026 if (mInstaller != null) { 15027 // Technically, we shouldn't be doing this with the package lock 15028 // held. However, this is very rare, and there is already so much 15029 // other disk I/O going on, that we'll let it slide for now. 15030 final StorageManager storage = StorageManager.from(mContext); 15031 final List<VolumeInfo> vols = storage.getVolumes(); 15032 for (VolumeInfo vol : vols) { 15033 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15034 final String volumeUuid = vol.getFsUuid(); 15035 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15036 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15037 } 15038 } 15039 } 15040 mUserNeedsBadging.delete(userHandle); 15041 removeUnusedPackagesLILPw(userManager, userHandle); 15042 } 15043 15044 /** 15045 * We're removing userHandle and would like to remove any downloaded packages 15046 * that are no longer in use by any other user. 15047 * @param userHandle the user being removed 15048 */ 15049 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15050 final boolean DEBUG_CLEAN_APKS = false; 15051 int [] users = userManager.getUserIdsLPr(); 15052 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15053 while (psit.hasNext()) { 15054 PackageSetting ps = psit.next(); 15055 if (ps.pkg == null) { 15056 continue; 15057 } 15058 final String packageName = ps.pkg.packageName; 15059 // Skip over if system app 15060 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15061 continue; 15062 } 15063 if (DEBUG_CLEAN_APKS) { 15064 Slog.i(TAG, "Checking package " + packageName); 15065 } 15066 boolean keep = false; 15067 for (int i = 0; i < users.length; i++) { 15068 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15069 keep = true; 15070 if (DEBUG_CLEAN_APKS) { 15071 Slog.i(TAG, " Keeping package " + packageName + " for user " 15072 + users[i]); 15073 } 15074 break; 15075 } 15076 } 15077 if (!keep) { 15078 if (DEBUG_CLEAN_APKS) { 15079 Slog.i(TAG, " Removing package " + packageName); 15080 } 15081 mHandler.post(new Runnable() { 15082 public void run() { 15083 deletePackageX(packageName, userHandle, 0); 15084 } //end run 15085 }); 15086 } 15087 } 15088 } 15089 15090 /** Called by UserManagerService */ 15091 void createNewUserLILPw(int userHandle, File path) { 15092 if (mInstaller != null) { 15093 mInstaller.createUserConfig(userHandle); 15094 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15095 } 15096 } 15097 15098 void newUserCreatedLILPw(final int userHandle) { 15099 // We cannot grant the default permissions with a lock held as 15100 // we query providers from other components for default handlers 15101 // such as enabled IMEs, etc. 15102 mHandler.post(new Runnable() { 15103 @Override 15104 public void run() { 15105 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15106 } 15107 }); 15108 } 15109 15110 @Override 15111 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15112 mContext.enforceCallingOrSelfPermission( 15113 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15114 "Only package verification agents can read the verifier device identity"); 15115 15116 synchronized (mPackages) { 15117 return mSettings.getVerifierDeviceIdentityLPw(); 15118 } 15119 } 15120 15121 @Override 15122 public void setPermissionEnforced(String permission, boolean enforced) { 15123 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15124 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15125 synchronized (mPackages) { 15126 if (mSettings.mReadExternalStorageEnforced == null 15127 || mSettings.mReadExternalStorageEnforced != enforced) { 15128 mSettings.mReadExternalStorageEnforced = enforced; 15129 mSettings.writeLPr(); 15130 } 15131 } 15132 // kill any non-foreground processes so we restart them and 15133 // grant/revoke the GID. 15134 final IActivityManager am = ActivityManagerNative.getDefault(); 15135 if (am != null) { 15136 final long token = Binder.clearCallingIdentity(); 15137 try { 15138 am.killProcessesBelowForeground("setPermissionEnforcement"); 15139 } catch (RemoteException e) { 15140 } finally { 15141 Binder.restoreCallingIdentity(token); 15142 } 15143 } 15144 } else { 15145 throw new IllegalArgumentException("No selective enforcement for " + permission); 15146 } 15147 } 15148 15149 @Override 15150 @Deprecated 15151 public boolean isPermissionEnforced(String permission) { 15152 return true; 15153 } 15154 15155 @Override 15156 public boolean isStorageLow() { 15157 final long token = Binder.clearCallingIdentity(); 15158 try { 15159 final DeviceStorageMonitorInternal 15160 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15161 if (dsm != null) { 15162 return dsm.isMemoryLow(); 15163 } else { 15164 return false; 15165 } 15166 } finally { 15167 Binder.restoreCallingIdentity(token); 15168 } 15169 } 15170 15171 @Override 15172 public IPackageInstaller getPackageInstaller() { 15173 return mInstallerService; 15174 } 15175 15176 private boolean userNeedsBadging(int userId) { 15177 int index = mUserNeedsBadging.indexOfKey(userId); 15178 if (index < 0) { 15179 final UserInfo userInfo; 15180 final long token = Binder.clearCallingIdentity(); 15181 try { 15182 userInfo = sUserManager.getUserInfo(userId); 15183 } finally { 15184 Binder.restoreCallingIdentity(token); 15185 } 15186 final boolean b; 15187 if (userInfo != null && userInfo.isManagedProfile()) { 15188 b = true; 15189 } else { 15190 b = false; 15191 } 15192 mUserNeedsBadging.put(userId, b); 15193 return b; 15194 } 15195 return mUserNeedsBadging.valueAt(index); 15196 } 15197 15198 @Override 15199 public KeySet getKeySetByAlias(String packageName, String alias) { 15200 if (packageName == null || alias == null) { 15201 return null; 15202 } 15203 synchronized(mPackages) { 15204 final PackageParser.Package pkg = mPackages.get(packageName); 15205 if (pkg == null) { 15206 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15207 throw new IllegalArgumentException("Unknown package: " + packageName); 15208 } 15209 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15210 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15211 } 15212 } 15213 15214 @Override 15215 public KeySet getSigningKeySet(String packageName) { 15216 if (packageName == null) { 15217 return null; 15218 } 15219 synchronized(mPackages) { 15220 final PackageParser.Package pkg = mPackages.get(packageName); 15221 if (pkg == null) { 15222 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15223 throw new IllegalArgumentException("Unknown package: " + packageName); 15224 } 15225 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15226 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15227 throw new SecurityException("May not access signing KeySet of other apps."); 15228 } 15229 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15230 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15231 } 15232 } 15233 15234 @Override 15235 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15236 if (packageName == null || ks == null) { 15237 return false; 15238 } 15239 synchronized(mPackages) { 15240 final PackageParser.Package pkg = mPackages.get(packageName); 15241 if (pkg == null) { 15242 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15243 throw new IllegalArgumentException("Unknown package: " + packageName); 15244 } 15245 IBinder ksh = ks.getToken(); 15246 if (ksh instanceof KeySetHandle) { 15247 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15248 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15249 } 15250 return false; 15251 } 15252 } 15253 15254 @Override 15255 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15256 if (packageName == null || ks == null) { 15257 return false; 15258 } 15259 synchronized(mPackages) { 15260 final PackageParser.Package pkg = mPackages.get(packageName); 15261 if (pkg == null) { 15262 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15263 throw new IllegalArgumentException("Unknown package: " + packageName); 15264 } 15265 IBinder ksh = ks.getToken(); 15266 if (ksh instanceof KeySetHandle) { 15267 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15268 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15269 } 15270 return false; 15271 } 15272 } 15273 15274 public void getUsageStatsIfNoPackageUsageInfo() { 15275 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15276 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15277 if (usm == null) { 15278 throw new IllegalStateException("UsageStatsManager must be initialized"); 15279 } 15280 long now = System.currentTimeMillis(); 15281 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15282 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15283 String packageName = entry.getKey(); 15284 PackageParser.Package pkg = mPackages.get(packageName); 15285 if (pkg == null) { 15286 continue; 15287 } 15288 UsageStats usage = entry.getValue(); 15289 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15290 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15291 } 15292 } 15293 } 15294 15295 /** 15296 * Check and throw if the given before/after packages would be considered a 15297 * downgrade. 15298 */ 15299 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15300 throws PackageManagerException { 15301 if (after.versionCode < before.mVersionCode) { 15302 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15303 "Update version code " + after.versionCode + " is older than current " 15304 + before.mVersionCode); 15305 } else if (after.versionCode == before.mVersionCode) { 15306 if (after.baseRevisionCode < before.baseRevisionCode) { 15307 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15308 "Update base revision code " + after.baseRevisionCode 15309 + " is older than current " + before.baseRevisionCode); 15310 } 15311 15312 if (!ArrayUtils.isEmpty(after.splitNames)) { 15313 for (int i = 0; i < after.splitNames.length; i++) { 15314 final String splitName = after.splitNames[i]; 15315 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15316 if (j != -1) { 15317 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15318 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15319 "Update split " + splitName + " revision code " 15320 + after.splitRevisionCodes[i] + " is older than current " 15321 + before.splitRevisionCodes[j]); 15322 } 15323 } 15324 } 15325 } 15326 } 15327 } 15328 15329 private static class MoveCallbacks extends Handler { 15330 private static final int MSG_CREATED = 1; 15331 private static final int MSG_STATUS_CHANGED = 2; 15332 15333 private final RemoteCallbackList<IPackageMoveObserver> 15334 mCallbacks = new RemoteCallbackList<>(); 15335 15336 private final SparseIntArray mLastStatus = new SparseIntArray(); 15337 15338 public MoveCallbacks(Looper looper) { 15339 super(looper); 15340 } 15341 15342 public void register(IPackageMoveObserver callback) { 15343 mCallbacks.register(callback); 15344 } 15345 15346 public void unregister(IPackageMoveObserver callback) { 15347 mCallbacks.unregister(callback); 15348 } 15349 15350 @Override 15351 public void handleMessage(Message msg) { 15352 final SomeArgs args = (SomeArgs) msg.obj; 15353 final int n = mCallbacks.beginBroadcast(); 15354 for (int i = 0; i < n; i++) { 15355 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15356 try { 15357 invokeCallback(callback, msg.what, args); 15358 } catch (RemoteException ignored) { 15359 } 15360 } 15361 mCallbacks.finishBroadcast(); 15362 args.recycle(); 15363 } 15364 15365 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15366 throws RemoteException { 15367 switch (what) { 15368 case MSG_CREATED: { 15369 callback.onCreated(args.argi1, (Bundle) args.arg2); 15370 break; 15371 } 15372 case MSG_STATUS_CHANGED: { 15373 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15374 break; 15375 } 15376 } 15377 } 15378 15379 private void notifyCreated(int moveId, Bundle extras) { 15380 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15381 15382 final SomeArgs args = SomeArgs.obtain(); 15383 args.argi1 = moveId; 15384 args.arg2 = extras; 15385 obtainMessage(MSG_CREATED, args).sendToTarget(); 15386 } 15387 15388 private void notifyStatusChanged(int moveId, int status) { 15389 notifyStatusChanged(moveId, status, -1); 15390 } 15391 15392 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15393 Slog.v(TAG, "Move " + moveId + " status " + status); 15394 15395 final SomeArgs args = SomeArgs.obtain(); 15396 args.argi1 = moveId; 15397 args.argi2 = status; 15398 args.arg3 = estMillis; 15399 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15400 15401 synchronized (mLastStatus) { 15402 mLastStatus.put(moveId, status); 15403 } 15404 } 15405 } 15406 15407 private final class OnPermissionChangeListeners extends Handler { 15408 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15409 15410 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15411 new RemoteCallbackList<>(); 15412 15413 public OnPermissionChangeListeners(Looper looper) { 15414 super(looper); 15415 } 15416 15417 @Override 15418 public void handleMessage(Message msg) { 15419 switch (msg.what) { 15420 case MSG_ON_PERMISSIONS_CHANGED: { 15421 final int uid = msg.arg1; 15422 handleOnPermissionsChanged(uid); 15423 } break; 15424 } 15425 } 15426 15427 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15428 mPermissionListeners.register(listener); 15429 15430 } 15431 15432 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15433 mPermissionListeners.unregister(listener); 15434 } 15435 15436 public void onPermissionsChanged(int uid) { 15437 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15438 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15439 } 15440 } 15441 15442 private void handleOnPermissionsChanged(int uid) { 15443 final int count = mPermissionListeners.beginBroadcast(); 15444 try { 15445 for (int i = 0; i < count; i++) { 15446 IOnPermissionsChangeListener callback = mPermissionListeners 15447 .getBroadcastItem(i); 15448 try { 15449 callback.onPermissionsChanged(uid); 15450 } catch (RemoteException e) { 15451 Log.e(TAG, "Permission listener is dead", e); 15452 } 15453 } 15454 } finally { 15455 mPermissionListeners.finishBroadcast(); 15456 } 15457 } 15458 } 15459 15460 private class PackageManagerInternalImpl extends PackageManagerInternal { 15461 @Override 15462 public void setLocationPackagesProvider(PackagesProvider provider) { 15463 synchronized (mPackages) { 15464 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15465 } 15466 } 15467 15468 @Override 15469 public void setImePackagesProvider(PackagesProvider provider) { 15470 synchronized (mPackages) { 15471 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15472 } 15473 } 15474 15475 @Override 15476 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15477 synchronized (mPackages) { 15478 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15479 } 15480 } 15481 } 15482} 15483