PackageManagerService.java revision 0f800f7c163383ce3a49cc99bc2d8097f8961bde
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 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 888 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 889 890 // backup/restore of preferred activity state 891 private static final String TAG_PREFERRED_BACKUP = "pa"; 892 893 private final String mRequiredVerifierPackage; 894 895 private final PackageUsage mPackageUsage = new PackageUsage(); 896 897 private class PackageUsage { 898 private static final int WRITE_INTERVAL 899 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 900 901 private final Object mFileLock = new Object(); 902 private final AtomicLong mLastWritten = new AtomicLong(0); 903 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 904 905 private boolean mIsHistoricalPackageUsageAvailable = true; 906 907 boolean isHistoricalPackageUsageAvailable() { 908 return mIsHistoricalPackageUsageAvailable; 909 } 910 911 void write(boolean force) { 912 if (force) { 913 writeInternal(); 914 return; 915 } 916 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 917 && !DEBUG_DEXOPT) { 918 return; 919 } 920 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 921 new Thread("PackageUsage_DiskWriter") { 922 @Override 923 public void run() { 924 try { 925 writeInternal(); 926 } finally { 927 mBackgroundWriteRunning.set(false); 928 } 929 } 930 }.start(); 931 } 932 } 933 934 private void writeInternal() { 935 synchronized (mPackages) { 936 synchronized (mFileLock) { 937 AtomicFile file = getFile(); 938 FileOutputStream f = null; 939 try { 940 f = file.startWrite(); 941 BufferedOutputStream out = new BufferedOutputStream(f); 942 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 943 StringBuilder sb = new StringBuilder(); 944 for (PackageParser.Package pkg : mPackages.values()) { 945 if (pkg.mLastPackageUsageTimeInMills == 0) { 946 continue; 947 } 948 sb.setLength(0); 949 sb.append(pkg.packageName); 950 sb.append(' '); 951 sb.append((long)pkg.mLastPackageUsageTimeInMills); 952 sb.append('\n'); 953 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 954 } 955 out.flush(); 956 file.finishWrite(f); 957 } catch (IOException e) { 958 if (f != null) { 959 file.failWrite(f); 960 } 961 Log.e(TAG, "Failed to write package usage times", e); 962 } 963 } 964 } 965 mLastWritten.set(SystemClock.elapsedRealtime()); 966 } 967 968 void readLP() { 969 synchronized (mFileLock) { 970 AtomicFile file = getFile(); 971 BufferedInputStream in = null; 972 try { 973 in = new BufferedInputStream(file.openRead()); 974 StringBuffer sb = new StringBuffer(); 975 while (true) { 976 String packageName = readToken(in, sb, ' '); 977 if (packageName == null) { 978 break; 979 } 980 String timeInMillisString = readToken(in, sb, '\n'); 981 if (timeInMillisString == null) { 982 throw new IOException("Failed to find last usage time for package " 983 + packageName); 984 } 985 PackageParser.Package pkg = mPackages.get(packageName); 986 if (pkg == null) { 987 continue; 988 } 989 long timeInMillis; 990 try { 991 timeInMillis = Long.parseLong(timeInMillisString.toString()); 992 } catch (NumberFormatException e) { 993 throw new IOException("Failed to parse " + timeInMillisString 994 + " as a long.", e); 995 } 996 pkg.mLastPackageUsageTimeInMills = timeInMillis; 997 } 998 } catch (FileNotFoundException expected) { 999 mIsHistoricalPackageUsageAvailable = false; 1000 } catch (IOException e) { 1001 Log.w(TAG, "Failed to read package usage times", e); 1002 } finally { 1003 IoUtils.closeQuietly(in); 1004 } 1005 } 1006 mLastWritten.set(SystemClock.elapsedRealtime()); 1007 } 1008 1009 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1010 throws IOException { 1011 sb.setLength(0); 1012 while (true) { 1013 int ch = in.read(); 1014 if (ch == -1) { 1015 if (sb.length() == 0) { 1016 return null; 1017 } 1018 throw new IOException("Unexpected EOF"); 1019 } 1020 if (ch == endOfToken) { 1021 return sb.toString(); 1022 } 1023 sb.append((char)ch); 1024 } 1025 } 1026 1027 private AtomicFile getFile() { 1028 File dataDir = Environment.getDataDirectory(); 1029 File systemDir = new File(dataDir, "system"); 1030 File fname = new File(systemDir, "package-usage.list"); 1031 return new AtomicFile(fname); 1032 } 1033 } 1034 1035 class PackageHandler extends Handler { 1036 private boolean mBound = false; 1037 final ArrayList<HandlerParams> mPendingInstalls = 1038 new ArrayList<HandlerParams>(); 1039 1040 private boolean connectToService() { 1041 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1042 " DefaultContainerService"); 1043 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1044 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1045 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1046 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1047 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1048 mBound = true; 1049 return true; 1050 } 1051 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1052 return false; 1053 } 1054 1055 private void disconnectService() { 1056 mContainerService = null; 1057 mBound = false; 1058 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1059 mContext.unbindService(mDefContainerConn); 1060 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1061 } 1062 1063 PackageHandler(Looper looper) { 1064 super(looper); 1065 } 1066 1067 public void handleMessage(Message msg) { 1068 try { 1069 doHandleMessage(msg); 1070 } finally { 1071 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1072 } 1073 } 1074 1075 void doHandleMessage(Message msg) { 1076 switch (msg.what) { 1077 case INIT_COPY: { 1078 HandlerParams params = (HandlerParams) msg.obj; 1079 int idx = mPendingInstalls.size(); 1080 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1081 // If a bind was already initiated we dont really 1082 // need to do anything. The pending install 1083 // will be processed later on. 1084 if (!mBound) { 1085 // If this is the only one pending we might 1086 // have to bind to the service again. 1087 if (!connectToService()) { 1088 Slog.e(TAG, "Failed to bind to media container service"); 1089 params.serviceError(); 1090 return; 1091 } else { 1092 // Once we bind to the service, the first 1093 // pending request will be processed. 1094 mPendingInstalls.add(idx, params); 1095 } 1096 } else { 1097 mPendingInstalls.add(idx, params); 1098 // Already bound to the service. Just make 1099 // sure we trigger off processing the first request. 1100 if (idx == 0) { 1101 mHandler.sendEmptyMessage(MCS_BOUND); 1102 } 1103 } 1104 break; 1105 } 1106 case MCS_BOUND: { 1107 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1108 if (msg.obj != null) { 1109 mContainerService = (IMediaContainerService) msg.obj; 1110 } 1111 if (mContainerService == null) { 1112 // Something seriously wrong. Bail out 1113 Slog.e(TAG, "Cannot bind to media container service"); 1114 for (HandlerParams params : mPendingInstalls) { 1115 // Indicate service bind error 1116 params.serviceError(); 1117 } 1118 mPendingInstalls.clear(); 1119 } else if (mPendingInstalls.size() > 0) { 1120 HandlerParams params = mPendingInstalls.get(0); 1121 if (params != null) { 1122 if (params.startCopy()) { 1123 // We are done... look for more work or to 1124 // go idle. 1125 if (DEBUG_SD_INSTALL) Log.i(TAG, 1126 "Checking for more work or unbind..."); 1127 // Delete pending install 1128 if (mPendingInstalls.size() > 0) { 1129 mPendingInstalls.remove(0); 1130 } 1131 if (mPendingInstalls.size() == 0) { 1132 if (mBound) { 1133 if (DEBUG_SD_INSTALL) Log.i(TAG, 1134 "Posting delayed MCS_UNBIND"); 1135 removeMessages(MCS_UNBIND); 1136 Message ubmsg = obtainMessage(MCS_UNBIND); 1137 // Unbind after a little delay, to avoid 1138 // continual thrashing. 1139 sendMessageDelayed(ubmsg, 10000); 1140 } 1141 } else { 1142 // There are more pending requests in queue. 1143 // Just post MCS_BOUND message to trigger processing 1144 // of next pending install. 1145 if (DEBUG_SD_INSTALL) Log.i(TAG, 1146 "Posting MCS_BOUND for next work"); 1147 mHandler.sendEmptyMessage(MCS_BOUND); 1148 } 1149 } 1150 } 1151 } else { 1152 // Should never happen ideally. 1153 Slog.w(TAG, "Empty queue"); 1154 } 1155 break; 1156 } 1157 case MCS_RECONNECT: { 1158 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1159 if (mPendingInstalls.size() > 0) { 1160 if (mBound) { 1161 disconnectService(); 1162 } 1163 if (!connectToService()) { 1164 Slog.e(TAG, "Failed to bind to media container service"); 1165 for (HandlerParams params : mPendingInstalls) { 1166 // Indicate service bind error 1167 params.serviceError(); 1168 } 1169 mPendingInstalls.clear(); 1170 } 1171 } 1172 break; 1173 } 1174 case MCS_UNBIND: { 1175 // If there is no actual work left, then time to unbind. 1176 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1177 1178 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1179 if (mBound) { 1180 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1181 1182 disconnectService(); 1183 } 1184 } else if (mPendingInstalls.size() > 0) { 1185 // There are more pending requests in queue. 1186 // Just post MCS_BOUND message to trigger processing 1187 // of next pending install. 1188 mHandler.sendEmptyMessage(MCS_BOUND); 1189 } 1190 1191 break; 1192 } 1193 case MCS_GIVE_UP: { 1194 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1195 mPendingInstalls.remove(0); 1196 break; 1197 } 1198 case SEND_PENDING_BROADCAST: { 1199 String packages[]; 1200 ArrayList<String> components[]; 1201 int size = 0; 1202 int uids[]; 1203 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1204 synchronized (mPackages) { 1205 if (mPendingBroadcasts == null) { 1206 return; 1207 } 1208 size = mPendingBroadcasts.size(); 1209 if (size <= 0) { 1210 // Nothing to be done. Just return 1211 return; 1212 } 1213 packages = new String[size]; 1214 components = new ArrayList[size]; 1215 uids = new int[size]; 1216 int i = 0; // filling out the above arrays 1217 1218 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1219 int packageUserId = mPendingBroadcasts.userIdAt(n); 1220 Iterator<Map.Entry<String, ArrayList<String>>> it 1221 = mPendingBroadcasts.packagesForUserId(packageUserId) 1222 .entrySet().iterator(); 1223 while (it.hasNext() && i < size) { 1224 Map.Entry<String, ArrayList<String>> ent = it.next(); 1225 packages[i] = ent.getKey(); 1226 components[i] = ent.getValue(); 1227 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1228 uids[i] = (ps != null) 1229 ? UserHandle.getUid(packageUserId, ps.appId) 1230 : -1; 1231 i++; 1232 } 1233 } 1234 size = i; 1235 mPendingBroadcasts.clear(); 1236 } 1237 // Send broadcasts 1238 for (int i = 0; i < size; i++) { 1239 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1240 } 1241 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1242 break; 1243 } 1244 case START_CLEANING_PACKAGE: { 1245 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1246 final String packageName = (String)msg.obj; 1247 final int userId = msg.arg1; 1248 final boolean andCode = msg.arg2 != 0; 1249 synchronized (mPackages) { 1250 if (userId == UserHandle.USER_ALL) { 1251 int[] users = sUserManager.getUserIds(); 1252 for (int user : users) { 1253 mSettings.addPackageToCleanLPw( 1254 new PackageCleanItem(user, packageName, andCode)); 1255 } 1256 } else { 1257 mSettings.addPackageToCleanLPw( 1258 new PackageCleanItem(userId, packageName, andCode)); 1259 } 1260 } 1261 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1262 startCleaningPackages(); 1263 } break; 1264 case POST_INSTALL: { 1265 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1266 PostInstallData data = mRunningInstalls.get(msg.arg1); 1267 mRunningInstalls.delete(msg.arg1); 1268 boolean deleteOld = false; 1269 1270 if (data != null) { 1271 InstallArgs args = data.args; 1272 PackageInstalledInfo res = data.res; 1273 1274 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1275 res.removedInfo.sendBroadcast(false, true, false); 1276 Bundle extras = new Bundle(1); 1277 extras.putInt(Intent.EXTRA_UID, res.uid); 1278 1279 // Now that we successfully installed the package, grant runtime 1280 // permissions if requested before broadcasting the install. 1281 if ((args.installFlags 1282 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1283 grantRequestedRuntimePermissions(res.pkg, 1284 args.user.getIdentifier()); 1285 } 1286 1287 // Determine the set of users who are adding this 1288 // package for the first time vs. those who are seeing 1289 // an update. 1290 int[] firstUsers; 1291 int[] updateUsers = new int[0]; 1292 if (res.origUsers == null || res.origUsers.length == 0) { 1293 firstUsers = res.newUsers; 1294 } else { 1295 firstUsers = new int[0]; 1296 for (int i=0; i<res.newUsers.length; i++) { 1297 int user = res.newUsers[i]; 1298 boolean isNew = true; 1299 for (int j=0; j<res.origUsers.length; j++) { 1300 if (res.origUsers[j] == user) { 1301 isNew = false; 1302 break; 1303 } 1304 } 1305 if (isNew) { 1306 int[] newFirst = new int[firstUsers.length+1]; 1307 System.arraycopy(firstUsers, 0, newFirst, 0, 1308 firstUsers.length); 1309 newFirst[firstUsers.length] = user; 1310 firstUsers = newFirst; 1311 } else { 1312 int[] newUpdate = new int[updateUsers.length+1]; 1313 System.arraycopy(updateUsers, 0, newUpdate, 0, 1314 updateUsers.length); 1315 newUpdate[updateUsers.length] = user; 1316 updateUsers = newUpdate; 1317 } 1318 } 1319 } 1320 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1321 res.pkg.applicationInfo.packageName, 1322 extras, null, null, firstUsers); 1323 final boolean update = res.removedInfo.removedPackage != null; 1324 if (update) { 1325 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1326 } 1327 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1328 res.pkg.applicationInfo.packageName, 1329 extras, null, null, updateUsers); 1330 if (update) { 1331 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1332 res.pkg.applicationInfo.packageName, 1333 extras, null, null, updateUsers); 1334 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1335 null, null, 1336 res.pkg.applicationInfo.packageName, null, updateUsers); 1337 1338 // treat asec-hosted packages like removable media on upgrade 1339 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1340 if (DEBUG_INSTALL) { 1341 Slog.i(TAG, "upgrading pkg " + res.pkg 1342 + " is ASEC-hosted -> AVAILABLE"); 1343 } 1344 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1345 ArrayList<String> pkgList = new ArrayList<String>(1); 1346 pkgList.add(res.pkg.applicationInfo.packageName); 1347 sendResourcesChangedBroadcast(true, true, 1348 pkgList,uidArray, null); 1349 } 1350 } 1351 if (res.removedInfo.args != null) { 1352 // Remove the replaced package's older resources safely now 1353 deleteOld = true; 1354 } 1355 1356 // Log current value of "unknown sources" setting 1357 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1358 getUnknownSourcesSettings()); 1359 } 1360 // Force a gc to clear up things 1361 Runtime.getRuntime().gc(); 1362 // We delete after a gc for applications on sdcard. 1363 if (deleteOld) { 1364 synchronized (mInstallLock) { 1365 res.removedInfo.args.doPostDeleteLI(true); 1366 } 1367 } 1368 if (args.observer != null) { 1369 try { 1370 Bundle extras = extrasForInstallResult(res); 1371 args.observer.onPackageInstalled(res.name, res.returnCode, 1372 res.returnMsg, extras); 1373 } catch (RemoteException e) { 1374 Slog.i(TAG, "Observer no longer exists."); 1375 } 1376 } 1377 } else { 1378 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1379 } 1380 } break; 1381 case UPDATED_MEDIA_STATUS: { 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1383 boolean reportStatus = msg.arg1 == 1; 1384 boolean doGc = msg.arg2 == 1; 1385 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1386 if (doGc) { 1387 // Force a gc to clear up stale containers. 1388 Runtime.getRuntime().gc(); 1389 } 1390 if (msg.obj != null) { 1391 @SuppressWarnings("unchecked") 1392 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1393 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1394 // Unload containers 1395 unloadAllContainers(args); 1396 } 1397 if (reportStatus) { 1398 try { 1399 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1400 PackageHelper.getMountService().finishMediaUpdate(); 1401 } catch (RemoteException e) { 1402 Log.e(TAG, "MountService not running?"); 1403 } 1404 } 1405 } break; 1406 case WRITE_SETTINGS: { 1407 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1408 synchronized (mPackages) { 1409 removeMessages(WRITE_SETTINGS); 1410 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1411 mSettings.writeLPr(); 1412 mDirtyUsers.clear(); 1413 } 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1415 } break; 1416 case WRITE_PACKAGE_RESTRICTIONS: { 1417 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1418 synchronized (mPackages) { 1419 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1420 for (int userId : mDirtyUsers) { 1421 mSettings.writePackageRestrictionsLPr(userId); 1422 } 1423 mDirtyUsers.clear(); 1424 } 1425 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1426 } break; 1427 case CHECK_PENDING_VERIFICATION: { 1428 final int verificationId = msg.arg1; 1429 final PackageVerificationState state = mPendingVerification.get(verificationId); 1430 1431 if ((state != null) && !state.timeoutExtended()) { 1432 final InstallArgs args = state.getInstallArgs(); 1433 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1434 1435 Slog.i(TAG, "Verification timed out for " + originUri); 1436 mPendingVerification.remove(verificationId); 1437 1438 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1439 1440 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1441 Slog.i(TAG, "Continuing with installation of " + originUri); 1442 state.setVerifierResponse(Binder.getCallingUid(), 1443 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1444 broadcastPackageVerified(verificationId, originUri, 1445 PackageManager.VERIFICATION_ALLOW, 1446 state.getInstallArgs().getUser()); 1447 try { 1448 ret = args.copyApk(mContainerService, true); 1449 } catch (RemoteException e) { 1450 Slog.e(TAG, "Could not contact the ContainerService"); 1451 } 1452 } else { 1453 broadcastPackageVerified(verificationId, originUri, 1454 PackageManager.VERIFICATION_REJECT, 1455 state.getInstallArgs().getUser()); 1456 } 1457 1458 processPendingInstall(args, ret); 1459 mHandler.sendEmptyMessage(MCS_UNBIND); 1460 } 1461 break; 1462 } 1463 case PACKAGE_VERIFIED: { 1464 final int verificationId = msg.arg1; 1465 1466 final PackageVerificationState state = mPendingVerification.get(verificationId); 1467 if (state == null) { 1468 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1469 break; 1470 } 1471 1472 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1473 1474 state.setVerifierResponse(response.callerUid, response.code); 1475 1476 if (state.isVerificationComplete()) { 1477 mPendingVerification.remove(verificationId); 1478 1479 final InstallArgs args = state.getInstallArgs(); 1480 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1481 1482 int ret; 1483 if (state.isInstallAllowed()) { 1484 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1485 broadcastPackageVerified(verificationId, originUri, 1486 response.code, state.getInstallArgs().getUser()); 1487 try { 1488 ret = args.copyApk(mContainerService, true); 1489 } catch (RemoteException e) { 1490 Slog.e(TAG, "Could not contact the ContainerService"); 1491 } 1492 } else { 1493 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1494 } 1495 1496 processPendingInstall(args, ret); 1497 1498 mHandler.sendEmptyMessage(MCS_UNBIND); 1499 } 1500 1501 break; 1502 } 1503 case START_INTENT_FILTER_VERIFICATIONS: { 1504 int userId = msg.arg1; 1505 int verifierUid = msg.arg2; 1506 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1507 1508 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1509 break; 1510 } 1511 case INTENT_FILTER_VERIFIED: { 1512 final int verificationId = msg.arg1; 1513 1514 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1515 verificationId); 1516 if (state == null) { 1517 Slog.w(TAG, "Invalid IntentFilter verification token " 1518 + verificationId + " received"); 1519 break; 1520 } 1521 1522 final int userId = state.getUserId(); 1523 1524 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1525 "Processing IntentFilter verification with token:" 1526 + verificationId + " and userId:" + userId); 1527 1528 final IntentFilterVerificationResponse response = 1529 (IntentFilterVerificationResponse) msg.obj; 1530 1531 state.setVerifierResponse(response.callerUid, response.code); 1532 1533 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1534 "IntentFilter verification with token:" + verificationId 1535 + " and userId:" + userId 1536 + " is settings verifier response with response code:" 1537 + response.code); 1538 1539 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1540 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1541 + response.getFailedDomainsString()); 1542 } 1543 1544 if (state.isVerificationComplete()) { 1545 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1546 } else { 1547 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1548 "IntentFilter verification with token:" + verificationId 1549 + " was not said to be complete"); 1550 } 1551 1552 break; 1553 } 1554 } 1555 } 1556 } 1557 1558 private StorageEventListener mStorageListener = new StorageEventListener() { 1559 @Override 1560 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1561 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1562 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1563 // TODO: ensure that private directories exist for all active users 1564 // TODO: remove user data whose serial number doesn't match 1565 loadPrivatePackages(vol); 1566 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1567 unloadPrivatePackages(vol); 1568 } 1569 } 1570 1571 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1572 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1573 updateExternalMediaStatus(true, false); 1574 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1575 updateExternalMediaStatus(false, false); 1576 } 1577 } 1578 } 1579 1580 @Override 1581 public void onVolumeForgotten(String fsUuid) { 1582 // TODO: remove all packages hosted on this uuid 1583 } 1584 }; 1585 1586 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1587 if (userId >= UserHandle.USER_OWNER) { 1588 grantRequestedRuntimePermissionsForUser(pkg, userId); 1589 } else if (userId == UserHandle.USER_ALL) { 1590 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1591 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1592 } 1593 } 1594 1595 // We could have touched GID membership, so flush out packages.list 1596 synchronized (mPackages) { 1597 mSettings.writePackageListLPr(); 1598 } 1599 } 1600 1601 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1602 SettingBase sb = (SettingBase) pkg.mExtras; 1603 if (sb == null) { 1604 return; 1605 } 1606 1607 PermissionsState permissionsState = sb.getPermissionsState(); 1608 1609 for (String permission : pkg.requestedPermissions) { 1610 BasePermission bp = mSettings.mPermissions.get(permission); 1611 if (bp != null && bp.isRuntime()) { 1612 permissionsState.grantRuntimePermission(bp, userId); 1613 } 1614 } 1615 } 1616 1617 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1618 Bundle extras = null; 1619 switch (res.returnCode) { 1620 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1621 extras = new Bundle(); 1622 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1623 res.origPermission); 1624 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1625 res.origPackage); 1626 break; 1627 } 1628 case PackageManager.INSTALL_SUCCEEDED: { 1629 extras = new Bundle(); 1630 extras.putBoolean(Intent.EXTRA_REPLACING, 1631 res.removedInfo != null && res.removedInfo.removedPackage != null); 1632 break; 1633 } 1634 } 1635 return extras; 1636 } 1637 1638 void scheduleWriteSettingsLocked() { 1639 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1640 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1641 } 1642 } 1643 1644 void scheduleWritePackageRestrictionsLocked(int userId) { 1645 if (!sUserManager.exists(userId)) return; 1646 mDirtyUsers.add(userId); 1647 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1648 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1649 } 1650 } 1651 1652 public static PackageManagerService main(Context context, Installer installer, 1653 boolean factoryTest, boolean onlyCore) { 1654 PackageManagerService m = new PackageManagerService(context, installer, 1655 factoryTest, onlyCore); 1656 ServiceManager.addService("package", m); 1657 return m; 1658 } 1659 1660 static String[] splitString(String str, char sep) { 1661 int count = 1; 1662 int i = 0; 1663 while ((i=str.indexOf(sep, i)) >= 0) { 1664 count++; 1665 i++; 1666 } 1667 1668 String[] res = new String[count]; 1669 i=0; 1670 count = 0; 1671 int lastI=0; 1672 while ((i=str.indexOf(sep, i)) >= 0) { 1673 res[count] = str.substring(lastI, i); 1674 count++; 1675 i++; 1676 lastI = i; 1677 } 1678 res[count] = str.substring(lastI, str.length()); 1679 return res; 1680 } 1681 1682 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1683 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1684 Context.DISPLAY_SERVICE); 1685 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1686 } 1687 1688 public PackageManagerService(Context context, Installer installer, 1689 boolean factoryTest, boolean onlyCore) { 1690 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1691 SystemClock.uptimeMillis()); 1692 1693 if (mSdkVersion <= 0) { 1694 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1695 } 1696 1697 mContext = context; 1698 mFactoryTest = factoryTest; 1699 mOnlyCore = onlyCore; 1700 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1701 mMetrics = new DisplayMetrics(); 1702 mSettings = new Settings(mPackages); 1703 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1704 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1705 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1706 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1707 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1708 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1709 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1710 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1711 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1712 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1713 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1714 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1715 1716 // TODO: add a property to control this? 1717 long dexOptLRUThresholdInMinutes; 1718 if (mLazyDexOpt) { 1719 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1720 } else { 1721 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1722 } 1723 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1724 1725 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1726 if (separateProcesses != null && separateProcesses.length() > 0) { 1727 if ("*".equals(separateProcesses)) { 1728 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1729 mSeparateProcesses = null; 1730 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1731 } else { 1732 mDefParseFlags = 0; 1733 mSeparateProcesses = separateProcesses.split(","); 1734 Slog.w(TAG, "Running with debug.separate_processes: " 1735 + separateProcesses); 1736 } 1737 } else { 1738 mDefParseFlags = 0; 1739 mSeparateProcesses = null; 1740 } 1741 1742 mInstaller = installer; 1743 mPackageDexOptimizer = new PackageDexOptimizer(this); 1744 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1745 1746 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1747 FgThread.get().getLooper()); 1748 1749 getDefaultDisplayMetrics(context, mMetrics); 1750 1751 SystemConfig systemConfig = SystemConfig.getInstance(); 1752 mGlobalGids = systemConfig.getGlobalGids(); 1753 mSystemPermissions = systemConfig.getSystemPermissions(); 1754 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1755 1756 synchronized (mInstallLock) { 1757 // writer 1758 synchronized (mPackages) { 1759 mHandlerThread = new ServiceThread(TAG, 1760 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1761 mHandlerThread.start(); 1762 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1763 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1764 1765 File dataDir = Environment.getDataDirectory(); 1766 mAppDataDir = new File(dataDir, "data"); 1767 mAppInstallDir = new File(dataDir, "app"); 1768 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1769 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1770 mUserAppDataDir = new File(dataDir, "user"); 1771 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1772 1773 sUserManager = new UserManagerService(context, this, 1774 mInstallLock, mPackages); 1775 1776 // Propagate permission configuration in to package manager. 1777 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1778 = systemConfig.getPermissions(); 1779 for (int i=0; i<permConfig.size(); i++) { 1780 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1781 BasePermission bp = mSettings.mPermissions.get(perm.name); 1782 if (bp == null) { 1783 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1784 mSettings.mPermissions.put(perm.name, bp); 1785 } 1786 if (perm.gids != null) { 1787 bp.setGids(perm.gids, perm.perUser); 1788 } 1789 } 1790 1791 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1792 for (int i=0; i<libConfig.size(); i++) { 1793 mSharedLibraries.put(libConfig.keyAt(i), 1794 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1795 } 1796 1797 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1798 1799 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1800 mSdkVersion, mOnlyCore); 1801 1802 String customResolverActivity = Resources.getSystem().getString( 1803 R.string.config_customResolverActivity); 1804 if (TextUtils.isEmpty(customResolverActivity)) { 1805 customResolverActivity = null; 1806 } else { 1807 mCustomResolverComponentName = ComponentName.unflattenFromString( 1808 customResolverActivity); 1809 } 1810 1811 long startTime = SystemClock.uptimeMillis(); 1812 1813 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1814 startTime); 1815 1816 // Set flag to monitor and not change apk file paths when 1817 // scanning install directories. 1818 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1819 1820 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1821 1822 /** 1823 * Add everything in the in the boot class path to the 1824 * list of process files because dexopt will have been run 1825 * if necessary during zygote startup. 1826 */ 1827 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1828 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1829 1830 if (bootClassPath != null) { 1831 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1832 for (String element : bootClassPathElements) { 1833 alreadyDexOpted.add(element); 1834 } 1835 } else { 1836 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1837 } 1838 1839 if (systemServerClassPath != null) { 1840 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1841 for (String element : systemServerClassPathElements) { 1842 alreadyDexOpted.add(element); 1843 } 1844 } else { 1845 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1846 } 1847 1848 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1849 final String[] dexCodeInstructionSets = 1850 getDexCodeInstructionSets( 1851 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1852 1853 /** 1854 * Ensure all external libraries have had dexopt run on them. 1855 */ 1856 if (mSharedLibraries.size() > 0) { 1857 // NOTE: For now, we're compiling these system "shared libraries" 1858 // (and framework jars) into all available architectures. It's possible 1859 // to compile them only when we come across an app that uses them (there's 1860 // already logic for that in scanPackageLI) but that adds some complexity. 1861 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1862 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1863 final String lib = libEntry.path; 1864 if (lib == null) { 1865 continue; 1866 } 1867 1868 try { 1869 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1870 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1871 alreadyDexOpted.add(lib); 1872 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1873 } 1874 } catch (FileNotFoundException e) { 1875 Slog.w(TAG, "Library not found: " + lib); 1876 } catch (IOException e) { 1877 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1878 + e.getMessage()); 1879 } 1880 } 1881 } 1882 } 1883 1884 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1885 1886 // Gross hack for now: we know this file doesn't contain any 1887 // code, so don't dexopt it to avoid the resulting log spew. 1888 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1889 1890 // Gross hack for now: we know this file is only part of 1891 // the boot class path for art, so don't dexopt it to 1892 // avoid the resulting log spew. 1893 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1894 1895 /** 1896 * There are a number of commands implemented in Java, which 1897 * we currently need to do the dexopt on so that they can be 1898 * run from a non-root shell. 1899 */ 1900 String[] frameworkFiles = frameworkDir.list(); 1901 if (frameworkFiles != null) { 1902 // TODO: We could compile these only for the most preferred ABI. We should 1903 // first double check that the dex files for these commands are not referenced 1904 // by other system apps. 1905 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1906 for (int i=0; i<frameworkFiles.length; i++) { 1907 File libPath = new File(frameworkDir, frameworkFiles[i]); 1908 String path = libPath.getPath(); 1909 // Skip the file if we already did it. 1910 if (alreadyDexOpted.contains(path)) { 1911 continue; 1912 } 1913 // Skip the file if it is not a type we want to dexopt. 1914 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1915 continue; 1916 } 1917 try { 1918 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1919 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1920 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1921 } 1922 } catch (FileNotFoundException e) { 1923 Slog.w(TAG, "Jar not found: " + path); 1924 } catch (IOException e) { 1925 Slog.w(TAG, "Exception reading jar: " + path, e); 1926 } 1927 } 1928 } 1929 } 1930 1931 // Collect vendor overlay packages. 1932 // (Do this before scanning any apps.) 1933 // For security and version matching reason, only consider 1934 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1935 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1936 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1937 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1938 1939 // Find base frameworks (resource packages without code). 1940 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1941 | PackageParser.PARSE_IS_SYSTEM_DIR 1942 | PackageParser.PARSE_IS_PRIVILEGED, 1943 scanFlags | SCAN_NO_DEX, 0); 1944 1945 // Collected privileged system packages. 1946 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1947 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1948 | PackageParser.PARSE_IS_SYSTEM_DIR 1949 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1950 1951 // Collect ordinary system packages. 1952 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1953 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1954 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1955 1956 // Collect all vendor packages. 1957 File vendorAppDir = new File("/vendor/app"); 1958 try { 1959 vendorAppDir = vendorAppDir.getCanonicalFile(); 1960 } catch (IOException e) { 1961 // failed to look up canonical path, continue with original one 1962 } 1963 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1964 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1965 1966 // Collect all OEM packages. 1967 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1968 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1969 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1970 1971 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1972 mInstaller.moveFiles(); 1973 1974 // Prune any system packages that no longer exist. 1975 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1976 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1977 if (!mOnlyCore) { 1978 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1979 while (psit.hasNext()) { 1980 PackageSetting ps = psit.next(); 1981 1982 /* 1983 * If this is not a system app, it can't be a 1984 * disable system app. 1985 */ 1986 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1987 continue; 1988 } 1989 1990 /* 1991 * If the package is scanned, it's not erased. 1992 */ 1993 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1994 if (scannedPkg != null) { 1995 /* 1996 * If the system app is both scanned and in the 1997 * disabled packages list, then it must have been 1998 * added via OTA. Remove it from the currently 1999 * scanned package so the previously user-installed 2000 * application can be scanned. 2001 */ 2002 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2003 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2004 + ps.name + "; removing system app. Last known codePath=" 2005 + ps.codePathString + ", installStatus=" + ps.installStatus 2006 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2007 + scannedPkg.mVersionCode); 2008 removePackageLI(ps, true); 2009 expectingBetter.put(ps.name, ps.codePath); 2010 } 2011 2012 continue; 2013 } 2014 2015 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2016 psit.remove(); 2017 logCriticalInfo(Log.WARN, "System package " + ps.name 2018 + " no longer exists; wiping its data"); 2019 removeDataDirsLI(null, ps.name); 2020 } else { 2021 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2022 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2023 possiblyDeletedUpdatedSystemApps.add(ps.name); 2024 } 2025 } 2026 } 2027 } 2028 2029 //look for any incomplete package installations 2030 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2031 //clean up list 2032 for(int i = 0; i < deletePkgsList.size(); i++) { 2033 //clean up here 2034 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2035 } 2036 //delete tmp files 2037 deleteTempPackageFiles(); 2038 2039 // Remove any shared userIDs that have no associated packages 2040 mSettings.pruneSharedUsersLPw(); 2041 2042 if (!mOnlyCore) { 2043 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2044 SystemClock.uptimeMillis()); 2045 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2046 2047 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2048 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2049 2050 /** 2051 * Remove disable package settings for any updated system 2052 * apps that were removed via an OTA. If they're not a 2053 * previously-updated app, remove them completely. 2054 * Otherwise, just revoke their system-level permissions. 2055 */ 2056 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2057 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2058 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2059 2060 String msg; 2061 if (deletedPkg == null) { 2062 msg = "Updated system package " + deletedAppName 2063 + " no longer exists; wiping its data"; 2064 removeDataDirsLI(null, deletedAppName); 2065 } else { 2066 msg = "Updated system app + " + deletedAppName 2067 + " no longer present; removing system privileges for " 2068 + deletedAppName; 2069 2070 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2071 2072 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2073 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2074 } 2075 logCriticalInfo(Log.WARN, msg); 2076 } 2077 2078 /** 2079 * Make sure all system apps that we expected to appear on 2080 * the userdata partition actually showed up. If they never 2081 * appeared, crawl back and revive the system version. 2082 */ 2083 for (int i = 0; i < expectingBetter.size(); i++) { 2084 final String packageName = expectingBetter.keyAt(i); 2085 if (!mPackages.containsKey(packageName)) { 2086 final File scanFile = expectingBetter.valueAt(i); 2087 2088 logCriticalInfo(Log.WARN, "Expected better " + packageName 2089 + " but never showed up; reverting to system"); 2090 2091 final int reparseFlags; 2092 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2093 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2094 | PackageParser.PARSE_IS_SYSTEM_DIR 2095 | PackageParser.PARSE_IS_PRIVILEGED; 2096 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2097 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2098 | PackageParser.PARSE_IS_SYSTEM_DIR; 2099 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2100 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2101 | PackageParser.PARSE_IS_SYSTEM_DIR; 2102 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2103 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2104 | PackageParser.PARSE_IS_SYSTEM_DIR; 2105 } else { 2106 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2107 continue; 2108 } 2109 2110 mSettings.enableSystemPackageLPw(packageName); 2111 2112 try { 2113 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2114 } catch (PackageManagerException e) { 2115 Slog.e(TAG, "Failed to parse original system package: " 2116 + e.getMessage()); 2117 } 2118 } 2119 } 2120 } 2121 2122 // Now that we know all of the shared libraries, update all clients to have 2123 // the correct library paths. 2124 updateAllSharedLibrariesLPw(); 2125 2126 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2127 // NOTE: We ignore potential failures here during a system scan (like 2128 // the rest of the commands above) because there's precious little we 2129 // can do about it. A settings error is reported, though. 2130 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2131 false /* force dexopt */, false /* defer dexopt */); 2132 } 2133 2134 // Now that we know all the packages we are keeping, 2135 // read and update their last usage times. 2136 mPackageUsage.readLP(); 2137 2138 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2139 SystemClock.uptimeMillis()); 2140 Slog.i(TAG, "Time to scan packages: " 2141 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2142 + " seconds"); 2143 2144 // If the platform SDK has changed since the last time we booted, 2145 // we need to re-grant app permission to catch any new ones that 2146 // appear. This is really a hack, and means that apps can in some 2147 // cases get permissions that the user didn't initially explicitly 2148 // allow... it would be nice to have some better way to handle 2149 // this situation. 2150 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2151 != mSdkVersion; 2152 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2153 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2154 + "; regranting permissions for internal storage"); 2155 mSettings.mInternalSdkPlatform = mSdkVersion; 2156 2157 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2158 | (regrantPermissions 2159 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2160 : 0)); 2161 2162 // If this is the first boot, and it is a normal boot, then 2163 // we need to initialize the default preferred apps. 2164 if (!mRestoredSettings && !onlyCore) { 2165 mSettings.readDefaultPreferredAppsLPw(this, 0); 2166 } 2167 2168 // If this is first boot after an OTA, and a normal boot, then 2169 // we need to clear code cache directories. 2170 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2171 if (mIsUpgrade && !onlyCore) { 2172 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2173 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2174 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2175 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2176 } 2177 mSettings.mFingerprint = Build.FINGERPRINT; 2178 } 2179 2180 primeDomainVerificationsLPw(); 2181 checkDefaultBrowser(); 2182 2183 // All the changes are done during package scanning. 2184 mSettings.updateInternalDatabaseVersion(); 2185 2186 // can downgrade to reader 2187 mSettings.writeLPr(); 2188 2189 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2190 SystemClock.uptimeMillis()); 2191 2192 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2193 2194 mInstallerService = new PackageInstallerService(context, this); 2195 2196 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2197 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2198 mIntentFilterVerifierComponent); 2199 2200 } // synchronized (mPackages) 2201 } // synchronized (mInstallLock) 2202 2203 // Now after opening every single application zip, make sure they 2204 // are all flushed. Not really needed, but keeps things nice and 2205 // tidy. 2206 Runtime.getRuntime().gc(); 2207 2208 // Expose private service for system components to use. 2209 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2210 } 2211 2212 @Override 2213 public boolean isFirstBoot() { 2214 return !mRestoredSettings; 2215 } 2216 2217 @Override 2218 public boolean isOnlyCoreApps() { 2219 return mOnlyCore; 2220 } 2221 2222 @Override 2223 public boolean isUpgrade() { 2224 return mIsUpgrade; 2225 } 2226 2227 private String getRequiredVerifierLPr() { 2228 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2229 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2230 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2231 2232 String requiredVerifier = null; 2233 2234 final int N = receivers.size(); 2235 for (int i = 0; i < N; i++) { 2236 final ResolveInfo info = receivers.get(i); 2237 2238 if (info.activityInfo == null) { 2239 continue; 2240 } 2241 2242 final String packageName = info.activityInfo.packageName; 2243 2244 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2245 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2246 continue; 2247 } 2248 2249 if (requiredVerifier != null) { 2250 throw new RuntimeException("There can be only one required verifier"); 2251 } 2252 2253 requiredVerifier = packageName; 2254 } 2255 2256 return requiredVerifier; 2257 } 2258 2259 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2260 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2261 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2262 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2263 2264 ComponentName verifierComponentName = null; 2265 2266 int priority = -1000; 2267 final int N = receivers.size(); 2268 for (int i = 0; i < N; i++) { 2269 final ResolveInfo info = receivers.get(i); 2270 2271 if (info.activityInfo == null) { 2272 continue; 2273 } 2274 2275 final String packageName = info.activityInfo.packageName; 2276 2277 final PackageSetting ps = mSettings.mPackages.get(packageName); 2278 if (ps == null) { 2279 continue; 2280 } 2281 2282 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2283 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2284 continue; 2285 } 2286 2287 // Select the IntentFilterVerifier with the highest priority 2288 if (priority < info.priority) { 2289 priority = info.priority; 2290 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2291 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2292 + verifierComponentName + " with priority: " + info.priority); 2293 } 2294 } 2295 2296 return verifierComponentName; 2297 } 2298 2299 private void primeDomainVerificationsLPw() { 2300 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2301 boolean updated = false; 2302 ArraySet<String> allHostsSet = new ArraySet<>(); 2303 for (PackageParser.Package pkg : mPackages.values()) { 2304 final String packageName = pkg.packageName; 2305 if (!hasDomainURLs(pkg)) { 2306 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2307 "package with no domain URLs: " + packageName); 2308 continue; 2309 } 2310 if (!pkg.isSystemApp()) { 2311 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2312 "No priming domain verifications for a non system package : " + 2313 packageName); 2314 continue; 2315 } 2316 for (PackageParser.Activity a : pkg.activities) { 2317 for (ActivityIntentInfo filter : a.intents) { 2318 if (hasValidDomains(filter)) { 2319 allHostsSet.addAll(filter.getHostsList()); 2320 } 2321 } 2322 } 2323 if (allHostsSet.size() == 0) { 2324 allHostsSet.add("*"); 2325 } 2326 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2327 IntentFilterVerificationInfo ivi = 2328 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2329 if (ivi != null) { 2330 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2331 "Priming domain verifications for package: " + packageName + 2332 " with hosts:" + ivi.getDomainsString()); 2333 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2334 updated = true; 2335 } 2336 else { 2337 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2338 "No priming domain verifications for package: " + packageName); 2339 } 2340 allHostsSet.clear(); 2341 } 2342 if (updated) { 2343 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2344 "Will need to write primed domain verifications"); 2345 } 2346 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2347 } 2348 2349 private void checkDefaultBrowser() { 2350 final int myUserId = UserHandle.myUserId(); 2351 final String packageName = getDefaultBrowserPackageName(myUserId); 2352 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2353 if (info == null) { 2354 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2355 packageName); 2356 setDefaultBrowserPackageName(null, myUserId); 2357 } 2358 } 2359 2360 @Override 2361 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2362 throws RemoteException { 2363 try { 2364 return super.onTransact(code, data, reply, flags); 2365 } catch (RuntimeException e) { 2366 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2367 Slog.wtf(TAG, "Package Manager Crash", e); 2368 } 2369 throw e; 2370 } 2371 } 2372 2373 void cleanupInstallFailedPackage(PackageSetting ps) { 2374 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2375 2376 removeDataDirsLI(ps.volumeUuid, ps.name); 2377 if (ps.codePath != null) { 2378 if (ps.codePath.isDirectory()) { 2379 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2380 } else { 2381 ps.codePath.delete(); 2382 } 2383 } 2384 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2385 if (ps.resourcePath.isDirectory()) { 2386 FileUtils.deleteContents(ps.resourcePath); 2387 } 2388 ps.resourcePath.delete(); 2389 } 2390 mSettings.removePackageLPw(ps.name); 2391 } 2392 2393 static int[] appendInts(int[] cur, int[] add) { 2394 if (add == null) return cur; 2395 if (cur == null) return add; 2396 final int N = add.length; 2397 for (int i=0; i<N; i++) { 2398 cur = appendInt(cur, add[i]); 2399 } 2400 return cur; 2401 } 2402 2403 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2404 if (!sUserManager.exists(userId)) return null; 2405 final PackageSetting ps = (PackageSetting) p.mExtras; 2406 if (ps == null) { 2407 return null; 2408 } 2409 2410 final PermissionsState permissionsState = ps.getPermissionsState(); 2411 2412 final int[] gids = permissionsState.computeGids(userId); 2413 final Set<String> permissions = permissionsState.getPermissions(userId); 2414 final PackageUserState state = ps.readUserState(userId); 2415 2416 return PackageParser.generatePackageInfo(p, gids, flags, 2417 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2418 } 2419 2420 @Override 2421 public boolean isPackageFrozen(String packageName) { 2422 synchronized (mPackages) { 2423 final PackageSetting ps = mSettings.mPackages.get(packageName); 2424 if (ps != null) { 2425 return ps.frozen; 2426 } 2427 } 2428 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2429 return true; 2430 } 2431 2432 @Override 2433 public boolean isPackageAvailable(String packageName, int userId) { 2434 if (!sUserManager.exists(userId)) return false; 2435 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2436 synchronized (mPackages) { 2437 PackageParser.Package p = mPackages.get(packageName); 2438 if (p != null) { 2439 final PackageSetting ps = (PackageSetting) p.mExtras; 2440 if (ps != null) { 2441 final PackageUserState state = ps.readUserState(userId); 2442 if (state != null) { 2443 return PackageParser.isAvailable(state); 2444 } 2445 } 2446 } 2447 } 2448 return false; 2449 } 2450 2451 @Override 2452 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2453 if (!sUserManager.exists(userId)) return null; 2454 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2455 // reader 2456 synchronized (mPackages) { 2457 PackageParser.Package p = mPackages.get(packageName); 2458 if (DEBUG_PACKAGE_INFO) 2459 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2460 if (p != null) { 2461 return generatePackageInfo(p, flags, userId); 2462 } 2463 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2464 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2465 } 2466 } 2467 return null; 2468 } 2469 2470 @Override 2471 public String[] currentToCanonicalPackageNames(String[] names) { 2472 String[] out = new String[names.length]; 2473 // reader 2474 synchronized (mPackages) { 2475 for (int i=names.length-1; i>=0; i--) { 2476 PackageSetting ps = mSettings.mPackages.get(names[i]); 2477 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2478 } 2479 } 2480 return out; 2481 } 2482 2483 @Override 2484 public String[] canonicalToCurrentPackageNames(String[] names) { 2485 String[] out = new String[names.length]; 2486 // reader 2487 synchronized (mPackages) { 2488 for (int i=names.length-1; i>=0; i--) { 2489 String cur = mSettings.mRenamedPackages.get(names[i]); 2490 out[i] = cur != null ? cur : names[i]; 2491 } 2492 } 2493 return out; 2494 } 2495 2496 @Override 2497 public int getPackageUid(String packageName, int userId) { 2498 if (!sUserManager.exists(userId)) return -1; 2499 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2500 2501 // reader 2502 synchronized (mPackages) { 2503 PackageParser.Package p = mPackages.get(packageName); 2504 if(p != null) { 2505 return UserHandle.getUid(userId, p.applicationInfo.uid); 2506 } 2507 PackageSetting ps = mSettings.mPackages.get(packageName); 2508 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2509 return -1; 2510 } 2511 p = ps.pkg; 2512 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2513 } 2514 } 2515 2516 @Override 2517 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2518 if (!sUserManager.exists(userId)) { 2519 return null; 2520 } 2521 2522 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2523 "getPackageGids"); 2524 2525 // reader 2526 synchronized (mPackages) { 2527 PackageParser.Package p = mPackages.get(packageName); 2528 if (DEBUG_PACKAGE_INFO) { 2529 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2530 } 2531 if (p != null) { 2532 PackageSetting ps = (PackageSetting) p.mExtras; 2533 return ps.getPermissionsState().computeGids(userId); 2534 } 2535 } 2536 2537 return null; 2538 } 2539 2540 static PermissionInfo generatePermissionInfo( 2541 BasePermission bp, int flags) { 2542 if (bp.perm != null) { 2543 return PackageParser.generatePermissionInfo(bp.perm, flags); 2544 } 2545 PermissionInfo pi = new PermissionInfo(); 2546 pi.name = bp.name; 2547 pi.packageName = bp.sourcePackage; 2548 pi.nonLocalizedLabel = bp.name; 2549 pi.protectionLevel = bp.protectionLevel; 2550 return pi; 2551 } 2552 2553 @Override 2554 public PermissionInfo getPermissionInfo(String name, int flags) { 2555 // reader 2556 synchronized (mPackages) { 2557 final BasePermission p = mSettings.mPermissions.get(name); 2558 if (p != null) { 2559 return generatePermissionInfo(p, flags); 2560 } 2561 return null; 2562 } 2563 } 2564 2565 @Override 2566 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2567 // reader 2568 synchronized (mPackages) { 2569 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2570 for (BasePermission p : mSettings.mPermissions.values()) { 2571 if (group == null) { 2572 if (p.perm == null || p.perm.info.group == null) { 2573 out.add(generatePermissionInfo(p, flags)); 2574 } 2575 } else { 2576 if (p.perm != null && group.equals(p.perm.info.group)) { 2577 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2578 } 2579 } 2580 } 2581 2582 if (out.size() > 0) { 2583 return out; 2584 } 2585 return mPermissionGroups.containsKey(group) ? out : null; 2586 } 2587 } 2588 2589 @Override 2590 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2591 // reader 2592 synchronized (mPackages) { 2593 return PackageParser.generatePermissionGroupInfo( 2594 mPermissionGroups.get(name), flags); 2595 } 2596 } 2597 2598 @Override 2599 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2600 // reader 2601 synchronized (mPackages) { 2602 final int N = mPermissionGroups.size(); 2603 ArrayList<PermissionGroupInfo> out 2604 = new ArrayList<PermissionGroupInfo>(N); 2605 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2606 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2607 } 2608 return out; 2609 } 2610 } 2611 2612 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2613 int userId) { 2614 if (!sUserManager.exists(userId)) return null; 2615 PackageSetting ps = mSettings.mPackages.get(packageName); 2616 if (ps != null) { 2617 if (ps.pkg == null) { 2618 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2619 flags, userId); 2620 if (pInfo != null) { 2621 return pInfo.applicationInfo; 2622 } 2623 return null; 2624 } 2625 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2626 ps.readUserState(userId), userId); 2627 } 2628 return null; 2629 } 2630 2631 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2632 int userId) { 2633 if (!sUserManager.exists(userId)) return null; 2634 PackageSetting ps = mSettings.mPackages.get(packageName); 2635 if (ps != null) { 2636 PackageParser.Package pkg = ps.pkg; 2637 if (pkg == null) { 2638 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2639 return null; 2640 } 2641 // Only data remains, so we aren't worried about code paths 2642 pkg = new PackageParser.Package(packageName); 2643 pkg.applicationInfo.packageName = packageName; 2644 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2645 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2646 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2647 packageName, userId).getAbsolutePath(); 2648 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2649 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2650 } 2651 return generatePackageInfo(pkg, flags, userId); 2652 } 2653 return null; 2654 } 2655 2656 @Override 2657 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2658 if (!sUserManager.exists(userId)) return null; 2659 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2660 // writer 2661 synchronized (mPackages) { 2662 PackageParser.Package p = mPackages.get(packageName); 2663 if (DEBUG_PACKAGE_INFO) Log.v( 2664 TAG, "getApplicationInfo " + packageName 2665 + ": " + p); 2666 if (p != null) { 2667 PackageSetting ps = mSettings.mPackages.get(packageName); 2668 if (ps == null) return null; 2669 // Note: isEnabledLP() does not apply here - always return info 2670 return PackageParser.generateApplicationInfo( 2671 p, flags, ps.readUserState(userId), userId); 2672 } 2673 if ("android".equals(packageName)||"system".equals(packageName)) { 2674 return mAndroidApplication; 2675 } 2676 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2677 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2678 } 2679 } 2680 return null; 2681 } 2682 2683 @Override 2684 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2685 final IPackageDataObserver observer) { 2686 mContext.enforceCallingOrSelfPermission( 2687 android.Manifest.permission.CLEAR_APP_CACHE, null); 2688 // Queue up an async operation since clearing cache may take a little while. 2689 mHandler.post(new Runnable() { 2690 public void run() { 2691 mHandler.removeCallbacks(this); 2692 int retCode = -1; 2693 synchronized (mInstallLock) { 2694 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2695 if (retCode < 0) { 2696 Slog.w(TAG, "Couldn't clear application caches"); 2697 } 2698 } 2699 if (observer != null) { 2700 try { 2701 observer.onRemoveCompleted(null, (retCode >= 0)); 2702 } catch (RemoteException e) { 2703 Slog.w(TAG, "RemoveException when invoking call back"); 2704 } 2705 } 2706 } 2707 }); 2708 } 2709 2710 @Override 2711 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2712 final IntentSender pi) { 2713 mContext.enforceCallingOrSelfPermission( 2714 android.Manifest.permission.CLEAR_APP_CACHE, null); 2715 // Queue up an async operation since clearing cache may take a little while. 2716 mHandler.post(new Runnable() { 2717 public void run() { 2718 mHandler.removeCallbacks(this); 2719 int retCode = -1; 2720 synchronized (mInstallLock) { 2721 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2722 if (retCode < 0) { 2723 Slog.w(TAG, "Couldn't clear application caches"); 2724 } 2725 } 2726 if(pi != null) { 2727 try { 2728 // Callback via pending intent 2729 int code = (retCode >= 0) ? 1 : 0; 2730 pi.sendIntent(null, code, null, 2731 null, null); 2732 } catch (SendIntentException e1) { 2733 Slog.i(TAG, "Failed to send pending intent"); 2734 } 2735 } 2736 } 2737 }); 2738 } 2739 2740 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2741 synchronized (mInstallLock) { 2742 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2743 throw new IOException("Failed to free enough space"); 2744 } 2745 } 2746 } 2747 2748 @Override 2749 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2750 if (!sUserManager.exists(userId)) return null; 2751 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2752 synchronized (mPackages) { 2753 PackageParser.Activity a = mActivities.mActivities.get(component); 2754 2755 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2756 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2757 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2758 if (ps == null) return null; 2759 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2760 userId); 2761 } 2762 if (mResolveComponentName.equals(component)) { 2763 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2764 new PackageUserState(), userId); 2765 } 2766 } 2767 return null; 2768 } 2769 2770 @Override 2771 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2772 String resolvedType) { 2773 synchronized (mPackages) { 2774 PackageParser.Activity a = mActivities.mActivities.get(component); 2775 if (a == null) { 2776 return false; 2777 } 2778 for (int i=0; i<a.intents.size(); i++) { 2779 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2780 intent.getData(), intent.getCategories(), TAG) >= 0) { 2781 return true; 2782 } 2783 } 2784 return false; 2785 } 2786 } 2787 2788 @Override 2789 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2790 if (!sUserManager.exists(userId)) return null; 2791 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2792 synchronized (mPackages) { 2793 PackageParser.Activity a = mReceivers.mActivities.get(component); 2794 if (DEBUG_PACKAGE_INFO) Log.v( 2795 TAG, "getReceiverInfo " + component + ": " + a); 2796 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2797 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2798 if (ps == null) return null; 2799 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2800 userId); 2801 } 2802 } 2803 return null; 2804 } 2805 2806 @Override 2807 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2808 if (!sUserManager.exists(userId)) return null; 2809 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2810 synchronized (mPackages) { 2811 PackageParser.Service s = mServices.mServices.get(component); 2812 if (DEBUG_PACKAGE_INFO) Log.v( 2813 TAG, "getServiceInfo " + component + ": " + s); 2814 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2815 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2816 if (ps == null) return null; 2817 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2818 userId); 2819 } 2820 } 2821 return null; 2822 } 2823 2824 @Override 2825 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2826 if (!sUserManager.exists(userId)) return null; 2827 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2828 synchronized (mPackages) { 2829 PackageParser.Provider p = mProviders.mProviders.get(component); 2830 if (DEBUG_PACKAGE_INFO) Log.v( 2831 TAG, "getProviderInfo " + component + ": " + p); 2832 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2833 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2834 if (ps == null) return null; 2835 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2836 userId); 2837 } 2838 } 2839 return null; 2840 } 2841 2842 @Override 2843 public String[] getSystemSharedLibraryNames() { 2844 Set<String> libSet; 2845 synchronized (mPackages) { 2846 libSet = mSharedLibraries.keySet(); 2847 int size = libSet.size(); 2848 if (size > 0) { 2849 String[] libs = new String[size]; 2850 libSet.toArray(libs); 2851 return libs; 2852 } 2853 } 2854 return null; 2855 } 2856 2857 /** 2858 * @hide 2859 */ 2860 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2861 synchronized (mPackages) { 2862 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2863 if (lib != null && lib.apk != null) { 2864 return mPackages.get(lib.apk); 2865 } 2866 } 2867 return null; 2868 } 2869 2870 @Override 2871 public FeatureInfo[] getSystemAvailableFeatures() { 2872 Collection<FeatureInfo> featSet; 2873 synchronized (mPackages) { 2874 featSet = mAvailableFeatures.values(); 2875 int size = featSet.size(); 2876 if (size > 0) { 2877 FeatureInfo[] features = new FeatureInfo[size+1]; 2878 featSet.toArray(features); 2879 FeatureInfo fi = new FeatureInfo(); 2880 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2881 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2882 features[size] = fi; 2883 return features; 2884 } 2885 } 2886 return null; 2887 } 2888 2889 @Override 2890 public boolean hasSystemFeature(String name) { 2891 synchronized (mPackages) { 2892 return mAvailableFeatures.containsKey(name); 2893 } 2894 } 2895 2896 private void checkValidCaller(int uid, int userId) { 2897 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2898 return; 2899 2900 throw new SecurityException("Caller uid=" + uid 2901 + " is not privileged to communicate with user=" + userId); 2902 } 2903 2904 @Override 2905 public int checkPermission(String permName, String pkgName, int userId) { 2906 if (!sUserManager.exists(userId)) { 2907 return PackageManager.PERMISSION_DENIED; 2908 } 2909 2910 synchronized (mPackages) { 2911 final PackageParser.Package p = mPackages.get(pkgName); 2912 if (p != null && p.mExtras != null) { 2913 final PackageSetting ps = (PackageSetting) p.mExtras; 2914 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2915 return PackageManager.PERMISSION_GRANTED; 2916 } 2917 } 2918 } 2919 2920 return PackageManager.PERMISSION_DENIED; 2921 } 2922 2923 @Override 2924 public int checkUidPermission(String permName, int uid) { 2925 final int userId = UserHandle.getUserId(uid); 2926 2927 if (!sUserManager.exists(userId)) { 2928 return PackageManager.PERMISSION_DENIED; 2929 } 2930 2931 synchronized (mPackages) { 2932 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2933 if (obj != null) { 2934 final SettingBase ps = (SettingBase) obj; 2935 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2936 return PackageManager.PERMISSION_GRANTED; 2937 } 2938 } else { 2939 ArraySet<String> perms = mSystemPermissions.get(uid); 2940 if (perms != null && perms.contains(permName)) { 2941 return PackageManager.PERMISSION_GRANTED; 2942 } 2943 } 2944 } 2945 2946 return PackageManager.PERMISSION_DENIED; 2947 } 2948 2949 /** 2950 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2951 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2952 * @param checkShell TODO(yamasani): 2953 * @param message the message to log on security exception 2954 */ 2955 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2956 boolean checkShell, String message) { 2957 if (userId < 0) { 2958 throw new IllegalArgumentException("Invalid userId " + userId); 2959 } 2960 if (checkShell) { 2961 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2962 } 2963 if (userId == UserHandle.getUserId(callingUid)) return; 2964 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2965 if (requireFullPermission) { 2966 mContext.enforceCallingOrSelfPermission( 2967 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2968 } else { 2969 try { 2970 mContext.enforceCallingOrSelfPermission( 2971 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2972 } catch (SecurityException se) { 2973 mContext.enforceCallingOrSelfPermission( 2974 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2975 } 2976 } 2977 } 2978 } 2979 2980 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2981 if (callingUid == Process.SHELL_UID) { 2982 if (userHandle >= 0 2983 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2984 throw new SecurityException("Shell does not have permission to access user " 2985 + userHandle); 2986 } else if (userHandle < 0) { 2987 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2988 + Debug.getCallers(3)); 2989 } 2990 } 2991 } 2992 2993 private BasePermission findPermissionTreeLP(String permName) { 2994 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2995 if (permName.startsWith(bp.name) && 2996 permName.length() > bp.name.length() && 2997 permName.charAt(bp.name.length()) == '.') { 2998 return bp; 2999 } 3000 } 3001 return null; 3002 } 3003 3004 private BasePermission checkPermissionTreeLP(String permName) { 3005 if (permName != null) { 3006 BasePermission bp = findPermissionTreeLP(permName); 3007 if (bp != null) { 3008 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3009 return bp; 3010 } 3011 throw new SecurityException("Calling uid " 3012 + Binder.getCallingUid() 3013 + " is not allowed to add to permission tree " 3014 + bp.name + " owned by uid " + bp.uid); 3015 } 3016 } 3017 throw new SecurityException("No permission tree found for " + permName); 3018 } 3019 3020 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3021 if (s1 == null) { 3022 return s2 == null; 3023 } 3024 if (s2 == null) { 3025 return false; 3026 } 3027 if (s1.getClass() != s2.getClass()) { 3028 return false; 3029 } 3030 return s1.equals(s2); 3031 } 3032 3033 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3034 if (pi1.icon != pi2.icon) return false; 3035 if (pi1.logo != pi2.logo) return false; 3036 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3037 if (!compareStrings(pi1.name, pi2.name)) return false; 3038 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3039 // We'll take care of setting this one. 3040 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3041 // These are not currently stored in settings. 3042 //if (!compareStrings(pi1.group, pi2.group)) return false; 3043 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3044 //if (pi1.labelRes != pi2.labelRes) return false; 3045 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3046 return true; 3047 } 3048 3049 int permissionInfoFootprint(PermissionInfo info) { 3050 int size = info.name.length(); 3051 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3052 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3053 return size; 3054 } 3055 3056 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3057 int size = 0; 3058 for (BasePermission perm : mSettings.mPermissions.values()) { 3059 if (perm.uid == tree.uid) { 3060 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3061 } 3062 } 3063 return size; 3064 } 3065 3066 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3067 // We calculate the max size of permissions defined by this uid and throw 3068 // if that plus the size of 'info' would exceed our stated maximum. 3069 if (tree.uid != Process.SYSTEM_UID) { 3070 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3071 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3072 throw new SecurityException("Permission tree size cap exceeded"); 3073 } 3074 } 3075 } 3076 3077 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3078 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3079 throw new SecurityException("Label must be specified in permission"); 3080 } 3081 BasePermission tree = checkPermissionTreeLP(info.name); 3082 BasePermission bp = mSettings.mPermissions.get(info.name); 3083 boolean added = bp == null; 3084 boolean changed = true; 3085 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3086 if (added) { 3087 enforcePermissionCapLocked(info, tree); 3088 bp = new BasePermission(info.name, tree.sourcePackage, 3089 BasePermission.TYPE_DYNAMIC); 3090 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3091 throw new SecurityException( 3092 "Not allowed to modify non-dynamic permission " 3093 + info.name); 3094 } else { 3095 if (bp.protectionLevel == fixedLevel 3096 && bp.perm.owner.equals(tree.perm.owner) 3097 && bp.uid == tree.uid 3098 && comparePermissionInfos(bp.perm.info, info)) { 3099 changed = false; 3100 } 3101 } 3102 bp.protectionLevel = fixedLevel; 3103 info = new PermissionInfo(info); 3104 info.protectionLevel = fixedLevel; 3105 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3106 bp.perm.info.packageName = tree.perm.info.packageName; 3107 bp.uid = tree.uid; 3108 if (added) { 3109 mSettings.mPermissions.put(info.name, bp); 3110 } 3111 if (changed) { 3112 if (!async) { 3113 mSettings.writeLPr(); 3114 } else { 3115 scheduleWriteSettingsLocked(); 3116 } 3117 } 3118 return added; 3119 } 3120 3121 @Override 3122 public boolean addPermission(PermissionInfo info) { 3123 synchronized (mPackages) { 3124 return addPermissionLocked(info, false); 3125 } 3126 } 3127 3128 @Override 3129 public boolean addPermissionAsync(PermissionInfo info) { 3130 synchronized (mPackages) { 3131 return addPermissionLocked(info, true); 3132 } 3133 } 3134 3135 @Override 3136 public void removePermission(String name) { 3137 synchronized (mPackages) { 3138 checkPermissionTreeLP(name); 3139 BasePermission bp = mSettings.mPermissions.get(name); 3140 if (bp != null) { 3141 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3142 throw new SecurityException( 3143 "Not allowed to modify non-dynamic permission " 3144 + name); 3145 } 3146 mSettings.mPermissions.remove(name); 3147 mSettings.writeLPr(); 3148 } 3149 } 3150 } 3151 3152 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3153 BasePermission bp) { 3154 int index = pkg.requestedPermissions.indexOf(bp.name); 3155 if (index == -1) { 3156 throw new SecurityException("Package " + pkg.packageName 3157 + " has not requested permission " + bp.name); 3158 } 3159 if (!bp.isRuntime()) { 3160 throw new SecurityException("Permission " + bp.name 3161 + " is not a changeable permission type"); 3162 } 3163 } 3164 3165 @Override 3166 public void grantRuntimePermission(String packageName, String name, final int userId) { 3167 if (!sUserManager.exists(userId)) { 3168 Log.e(TAG, "No such user:" + userId); 3169 return; 3170 } 3171 3172 mContext.enforceCallingOrSelfPermission( 3173 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3174 "grantRuntimePermission"); 3175 3176 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3177 "grantRuntimePermission"); 3178 3179 final SettingBase sb; 3180 3181 synchronized (mPackages) { 3182 final PackageParser.Package pkg = mPackages.get(packageName); 3183 if (pkg == null) { 3184 throw new IllegalArgumentException("Unknown package: " + packageName); 3185 } 3186 3187 final BasePermission bp = mSettings.mPermissions.get(name); 3188 if (bp == null) { 3189 throw new IllegalArgumentException("Unknown permission: " + name); 3190 } 3191 3192 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3193 3194 sb = (SettingBase) pkg.mExtras; 3195 if (sb == null) { 3196 throw new IllegalArgumentException("Unknown package: " + packageName); 3197 } 3198 3199 final PermissionsState permissionsState = sb.getPermissionsState(); 3200 3201 final int flags = permissionsState.getPermissionFlags(name, userId); 3202 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3203 throw new SecurityException("Cannot grant system fixed permission: " 3204 + name + " for package: " + packageName); 3205 } 3206 3207 final int result = permissionsState.grantRuntimePermission(bp, userId); 3208 switch (result) { 3209 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3210 return; 3211 } 3212 3213 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3214 mHandler.post(new Runnable() { 3215 @Override 3216 public void run() { 3217 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3218 } 3219 }); 3220 } break; 3221 } 3222 3223 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3224 3225 // Not critical if that is lost - app has to request again. 3226 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3227 } 3228 } 3229 3230 @Override 3231 public void revokeRuntimePermission(String packageName, String name, int userId) { 3232 if (!sUserManager.exists(userId)) { 3233 Log.e(TAG, "No such user:" + userId); 3234 return; 3235 } 3236 3237 mContext.enforceCallingOrSelfPermission( 3238 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3239 "revokeRuntimePermission"); 3240 3241 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3242 "revokeRuntimePermission"); 3243 3244 final SettingBase sb; 3245 3246 synchronized (mPackages) { 3247 final PackageParser.Package pkg = mPackages.get(packageName); 3248 if (pkg == null) { 3249 throw new IllegalArgumentException("Unknown package: " + packageName); 3250 } 3251 3252 final BasePermission bp = mSettings.mPermissions.get(name); 3253 if (bp == null) { 3254 throw new IllegalArgumentException("Unknown permission: " + name); 3255 } 3256 3257 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3258 3259 sb = (SettingBase) pkg.mExtras; 3260 if (sb == null) { 3261 throw new IllegalArgumentException("Unknown package: " + packageName); 3262 } 3263 3264 final PermissionsState permissionsState = sb.getPermissionsState(); 3265 3266 final int flags = permissionsState.getPermissionFlags(name, userId); 3267 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3268 throw new SecurityException("Cannot revoke system fixed permission: " 3269 + name + " for package: " + packageName); 3270 } 3271 3272 if (permissionsState.revokeRuntimePermission(bp, userId) == 3273 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3274 return; 3275 } 3276 3277 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3278 3279 // Critical, after this call app should never have the permission. 3280 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3281 } 3282 3283 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3284 } 3285 3286 @Override 3287 public int getPermissionFlags(String name, String packageName, int userId) { 3288 if (!sUserManager.exists(userId)) { 3289 return 0; 3290 } 3291 3292 mContext.enforceCallingOrSelfPermission( 3293 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3294 "getPermissionFlags"); 3295 3296 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3297 "getPermissionFlags"); 3298 3299 synchronized (mPackages) { 3300 final PackageParser.Package pkg = mPackages.get(packageName); 3301 if (pkg == null) { 3302 throw new IllegalArgumentException("Unknown package: " + packageName); 3303 } 3304 3305 final BasePermission bp = mSettings.mPermissions.get(name); 3306 if (bp == null) { 3307 throw new IllegalArgumentException("Unknown permission: " + name); 3308 } 3309 3310 SettingBase sb = (SettingBase) pkg.mExtras; 3311 if (sb == null) { 3312 throw new IllegalArgumentException("Unknown package: " + packageName); 3313 } 3314 3315 PermissionsState permissionsState = sb.getPermissionsState(); 3316 return permissionsState.getPermissionFlags(name, userId); 3317 } 3318 } 3319 3320 @Override 3321 public void updatePermissionFlags(String name, String packageName, int flagMask, 3322 int flagValues, int userId) { 3323 if (!sUserManager.exists(userId)) { 3324 return; 3325 } 3326 3327 mContext.enforceCallingOrSelfPermission( 3328 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3329 "updatePermissionFlags"); 3330 3331 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3332 "updatePermissionFlags"); 3333 3334 // Only the system can change policy and system fixed flags. 3335 if (getCallingUid() != Process.SYSTEM_UID) { 3336 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3337 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3338 3339 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3340 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3341 } 3342 3343 synchronized (mPackages) { 3344 final PackageParser.Package pkg = mPackages.get(packageName); 3345 if (pkg == null) { 3346 throw new IllegalArgumentException("Unknown package: " + packageName); 3347 } 3348 3349 final BasePermission bp = mSettings.mPermissions.get(name); 3350 if (bp == null) { 3351 throw new IllegalArgumentException("Unknown permission: " + name); 3352 } 3353 3354 SettingBase sb = (SettingBase) pkg.mExtras; 3355 if (sb == null) { 3356 throw new IllegalArgumentException("Unknown package: " + packageName); 3357 } 3358 3359 PermissionsState permissionsState = sb.getPermissionsState(); 3360 3361 // Only the package manager can change flags for system component permissions. 3362 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3363 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3364 return; 3365 } 3366 3367 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3368 // Install and runtime permissions are stored in different places, 3369 // so figure out what permission changed and persist the change. 3370 if (permissionsState.getInstallPermissionState(name) != null) { 3371 scheduleWriteSettingsLocked(); 3372 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3373 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3374 } 3375 } 3376 } 3377 } 3378 3379 @Override 3380 public boolean shouldShowRequestPermissionRationale(String permissionName, 3381 String packageName, int userId) { 3382 if (UserHandle.getCallingUserId() != userId) { 3383 mContext.enforceCallingPermission( 3384 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3385 "canShowRequestPermissionRationale for user " + userId); 3386 } 3387 3388 final int uid = getPackageUid(packageName, userId); 3389 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3390 return false; 3391 } 3392 3393 if (checkPermission(permissionName, packageName, userId) 3394 == PackageManager.PERMISSION_GRANTED) { 3395 return false; 3396 } 3397 3398 final int flags; 3399 3400 final long identity = Binder.clearCallingIdentity(); 3401 try { 3402 flags = getPermissionFlags(permissionName, 3403 packageName, userId); 3404 } finally { 3405 Binder.restoreCallingIdentity(identity); 3406 } 3407 3408 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3409 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3410 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3411 3412 if ((flags & fixedFlags) != 0) { 3413 return false; 3414 } 3415 3416 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3417 } 3418 3419 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3420 BasePermission bp = mSettings.mPermissions.get(permission); 3421 if (bp == null) { 3422 throw new SecurityException("Missing " + permission + " permission"); 3423 } 3424 3425 SettingBase sb = (SettingBase) pkg.mExtras; 3426 PermissionsState permissionsState = sb.getPermissionsState(); 3427 3428 if (permissionsState.grantInstallPermission(bp) != 3429 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3430 scheduleWriteSettingsLocked(); 3431 } 3432 } 3433 3434 @Override 3435 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3436 mContext.enforceCallingOrSelfPermission( 3437 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3438 "addOnPermissionsChangeListener"); 3439 3440 synchronized (mPackages) { 3441 mOnPermissionChangeListeners.addListenerLocked(listener); 3442 } 3443 } 3444 3445 @Override 3446 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3447 synchronized (mPackages) { 3448 mOnPermissionChangeListeners.removeListenerLocked(listener); 3449 } 3450 } 3451 3452 @Override 3453 public boolean isProtectedBroadcast(String actionName) { 3454 synchronized (mPackages) { 3455 return mProtectedBroadcasts.contains(actionName); 3456 } 3457 } 3458 3459 @Override 3460 public int checkSignatures(String pkg1, String pkg2) { 3461 synchronized (mPackages) { 3462 final PackageParser.Package p1 = mPackages.get(pkg1); 3463 final PackageParser.Package p2 = mPackages.get(pkg2); 3464 if (p1 == null || p1.mExtras == null 3465 || p2 == null || p2.mExtras == null) { 3466 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3467 } 3468 return compareSignatures(p1.mSignatures, p2.mSignatures); 3469 } 3470 } 3471 3472 @Override 3473 public int checkUidSignatures(int uid1, int uid2) { 3474 // Map to base uids. 3475 uid1 = UserHandle.getAppId(uid1); 3476 uid2 = UserHandle.getAppId(uid2); 3477 // reader 3478 synchronized (mPackages) { 3479 Signature[] s1; 3480 Signature[] s2; 3481 Object obj = mSettings.getUserIdLPr(uid1); 3482 if (obj != null) { 3483 if (obj instanceof SharedUserSetting) { 3484 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3485 } else if (obj instanceof PackageSetting) { 3486 s1 = ((PackageSetting)obj).signatures.mSignatures; 3487 } else { 3488 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3489 } 3490 } else { 3491 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3492 } 3493 obj = mSettings.getUserIdLPr(uid2); 3494 if (obj != null) { 3495 if (obj instanceof SharedUserSetting) { 3496 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3497 } else if (obj instanceof PackageSetting) { 3498 s2 = ((PackageSetting)obj).signatures.mSignatures; 3499 } else { 3500 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3501 } 3502 } else { 3503 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3504 } 3505 return compareSignatures(s1, s2); 3506 } 3507 } 3508 3509 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3510 final long identity = Binder.clearCallingIdentity(); 3511 try { 3512 if (sb instanceof SharedUserSetting) { 3513 SharedUserSetting sus = (SharedUserSetting) sb; 3514 final int packageCount = sus.packages.size(); 3515 for (int i = 0; i < packageCount; i++) { 3516 PackageSetting susPs = sus.packages.valueAt(i); 3517 if (userId == UserHandle.USER_ALL) { 3518 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3519 } else { 3520 final int uid = UserHandle.getUid(userId, susPs.appId); 3521 killUid(uid, reason); 3522 } 3523 } 3524 } else if (sb instanceof PackageSetting) { 3525 PackageSetting ps = (PackageSetting) sb; 3526 if (userId == UserHandle.USER_ALL) { 3527 killApplication(ps.pkg.packageName, ps.appId, reason); 3528 } else { 3529 final int uid = UserHandle.getUid(userId, ps.appId); 3530 killUid(uid, reason); 3531 } 3532 } 3533 } finally { 3534 Binder.restoreCallingIdentity(identity); 3535 } 3536 } 3537 3538 private static void killUid(int uid, String reason) { 3539 IActivityManager am = ActivityManagerNative.getDefault(); 3540 if (am != null) { 3541 try { 3542 am.killUid(uid, reason); 3543 } catch (RemoteException e) { 3544 /* ignore - same process */ 3545 } 3546 } 3547 } 3548 3549 /** 3550 * Compares two sets of signatures. Returns: 3551 * <br /> 3552 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3553 * <br /> 3554 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3555 * <br /> 3556 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3557 * <br /> 3558 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3559 * <br /> 3560 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3561 */ 3562 static int compareSignatures(Signature[] s1, Signature[] s2) { 3563 if (s1 == null) { 3564 return s2 == null 3565 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3566 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3567 } 3568 3569 if (s2 == null) { 3570 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3571 } 3572 3573 if (s1.length != s2.length) { 3574 return PackageManager.SIGNATURE_NO_MATCH; 3575 } 3576 3577 // Since both signature sets are of size 1, we can compare without HashSets. 3578 if (s1.length == 1) { 3579 return s1[0].equals(s2[0]) ? 3580 PackageManager.SIGNATURE_MATCH : 3581 PackageManager.SIGNATURE_NO_MATCH; 3582 } 3583 3584 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3585 for (Signature sig : s1) { 3586 set1.add(sig); 3587 } 3588 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3589 for (Signature sig : s2) { 3590 set2.add(sig); 3591 } 3592 // Make sure s2 contains all signatures in s1. 3593 if (set1.equals(set2)) { 3594 return PackageManager.SIGNATURE_MATCH; 3595 } 3596 return PackageManager.SIGNATURE_NO_MATCH; 3597 } 3598 3599 /** 3600 * If the database version for this type of package (internal storage or 3601 * external storage) is less than the version where package signatures 3602 * were updated, return true. 3603 */ 3604 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3605 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3606 DatabaseVersion.SIGNATURE_END_ENTITY)) 3607 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3608 DatabaseVersion.SIGNATURE_END_ENTITY)); 3609 } 3610 3611 /** 3612 * Used for backward compatibility to make sure any packages with 3613 * certificate chains get upgraded to the new style. {@code existingSigs} 3614 * will be in the old format (since they were stored on disk from before the 3615 * system upgrade) and {@code scannedSigs} will be in the newer format. 3616 */ 3617 private int compareSignaturesCompat(PackageSignatures existingSigs, 3618 PackageParser.Package scannedPkg) { 3619 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3620 return PackageManager.SIGNATURE_NO_MATCH; 3621 } 3622 3623 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3624 for (Signature sig : existingSigs.mSignatures) { 3625 existingSet.add(sig); 3626 } 3627 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3628 for (Signature sig : scannedPkg.mSignatures) { 3629 try { 3630 Signature[] chainSignatures = sig.getChainSignatures(); 3631 for (Signature chainSig : chainSignatures) { 3632 scannedCompatSet.add(chainSig); 3633 } 3634 } catch (CertificateEncodingException e) { 3635 scannedCompatSet.add(sig); 3636 } 3637 } 3638 /* 3639 * Make sure the expanded scanned set contains all signatures in the 3640 * existing one. 3641 */ 3642 if (scannedCompatSet.equals(existingSet)) { 3643 // Migrate the old signatures to the new scheme. 3644 existingSigs.assignSignatures(scannedPkg.mSignatures); 3645 // The new KeySets will be re-added later in the scanning process. 3646 synchronized (mPackages) { 3647 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3648 } 3649 return PackageManager.SIGNATURE_MATCH; 3650 } 3651 return PackageManager.SIGNATURE_NO_MATCH; 3652 } 3653 3654 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3655 if (isExternal(scannedPkg)) { 3656 return mSettings.isExternalDatabaseVersionOlderThan( 3657 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3658 } else { 3659 return mSettings.isInternalDatabaseVersionOlderThan( 3660 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3661 } 3662 } 3663 3664 private int compareSignaturesRecover(PackageSignatures existingSigs, 3665 PackageParser.Package scannedPkg) { 3666 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3667 return PackageManager.SIGNATURE_NO_MATCH; 3668 } 3669 3670 String msg = null; 3671 try { 3672 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3673 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3674 + scannedPkg.packageName); 3675 return PackageManager.SIGNATURE_MATCH; 3676 } 3677 } catch (CertificateException e) { 3678 msg = e.getMessage(); 3679 } 3680 3681 logCriticalInfo(Log.INFO, 3682 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3683 return PackageManager.SIGNATURE_NO_MATCH; 3684 } 3685 3686 @Override 3687 public String[] getPackagesForUid(int uid) { 3688 uid = UserHandle.getAppId(uid); 3689 // reader 3690 synchronized (mPackages) { 3691 Object obj = mSettings.getUserIdLPr(uid); 3692 if (obj instanceof SharedUserSetting) { 3693 final SharedUserSetting sus = (SharedUserSetting) obj; 3694 final int N = sus.packages.size(); 3695 final String[] res = new String[N]; 3696 final Iterator<PackageSetting> it = sus.packages.iterator(); 3697 int i = 0; 3698 while (it.hasNext()) { 3699 res[i++] = it.next().name; 3700 } 3701 return res; 3702 } else if (obj instanceof PackageSetting) { 3703 final PackageSetting ps = (PackageSetting) obj; 3704 return new String[] { ps.name }; 3705 } 3706 } 3707 return null; 3708 } 3709 3710 @Override 3711 public String getNameForUid(int uid) { 3712 // reader 3713 synchronized (mPackages) { 3714 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3715 if (obj instanceof SharedUserSetting) { 3716 final SharedUserSetting sus = (SharedUserSetting) obj; 3717 return sus.name + ":" + sus.userId; 3718 } else if (obj instanceof PackageSetting) { 3719 final PackageSetting ps = (PackageSetting) obj; 3720 return ps.name; 3721 } 3722 } 3723 return null; 3724 } 3725 3726 @Override 3727 public int getUidForSharedUser(String sharedUserName) { 3728 if(sharedUserName == null) { 3729 return -1; 3730 } 3731 // reader 3732 synchronized (mPackages) { 3733 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3734 if (suid == null) { 3735 return -1; 3736 } 3737 return suid.userId; 3738 } 3739 } 3740 3741 @Override 3742 public int getFlagsForUid(int uid) { 3743 synchronized (mPackages) { 3744 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3745 if (obj instanceof SharedUserSetting) { 3746 final SharedUserSetting sus = (SharedUserSetting) obj; 3747 return sus.pkgFlags; 3748 } else if (obj instanceof PackageSetting) { 3749 final PackageSetting ps = (PackageSetting) obj; 3750 return ps.pkgFlags; 3751 } 3752 } 3753 return 0; 3754 } 3755 3756 @Override 3757 public int getPrivateFlagsForUid(int uid) { 3758 synchronized (mPackages) { 3759 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3760 if (obj instanceof SharedUserSetting) { 3761 final SharedUserSetting sus = (SharedUserSetting) obj; 3762 return sus.pkgPrivateFlags; 3763 } else if (obj instanceof PackageSetting) { 3764 final PackageSetting ps = (PackageSetting) obj; 3765 return ps.pkgPrivateFlags; 3766 } 3767 } 3768 return 0; 3769 } 3770 3771 @Override 3772 public boolean isUidPrivileged(int uid) { 3773 uid = UserHandle.getAppId(uid); 3774 // reader 3775 synchronized (mPackages) { 3776 Object obj = mSettings.getUserIdLPr(uid); 3777 if (obj instanceof SharedUserSetting) { 3778 final SharedUserSetting sus = (SharedUserSetting) obj; 3779 final Iterator<PackageSetting> it = sus.packages.iterator(); 3780 while (it.hasNext()) { 3781 if (it.next().isPrivileged()) { 3782 return true; 3783 } 3784 } 3785 } else if (obj instanceof PackageSetting) { 3786 final PackageSetting ps = (PackageSetting) obj; 3787 return ps.isPrivileged(); 3788 } 3789 } 3790 return false; 3791 } 3792 3793 @Override 3794 public String[] getAppOpPermissionPackages(String permissionName) { 3795 synchronized (mPackages) { 3796 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3797 if (pkgs == null) { 3798 return null; 3799 } 3800 return pkgs.toArray(new String[pkgs.size()]); 3801 } 3802 } 3803 3804 @Override 3805 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3806 int flags, int userId) { 3807 if (!sUserManager.exists(userId)) return null; 3808 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3809 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3810 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3811 } 3812 3813 @Override 3814 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3815 IntentFilter filter, int match, ComponentName activity) { 3816 final int userId = UserHandle.getCallingUserId(); 3817 if (DEBUG_PREFERRED) { 3818 Log.v(TAG, "setLastChosenActivity intent=" + intent 3819 + " resolvedType=" + resolvedType 3820 + " flags=" + flags 3821 + " filter=" + filter 3822 + " match=" + match 3823 + " activity=" + activity); 3824 filter.dump(new PrintStreamPrinter(System.out), " "); 3825 } 3826 intent.setComponent(null); 3827 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3828 // Find any earlier preferred or last chosen entries and nuke them 3829 findPreferredActivity(intent, resolvedType, 3830 flags, query, 0, false, true, false, userId); 3831 // Add the new activity as the last chosen for this filter 3832 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3833 "Setting last chosen"); 3834 } 3835 3836 @Override 3837 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3838 final int userId = UserHandle.getCallingUserId(); 3839 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3840 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3841 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3842 false, false, false, userId); 3843 } 3844 3845 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3846 int flags, List<ResolveInfo> query, int userId) { 3847 if (query != null) { 3848 final int N = query.size(); 3849 if (N == 1) { 3850 return query.get(0); 3851 } else if (N > 1) { 3852 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3853 // If there is more than one activity with the same priority, 3854 // then let the user decide between them. 3855 ResolveInfo r0 = query.get(0); 3856 ResolveInfo r1 = query.get(1); 3857 if (DEBUG_INTENT_MATCHING || debug) { 3858 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3859 + r1.activityInfo.name + "=" + r1.priority); 3860 } 3861 // If the first activity has a higher priority, or a different 3862 // default, then it is always desireable to pick it. 3863 if (r0.priority != r1.priority 3864 || r0.preferredOrder != r1.preferredOrder 3865 || r0.isDefault != r1.isDefault) { 3866 return query.get(0); 3867 } 3868 // If we have saved a preference for a preferred activity for 3869 // this Intent, use that. 3870 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3871 flags, query, r0.priority, true, false, debug, userId); 3872 if (ri != null) { 3873 return ri; 3874 } 3875 if (userId != 0) { 3876 ri = new ResolveInfo(mResolveInfo); 3877 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3878 ri.activityInfo.applicationInfo = new ApplicationInfo( 3879 ri.activityInfo.applicationInfo); 3880 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3881 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3882 return ri; 3883 } 3884 return mResolveInfo; 3885 } 3886 } 3887 return null; 3888 } 3889 3890 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3891 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3892 final int N = query.size(); 3893 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3894 .get(userId); 3895 // Get the list of persistent preferred activities that handle the intent 3896 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3897 List<PersistentPreferredActivity> pprefs = ppir != null 3898 ? ppir.queryIntent(intent, resolvedType, 3899 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3900 : null; 3901 if (pprefs != null && pprefs.size() > 0) { 3902 final int M = pprefs.size(); 3903 for (int i=0; i<M; i++) { 3904 final PersistentPreferredActivity ppa = pprefs.get(i); 3905 if (DEBUG_PREFERRED || debug) { 3906 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3907 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3908 + "\n component=" + ppa.mComponent); 3909 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3910 } 3911 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3912 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3913 if (DEBUG_PREFERRED || debug) { 3914 Slog.v(TAG, "Found persistent preferred activity:"); 3915 if (ai != null) { 3916 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3917 } else { 3918 Slog.v(TAG, " null"); 3919 } 3920 } 3921 if (ai == null) { 3922 // This previously registered persistent preferred activity 3923 // component is no longer known. Ignore it and do NOT remove it. 3924 continue; 3925 } 3926 for (int j=0; j<N; j++) { 3927 final ResolveInfo ri = query.get(j); 3928 if (!ri.activityInfo.applicationInfo.packageName 3929 .equals(ai.applicationInfo.packageName)) { 3930 continue; 3931 } 3932 if (!ri.activityInfo.name.equals(ai.name)) { 3933 continue; 3934 } 3935 // Found a persistent preference that can handle the intent. 3936 if (DEBUG_PREFERRED || debug) { 3937 Slog.v(TAG, "Returning persistent preferred activity: " + 3938 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3939 } 3940 return ri; 3941 } 3942 } 3943 } 3944 return null; 3945 } 3946 3947 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3948 List<ResolveInfo> query, int priority, boolean always, 3949 boolean removeMatches, boolean debug, int userId) { 3950 if (!sUserManager.exists(userId)) return null; 3951 // writer 3952 synchronized (mPackages) { 3953 if (intent.getSelector() != null) { 3954 intent = intent.getSelector(); 3955 } 3956 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3957 3958 // Try to find a matching persistent preferred activity. 3959 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3960 debug, userId); 3961 3962 // If a persistent preferred activity matched, use it. 3963 if (pri != null) { 3964 return pri; 3965 } 3966 3967 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3968 // Get the list of preferred activities that handle the intent 3969 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3970 List<PreferredActivity> prefs = pir != null 3971 ? pir.queryIntent(intent, resolvedType, 3972 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3973 : null; 3974 if (prefs != null && prefs.size() > 0) { 3975 boolean changed = false; 3976 try { 3977 // First figure out how good the original match set is. 3978 // We will only allow preferred activities that came 3979 // from the same match quality. 3980 int match = 0; 3981 3982 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3983 3984 final int N = query.size(); 3985 for (int j=0; j<N; j++) { 3986 final ResolveInfo ri = query.get(j); 3987 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3988 + ": 0x" + Integer.toHexString(match)); 3989 if (ri.match > match) { 3990 match = ri.match; 3991 } 3992 } 3993 3994 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3995 + Integer.toHexString(match)); 3996 3997 match &= IntentFilter.MATCH_CATEGORY_MASK; 3998 final int M = prefs.size(); 3999 for (int i=0; i<M; i++) { 4000 final PreferredActivity pa = prefs.get(i); 4001 if (DEBUG_PREFERRED || debug) { 4002 Slog.v(TAG, "Checking PreferredActivity ds=" 4003 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4004 + "\n component=" + pa.mPref.mComponent); 4005 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4006 } 4007 if (pa.mPref.mMatch != match) { 4008 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4009 + Integer.toHexString(pa.mPref.mMatch)); 4010 continue; 4011 } 4012 // If it's not an "always" type preferred activity and that's what we're 4013 // looking for, skip it. 4014 if (always && !pa.mPref.mAlways) { 4015 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4016 continue; 4017 } 4018 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4019 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4020 if (DEBUG_PREFERRED || debug) { 4021 Slog.v(TAG, "Found preferred activity:"); 4022 if (ai != null) { 4023 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4024 } else { 4025 Slog.v(TAG, " null"); 4026 } 4027 } 4028 if (ai == null) { 4029 // This previously registered preferred activity 4030 // component is no longer known. Most likely an update 4031 // to the app was installed and in the new version this 4032 // component no longer exists. Clean it up by removing 4033 // it from the preferred activities list, and skip it. 4034 Slog.w(TAG, "Removing dangling preferred activity: " 4035 + pa.mPref.mComponent); 4036 pir.removeFilter(pa); 4037 changed = true; 4038 continue; 4039 } 4040 for (int j=0; j<N; j++) { 4041 final ResolveInfo ri = query.get(j); 4042 if (!ri.activityInfo.applicationInfo.packageName 4043 .equals(ai.applicationInfo.packageName)) { 4044 continue; 4045 } 4046 if (!ri.activityInfo.name.equals(ai.name)) { 4047 continue; 4048 } 4049 4050 if (removeMatches) { 4051 pir.removeFilter(pa); 4052 changed = true; 4053 if (DEBUG_PREFERRED) { 4054 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4055 } 4056 break; 4057 } 4058 4059 // Okay we found a previously set preferred or last chosen app. 4060 // If the result set is different from when this 4061 // was created, we need to clear it and re-ask the 4062 // user their preference, if we're looking for an "always" type entry. 4063 if (always && !pa.mPref.sameSet(query)) { 4064 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4065 + intent + " type " + resolvedType); 4066 if (DEBUG_PREFERRED) { 4067 Slog.v(TAG, "Removing preferred activity since set changed " 4068 + pa.mPref.mComponent); 4069 } 4070 pir.removeFilter(pa); 4071 // Re-add the filter as a "last chosen" entry (!always) 4072 PreferredActivity lastChosen = new PreferredActivity( 4073 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4074 pir.addFilter(lastChosen); 4075 changed = true; 4076 return null; 4077 } 4078 4079 // Yay! Either the set matched or we're looking for the last chosen 4080 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4081 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4082 return ri; 4083 } 4084 } 4085 } finally { 4086 if (changed) { 4087 if (DEBUG_PREFERRED) { 4088 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4089 } 4090 scheduleWritePackageRestrictionsLocked(userId); 4091 } 4092 } 4093 } 4094 } 4095 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4096 return null; 4097 } 4098 4099 /* 4100 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4101 */ 4102 @Override 4103 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4104 int targetUserId) { 4105 mContext.enforceCallingOrSelfPermission( 4106 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4107 List<CrossProfileIntentFilter> matches = 4108 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4109 if (matches != null) { 4110 int size = matches.size(); 4111 for (int i = 0; i < size; i++) { 4112 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4113 } 4114 } 4115 return false; 4116 } 4117 4118 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4119 String resolvedType, int userId) { 4120 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4121 if (resolver != null) { 4122 return resolver.queryIntent(intent, resolvedType, false, userId); 4123 } 4124 return null; 4125 } 4126 4127 @Override 4128 public List<ResolveInfo> queryIntentActivities(Intent intent, 4129 String resolvedType, int flags, int userId) { 4130 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4131 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4132 ComponentName comp = intent.getComponent(); 4133 if (comp == null) { 4134 if (intent.getSelector() != null) { 4135 intent = intent.getSelector(); 4136 comp = intent.getComponent(); 4137 } 4138 } 4139 4140 if (comp != null) { 4141 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4142 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4143 if (ai != null) { 4144 final ResolveInfo ri = new ResolveInfo(); 4145 ri.activityInfo = ai; 4146 list.add(ri); 4147 } 4148 return list; 4149 } 4150 4151 // reader 4152 synchronized (mPackages) { 4153 final String pkgName = intent.getPackage(); 4154 if (pkgName == null) { 4155 List<CrossProfileIntentFilter> matchingFilters = 4156 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4157 // Check for results that need to skip the current profile. 4158 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4159 resolvedType, flags, userId); 4160 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4161 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4162 result.add(resolveInfo); 4163 return filterIfNotPrimaryUser(result, userId); 4164 } 4165 4166 // Check for results in the current profile. 4167 List<ResolveInfo> result = mActivities.queryIntent( 4168 intent, resolvedType, flags, userId); 4169 4170 // Check for cross profile results. 4171 resolveInfo = queryCrossProfileIntents( 4172 matchingFilters, intent, resolvedType, flags, userId); 4173 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4174 result.add(resolveInfo); 4175 Collections.sort(result, mResolvePrioritySorter); 4176 } 4177 result = filterIfNotPrimaryUser(result, userId); 4178 if (result.size() > 1 && hasWebURI(intent)) { 4179 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4180 } 4181 return result; 4182 } 4183 final PackageParser.Package pkg = mPackages.get(pkgName); 4184 if (pkg != null) { 4185 return filterIfNotPrimaryUser( 4186 mActivities.queryIntentForPackage( 4187 intent, resolvedType, flags, pkg.activities, userId), 4188 userId); 4189 } 4190 return new ArrayList<ResolveInfo>(); 4191 } 4192 } 4193 4194 private boolean isUserEnabled(int userId) { 4195 long callingId = Binder.clearCallingIdentity(); 4196 try { 4197 UserInfo userInfo = sUserManager.getUserInfo(userId); 4198 return userInfo != null && userInfo.isEnabled(); 4199 } finally { 4200 Binder.restoreCallingIdentity(callingId); 4201 } 4202 } 4203 4204 /** 4205 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4206 * 4207 * @return filtered list 4208 */ 4209 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4210 if (userId == UserHandle.USER_OWNER) { 4211 return resolveInfos; 4212 } 4213 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4214 ResolveInfo info = resolveInfos.get(i); 4215 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4216 resolveInfos.remove(i); 4217 } 4218 } 4219 return resolveInfos; 4220 } 4221 4222 private static boolean hasWebURI(Intent intent) { 4223 if (intent.getData() == null) { 4224 return false; 4225 } 4226 final String scheme = intent.getScheme(); 4227 if (TextUtils.isEmpty(scheme)) { 4228 return false; 4229 } 4230 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4231 } 4232 4233 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4234 int flags, List<ResolveInfo> candidates) { 4235 if (DEBUG_PREFERRED) { 4236 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4237 candidates.size()); 4238 } 4239 4240 final int userId = UserHandle.getCallingUserId(); 4241 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4242 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4243 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4244 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4245 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4246 4247 synchronized (mPackages) { 4248 final int count = candidates.size(); 4249 // First, try to use the domain prefered App. Partition the candidates into four lists: 4250 // one for the final results, one for the "do not use ever", one for "undefined status" 4251 // and finally one for "Browser App type". 4252 for (int n=0; n<count; n++) { 4253 ResolveInfo info = candidates.get(n); 4254 String packageName = info.activityInfo.packageName; 4255 PackageSetting ps = mSettings.mPackages.get(packageName); 4256 if (ps != null) { 4257 // Add to the special match all list (Browser use case) 4258 if (info.handleAllWebDataURI) { 4259 matchAllList.add(info); 4260 continue; 4261 } 4262 // Try to get the status from User settings first 4263 int status = getDomainVerificationStatusLPr(ps, userId); 4264 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4265 alwaysList.add(info); 4266 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4267 neverList.add(info); 4268 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4269 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4270 undefinedList.add(info); 4271 } 4272 } 4273 } 4274 // First try to add the "always" if there is any 4275 if (alwaysList.size() > 0) { 4276 result.addAll(alwaysList); 4277 } else { 4278 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4279 result.addAll(undefinedList); 4280 // Also add Browsers (all of them or only the default one) 4281 if ((flags & MATCH_ALL) != 0) { 4282 result.addAll(matchAllList); 4283 } else { 4284 // Try to add the Default Browser if we can 4285 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4286 UserHandle.myUserId()); 4287 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4288 boolean defaultBrowserFound = false; 4289 final int browserCount = matchAllList.size(); 4290 for (int n=0; n<browserCount; n++) { 4291 ResolveInfo browser = matchAllList.get(n); 4292 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4293 result.add(browser); 4294 defaultBrowserFound = true; 4295 break; 4296 } 4297 } 4298 if (!defaultBrowserFound) { 4299 result.addAll(matchAllList); 4300 } 4301 } else { 4302 result.addAll(matchAllList); 4303 } 4304 } 4305 4306 // If there is nothing selected, add all candidates and remove the ones that the User 4307 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4308 if (result.size() == 0) { 4309 result.addAll(candidates); 4310 result.removeAll(neverList); 4311 } 4312 } 4313 } 4314 if (DEBUG_PREFERRED) { 4315 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4316 result.size()); 4317 } 4318 return result; 4319 } 4320 4321 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4322 int status = ps.getDomainVerificationStatusForUser(userId); 4323 // if none available, get the master status 4324 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4325 if (ps.getIntentFilterVerificationInfo() != null) { 4326 status = ps.getIntentFilterVerificationInfo().getStatus(); 4327 } 4328 } 4329 return status; 4330 } 4331 4332 private ResolveInfo querySkipCurrentProfileIntents( 4333 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4334 int flags, int sourceUserId) { 4335 if (matchingFilters != null) { 4336 int size = matchingFilters.size(); 4337 for (int i = 0; i < size; i ++) { 4338 CrossProfileIntentFilter filter = matchingFilters.get(i); 4339 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4340 // Checking if there are activities in the target user that can handle the 4341 // intent. 4342 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4343 flags, sourceUserId); 4344 if (resolveInfo != null) { 4345 return resolveInfo; 4346 } 4347 } 4348 } 4349 } 4350 return null; 4351 } 4352 4353 // Return matching ResolveInfo if any for skip current profile intent filters. 4354 private ResolveInfo queryCrossProfileIntents( 4355 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4356 int flags, int sourceUserId) { 4357 if (matchingFilters != null) { 4358 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4359 // match the same intent. For performance reasons, it is better not to 4360 // run queryIntent twice for the same userId 4361 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4362 int size = matchingFilters.size(); 4363 for (int i = 0; i < size; i++) { 4364 CrossProfileIntentFilter filter = matchingFilters.get(i); 4365 int targetUserId = filter.getTargetUserId(); 4366 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4367 && !alreadyTriedUserIds.get(targetUserId)) { 4368 // Checking if there are activities in the target user that can handle the 4369 // intent. 4370 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4371 flags, sourceUserId); 4372 if (resolveInfo != null) return resolveInfo; 4373 alreadyTriedUserIds.put(targetUserId, true); 4374 } 4375 } 4376 } 4377 return null; 4378 } 4379 4380 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4381 String resolvedType, int flags, int sourceUserId) { 4382 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4383 resolvedType, flags, filter.getTargetUserId()); 4384 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4385 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4386 } 4387 return null; 4388 } 4389 4390 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4391 int sourceUserId, int targetUserId) { 4392 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4393 String className; 4394 if (targetUserId == UserHandle.USER_OWNER) { 4395 className = FORWARD_INTENT_TO_USER_OWNER; 4396 } else { 4397 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4398 } 4399 ComponentName forwardingActivityComponentName = new ComponentName( 4400 mAndroidApplication.packageName, className); 4401 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4402 sourceUserId); 4403 if (targetUserId == UserHandle.USER_OWNER) { 4404 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4405 forwardingResolveInfo.noResourceId = true; 4406 } 4407 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4408 forwardingResolveInfo.priority = 0; 4409 forwardingResolveInfo.preferredOrder = 0; 4410 forwardingResolveInfo.match = 0; 4411 forwardingResolveInfo.isDefault = true; 4412 forwardingResolveInfo.filter = filter; 4413 forwardingResolveInfo.targetUserId = targetUserId; 4414 return forwardingResolveInfo; 4415 } 4416 4417 @Override 4418 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4419 Intent[] specifics, String[] specificTypes, Intent intent, 4420 String resolvedType, int flags, int userId) { 4421 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4422 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4423 false, "query intent activity options"); 4424 final String resultsAction = intent.getAction(); 4425 4426 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4427 | PackageManager.GET_RESOLVED_FILTER, userId); 4428 4429 if (DEBUG_INTENT_MATCHING) { 4430 Log.v(TAG, "Query " + intent + ": " + results); 4431 } 4432 4433 int specificsPos = 0; 4434 int N; 4435 4436 // todo: note that the algorithm used here is O(N^2). This 4437 // isn't a problem in our current environment, but if we start running 4438 // into situations where we have more than 5 or 10 matches then this 4439 // should probably be changed to something smarter... 4440 4441 // First we go through and resolve each of the specific items 4442 // that were supplied, taking care of removing any corresponding 4443 // duplicate items in the generic resolve list. 4444 if (specifics != null) { 4445 for (int i=0; i<specifics.length; i++) { 4446 final Intent sintent = specifics[i]; 4447 if (sintent == null) { 4448 continue; 4449 } 4450 4451 if (DEBUG_INTENT_MATCHING) { 4452 Log.v(TAG, "Specific #" + i + ": " + sintent); 4453 } 4454 4455 String action = sintent.getAction(); 4456 if (resultsAction != null && resultsAction.equals(action)) { 4457 // If this action was explicitly requested, then don't 4458 // remove things that have it. 4459 action = null; 4460 } 4461 4462 ResolveInfo ri = null; 4463 ActivityInfo ai = null; 4464 4465 ComponentName comp = sintent.getComponent(); 4466 if (comp == null) { 4467 ri = resolveIntent( 4468 sintent, 4469 specificTypes != null ? specificTypes[i] : null, 4470 flags, userId); 4471 if (ri == null) { 4472 continue; 4473 } 4474 if (ri == mResolveInfo) { 4475 // ACK! Must do something better with this. 4476 } 4477 ai = ri.activityInfo; 4478 comp = new ComponentName(ai.applicationInfo.packageName, 4479 ai.name); 4480 } else { 4481 ai = getActivityInfo(comp, flags, userId); 4482 if (ai == null) { 4483 continue; 4484 } 4485 } 4486 4487 // Look for any generic query activities that are duplicates 4488 // of this specific one, and remove them from the results. 4489 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4490 N = results.size(); 4491 int j; 4492 for (j=specificsPos; j<N; j++) { 4493 ResolveInfo sri = results.get(j); 4494 if ((sri.activityInfo.name.equals(comp.getClassName()) 4495 && sri.activityInfo.applicationInfo.packageName.equals( 4496 comp.getPackageName())) 4497 || (action != null && sri.filter.matchAction(action))) { 4498 results.remove(j); 4499 if (DEBUG_INTENT_MATCHING) Log.v( 4500 TAG, "Removing duplicate item from " + j 4501 + " due to specific " + specificsPos); 4502 if (ri == null) { 4503 ri = sri; 4504 } 4505 j--; 4506 N--; 4507 } 4508 } 4509 4510 // Add this specific item to its proper place. 4511 if (ri == null) { 4512 ri = new ResolveInfo(); 4513 ri.activityInfo = ai; 4514 } 4515 results.add(specificsPos, ri); 4516 ri.specificIndex = i; 4517 specificsPos++; 4518 } 4519 } 4520 4521 // Now we go through the remaining generic results and remove any 4522 // duplicate actions that are found here. 4523 N = results.size(); 4524 for (int i=specificsPos; i<N-1; i++) { 4525 final ResolveInfo rii = results.get(i); 4526 if (rii.filter == null) { 4527 continue; 4528 } 4529 4530 // Iterate over all of the actions of this result's intent 4531 // filter... typically this should be just one. 4532 final Iterator<String> it = rii.filter.actionsIterator(); 4533 if (it == null) { 4534 continue; 4535 } 4536 while (it.hasNext()) { 4537 final String action = it.next(); 4538 if (resultsAction != null && resultsAction.equals(action)) { 4539 // If this action was explicitly requested, then don't 4540 // remove things that have it. 4541 continue; 4542 } 4543 for (int j=i+1; j<N; j++) { 4544 final ResolveInfo rij = results.get(j); 4545 if (rij.filter != null && rij.filter.hasAction(action)) { 4546 results.remove(j); 4547 if (DEBUG_INTENT_MATCHING) Log.v( 4548 TAG, "Removing duplicate item from " + j 4549 + " due to action " + action + " at " + i); 4550 j--; 4551 N--; 4552 } 4553 } 4554 } 4555 4556 // If the caller didn't request filter information, drop it now 4557 // so we don't have to marshall/unmarshall it. 4558 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4559 rii.filter = null; 4560 } 4561 } 4562 4563 // Filter out the caller activity if so requested. 4564 if (caller != null) { 4565 N = results.size(); 4566 for (int i=0; i<N; i++) { 4567 ActivityInfo ainfo = results.get(i).activityInfo; 4568 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4569 && caller.getClassName().equals(ainfo.name)) { 4570 results.remove(i); 4571 break; 4572 } 4573 } 4574 } 4575 4576 // If the caller didn't request filter information, 4577 // drop them now so we don't have to 4578 // marshall/unmarshall it. 4579 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4580 N = results.size(); 4581 for (int i=0; i<N; i++) { 4582 results.get(i).filter = null; 4583 } 4584 } 4585 4586 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4587 return results; 4588 } 4589 4590 @Override 4591 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4592 int userId) { 4593 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4594 ComponentName comp = intent.getComponent(); 4595 if (comp == null) { 4596 if (intent.getSelector() != null) { 4597 intent = intent.getSelector(); 4598 comp = intent.getComponent(); 4599 } 4600 } 4601 if (comp != null) { 4602 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4603 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4604 if (ai != null) { 4605 ResolveInfo ri = new ResolveInfo(); 4606 ri.activityInfo = ai; 4607 list.add(ri); 4608 } 4609 return list; 4610 } 4611 4612 // reader 4613 synchronized (mPackages) { 4614 String pkgName = intent.getPackage(); 4615 if (pkgName == null) { 4616 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4617 } 4618 final PackageParser.Package pkg = mPackages.get(pkgName); 4619 if (pkg != null) { 4620 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4621 userId); 4622 } 4623 return null; 4624 } 4625 } 4626 4627 @Override 4628 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4629 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4630 if (!sUserManager.exists(userId)) return null; 4631 if (query != null) { 4632 if (query.size() >= 1) { 4633 // If there is more than one service with the same priority, 4634 // just arbitrarily pick the first one. 4635 return query.get(0); 4636 } 4637 } 4638 return null; 4639 } 4640 4641 @Override 4642 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4643 int userId) { 4644 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4645 ComponentName comp = intent.getComponent(); 4646 if (comp == null) { 4647 if (intent.getSelector() != null) { 4648 intent = intent.getSelector(); 4649 comp = intent.getComponent(); 4650 } 4651 } 4652 if (comp != null) { 4653 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4654 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4655 if (si != null) { 4656 final ResolveInfo ri = new ResolveInfo(); 4657 ri.serviceInfo = si; 4658 list.add(ri); 4659 } 4660 return list; 4661 } 4662 4663 // reader 4664 synchronized (mPackages) { 4665 String pkgName = intent.getPackage(); 4666 if (pkgName == null) { 4667 return mServices.queryIntent(intent, resolvedType, flags, userId); 4668 } 4669 final PackageParser.Package pkg = mPackages.get(pkgName); 4670 if (pkg != null) { 4671 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4672 userId); 4673 } 4674 return null; 4675 } 4676 } 4677 4678 @Override 4679 public List<ResolveInfo> queryIntentContentProviders( 4680 Intent intent, String resolvedType, int flags, int userId) { 4681 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4682 ComponentName comp = intent.getComponent(); 4683 if (comp == null) { 4684 if (intent.getSelector() != null) { 4685 intent = intent.getSelector(); 4686 comp = intent.getComponent(); 4687 } 4688 } 4689 if (comp != null) { 4690 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4691 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4692 if (pi != null) { 4693 final ResolveInfo ri = new ResolveInfo(); 4694 ri.providerInfo = pi; 4695 list.add(ri); 4696 } 4697 return list; 4698 } 4699 4700 // reader 4701 synchronized (mPackages) { 4702 String pkgName = intent.getPackage(); 4703 if (pkgName == null) { 4704 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4705 } 4706 final PackageParser.Package pkg = mPackages.get(pkgName); 4707 if (pkg != null) { 4708 return mProviders.queryIntentForPackage( 4709 intent, resolvedType, flags, pkg.providers, userId); 4710 } 4711 return null; 4712 } 4713 } 4714 4715 @Override 4716 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4717 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4718 4719 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4720 4721 // writer 4722 synchronized (mPackages) { 4723 ArrayList<PackageInfo> list; 4724 if (listUninstalled) { 4725 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4726 for (PackageSetting ps : mSettings.mPackages.values()) { 4727 PackageInfo pi; 4728 if (ps.pkg != null) { 4729 pi = generatePackageInfo(ps.pkg, flags, userId); 4730 } else { 4731 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4732 } 4733 if (pi != null) { 4734 list.add(pi); 4735 } 4736 } 4737 } else { 4738 list = new ArrayList<PackageInfo>(mPackages.size()); 4739 for (PackageParser.Package p : mPackages.values()) { 4740 PackageInfo pi = generatePackageInfo(p, flags, userId); 4741 if (pi != null) { 4742 list.add(pi); 4743 } 4744 } 4745 } 4746 4747 return new ParceledListSlice<PackageInfo>(list); 4748 } 4749 } 4750 4751 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4752 String[] permissions, boolean[] tmp, int flags, int userId) { 4753 int numMatch = 0; 4754 final PermissionsState permissionsState = ps.getPermissionsState(); 4755 for (int i=0; i<permissions.length; i++) { 4756 final String permission = permissions[i]; 4757 if (permissionsState.hasPermission(permission, userId)) { 4758 tmp[i] = true; 4759 numMatch++; 4760 } else { 4761 tmp[i] = false; 4762 } 4763 } 4764 if (numMatch == 0) { 4765 return; 4766 } 4767 PackageInfo pi; 4768 if (ps.pkg != null) { 4769 pi = generatePackageInfo(ps.pkg, flags, userId); 4770 } else { 4771 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4772 } 4773 // The above might return null in cases of uninstalled apps or install-state 4774 // skew across users/profiles. 4775 if (pi != null) { 4776 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4777 if (numMatch == permissions.length) { 4778 pi.requestedPermissions = permissions; 4779 } else { 4780 pi.requestedPermissions = new String[numMatch]; 4781 numMatch = 0; 4782 for (int i=0; i<permissions.length; i++) { 4783 if (tmp[i]) { 4784 pi.requestedPermissions[numMatch] = permissions[i]; 4785 numMatch++; 4786 } 4787 } 4788 } 4789 } 4790 list.add(pi); 4791 } 4792 } 4793 4794 @Override 4795 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4796 String[] permissions, int flags, int userId) { 4797 if (!sUserManager.exists(userId)) return null; 4798 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4799 4800 // writer 4801 synchronized (mPackages) { 4802 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4803 boolean[] tmpBools = new boolean[permissions.length]; 4804 if (listUninstalled) { 4805 for (PackageSetting ps : mSettings.mPackages.values()) { 4806 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4807 } 4808 } else { 4809 for (PackageParser.Package pkg : mPackages.values()) { 4810 PackageSetting ps = (PackageSetting)pkg.mExtras; 4811 if (ps != null) { 4812 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4813 userId); 4814 } 4815 } 4816 } 4817 4818 return new ParceledListSlice<PackageInfo>(list); 4819 } 4820 } 4821 4822 @Override 4823 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4824 if (!sUserManager.exists(userId)) return null; 4825 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4826 4827 // writer 4828 synchronized (mPackages) { 4829 ArrayList<ApplicationInfo> list; 4830 if (listUninstalled) { 4831 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4832 for (PackageSetting ps : mSettings.mPackages.values()) { 4833 ApplicationInfo ai; 4834 if (ps.pkg != null) { 4835 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4836 ps.readUserState(userId), userId); 4837 } else { 4838 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4839 } 4840 if (ai != null) { 4841 list.add(ai); 4842 } 4843 } 4844 } else { 4845 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4846 for (PackageParser.Package p : mPackages.values()) { 4847 if (p.mExtras != null) { 4848 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4849 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4850 if (ai != null) { 4851 list.add(ai); 4852 } 4853 } 4854 } 4855 } 4856 4857 return new ParceledListSlice<ApplicationInfo>(list); 4858 } 4859 } 4860 4861 public List<ApplicationInfo> getPersistentApplications(int flags) { 4862 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4863 4864 // reader 4865 synchronized (mPackages) { 4866 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4867 final int userId = UserHandle.getCallingUserId(); 4868 while (i.hasNext()) { 4869 final PackageParser.Package p = i.next(); 4870 if (p.applicationInfo != null 4871 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4872 && (!mSafeMode || isSystemApp(p))) { 4873 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4874 if (ps != null) { 4875 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4876 ps.readUserState(userId), userId); 4877 if (ai != null) { 4878 finalList.add(ai); 4879 } 4880 } 4881 } 4882 } 4883 } 4884 4885 return finalList; 4886 } 4887 4888 @Override 4889 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4890 if (!sUserManager.exists(userId)) return null; 4891 // reader 4892 synchronized (mPackages) { 4893 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4894 PackageSetting ps = provider != null 4895 ? mSettings.mPackages.get(provider.owner.packageName) 4896 : null; 4897 return ps != null 4898 && mSettings.isEnabledLPr(provider.info, flags, userId) 4899 && (!mSafeMode || (provider.info.applicationInfo.flags 4900 &ApplicationInfo.FLAG_SYSTEM) != 0) 4901 ? PackageParser.generateProviderInfo(provider, flags, 4902 ps.readUserState(userId), userId) 4903 : null; 4904 } 4905 } 4906 4907 /** 4908 * @deprecated 4909 */ 4910 @Deprecated 4911 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4912 // reader 4913 synchronized (mPackages) { 4914 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4915 .entrySet().iterator(); 4916 final int userId = UserHandle.getCallingUserId(); 4917 while (i.hasNext()) { 4918 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4919 PackageParser.Provider p = entry.getValue(); 4920 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4921 4922 if (ps != null && p.syncable 4923 && (!mSafeMode || (p.info.applicationInfo.flags 4924 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4925 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4926 ps.readUserState(userId), userId); 4927 if (info != null) { 4928 outNames.add(entry.getKey()); 4929 outInfo.add(info); 4930 } 4931 } 4932 } 4933 } 4934 } 4935 4936 @Override 4937 public List<ProviderInfo> queryContentProviders(String processName, 4938 int uid, int flags) { 4939 ArrayList<ProviderInfo> finalList = null; 4940 // reader 4941 synchronized (mPackages) { 4942 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4943 final int userId = processName != null ? 4944 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4945 while (i.hasNext()) { 4946 final PackageParser.Provider p = i.next(); 4947 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4948 if (ps != null && p.info.authority != null 4949 && (processName == null 4950 || (p.info.processName.equals(processName) 4951 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4952 && mSettings.isEnabledLPr(p.info, flags, userId) 4953 && (!mSafeMode 4954 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4955 if (finalList == null) { 4956 finalList = new ArrayList<ProviderInfo>(3); 4957 } 4958 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4959 ps.readUserState(userId), userId); 4960 if (info != null) { 4961 finalList.add(info); 4962 } 4963 } 4964 } 4965 } 4966 4967 if (finalList != null) { 4968 Collections.sort(finalList, mProviderInitOrderSorter); 4969 } 4970 4971 return finalList; 4972 } 4973 4974 @Override 4975 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4976 int flags) { 4977 // reader 4978 synchronized (mPackages) { 4979 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4980 return PackageParser.generateInstrumentationInfo(i, flags); 4981 } 4982 } 4983 4984 @Override 4985 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4986 int flags) { 4987 ArrayList<InstrumentationInfo> finalList = 4988 new ArrayList<InstrumentationInfo>(); 4989 4990 // reader 4991 synchronized (mPackages) { 4992 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4993 while (i.hasNext()) { 4994 final PackageParser.Instrumentation p = i.next(); 4995 if (targetPackage == null 4996 || targetPackage.equals(p.info.targetPackage)) { 4997 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4998 flags); 4999 if (ii != null) { 5000 finalList.add(ii); 5001 } 5002 } 5003 } 5004 } 5005 5006 return finalList; 5007 } 5008 5009 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5010 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5011 if (overlays == null) { 5012 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5013 return; 5014 } 5015 for (PackageParser.Package opkg : overlays.values()) { 5016 // Not much to do if idmap fails: we already logged the error 5017 // and we certainly don't want to abort installation of pkg simply 5018 // because an overlay didn't fit properly. For these reasons, 5019 // ignore the return value of createIdmapForPackagePairLI. 5020 createIdmapForPackagePairLI(pkg, opkg); 5021 } 5022 } 5023 5024 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5025 PackageParser.Package opkg) { 5026 if (!opkg.mTrustedOverlay) { 5027 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5028 opkg.baseCodePath + ": overlay not trusted"); 5029 return false; 5030 } 5031 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5032 if (overlaySet == null) { 5033 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5034 opkg.baseCodePath + " but target package has no known overlays"); 5035 return false; 5036 } 5037 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5038 // TODO: generate idmap for split APKs 5039 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5040 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5041 + opkg.baseCodePath); 5042 return false; 5043 } 5044 PackageParser.Package[] overlayArray = 5045 overlaySet.values().toArray(new PackageParser.Package[0]); 5046 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5047 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5048 return p1.mOverlayPriority - p2.mOverlayPriority; 5049 } 5050 }; 5051 Arrays.sort(overlayArray, cmp); 5052 5053 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5054 int i = 0; 5055 for (PackageParser.Package p : overlayArray) { 5056 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5057 } 5058 return true; 5059 } 5060 5061 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5062 final File[] files = dir.listFiles(); 5063 if (ArrayUtils.isEmpty(files)) { 5064 Log.d(TAG, "No files in app dir " + dir); 5065 return; 5066 } 5067 5068 if (DEBUG_PACKAGE_SCANNING) { 5069 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5070 + " flags=0x" + Integer.toHexString(parseFlags)); 5071 } 5072 5073 for (File file : files) { 5074 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5075 && !PackageInstallerService.isStageName(file.getName()); 5076 if (!isPackage) { 5077 // Ignore entries which are not packages 5078 continue; 5079 } 5080 try { 5081 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5082 scanFlags, currentTime, null); 5083 } catch (PackageManagerException e) { 5084 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5085 5086 // Delete invalid userdata apps 5087 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5088 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5089 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5090 if (file.isDirectory()) { 5091 mInstaller.rmPackageDir(file.getAbsolutePath()); 5092 } else { 5093 file.delete(); 5094 } 5095 } 5096 } 5097 } 5098 } 5099 5100 private static File getSettingsProblemFile() { 5101 File dataDir = Environment.getDataDirectory(); 5102 File systemDir = new File(dataDir, "system"); 5103 File fname = new File(systemDir, "uiderrors.txt"); 5104 return fname; 5105 } 5106 5107 static void reportSettingsProblem(int priority, String msg) { 5108 logCriticalInfo(priority, msg); 5109 } 5110 5111 static void logCriticalInfo(int priority, String msg) { 5112 Slog.println(priority, TAG, msg); 5113 EventLogTags.writePmCriticalInfo(msg); 5114 try { 5115 File fname = getSettingsProblemFile(); 5116 FileOutputStream out = new FileOutputStream(fname, true); 5117 PrintWriter pw = new FastPrintWriter(out); 5118 SimpleDateFormat formatter = new SimpleDateFormat(); 5119 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5120 pw.println(dateString + ": " + msg); 5121 pw.close(); 5122 FileUtils.setPermissions( 5123 fname.toString(), 5124 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5125 -1, -1); 5126 } catch (java.io.IOException e) { 5127 } 5128 } 5129 5130 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5131 PackageParser.Package pkg, File srcFile, int parseFlags) 5132 throws PackageManagerException { 5133 if (ps != null 5134 && ps.codePath.equals(srcFile) 5135 && ps.timeStamp == srcFile.lastModified() 5136 && !isCompatSignatureUpdateNeeded(pkg) 5137 && !isRecoverSignatureUpdateNeeded(pkg)) { 5138 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5139 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5140 ArraySet<PublicKey> signingKs; 5141 synchronized (mPackages) { 5142 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5143 } 5144 if (ps.signatures.mSignatures != null 5145 && ps.signatures.mSignatures.length != 0 5146 && signingKs != null) { 5147 // Optimization: reuse the existing cached certificates 5148 // if the package appears to be unchanged. 5149 pkg.mSignatures = ps.signatures.mSignatures; 5150 pkg.mSigningKeys = signingKs; 5151 return; 5152 } 5153 5154 Slog.w(TAG, "PackageSetting for " + ps.name 5155 + " is missing signatures. Collecting certs again to recover them."); 5156 } else { 5157 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5158 } 5159 5160 try { 5161 pp.collectCertificates(pkg, parseFlags); 5162 pp.collectManifestDigest(pkg); 5163 } catch (PackageParserException e) { 5164 throw PackageManagerException.from(e); 5165 } 5166 } 5167 5168 /* 5169 * Scan a package and return the newly parsed package. 5170 * Returns null in case of errors and the error code is stored in mLastScanError 5171 */ 5172 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5173 long currentTime, UserHandle user) throws PackageManagerException { 5174 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5175 parseFlags |= mDefParseFlags; 5176 PackageParser pp = new PackageParser(); 5177 pp.setSeparateProcesses(mSeparateProcesses); 5178 pp.setOnlyCoreApps(mOnlyCore); 5179 pp.setDisplayMetrics(mMetrics); 5180 5181 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5182 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5183 } 5184 5185 final PackageParser.Package pkg; 5186 try { 5187 pkg = pp.parsePackage(scanFile, parseFlags); 5188 } catch (PackageParserException e) { 5189 throw PackageManagerException.from(e); 5190 } 5191 5192 PackageSetting ps = null; 5193 PackageSetting updatedPkg; 5194 // reader 5195 synchronized (mPackages) { 5196 // Look to see if we already know about this package. 5197 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5198 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5199 // This package has been renamed to its original name. Let's 5200 // use that. 5201 ps = mSettings.peekPackageLPr(oldName); 5202 } 5203 // If there was no original package, see one for the real package name. 5204 if (ps == null) { 5205 ps = mSettings.peekPackageLPr(pkg.packageName); 5206 } 5207 // Check to see if this package could be hiding/updating a system 5208 // package. Must look for it either under the original or real 5209 // package name depending on our state. 5210 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5211 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5212 } 5213 boolean updatedPkgBetter = false; 5214 // First check if this is a system package that may involve an update 5215 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5216 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5217 // it needs to drop FLAG_PRIVILEGED. 5218 if (locationIsPrivileged(scanFile)) { 5219 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5220 } else { 5221 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5222 } 5223 5224 if (ps != null && !ps.codePath.equals(scanFile)) { 5225 // The path has changed from what was last scanned... check the 5226 // version of the new path against what we have stored to determine 5227 // what to do. 5228 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5229 if (pkg.mVersionCode <= ps.versionCode) { 5230 // The system package has been updated and the code path does not match 5231 // Ignore entry. Skip it. 5232 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5233 + " ignored: updated version " + ps.versionCode 5234 + " better than this " + pkg.mVersionCode); 5235 if (!updatedPkg.codePath.equals(scanFile)) { 5236 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5237 + ps.name + " changing from " + updatedPkg.codePathString 5238 + " to " + scanFile); 5239 updatedPkg.codePath = scanFile; 5240 updatedPkg.codePathString = scanFile.toString(); 5241 updatedPkg.resourcePath = scanFile; 5242 updatedPkg.resourcePathString = scanFile.toString(); 5243 } 5244 updatedPkg.pkg = pkg; 5245 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5246 } else { 5247 // The current app on the system partition is better than 5248 // what we have updated to on the data partition; switch 5249 // back to the system partition version. 5250 // At this point, its safely assumed that package installation for 5251 // apps in system partition will go through. If not there won't be a working 5252 // version of the app 5253 // writer 5254 synchronized (mPackages) { 5255 // Just remove the loaded entries from package lists. 5256 mPackages.remove(ps.name); 5257 } 5258 5259 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5260 + " reverting from " + ps.codePathString 5261 + ": new version " + pkg.mVersionCode 5262 + " better than installed " + ps.versionCode); 5263 5264 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5265 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5266 synchronized (mInstallLock) { 5267 args.cleanUpResourcesLI(); 5268 } 5269 synchronized (mPackages) { 5270 mSettings.enableSystemPackageLPw(ps.name); 5271 } 5272 updatedPkgBetter = true; 5273 } 5274 } 5275 } 5276 5277 if (updatedPkg != null) { 5278 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5279 // initially 5280 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5281 5282 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5283 // flag set initially 5284 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5285 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5286 } 5287 } 5288 5289 // Verify certificates against what was last scanned 5290 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5291 5292 /* 5293 * A new system app appeared, but we already had a non-system one of the 5294 * same name installed earlier. 5295 */ 5296 boolean shouldHideSystemApp = false; 5297 if (updatedPkg == null && ps != null 5298 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5299 /* 5300 * Check to make sure the signatures match first. If they don't, 5301 * wipe the installed application and its data. 5302 */ 5303 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5304 != PackageManager.SIGNATURE_MATCH) { 5305 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5306 + " signatures don't match existing userdata copy; removing"); 5307 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5308 ps = null; 5309 } else { 5310 /* 5311 * If the newly-added system app is an older version than the 5312 * already installed version, hide it. It will be scanned later 5313 * and re-added like an update. 5314 */ 5315 if (pkg.mVersionCode <= ps.versionCode) { 5316 shouldHideSystemApp = true; 5317 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5318 + " but new version " + pkg.mVersionCode + " better than installed " 5319 + ps.versionCode + "; hiding system"); 5320 } else { 5321 /* 5322 * The newly found system app is a newer version that the 5323 * one previously installed. Simply remove the 5324 * already-installed application and replace it with our own 5325 * while keeping the application data. 5326 */ 5327 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5328 + " reverting from " + ps.codePathString + ": new version " 5329 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5330 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5331 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5332 synchronized (mInstallLock) { 5333 args.cleanUpResourcesLI(); 5334 } 5335 } 5336 } 5337 } 5338 5339 // The apk is forward locked (not public) if its code and resources 5340 // are kept in different files. (except for app in either system or 5341 // vendor path). 5342 // TODO grab this value from PackageSettings 5343 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5344 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5345 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5346 } 5347 } 5348 5349 // TODO: extend to support forward-locked splits 5350 String resourcePath = null; 5351 String baseResourcePath = null; 5352 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5353 if (ps != null && ps.resourcePathString != null) { 5354 resourcePath = ps.resourcePathString; 5355 baseResourcePath = ps.resourcePathString; 5356 } else { 5357 // Should not happen at all. Just log an error. 5358 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5359 } 5360 } else { 5361 resourcePath = pkg.codePath; 5362 baseResourcePath = pkg.baseCodePath; 5363 } 5364 5365 // Set application objects path explicitly. 5366 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5367 pkg.applicationInfo.setCodePath(pkg.codePath); 5368 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5369 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5370 pkg.applicationInfo.setResourcePath(resourcePath); 5371 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5372 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5373 5374 // Note that we invoke the following method only if we are about to unpack an application 5375 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5376 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5377 5378 /* 5379 * If the system app should be overridden by a previously installed 5380 * data, hide the system app now and let the /data/app scan pick it up 5381 * again. 5382 */ 5383 if (shouldHideSystemApp) { 5384 synchronized (mPackages) { 5385 /* 5386 * We have to grant systems permissions before we hide, because 5387 * grantPermissions will assume the package update is trying to 5388 * expand its permissions. 5389 */ 5390 grantPermissionsLPw(pkg, true, pkg.packageName); 5391 mSettings.disableSystemPackageLPw(pkg.packageName); 5392 } 5393 } 5394 5395 return scannedPkg; 5396 } 5397 5398 private static String fixProcessName(String defProcessName, 5399 String processName, int uid) { 5400 if (processName == null) { 5401 return defProcessName; 5402 } 5403 return processName; 5404 } 5405 5406 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5407 throws PackageManagerException { 5408 if (pkgSetting.signatures.mSignatures != null) { 5409 // Already existing package. Make sure signatures match 5410 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5411 == PackageManager.SIGNATURE_MATCH; 5412 if (!match) { 5413 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5414 == PackageManager.SIGNATURE_MATCH; 5415 } 5416 if (!match) { 5417 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5418 == PackageManager.SIGNATURE_MATCH; 5419 } 5420 if (!match) { 5421 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5422 + pkg.packageName + " signatures do not match the " 5423 + "previously installed version; ignoring!"); 5424 } 5425 } 5426 5427 // Check for shared user signatures 5428 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5429 // Already existing package. Make sure signatures match 5430 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5431 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5432 if (!match) { 5433 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5434 == PackageManager.SIGNATURE_MATCH; 5435 } 5436 if (!match) { 5437 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5438 == PackageManager.SIGNATURE_MATCH; 5439 } 5440 if (!match) { 5441 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5442 "Package " + pkg.packageName 5443 + " has no signatures that match those in shared user " 5444 + pkgSetting.sharedUser.name + "; ignoring!"); 5445 } 5446 } 5447 } 5448 5449 /** 5450 * Enforces that only the system UID or root's UID can call a method exposed 5451 * via Binder. 5452 * 5453 * @param message used as message if SecurityException is thrown 5454 * @throws SecurityException if the caller is not system or root 5455 */ 5456 private static final void enforceSystemOrRoot(String message) { 5457 final int uid = Binder.getCallingUid(); 5458 if (uid != Process.SYSTEM_UID && uid != 0) { 5459 throw new SecurityException(message); 5460 } 5461 } 5462 5463 @Override 5464 public void performBootDexOpt() { 5465 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5466 5467 // Before everything else, see whether we need to fstrim. 5468 try { 5469 IMountService ms = PackageHelper.getMountService(); 5470 if (ms != null) { 5471 final boolean isUpgrade = isUpgrade(); 5472 boolean doTrim = isUpgrade; 5473 if (doTrim) { 5474 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5475 } else { 5476 final long interval = android.provider.Settings.Global.getLong( 5477 mContext.getContentResolver(), 5478 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5479 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5480 if (interval > 0) { 5481 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5482 if (timeSinceLast > interval) { 5483 doTrim = true; 5484 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5485 + "; running immediately"); 5486 } 5487 } 5488 } 5489 if (doTrim) { 5490 if (!isFirstBoot()) { 5491 try { 5492 ActivityManagerNative.getDefault().showBootMessage( 5493 mContext.getResources().getString( 5494 R.string.android_upgrading_fstrim), true); 5495 } catch (RemoteException e) { 5496 } 5497 } 5498 ms.runMaintenance(); 5499 } 5500 } else { 5501 Slog.e(TAG, "Mount service unavailable!"); 5502 } 5503 } catch (RemoteException e) { 5504 // Can't happen; MountService is local 5505 } 5506 5507 final ArraySet<PackageParser.Package> pkgs; 5508 synchronized (mPackages) { 5509 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5510 } 5511 5512 if (pkgs != null) { 5513 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5514 // in case the device runs out of space. 5515 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5516 // Give priority to core apps. 5517 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5518 PackageParser.Package pkg = it.next(); 5519 if (pkg.coreApp) { 5520 if (DEBUG_DEXOPT) { 5521 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5522 } 5523 sortedPkgs.add(pkg); 5524 it.remove(); 5525 } 5526 } 5527 // Give priority to system apps that listen for pre boot complete. 5528 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5529 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5530 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5531 PackageParser.Package pkg = it.next(); 5532 if (pkgNames.contains(pkg.packageName)) { 5533 if (DEBUG_DEXOPT) { 5534 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5535 } 5536 sortedPkgs.add(pkg); 5537 it.remove(); 5538 } 5539 } 5540 // Give priority to system apps. 5541 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5542 PackageParser.Package pkg = it.next(); 5543 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5544 if (DEBUG_DEXOPT) { 5545 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5546 } 5547 sortedPkgs.add(pkg); 5548 it.remove(); 5549 } 5550 } 5551 // Give priority to updated system apps. 5552 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5553 PackageParser.Package pkg = it.next(); 5554 if (pkg.isUpdatedSystemApp()) { 5555 if (DEBUG_DEXOPT) { 5556 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5557 } 5558 sortedPkgs.add(pkg); 5559 it.remove(); 5560 } 5561 } 5562 // Give priority to apps that listen for boot complete. 5563 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5564 pkgNames = getPackageNamesForIntent(intent); 5565 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5566 PackageParser.Package pkg = it.next(); 5567 if (pkgNames.contains(pkg.packageName)) { 5568 if (DEBUG_DEXOPT) { 5569 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5570 } 5571 sortedPkgs.add(pkg); 5572 it.remove(); 5573 } 5574 } 5575 // Filter out packages that aren't recently used. 5576 filterRecentlyUsedApps(pkgs); 5577 // Add all remaining apps. 5578 for (PackageParser.Package pkg : pkgs) { 5579 if (DEBUG_DEXOPT) { 5580 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5581 } 5582 sortedPkgs.add(pkg); 5583 } 5584 5585 // If we want to be lazy, filter everything that wasn't recently used. 5586 if (mLazyDexOpt) { 5587 filterRecentlyUsedApps(sortedPkgs); 5588 } 5589 5590 int i = 0; 5591 int total = sortedPkgs.size(); 5592 File dataDir = Environment.getDataDirectory(); 5593 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5594 if (lowThreshold == 0) { 5595 throw new IllegalStateException("Invalid low memory threshold"); 5596 } 5597 for (PackageParser.Package pkg : sortedPkgs) { 5598 long usableSpace = dataDir.getUsableSpace(); 5599 if (usableSpace < lowThreshold) { 5600 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5601 break; 5602 } 5603 performBootDexOpt(pkg, ++i, total); 5604 } 5605 } 5606 } 5607 5608 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5609 // Filter out packages that aren't recently used. 5610 // 5611 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5612 // should do a full dexopt. 5613 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5614 int total = pkgs.size(); 5615 int skipped = 0; 5616 long now = System.currentTimeMillis(); 5617 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5618 PackageParser.Package pkg = i.next(); 5619 long then = pkg.mLastPackageUsageTimeInMills; 5620 if (then + mDexOptLRUThresholdInMills < now) { 5621 if (DEBUG_DEXOPT) { 5622 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5623 ((then == 0) ? "never" : new Date(then))); 5624 } 5625 i.remove(); 5626 skipped++; 5627 } 5628 } 5629 if (DEBUG_DEXOPT) { 5630 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5631 } 5632 } 5633 } 5634 5635 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5636 List<ResolveInfo> ris = null; 5637 try { 5638 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5639 intent, null, 0, UserHandle.USER_OWNER); 5640 } catch (RemoteException e) { 5641 } 5642 ArraySet<String> pkgNames = new ArraySet<String>(); 5643 if (ris != null) { 5644 for (ResolveInfo ri : ris) { 5645 pkgNames.add(ri.activityInfo.packageName); 5646 } 5647 } 5648 return pkgNames; 5649 } 5650 5651 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5652 if (DEBUG_DEXOPT) { 5653 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5654 } 5655 if (!isFirstBoot()) { 5656 try { 5657 ActivityManagerNative.getDefault().showBootMessage( 5658 mContext.getResources().getString(R.string.android_upgrading_apk, 5659 curr, total), true); 5660 } catch (RemoteException e) { 5661 } 5662 } 5663 PackageParser.Package p = pkg; 5664 synchronized (mInstallLock) { 5665 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5666 false /* force dex */, false /* defer */, true /* include dependencies */); 5667 } 5668 } 5669 5670 @Override 5671 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5672 return performDexOpt(packageName, instructionSet, false); 5673 } 5674 5675 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5676 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5677 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5678 if (!dexopt && !updateUsage) { 5679 // We aren't going to dexopt or update usage, so bail early. 5680 return false; 5681 } 5682 PackageParser.Package p; 5683 final String targetInstructionSet; 5684 synchronized (mPackages) { 5685 p = mPackages.get(packageName); 5686 if (p == null) { 5687 return false; 5688 } 5689 if (updateUsage) { 5690 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5691 } 5692 mPackageUsage.write(false); 5693 if (!dexopt) { 5694 // We aren't going to dexopt, so bail early. 5695 return false; 5696 } 5697 5698 targetInstructionSet = instructionSet != null ? instructionSet : 5699 getPrimaryInstructionSet(p.applicationInfo); 5700 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5701 return false; 5702 } 5703 } 5704 5705 synchronized (mInstallLock) { 5706 final String[] instructionSets = new String[] { targetInstructionSet }; 5707 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5708 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5709 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5710 } 5711 } 5712 5713 public ArraySet<String> getPackagesThatNeedDexOpt() { 5714 ArraySet<String> pkgs = null; 5715 synchronized (mPackages) { 5716 for (PackageParser.Package p : mPackages.values()) { 5717 if (DEBUG_DEXOPT) { 5718 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5719 } 5720 if (!p.mDexOptPerformed.isEmpty()) { 5721 continue; 5722 } 5723 if (pkgs == null) { 5724 pkgs = new ArraySet<String>(); 5725 } 5726 pkgs.add(p.packageName); 5727 } 5728 } 5729 return pkgs; 5730 } 5731 5732 public void shutdown() { 5733 mPackageUsage.write(true); 5734 } 5735 5736 @Override 5737 public void forceDexOpt(String packageName) { 5738 enforceSystemOrRoot("forceDexOpt"); 5739 5740 PackageParser.Package pkg; 5741 synchronized (mPackages) { 5742 pkg = mPackages.get(packageName); 5743 if (pkg == null) { 5744 throw new IllegalArgumentException("Missing package: " + packageName); 5745 } 5746 } 5747 5748 synchronized (mInstallLock) { 5749 final String[] instructionSets = new String[] { 5750 getPrimaryInstructionSet(pkg.applicationInfo) }; 5751 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5752 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5753 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5754 throw new IllegalStateException("Failed to dexopt: " + res); 5755 } 5756 } 5757 } 5758 5759 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5760 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5761 Slog.w(TAG, "Unable to update from " + oldPkg.name 5762 + " to " + newPkg.packageName 5763 + ": old package not in system partition"); 5764 return false; 5765 } else if (mPackages.get(oldPkg.name) != null) { 5766 Slog.w(TAG, "Unable to update from " + oldPkg.name 5767 + " to " + newPkg.packageName 5768 + ": old package still exists"); 5769 return false; 5770 } 5771 return true; 5772 } 5773 5774 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5775 int[] users = sUserManager.getUserIds(); 5776 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5777 if (res < 0) { 5778 return res; 5779 } 5780 for (int user : users) { 5781 if (user != 0) { 5782 res = mInstaller.createUserData(volumeUuid, packageName, 5783 UserHandle.getUid(user, uid), user, seinfo); 5784 if (res < 0) { 5785 return res; 5786 } 5787 } 5788 } 5789 return res; 5790 } 5791 5792 private int removeDataDirsLI(String volumeUuid, String packageName) { 5793 int[] users = sUserManager.getUserIds(); 5794 int res = 0; 5795 for (int user : users) { 5796 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5797 if (resInner < 0) { 5798 res = resInner; 5799 } 5800 } 5801 5802 return res; 5803 } 5804 5805 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5806 int[] users = sUserManager.getUserIds(); 5807 int res = 0; 5808 for (int user : users) { 5809 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5810 if (resInner < 0) { 5811 res = resInner; 5812 } 5813 } 5814 return res; 5815 } 5816 5817 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5818 PackageParser.Package changingLib) { 5819 if (file.path != null) { 5820 usesLibraryFiles.add(file.path); 5821 return; 5822 } 5823 PackageParser.Package p = mPackages.get(file.apk); 5824 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5825 // If we are doing this while in the middle of updating a library apk, 5826 // then we need to make sure to use that new apk for determining the 5827 // dependencies here. (We haven't yet finished committing the new apk 5828 // to the package manager state.) 5829 if (p == null || p.packageName.equals(changingLib.packageName)) { 5830 p = changingLib; 5831 } 5832 } 5833 if (p != null) { 5834 usesLibraryFiles.addAll(p.getAllCodePaths()); 5835 } 5836 } 5837 5838 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5839 PackageParser.Package changingLib) throws PackageManagerException { 5840 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5841 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5842 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5843 for (int i=0; i<N; i++) { 5844 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5845 if (file == null) { 5846 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5847 "Package " + pkg.packageName + " requires unavailable shared library " 5848 + pkg.usesLibraries.get(i) + "; failing!"); 5849 } 5850 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5851 } 5852 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5853 for (int i=0; i<N; i++) { 5854 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5855 if (file == null) { 5856 Slog.w(TAG, "Package " + pkg.packageName 5857 + " desires unavailable shared library " 5858 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5859 } else { 5860 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5861 } 5862 } 5863 N = usesLibraryFiles.size(); 5864 if (N > 0) { 5865 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5866 } else { 5867 pkg.usesLibraryFiles = null; 5868 } 5869 } 5870 } 5871 5872 private static boolean hasString(List<String> list, List<String> which) { 5873 if (list == null) { 5874 return false; 5875 } 5876 for (int i=list.size()-1; i>=0; i--) { 5877 for (int j=which.size()-1; j>=0; j--) { 5878 if (which.get(j).equals(list.get(i))) { 5879 return true; 5880 } 5881 } 5882 } 5883 return false; 5884 } 5885 5886 private void updateAllSharedLibrariesLPw() { 5887 for (PackageParser.Package pkg : mPackages.values()) { 5888 try { 5889 updateSharedLibrariesLPw(pkg, null); 5890 } catch (PackageManagerException e) { 5891 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5892 } 5893 } 5894 } 5895 5896 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5897 PackageParser.Package changingPkg) { 5898 ArrayList<PackageParser.Package> res = null; 5899 for (PackageParser.Package pkg : mPackages.values()) { 5900 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5901 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5902 if (res == null) { 5903 res = new ArrayList<PackageParser.Package>(); 5904 } 5905 res.add(pkg); 5906 try { 5907 updateSharedLibrariesLPw(pkg, changingPkg); 5908 } catch (PackageManagerException e) { 5909 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5910 } 5911 } 5912 } 5913 return res; 5914 } 5915 5916 /** 5917 * Derive the value of the {@code cpuAbiOverride} based on the provided 5918 * value and an optional stored value from the package settings. 5919 */ 5920 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5921 String cpuAbiOverride = null; 5922 5923 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5924 cpuAbiOverride = null; 5925 } else if (abiOverride != null) { 5926 cpuAbiOverride = abiOverride; 5927 } else if (settings != null) { 5928 cpuAbiOverride = settings.cpuAbiOverrideString; 5929 } 5930 5931 return cpuAbiOverride; 5932 } 5933 5934 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5935 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5936 boolean success = false; 5937 try { 5938 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5939 currentTime, user); 5940 success = true; 5941 return res; 5942 } finally { 5943 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5944 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5945 } 5946 } 5947 } 5948 5949 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5950 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5951 final File scanFile = new File(pkg.codePath); 5952 if (pkg.applicationInfo.getCodePath() == null || 5953 pkg.applicationInfo.getResourcePath() == null) { 5954 // Bail out. The resource and code paths haven't been set. 5955 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5956 "Code and resource paths haven't been set correctly"); 5957 } 5958 5959 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5960 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5961 } else { 5962 // Only allow system apps to be flagged as core apps. 5963 pkg.coreApp = false; 5964 } 5965 5966 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5967 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5968 } 5969 5970 if (mCustomResolverComponentName != null && 5971 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5972 setUpCustomResolverActivity(pkg); 5973 } 5974 5975 if (pkg.packageName.equals("android")) { 5976 synchronized (mPackages) { 5977 if (mAndroidApplication != null) { 5978 Slog.w(TAG, "*************************************************"); 5979 Slog.w(TAG, "Core android package being redefined. Skipping."); 5980 Slog.w(TAG, " file=" + scanFile); 5981 Slog.w(TAG, "*************************************************"); 5982 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5983 "Core android package being redefined. Skipping."); 5984 } 5985 5986 // Set up information for our fall-back user intent resolution activity. 5987 mPlatformPackage = pkg; 5988 pkg.mVersionCode = mSdkVersion; 5989 mAndroidApplication = pkg.applicationInfo; 5990 5991 if (!mResolverReplaced) { 5992 mResolveActivity.applicationInfo = mAndroidApplication; 5993 mResolveActivity.name = ResolverActivity.class.getName(); 5994 mResolveActivity.packageName = mAndroidApplication.packageName; 5995 mResolveActivity.processName = "system:ui"; 5996 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5997 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5998 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5999 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6000 mResolveActivity.exported = true; 6001 mResolveActivity.enabled = true; 6002 mResolveInfo.activityInfo = mResolveActivity; 6003 mResolveInfo.priority = 0; 6004 mResolveInfo.preferredOrder = 0; 6005 mResolveInfo.match = 0; 6006 mResolveComponentName = new ComponentName( 6007 mAndroidApplication.packageName, mResolveActivity.name); 6008 } 6009 } 6010 } 6011 6012 if (DEBUG_PACKAGE_SCANNING) { 6013 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6014 Log.d(TAG, "Scanning package " + pkg.packageName); 6015 } 6016 6017 if (mPackages.containsKey(pkg.packageName) 6018 || mSharedLibraries.containsKey(pkg.packageName)) { 6019 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6020 "Application package " + pkg.packageName 6021 + " already installed. Skipping duplicate."); 6022 } 6023 6024 // If we're only installing presumed-existing packages, require that the 6025 // scanned APK is both already known and at the path previously established 6026 // for it. Previously unknown packages we pick up normally, but if we have an 6027 // a priori expectation about this package's install presence, enforce it. 6028 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6029 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6030 if (known != null) { 6031 if (DEBUG_PACKAGE_SCANNING) { 6032 Log.d(TAG, "Examining " + pkg.codePath 6033 + " and requiring known paths " + known.codePathString 6034 + " & " + known.resourcePathString); 6035 } 6036 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6037 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6038 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6039 "Application package " + pkg.packageName 6040 + " found at " + pkg.applicationInfo.getCodePath() 6041 + " but expected at " + known.codePathString + "; ignoring."); 6042 } 6043 } 6044 } 6045 6046 // Initialize package source and resource directories 6047 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6048 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6049 6050 SharedUserSetting suid = null; 6051 PackageSetting pkgSetting = null; 6052 6053 if (!isSystemApp(pkg)) { 6054 // Only system apps can use these features. 6055 pkg.mOriginalPackages = null; 6056 pkg.mRealPackage = null; 6057 pkg.mAdoptPermissions = null; 6058 } 6059 6060 // writer 6061 synchronized (mPackages) { 6062 if (pkg.mSharedUserId != null) { 6063 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6064 if (suid == null) { 6065 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6066 "Creating application package " + pkg.packageName 6067 + " for shared user failed"); 6068 } 6069 if (DEBUG_PACKAGE_SCANNING) { 6070 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6071 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6072 + "): packages=" + suid.packages); 6073 } 6074 } 6075 6076 // Check if we are renaming from an original package name. 6077 PackageSetting origPackage = null; 6078 String realName = null; 6079 if (pkg.mOriginalPackages != null) { 6080 // This package may need to be renamed to a previously 6081 // installed name. Let's check on that... 6082 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6083 if (pkg.mOriginalPackages.contains(renamed)) { 6084 // This package had originally been installed as the 6085 // original name, and we have already taken care of 6086 // transitioning to the new one. Just update the new 6087 // one to continue using the old name. 6088 realName = pkg.mRealPackage; 6089 if (!pkg.packageName.equals(renamed)) { 6090 // Callers into this function may have already taken 6091 // care of renaming the package; only do it here if 6092 // it is not already done. 6093 pkg.setPackageName(renamed); 6094 } 6095 6096 } else { 6097 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6098 if ((origPackage = mSettings.peekPackageLPr( 6099 pkg.mOriginalPackages.get(i))) != null) { 6100 // We do have the package already installed under its 6101 // original name... should we use it? 6102 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6103 // New package is not compatible with original. 6104 origPackage = null; 6105 continue; 6106 } else if (origPackage.sharedUser != null) { 6107 // Make sure uid is compatible between packages. 6108 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6109 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6110 + " to " + pkg.packageName + ": old uid " 6111 + origPackage.sharedUser.name 6112 + " differs from " + pkg.mSharedUserId); 6113 origPackage = null; 6114 continue; 6115 } 6116 } else { 6117 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6118 + pkg.packageName + " to old name " + origPackage.name); 6119 } 6120 break; 6121 } 6122 } 6123 } 6124 } 6125 6126 if (mTransferedPackages.contains(pkg.packageName)) { 6127 Slog.w(TAG, "Package " + pkg.packageName 6128 + " was transferred to another, but its .apk remains"); 6129 } 6130 6131 // Just create the setting, don't add it yet. For already existing packages 6132 // the PkgSetting exists already and doesn't have to be created. 6133 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6134 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6135 pkg.applicationInfo.primaryCpuAbi, 6136 pkg.applicationInfo.secondaryCpuAbi, 6137 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6138 user, false); 6139 if (pkgSetting == null) { 6140 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6141 "Creating application package " + pkg.packageName + " failed"); 6142 } 6143 6144 if (pkgSetting.origPackage != null) { 6145 // If we are first transitioning from an original package, 6146 // fix up the new package's name now. We need to do this after 6147 // looking up the package under its new name, so getPackageLP 6148 // can take care of fiddling things correctly. 6149 pkg.setPackageName(origPackage.name); 6150 6151 // File a report about this. 6152 String msg = "New package " + pkgSetting.realName 6153 + " renamed to replace old package " + pkgSetting.name; 6154 reportSettingsProblem(Log.WARN, msg); 6155 6156 // Make a note of it. 6157 mTransferedPackages.add(origPackage.name); 6158 6159 // No longer need to retain this. 6160 pkgSetting.origPackage = null; 6161 } 6162 6163 if (realName != null) { 6164 // Make a note of it. 6165 mTransferedPackages.add(pkg.packageName); 6166 } 6167 6168 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6169 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6170 } 6171 6172 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6173 // Check all shared libraries and map to their actual file path. 6174 // We only do this here for apps not on a system dir, because those 6175 // are the only ones that can fail an install due to this. We 6176 // will take care of the system apps by updating all of their 6177 // library paths after the scan is done. 6178 updateSharedLibrariesLPw(pkg, null); 6179 } 6180 6181 if (mFoundPolicyFile) { 6182 SELinuxMMAC.assignSeinfoValue(pkg); 6183 } 6184 6185 pkg.applicationInfo.uid = pkgSetting.appId; 6186 pkg.mExtras = pkgSetting; 6187 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6188 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6189 // We just determined the app is signed correctly, so bring 6190 // over the latest parsed certs. 6191 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6192 } else { 6193 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6194 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6195 "Package " + pkg.packageName + " upgrade keys do not match the " 6196 + "previously installed version"); 6197 } else { 6198 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6199 String msg = "System package " + pkg.packageName 6200 + " signature changed; retaining data."; 6201 reportSettingsProblem(Log.WARN, msg); 6202 } 6203 } 6204 } else { 6205 try { 6206 verifySignaturesLP(pkgSetting, pkg); 6207 // We just determined the app is signed correctly, so bring 6208 // over the latest parsed certs. 6209 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6210 } catch (PackageManagerException e) { 6211 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6212 throw e; 6213 } 6214 // The signature has changed, but this package is in the system 6215 // image... let's recover! 6216 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6217 // However... if this package is part of a shared user, but it 6218 // doesn't match the signature of the shared user, let's fail. 6219 // What this means is that you can't change the signatures 6220 // associated with an overall shared user, which doesn't seem all 6221 // that unreasonable. 6222 if (pkgSetting.sharedUser != null) { 6223 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6224 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6225 throw new PackageManagerException( 6226 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6227 "Signature mismatch for shared user : " 6228 + pkgSetting.sharedUser); 6229 } 6230 } 6231 // File a report about this. 6232 String msg = "System package " + pkg.packageName 6233 + " signature changed; retaining data."; 6234 reportSettingsProblem(Log.WARN, msg); 6235 } 6236 } 6237 // Verify that this new package doesn't have any content providers 6238 // that conflict with existing packages. Only do this if the 6239 // package isn't already installed, since we don't want to break 6240 // things that are installed. 6241 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6242 final int N = pkg.providers.size(); 6243 int i; 6244 for (i=0; i<N; i++) { 6245 PackageParser.Provider p = pkg.providers.get(i); 6246 if (p.info.authority != null) { 6247 String names[] = p.info.authority.split(";"); 6248 for (int j = 0; j < names.length; j++) { 6249 if (mProvidersByAuthority.containsKey(names[j])) { 6250 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6251 final String otherPackageName = 6252 ((other != null && other.getComponentName() != null) ? 6253 other.getComponentName().getPackageName() : "?"); 6254 throw new PackageManagerException( 6255 INSTALL_FAILED_CONFLICTING_PROVIDER, 6256 "Can't install because provider name " + names[j] 6257 + " (in package " + pkg.applicationInfo.packageName 6258 + ") is already used by " + otherPackageName); 6259 } 6260 } 6261 } 6262 } 6263 } 6264 6265 if (pkg.mAdoptPermissions != null) { 6266 // This package wants to adopt ownership of permissions from 6267 // another package. 6268 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6269 final String origName = pkg.mAdoptPermissions.get(i); 6270 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6271 if (orig != null) { 6272 if (verifyPackageUpdateLPr(orig, pkg)) { 6273 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6274 + pkg.packageName); 6275 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6276 } 6277 } 6278 } 6279 } 6280 } 6281 6282 final String pkgName = pkg.packageName; 6283 6284 final long scanFileTime = scanFile.lastModified(); 6285 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6286 pkg.applicationInfo.processName = fixProcessName( 6287 pkg.applicationInfo.packageName, 6288 pkg.applicationInfo.processName, 6289 pkg.applicationInfo.uid); 6290 6291 File dataPath; 6292 if (mPlatformPackage == pkg) { 6293 // The system package is special. 6294 dataPath = new File(Environment.getDataDirectory(), "system"); 6295 6296 pkg.applicationInfo.dataDir = dataPath.getPath(); 6297 6298 } else { 6299 // This is a normal package, need to make its data directory. 6300 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6301 UserHandle.USER_OWNER); 6302 6303 boolean uidError = false; 6304 if (dataPath.exists()) { 6305 int currentUid = 0; 6306 try { 6307 StructStat stat = Os.stat(dataPath.getPath()); 6308 currentUid = stat.st_uid; 6309 } catch (ErrnoException e) { 6310 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6311 } 6312 6313 // If we have mismatched owners for the data path, we have a problem. 6314 if (currentUid != pkg.applicationInfo.uid) { 6315 boolean recovered = false; 6316 if (currentUid == 0) { 6317 // The directory somehow became owned by root. Wow. 6318 // This is probably because the system was stopped while 6319 // installd was in the middle of messing with its libs 6320 // directory. Ask installd to fix that. 6321 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6322 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6323 if (ret >= 0) { 6324 recovered = true; 6325 String msg = "Package " + pkg.packageName 6326 + " unexpectedly changed to uid 0; recovered to " + 6327 + pkg.applicationInfo.uid; 6328 reportSettingsProblem(Log.WARN, msg); 6329 } 6330 } 6331 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6332 || (scanFlags&SCAN_BOOTING) != 0)) { 6333 // If this is a system app, we can at least delete its 6334 // current data so the application will still work. 6335 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6336 if (ret >= 0) { 6337 // TODO: Kill the processes first 6338 // Old data gone! 6339 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6340 ? "System package " : "Third party package "; 6341 String msg = prefix + pkg.packageName 6342 + " has changed from uid: " 6343 + currentUid + " to " 6344 + pkg.applicationInfo.uid + "; old data erased"; 6345 reportSettingsProblem(Log.WARN, msg); 6346 recovered = true; 6347 6348 // And now re-install the app. 6349 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6350 pkg.applicationInfo.seinfo); 6351 if (ret == -1) { 6352 // Ack should not happen! 6353 msg = prefix + pkg.packageName 6354 + " could not have data directory re-created after delete."; 6355 reportSettingsProblem(Log.WARN, msg); 6356 throw new PackageManagerException( 6357 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6358 } 6359 } 6360 if (!recovered) { 6361 mHasSystemUidErrors = true; 6362 } 6363 } else if (!recovered) { 6364 // If we allow this install to proceed, we will be broken. 6365 // Abort, abort! 6366 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6367 "scanPackageLI"); 6368 } 6369 if (!recovered) { 6370 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6371 + pkg.applicationInfo.uid + "/fs_" 6372 + currentUid; 6373 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6374 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6375 String msg = "Package " + pkg.packageName 6376 + " has mismatched uid: " 6377 + currentUid + " on disk, " 6378 + pkg.applicationInfo.uid + " in settings"; 6379 // writer 6380 synchronized (mPackages) { 6381 mSettings.mReadMessages.append(msg); 6382 mSettings.mReadMessages.append('\n'); 6383 uidError = true; 6384 if (!pkgSetting.uidError) { 6385 reportSettingsProblem(Log.ERROR, msg); 6386 } 6387 } 6388 } 6389 } 6390 pkg.applicationInfo.dataDir = dataPath.getPath(); 6391 if (mShouldRestoreconData) { 6392 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6393 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6394 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6395 } 6396 } else { 6397 if (DEBUG_PACKAGE_SCANNING) { 6398 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6399 Log.v(TAG, "Want this data dir: " + dataPath); 6400 } 6401 //invoke installer to do the actual installation 6402 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6403 pkg.applicationInfo.seinfo); 6404 if (ret < 0) { 6405 // Error from installer 6406 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6407 "Unable to create data dirs [errorCode=" + ret + "]"); 6408 } 6409 6410 if (dataPath.exists()) { 6411 pkg.applicationInfo.dataDir = dataPath.getPath(); 6412 } else { 6413 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6414 pkg.applicationInfo.dataDir = null; 6415 } 6416 } 6417 6418 pkgSetting.uidError = uidError; 6419 } 6420 6421 final String path = scanFile.getPath(); 6422 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6423 6424 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6425 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6426 6427 // Some system apps still use directory structure for native libraries 6428 // in which case we might end up not detecting abi solely based on apk 6429 // structure. Try to detect abi based on directory structure. 6430 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6431 pkg.applicationInfo.primaryCpuAbi == null) { 6432 setBundledAppAbisAndRoots(pkg, pkgSetting); 6433 setNativeLibraryPaths(pkg); 6434 } 6435 6436 } else { 6437 if ((scanFlags & SCAN_MOVE) != 0) { 6438 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6439 // but we already have this packages package info in the PackageSetting. We just 6440 // use that and derive the native library path based on the new codepath. 6441 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6442 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6443 } 6444 6445 // Set native library paths again. For moves, the path will be updated based on the 6446 // ABIs we've determined above. For non-moves, the path will be updated based on the 6447 // ABIs we determined during compilation, but the path will depend on the final 6448 // package path (after the rename away from the stage path). 6449 setNativeLibraryPaths(pkg); 6450 } 6451 6452 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6453 final int[] userIds = sUserManager.getUserIds(); 6454 synchronized (mInstallLock) { 6455 // Create a native library symlink only if we have native libraries 6456 // and if the native libraries are 32 bit libraries. We do not provide 6457 // this symlink for 64 bit libraries. 6458 if (pkg.applicationInfo.primaryCpuAbi != null && 6459 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6460 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6461 for (int userId : userIds) { 6462 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6463 nativeLibPath, userId) < 0) { 6464 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6465 "Failed linking native library dir (user=" + userId + ")"); 6466 } 6467 } 6468 } 6469 } 6470 6471 // This is a special case for the "system" package, where the ABI is 6472 // dictated by the zygote configuration (and init.rc). We should keep track 6473 // of this ABI so that we can deal with "normal" applications that run under 6474 // the same UID correctly. 6475 if (mPlatformPackage == pkg) { 6476 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6477 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6478 } 6479 6480 // If there's a mismatch between the abi-override in the package setting 6481 // and the abiOverride specified for the install. Warn about this because we 6482 // would've already compiled the app without taking the package setting into 6483 // account. 6484 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6485 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6486 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6487 " for package: " + pkg.packageName); 6488 } 6489 } 6490 6491 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6492 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6493 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6494 6495 // Copy the derived override back to the parsed package, so that we can 6496 // update the package settings accordingly. 6497 pkg.cpuAbiOverride = cpuAbiOverride; 6498 6499 if (DEBUG_ABI_SELECTION) { 6500 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6501 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6502 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6503 } 6504 6505 // Push the derived path down into PackageSettings so we know what to 6506 // clean up at uninstall time. 6507 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6508 6509 if (DEBUG_ABI_SELECTION) { 6510 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6511 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6512 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6513 } 6514 6515 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6516 // We don't do this here during boot because we can do it all 6517 // at once after scanning all existing packages. 6518 // 6519 // We also do this *before* we perform dexopt on this package, so that 6520 // we can avoid redundant dexopts, and also to make sure we've got the 6521 // code and package path correct. 6522 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6523 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6524 } 6525 6526 if ((scanFlags & SCAN_NO_DEX) == 0) { 6527 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6528 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6529 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6530 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6531 } 6532 } 6533 if (mFactoryTest && pkg.requestedPermissions.contains( 6534 android.Manifest.permission.FACTORY_TEST)) { 6535 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6536 } 6537 6538 ArrayList<PackageParser.Package> clientLibPkgs = null; 6539 6540 // writer 6541 synchronized (mPackages) { 6542 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6543 // Only system apps can add new shared libraries. 6544 if (pkg.libraryNames != null) { 6545 for (int i=0; i<pkg.libraryNames.size(); i++) { 6546 String name = pkg.libraryNames.get(i); 6547 boolean allowed = false; 6548 if (pkg.isUpdatedSystemApp()) { 6549 // New library entries can only be added through the 6550 // system image. This is important to get rid of a lot 6551 // of nasty edge cases: for example if we allowed a non- 6552 // system update of the app to add a library, then uninstalling 6553 // the update would make the library go away, and assumptions 6554 // we made such as through app install filtering would now 6555 // have allowed apps on the device which aren't compatible 6556 // with it. Better to just have the restriction here, be 6557 // conservative, and create many fewer cases that can negatively 6558 // impact the user experience. 6559 final PackageSetting sysPs = mSettings 6560 .getDisabledSystemPkgLPr(pkg.packageName); 6561 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6562 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6563 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6564 allowed = true; 6565 allowed = true; 6566 break; 6567 } 6568 } 6569 } 6570 } else { 6571 allowed = true; 6572 } 6573 if (allowed) { 6574 if (!mSharedLibraries.containsKey(name)) { 6575 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6576 } else if (!name.equals(pkg.packageName)) { 6577 Slog.w(TAG, "Package " + pkg.packageName + " library " 6578 + name + " already exists; skipping"); 6579 } 6580 } else { 6581 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6582 + name + " that is not declared on system image; skipping"); 6583 } 6584 } 6585 if ((scanFlags&SCAN_BOOTING) == 0) { 6586 // If we are not booting, we need to update any applications 6587 // that are clients of our shared library. If we are booting, 6588 // this will all be done once the scan is complete. 6589 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6590 } 6591 } 6592 } 6593 } 6594 6595 // We also need to dexopt any apps that are dependent on this library. Note that 6596 // if these fail, we should abort the install since installing the library will 6597 // result in some apps being broken. 6598 if (clientLibPkgs != null) { 6599 if ((scanFlags & SCAN_NO_DEX) == 0) { 6600 for (int i = 0; i < clientLibPkgs.size(); i++) { 6601 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6602 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6603 null /* instruction sets */, forceDex, 6604 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6605 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6606 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6607 "scanPackageLI failed to dexopt clientLibPkgs"); 6608 } 6609 } 6610 } 6611 } 6612 6613 // Also need to kill any apps that are dependent on the library. 6614 if (clientLibPkgs != null) { 6615 for (int i=0; i<clientLibPkgs.size(); i++) { 6616 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6617 killApplication(clientPkg.applicationInfo.packageName, 6618 clientPkg.applicationInfo.uid, "update lib"); 6619 } 6620 } 6621 6622 // Make sure we're not adding any bogus keyset info 6623 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6624 ksms.assertScannedPackageValid(pkg); 6625 6626 // writer 6627 synchronized (mPackages) { 6628 // We don't expect installation to fail beyond this point 6629 6630 // Add the new setting to mSettings 6631 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6632 // Add the new setting to mPackages 6633 mPackages.put(pkg.applicationInfo.packageName, pkg); 6634 // Make sure we don't accidentally delete its data. 6635 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6636 while (iter.hasNext()) { 6637 PackageCleanItem item = iter.next(); 6638 if (pkgName.equals(item.packageName)) { 6639 iter.remove(); 6640 } 6641 } 6642 6643 // Take care of first install / last update times. 6644 if (currentTime != 0) { 6645 if (pkgSetting.firstInstallTime == 0) { 6646 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6647 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6648 pkgSetting.lastUpdateTime = currentTime; 6649 } 6650 } else if (pkgSetting.firstInstallTime == 0) { 6651 // We need *something*. Take time time stamp of the file. 6652 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6653 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6654 if (scanFileTime != pkgSetting.timeStamp) { 6655 // A package on the system image has changed; consider this 6656 // to be an update. 6657 pkgSetting.lastUpdateTime = scanFileTime; 6658 } 6659 } 6660 6661 // Add the package's KeySets to the global KeySetManagerService 6662 ksms.addScannedPackageLPw(pkg); 6663 6664 int N = pkg.providers.size(); 6665 StringBuilder r = null; 6666 int i; 6667 for (i=0; i<N; i++) { 6668 PackageParser.Provider p = pkg.providers.get(i); 6669 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6670 p.info.processName, pkg.applicationInfo.uid); 6671 mProviders.addProvider(p); 6672 p.syncable = p.info.isSyncable; 6673 if (p.info.authority != null) { 6674 String names[] = p.info.authority.split(";"); 6675 p.info.authority = null; 6676 for (int j = 0; j < names.length; j++) { 6677 if (j == 1 && p.syncable) { 6678 // We only want the first authority for a provider to possibly be 6679 // syncable, so if we already added this provider using a different 6680 // authority clear the syncable flag. We copy the provider before 6681 // changing it because the mProviders object contains a reference 6682 // to a provider that we don't want to change. 6683 // Only do this for the second authority since the resulting provider 6684 // object can be the same for all future authorities for this provider. 6685 p = new PackageParser.Provider(p); 6686 p.syncable = false; 6687 } 6688 if (!mProvidersByAuthority.containsKey(names[j])) { 6689 mProvidersByAuthority.put(names[j], p); 6690 if (p.info.authority == null) { 6691 p.info.authority = names[j]; 6692 } else { 6693 p.info.authority = p.info.authority + ";" + names[j]; 6694 } 6695 if (DEBUG_PACKAGE_SCANNING) { 6696 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6697 Log.d(TAG, "Registered content provider: " + names[j] 6698 + ", className = " + p.info.name + ", isSyncable = " 6699 + p.info.isSyncable); 6700 } 6701 } else { 6702 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6703 Slog.w(TAG, "Skipping provider name " + names[j] + 6704 " (in package " + pkg.applicationInfo.packageName + 6705 "): name already used by " 6706 + ((other != null && other.getComponentName() != null) 6707 ? other.getComponentName().getPackageName() : "?")); 6708 } 6709 } 6710 } 6711 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6712 if (r == null) { 6713 r = new StringBuilder(256); 6714 } else { 6715 r.append(' '); 6716 } 6717 r.append(p.info.name); 6718 } 6719 } 6720 if (r != null) { 6721 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6722 } 6723 6724 N = pkg.services.size(); 6725 r = null; 6726 for (i=0; i<N; i++) { 6727 PackageParser.Service s = pkg.services.get(i); 6728 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6729 s.info.processName, pkg.applicationInfo.uid); 6730 mServices.addService(s); 6731 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6732 if (r == null) { 6733 r = new StringBuilder(256); 6734 } else { 6735 r.append(' '); 6736 } 6737 r.append(s.info.name); 6738 } 6739 } 6740 if (r != null) { 6741 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6742 } 6743 6744 N = pkg.receivers.size(); 6745 r = null; 6746 for (i=0; i<N; i++) { 6747 PackageParser.Activity a = pkg.receivers.get(i); 6748 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6749 a.info.processName, pkg.applicationInfo.uid); 6750 mReceivers.addActivity(a, "receiver"); 6751 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6752 if (r == null) { 6753 r = new StringBuilder(256); 6754 } else { 6755 r.append(' '); 6756 } 6757 r.append(a.info.name); 6758 } 6759 } 6760 if (r != null) { 6761 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6762 } 6763 6764 N = pkg.activities.size(); 6765 r = null; 6766 for (i=0; i<N; i++) { 6767 PackageParser.Activity a = pkg.activities.get(i); 6768 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6769 a.info.processName, pkg.applicationInfo.uid); 6770 mActivities.addActivity(a, "activity"); 6771 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6772 if (r == null) { 6773 r = new StringBuilder(256); 6774 } else { 6775 r.append(' '); 6776 } 6777 r.append(a.info.name); 6778 } 6779 } 6780 if (r != null) { 6781 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6782 } 6783 6784 N = pkg.permissionGroups.size(); 6785 r = null; 6786 for (i=0; i<N; i++) { 6787 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6788 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6789 if (cur == null) { 6790 mPermissionGroups.put(pg.info.name, pg); 6791 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6792 if (r == null) { 6793 r = new StringBuilder(256); 6794 } else { 6795 r.append(' '); 6796 } 6797 r.append(pg.info.name); 6798 } 6799 } else { 6800 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6801 + pg.info.packageName + " ignored: original from " 6802 + cur.info.packageName); 6803 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6804 if (r == null) { 6805 r = new StringBuilder(256); 6806 } else { 6807 r.append(' '); 6808 } 6809 r.append("DUP:"); 6810 r.append(pg.info.name); 6811 } 6812 } 6813 } 6814 if (r != null) { 6815 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6816 } 6817 6818 N = pkg.permissions.size(); 6819 r = null; 6820 for (i=0; i<N; i++) { 6821 PackageParser.Permission p = pkg.permissions.get(i); 6822 6823 // Now that permission groups have a special meaning, we ignore permission 6824 // groups for legacy apps to prevent unexpected behavior. In particular, 6825 // permissions for one app being granted to someone just becuase they happen 6826 // to be in a group defined by another app (before this had no implications). 6827 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6828 p.group = mPermissionGroups.get(p.info.group); 6829 // Warn for a permission in an unknown group. 6830 if (p.info.group != null && p.group == null) { 6831 Slog.w(TAG, "Permission " + p.info.name + " from package " 6832 + p.info.packageName + " in an unknown group " + p.info.group); 6833 } 6834 } 6835 6836 ArrayMap<String, BasePermission> permissionMap = 6837 p.tree ? mSettings.mPermissionTrees 6838 : mSettings.mPermissions; 6839 BasePermission bp = permissionMap.get(p.info.name); 6840 6841 // Allow system apps to redefine non-system permissions 6842 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6843 final boolean currentOwnerIsSystem = (bp.perm != null 6844 && isSystemApp(bp.perm.owner)); 6845 if (isSystemApp(p.owner)) { 6846 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6847 // It's a built-in permission and no owner, take ownership now 6848 bp.packageSetting = pkgSetting; 6849 bp.perm = p; 6850 bp.uid = pkg.applicationInfo.uid; 6851 bp.sourcePackage = p.info.packageName; 6852 } else if (!currentOwnerIsSystem) { 6853 String msg = "New decl " + p.owner + " of permission " 6854 + p.info.name + " is system; overriding " + bp.sourcePackage; 6855 reportSettingsProblem(Log.WARN, msg); 6856 bp = null; 6857 } 6858 } 6859 } 6860 6861 if (bp == null) { 6862 bp = new BasePermission(p.info.name, p.info.packageName, 6863 BasePermission.TYPE_NORMAL); 6864 permissionMap.put(p.info.name, bp); 6865 } 6866 6867 if (bp.perm == null) { 6868 if (bp.sourcePackage == null 6869 || bp.sourcePackage.equals(p.info.packageName)) { 6870 BasePermission tree = findPermissionTreeLP(p.info.name); 6871 if (tree == null 6872 || tree.sourcePackage.equals(p.info.packageName)) { 6873 bp.packageSetting = pkgSetting; 6874 bp.perm = p; 6875 bp.uid = pkg.applicationInfo.uid; 6876 bp.sourcePackage = p.info.packageName; 6877 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6878 if (r == null) { 6879 r = new StringBuilder(256); 6880 } else { 6881 r.append(' '); 6882 } 6883 r.append(p.info.name); 6884 } 6885 } else { 6886 Slog.w(TAG, "Permission " + p.info.name + " from package " 6887 + p.info.packageName + " ignored: base tree " 6888 + tree.name + " is from package " 6889 + tree.sourcePackage); 6890 } 6891 } else { 6892 Slog.w(TAG, "Permission " + p.info.name + " from package " 6893 + p.info.packageName + " ignored: original from " 6894 + bp.sourcePackage); 6895 } 6896 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6897 if (r == null) { 6898 r = new StringBuilder(256); 6899 } else { 6900 r.append(' '); 6901 } 6902 r.append("DUP:"); 6903 r.append(p.info.name); 6904 } 6905 if (bp.perm == p) { 6906 bp.protectionLevel = p.info.protectionLevel; 6907 } 6908 } 6909 6910 if (r != null) { 6911 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6912 } 6913 6914 N = pkg.instrumentation.size(); 6915 r = null; 6916 for (i=0; i<N; i++) { 6917 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6918 a.info.packageName = pkg.applicationInfo.packageName; 6919 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6920 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6921 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6922 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6923 a.info.dataDir = pkg.applicationInfo.dataDir; 6924 6925 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6926 // need other information about the application, like the ABI and what not ? 6927 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6928 mInstrumentation.put(a.getComponentName(), a); 6929 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6930 if (r == null) { 6931 r = new StringBuilder(256); 6932 } else { 6933 r.append(' '); 6934 } 6935 r.append(a.info.name); 6936 } 6937 } 6938 if (r != null) { 6939 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6940 } 6941 6942 if (pkg.protectedBroadcasts != null) { 6943 N = pkg.protectedBroadcasts.size(); 6944 for (i=0; i<N; i++) { 6945 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6946 } 6947 } 6948 6949 pkgSetting.setTimeStamp(scanFileTime); 6950 6951 // Create idmap files for pairs of (packages, overlay packages). 6952 // Note: "android", ie framework-res.apk, is handled by native layers. 6953 if (pkg.mOverlayTarget != null) { 6954 // This is an overlay package. 6955 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6956 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6957 mOverlays.put(pkg.mOverlayTarget, 6958 new ArrayMap<String, PackageParser.Package>()); 6959 } 6960 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6961 map.put(pkg.packageName, pkg); 6962 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6963 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6964 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6965 "scanPackageLI failed to createIdmap"); 6966 } 6967 } 6968 } else if (mOverlays.containsKey(pkg.packageName) && 6969 !pkg.packageName.equals("android")) { 6970 // This is a regular package, with one or more known overlay packages. 6971 createIdmapsForPackageLI(pkg); 6972 } 6973 } 6974 6975 return pkg; 6976 } 6977 6978 /** 6979 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6980 * is derived purely on the basis of the contents of {@code scanFile} and 6981 * {@code cpuAbiOverride}. 6982 * 6983 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6984 */ 6985 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6986 String cpuAbiOverride, boolean extractLibs) 6987 throws PackageManagerException { 6988 // TODO: We can probably be smarter about this stuff. For installed apps, 6989 // we can calculate this information at install time once and for all. For 6990 // system apps, we can probably assume that this information doesn't change 6991 // after the first boot scan. As things stand, we do lots of unnecessary work. 6992 6993 // Give ourselves some initial paths; we'll come back for another 6994 // pass once we've determined ABI below. 6995 setNativeLibraryPaths(pkg); 6996 6997 // We would never need to extract libs for forward-locked and external packages, 6998 // since the container service will do it for us. We shouldn't attempt to 6999 // extract libs from system app when it was not updated. 7000 if (pkg.isForwardLocked() || isExternal(pkg) || 7001 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7002 extractLibs = false; 7003 } 7004 7005 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7006 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7007 7008 NativeLibraryHelper.Handle handle = null; 7009 try { 7010 handle = NativeLibraryHelper.Handle.create(scanFile); 7011 // TODO(multiArch): This can be null for apps that didn't go through the 7012 // usual installation process. We can calculate it again, like we 7013 // do during install time. 7014 // 7015 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7016 // unnecessary. 7017 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7018 7019 // Null out the abis so that they can be recalculated. 7020 pkg.applicationInfo.primaryCpuAbi = null; 7021 pkg.applicationInfo.secondaryCpuAbi = null; 7022 if (isMultiArch(pkg.applicationInfo)) { 7023 // Warn if we've set an abiOverride for multi-lib packages.. 7024 // By definition, we need to copy both 32 and 64 bit libraries for 7025 // such packages. 7026 if (pkg.cpuAbiOverride != null 7027 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7028 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7029 } 7030 7031 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7032 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7033 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7034 if (extractLibs) { 7035 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7036 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7037 useIsaSpecificSubdirs); 7038 } else { 7039 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7040 } 7041 } 7042 7043 maybeThrowExceptionForMultiArchCopy( 7044 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7045 7046 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7047 if (extractLibs) { 7048 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7049 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7050 useIsaSpecificSubdirs); 7051 } else { 7052 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7053 } 7054 } 7055 7056 maybeThrowExceptionForMultiArchCopy( 7057 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7058 7059 if (abi64 >= 0) { 7060 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7061 } 7062 7063 if (abi32 >= 0) { 7064 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7065 if (abi64 >= 0) { 7066 pkg.applicationInfo.secondaryCpuAbi = abi; 7067 } else { 7068 pkg.applicationInfo.primaryCpuAbi = abi; 7069 } 7070 } 7071 } else { 7072 String[] abiList = (cpuAbiOverride != null) ? 7073 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7074 7075 // Enable gross and lame hacks for apps that are built with old 7076 // SDK tools. We must scan their APKs for renderscript bitcode and 7077 // not launch them if it's present. Don't bother checking on devices 7078 // that don't have 64 bit support. 7079 boolean needsRenderScriptOverride = false; 7080 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7081 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7082 abiList = Build.SUPPORTED_32_BIT_ABIS; 7083 needsRenderScriptOverride = true; 7084 } 7085 7086 final int copyRet; 7087 if (extractLibs) { 7088 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7089 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7090 } else { 7091 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7092 } 7093 7094 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7095 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7096 "Error unpackaging native libs for app, errorCode=" + copyRet); 7097 } 7098 7099 if (copyRet >= 0) { 7100 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7101 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7102 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7103 } else if (needsRenderScriptOverride) { 7104 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7105 } 7106 } 7107 } catch (IOException ioe) { 7108 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7109 } finally { 7110 IoUtils.closeQuietly(handle); 7111 } 7112 7113 // Now that we've calculated the ABIs and determined if it's an internal app, 7114 // we will go ahead and populate the nativeLibraryPath. 7115 setNativeLibraryPaths(pkg); 7116 } 7117 7118 /** 7119 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7120 * i.e, so that all packages can be run inside a single process if required. 7121 * 7122 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7123 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7124 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7125 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7126 * updating a package that belongs to a shared user. 7127 * 7128 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7129 * adds unnecessary complexity. 7130 */ 7131 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7132 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7133 String requiredInstructionSet = null; 7134 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7135 requiredInstructionSet = VMRuntime.getInstructionSet( 7136 scannedPackage.applicationInfo.primaryCpuAbi); 7137 } 7138 7139 PackageSetting requirer = null; 7140 for (PackageSetting ps : packagesForUser) { 7141 // If packagesForUser contains scannedPackage, we skip it. This will happen 7142 // when scannedPackage is an update of an existing package. Without this check, 7143 // we will never be able to change the ABI of any package belonging to a shared 7144 // user, even if it's compatible with other packages. 7145 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7146 if (ps.primaryCpuAbiString == null) { 7147 continue; 7148 } 7149 7150 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7151 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7152 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7153 // this but there's not much we can do. 7154 String errorMessage = "Instruction set mismatch, " 7155 + ((requirer == null) ? "[caller]" : requirer) 7156 + " requires " + requiredInstructionSet + " whereas " + ps 7157 + " requires " + instructionSet; 7158 Slog.w(TAG, errorMessage); 7159 } 7160 7161 if (requiredInstructionSet == null) { 7162 requiredInstructionSet = instructionSet; 7163 requirer = ps; 7164 } 7165 } 7166 } 7167 7168 if (requiredInstructionSet != null) { 7169 String adjustedAbi; 7170 if (requirer != null) { 7171 // requirer != null implies that either scannedPackage was null or that scannedPackage 7172 // did not require an ABI, in which case we have to adjust scannedPackage to match 7173 // the ABI of the set (which is the same as requirer's ABI) 7174 adjustedAbi = requirer.primaryCpuAbiString; 7175 if (scannedPackage != null) { 7176 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7177 } 7178 } else { 7179 // requirer == null implies that we're updating all ABIs in the set to 7180 // match scannedPackage. 7181 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7182 } 7183 7184 for (PackageSetting ps : packagesForUser) { 7185 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7186 if (ps.primaryCpuAbiString != null) { 7187 continue; 7188 } 7189 7190 ps.primaryCpuAbiString = adjustedAbi; 7191 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7192 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7193 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7194 7195 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7196 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7197 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7198 ps.primaryCpuAbiString = null; 7199 ps.pkg.applicationInfo.primaryCpuAbi = null; 7200 return; 7201 } else { 7202 mInstaller.rmdex(ps.codePathString, 7203 getDexCodeInstructionSet(getPreferredInstructionSet())); 7204 } 7205 } 7206 } 7207 } 7208 } 7209 } 7210 7211 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7212 synchronized (mPackages) { 7213 mResolverReplaced = true; 7214 // Set up information for custom user intent resolution activity. 7215 mResolveActivity.applicationInfo = pkg.applicationInfo; 7216 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7217 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7218 mResolveActivity.processName = pkg.applicationInfo.packageName; 7219 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7220 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7221 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7222 mResolveActivity.theme = 0; 7223 mResolveActivity.exported = true; 7224 mResolveActivity.enabled = true; 7225 mResolveInfo.activityInfo = mResolveActivity; 7226 mResolveInfo.priority = 0; 7227 mResolveInfo.preferredOrder = 0; 7228 mResolveInfo.match = 0; 7229 mResolveComponentName = mCustomResolverComponentName; 7230 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7231 mResolveComponentName); 7232 } 7233 } 7234 7235 private static String calculateBundledApkRoot(final String codePathString) { 7236 final File codePath = new File(codePathString); 7237 final File codeRoot; 7238 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7239 codeRoot = Environment.getRootDirectory(); 7240 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7241 codeRoot = Environment.getOemDirectory(); 7242 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7243 codeRoot = Environment.getVendorDirectory(); 7244 } else { 7245 // Unrecognized code path; take its top real segment as the apk root: 7246 // e.g. /something/app/blah.apk => /something 7247 try { 7248 File f = codePath.getCanonicalFile(); 7249 File parent = f.getParentFile(); // non-null because codePath is a file 7250 File tmp; 7251 while ((tmp = parent.getParentFile()) != null) { 7252 f = parent; 7253 parent = tmp; 7254 } 7255 codeRoot = f; 7256 Slog.w(TAG, "Unrecognized code path " 7257 + codePath + " - using " + codeRoot); 7258 } catch (IOException e) { 7259 // Can't canonicalize the code path -- shenanigans? 7260 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7261 return Environment.getRootDirectory().getPath(); 7262 } 7263 } 7264 return codeRoot.getPath(); 7265 } 7266 7267 /** 7268 * Derive and set the location of native libraries for the given package, 7269 * which varies depending on where and how the package was installed. 7270 */ 7271 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7272 final ApplicationInfo info = pkg.applicationInfo; 7273 final String codePath = pkg.codePath; 7274 final File codeFile = new File(codePath); 7275 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7276 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7277 7278 info.nativeLibraryRootDir = null; 7279 info.nativeLibraryRootRequiresIsa = false; 7280 info.nativeLibraryDir = null; 7281 info.secondaryNativeLibraryDir = null; 7282 7283 if (isApkFile(codeFile)) { 7284 // Monolithic install 7285 if (bundledApp) { 7286 // If "/system/lib64/apkname" exists, assume that is the per-package 7287 // native library directory to use; otherwise use "/system/lib/apkname". 7288 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7289 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7290 getPrimaryInstructionSet(info)); 7291 7292 // This is a bundled system app so choose the path based on the ABI. 7293 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7294 // is just the default path. 7295 final String apkName = deriveCodePathName(codePath); 7296 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7297 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7298 apkName).getAbsolutePath(); 7299 7300 if (info.secondaryCpuAbi != null) { 7301 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7302 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7303 secondaryLibDir, apkName).getAbsolutePath(); 7304 } 7305 } else if (asecApp) { 7306 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7307 .getAbsolutePath(); 7308 } else { 7309 final String apkName = deriveCodePathName(codePath); 7310 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7311 .getAbsolutePath(); 7312 } 7313 7314 info.nativeLibraryRootRequiresIsa = false; 7315 info.nativeLibraryDir = info.nativeLibraryRootDir; 7316 } else { 7317 // Cluster install 7318 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7319 info.nativeLibraryRootRequiresIsa = true; 7320 7321 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7322 getPrimaryInstructionSet(info)).getAbsolutePath(); 7323 7324 if (info.secondaryCpuAbi != null) { 7325 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7326 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7327 } 7328 } 7329 } 7330 7331 /** 7332 * Calculate the abis and roots for a bundled app. These can uniquely 7333 * be determined from the contents of the system partition, i.e whether 7334 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7335 * of this information, and instead assume that the system was built 7336 * sensibly. 7337 */ 7338 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7339 PackageSetting pkgSetting) { 7340 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7341 7342 // If "/system/lib64/apkname" exists, assume that is the per-package 7343 // native library directory to use; otherwise use "/system/lib/apkname". 7344 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7345 setBundledAppAbi(pkg, apkRoot, apkName); 7346 // pkgSetting might be null during rescan following uninstall of updates 7347 // to a bundled app, so accommodate that possibility. The settings in 7348 // that case will be established later from the parsed package. 7349 // 7350 // If the settings aren't null, sync them up with what we've just derived. 7351 // note that apkRoot isn't stored in the package settings. 7352 if (pkgSetting != null) { 7353 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7354 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7355 } 7356 } 7357 7358 /** 7359 * Deduces the ABI of a bundled app and sets the relevant fields on the 7360 * parsed pkg object. 7361 * 7362 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7363 * under which system libraries are installed. 7364 * @param apkName the name of the installed package. 7365 */ 7366 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7367 final File codeFile = new File(pkg.codePath); 7368 7369 final boolean has64BitLibs; 7370 final boolean has32BitLibs; 7371 if (isApkFile(codeFile)) { 7372 // Monolithic install 7373 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7374 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7375 } else { 7376 // Cluster install 7377 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7378 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7379 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7380 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7381 has64BitLibs = (new File(rootDir, isa)).exists(); 7382 } else { 7383 has64BitLibs = false; 7384 } 7385 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7386 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7387 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7388 has32BitLibs = (new File(rootDir, isa)).exists(); 7389 } else { 7390 has32BitLibs = false; 7391 } 7392 } 7393 7394 if (has64BitLibs && !has32BitLibs) { 7395 // The package has 64 bit libs, but not 32 bit libs. Its primary 7396 // ABI should be 64 bit. We can safely assume here that the bundled 7397 // native libraries correspond to the most preferred ABI in the list. 7398 7399 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7400 pkg.applicationInfo.secondaryCpuAbi = null; 7401 } else if (has32BitLibs && !has64BitLibs) { 7402 // The package has 32 bit libs but not 64 bit libs. Its primary 7403 // ABI should be 32 bit. 7404 7405 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7406 pkg.applicationInfo.secondaryCpuAbi = null; 7407 } else if (has32BitLibs && has64BitLibs) { 7408 // The application has both 64 and 32 bit bundled libraries. We check 7409 // here that the app declares multiArch support, and warn if it doesn't. 7410 // 7411 // We will be lenient here and record both ABIs. The primary will be the 7412 // ABI that's higher on the list, i.e, a device that's configured to prefer 7413 // 64 bit apps will see a 64 bit primary ABI, 7414 7415 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7416 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7417 } 7418 7419 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7420 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7421 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7422 } else { 7423 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7424 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7425 } 7426 } else { 7427 pkg.applicationInfo.primaryCpuAbi = null; 7428 pkg.applicationInfo.secondaryCpuAbi = null; 7429 } 7430 } 7431 7432 private void killApplication(String pkgName, int appId, String reason) { 7433 // Request the ActivityManager to kill the process(only for existing packages) 7434 // so that we do not end up in a confused state while the user is still using the older 7435 // version of the application while the new one gets installed. 7436 IActivityManager am = ActivityManagerNative.getDefault(); 7437 if (am != null) { 7438 try { 7439 am.killApplicationWithAppId(pkgName, appId, reason); 7440 } catch (RemoteException e) { 7441 } 7442 } 7443 } 7444 7445 void removePackageLI(PackageSetting ps, boolean chatty) { 7446 if (DEBUG_INSTALL) { 7447 if (chatty) 7448 Log.d(TAG, "Removing package " + ps.name); 7449 } 7450 7451 // writer 7452 synchronized (mPackages) { 7453 mPackages.remove(ps.name); 7454 final PackageParser.Package pkg = ps.pkg; 7455 if (pkg != null) { 7456 cleanPackageDataStructuresLILPw(pkg, chatty); 7457 } 7458 } 7459 } 7460 7461 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7462 if (DEBUG_INSTALL) { 7463 if (chatty) 7464 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7465 } 7466 7467 // writer 7468 synchronized (mPackages) { 7469 mPackages.remove(pkg.applicationInfo.packageName); 7470 cleanPackageDataStructuresLILPw(pkg, chatty); 7471 } 7472 } 7473 7474 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7475 int N = pkg.providers.size(); 7476 StringBuilder r = null; 7477 int i; 7478 for (i=0; i<N; i++) { 7479 PackageParser.Provider p = pkg.providers.get(i); 7480 mProviders.removeProvider(p); 7481 if (p.info.authority == null) { 7482 7483 /* There was another ContentProvider with this authority when 7484 * this app was installed so this authority is null, 7485 * Ignore it as we don't have to unregister the provider. 7486 */ 7487 continue; 7488 } 7489 String names[] = p.info.authority.split(";"); 7490 for (int j = 0; j < names.length; j++) { 7491 if (mProvidersByAuthority.get(names[j]) == p) { 7492 mProvidersByAuthority.remove(names[j]); 7493 if (DEBUG_REMOVE) { 7494 if (chatty) 7495 Log.d(TAG, "Unregistered content provider: " + names[j] 7496 + ", className = " + p.info.name + ", isSyncable = " 7497 + p.info.isSyncable); 7498 } 7499 } 7500 } 7501 if (DEBUG_REMOVE && chatty) { 7502 if (r == null) { 7503 r = new StringBuilder(256); 7504 } else { 7505 r.append(' '); 7506 } 7507 r.append(p.info.name); 7508 } 7509 } 7510 if (r != null) { 7511 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7512 } 7513 7514 N = pkg.services.size(); 7515 r = null; 7516 for (i=0; i<N; i++) { 7517 PackageParser.Service s = pkg.services.get(i); 7518 mServices.removeService(s); 7519 if (chatty) { 7520 if (r == null) { 7521 r = new StringBuilder(256); 7522 } else { 7523 r.append(' '); 7524 } 7525 r.append(s.info.name); 7526 } 7527 } 7528 if (r != null) { 7529 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7530 } 7531 7532 N = pkg.receivers.size(); 7533 r = null; 7534 for (i=0; i<N; i++) { 7535 PackageParser.Activity a = pkg.receivers.get(i); 7536 mReceivers.removeActivity(a, "receiver"); 7537 if (DEBUG_REMOVE && chatty) { 7538 if (r == null) { 7539 r = new StringBuilder(256); 7540 } else { 7541 r.append(' '); 7542 } 7543 r.append(a.info.name); 7544 } 7545 } 7546 if (r != null) { 7547 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7548 } 7549 7550 N = pkg.activities.size(); 7551 r = null; 7552 for (i=0; i<N; i++) { 7553 PackageParser.Activity a = pkg.activities.get(i); 7554 mActivities.removeActivity(a, "activity"); 7555 if (DEBUG_REMOVE && chatty) { 7556 if (r == null) { 7557 r = new StringBuilder(256); 7558 } else { 7559 r.append(' '); 7560 } 7561 r.append(a.info.name); 7562 } 7563 } 7564 if (r != null) { 7565 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7566 } 7567 7568 N = pkg.permissions.size(); 7569 r = null; 7570 for (i=0; i<N; i++) { 7571 PackageParser.Permission p = pkg.permissions.get(i); 7572 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7573 if (bp == null) { 7574 bp = mSettings.mPermissionTrees.get(p.info.name); 7575 } 7576 if (bp != null && bp.perm == p) { 7577 bp.perm = null; 7578 if (DEBUG_REMOVE && chatty) { 7579 if (r == null) { 7580 r = new StringBuilder(256); 7581 } else { 7582 r.append(' '); 7583 } 7584 r.append(p.info.name); 7585 } 7586 } 7587 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7588 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7589 if (appOpPerms != null) { 7590 appOpPerms.remove(pkg.packageName); 7591 } 7592 } 7593 } 7594 if (r != null) { 7595 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7596 } 7597 7598 N = pkg.requestedPermissions.size(); 7599 r = null; 7600 for (i=0; i<N; i++) { 7601 String perm = pkg.requestedPermissions.get(i); 7602 BasePermission bp = mSettings.mPermissions.get(perm); 7603 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7604 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7605 if (appOpPerms != null) { 7606 appOpPerms.remove(pkg.packageName); 7607 if (appOpPerms.isEmpty()) { 7608 mAppOpPermissionPackages.remove(perm); 7609 } 7610 } 7611 } 7612 } 7613 if (r != null) { 7614 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7615 } 7616 7617 N = pkg.instrumentation.size(); 7618 r = null; 7619 for (i=0; i<N; i++) { 7620 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7621 mInstrumentation.remove(a.getComponentName()); 7622 if (DEBUG_REMOVE && chatty) { 7623 if (r == null) { 7624 r = new StringBuilder(256); 7625 } else { 7626 r.append(' '); 7627 } 7628 r.append(a.info.name); 7629 } 7630 } 7631 if (r != null) { 7632 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7633 } 7634 7635 r = null; 7636 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7637 // Only system apps can hold shared libraries. 7638 if (pkg.libraryNames != null) { 7639 for (i=0; i<pkg.libraryNames.size(); i++) { 7640 String name = pkg.libraryNames.get(i); 7641 SharedLibraryEntry cur = mSharedLibraries.get(name); 7642 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7643 mSharedLibraries.remove(name); 7644 if (DEBUG_REMOVE && chatty) { 7645 if (r == null) { 7646 r = new StringBuilder(256); 7647 } else { 7648 r.append(' '); 7649 } 7650 r.append(name); 7651 } 7652 } 7653 } 7654 } 7655 } 7656 if (r != null) { 7657 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7658 } 7659 } 7660 7661 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7662 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7663 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7664 return true; 7665 } 7666 } 7667 return false; 7668 } 7669 7670 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7671 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7672 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7673 7674 private void updatePermissionsLPw(String changingPkg, 7675 PackageParser.Package pkgInfo, int flags) { 7676 // Make sure there are no dangling permission trees. 7677 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7678 while (it.hasNext()) { 7679 final BasePermission bp = it.next(); 7680 if (bp.packageSetting == null) { 7681 // We may not yet have parsed the package, so just see if 7682 // we still know about its settings. 7683 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7684 } 7685 if (bp.packageSetting == null) { 7686 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7687 + " from package " + bp.sourcePackage); 7688 it.remove(); 7689 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7690 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7691 Slog.i(TAG, "Removing old permission tree: " + bp.name 7692 + " from package " + bp.sourcePackage); 7693 flags |= UPDATE_PERMISSIONS_ALL; 7694 it.remove(); 7695 } 7696 } 7697 } 7698 7699 // Make sure all dynamic permissions have been assigned to a package, 7700 // and make sure there are no dangling permissions. 7701 it = mSettings.mPermissions.values().iterator(); 7702 while (it.hasNext()) { 7703 final BasePermission bp = it.next(); 7704 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7705 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7706 + bp.name + " pkg=" + bp.sourcePackage 7707 + " info=" + bp.pendingInfo); 7708 if (bp.packageSetting == null && bp.pendingInfo != null) { 7709 final BasePermission tree = findPermissionTreeLP(bp.name); 7710 if (tree != null && tree.perm != null) { 7711 bp.packageSetting = tree.packageSetting; 7712 bp.perm = new PackageParser.Permission(tree.perm.owner, 7713 new PermissionInfo(bp.pendingInfo)); 7714 bp.perm.info.packageName = tree.perm.info.packageName; 7715 bp.perm.info.name = bp.name; 7716 bp.uid = tree.uid; 7717 } 7718 } 7719 } 7720 if (bp.packageSetting == null) { 7721 // We may not yet have parsed the package, so just see if 7722 // we still know about its settings. 7723 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7724 } 7725 if (bp.packageSetting == null) { 7726 Slog.w(TAG, "Removing dangling permission: " + bp.name 7727 + " from package " + bp.sourcePackage); 7728 it.remove(); 7729 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7730 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7731 Slog.i(TAG, "Removing old permission: " + bp.name 7732 + " from package " + bp.sourcePackage); 7733 flags |= UPDATE_PERMISSIONS_ALL; 7734 it.remove(); 7735 } 7736 } 7737 } 7738 7739 // Now update the permissions for all packages, in particular 7740 // replace the granted permissions of the system packages. 7741 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7742 for (PackageParser.Package pkg : mPackages.values()) { 7743 if (pkg != pkgInfo) { 7744 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7745 changingPkg); 7746 } 7747 } 7748 } 7749 7750 if (pkgInfo != null) { 7751 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7752 } 7753 } 7754 7755 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7756 String packageOfInterest) { 7757 // IMPORTANT: There are two types of permissions: install and runtime. 7758 // Install time permissions are granted when the app is installed to 7759 // all device users and users added in the future. Runtime permissions 7760 // are granted at runtime explicitly to specific users. Normal and signature 7761 // protected permissions are install time permissions. Dangerous permissions 7762 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7763 // otherwise they are runtime permissions. This function does not manage 7764 // runtime permissions except for the case an app targeting Lollipop MR1 7765 // being upgraded to target a newer SDK, in which case dangerous permissions 7766 // are transformed from install time to runtime ones. 7767 7768 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7769 if (ps == null) { 7770 return; 7771 } 7772 7773 PermissionsState permissionsState = ps.getPermissionsState(); 7774 PermissionsState origPermissions = permissionsState; 7775 7776 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7777 7778 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7779 7780 boolean changedInstallPermission = false; 7781 7782 if (replace) { 7783 ps.installPermissionsFixed = false; 7784 if (!ps.isSharedUser()) { 7785 origPermissions = new PermissionsState(permissionsState); 7786 permissionsState.reset(); 7787 } 7788 } 7789 7790 permissionsState.setGlobalGids(mGlobalGids); 7791 7792 final int N = pkg.requestedPermissions.size(); 7793 for (int i=0; i<N; i++) { 7794 final String name = pkg.requestedPermissions.get(i); 7795 final BasePermission bp = mSettings.mPermissions.get(name); 7796 7797 if (DEBUG_INSTALL) { 7798 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7799 } 7800 7801 if (bp == null || bp.packageSetting == null) { 7802 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7803 Slog.w(TAG, "Unknown permission " + name 7804 + " in package " + pkg.packageName); 7805 } 7806 continue; 7807 } 7808 7809 final String perm = bp.name; 7810 boolean allowedSig = false; 7811 int grant = GRANT_DENIED; 7812 7813 // Keep track of app op permissions. 7814 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7815 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7816 if (pkgs == null) { 7817 pkgs = new ArraySet<>(); 7818 mAppOpPermissionPackages.put(bp.name, pkgs); 7819 } 7820 pkgs.add(pkg.packageName); 7821 } 7822 7823 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7824 switch (level) { 7825 case PermissionInfo.PROTECTION_NORMAL: { 7826 // For all apps normal permissions are install time ones. 7827 grant = GRANT_INSTALL; 7828 } break; 7829 7830 case PermissionInfo.PROTECTION_DANGEROUS: { 7831 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7832 // For legacy apps dangerous permissions are install time ones. 7833 grant = GRANT_INSTALL_LEGACY; 7834 } else if (origPermissions.hasInstallPermission(bp.name)) { 7835 // For legacy apps that became modern, install becomes runtime. 7836 grant = GRANT_UPGRADE; 7837 } else { 7838 // For modern apps keep runtime permissions unchanged. 7839 grant = GRANT_RUNTIME; 7840 } 7841 } break; 7842 7843 case PermissionInfo.PROTECTION_SIGNATURE: { 7844 // For all apps signature permissions are install time ones. 7845 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7846 if (allowedSig) { 7847 grant = GRANT_INSTALL; 7848 } 7849 } break; 7850 } 7851 7852 if (DEBUG_INSTALL) { 7853 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7854 } 7855 7856 if (grant != GRANT_DENIED) { 7857 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7858 // If this is an existing, non-system package, then 7859 // we can't add any new permissions to it. 7860 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7861 // Except... if this is a permission that was added 7862 // to the platform (note: need to only do this when 7863 // updating the platform). 7864 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7865 grant = GRANT_DENIED; 7866 } 7867 } 7868 } 7869 7870 switch (grant) { 7871 case GRANT_INSTALL: { 7872 // Revoke this as runtime permission to handle the case of 7873 // a runtime permission being downgraded to an install one. 7874 for (int userId : UserManagerService.getInstance().getUserIds()) { 7875 if (origPermissions.getRuntimePermissionState( 7876 bp.name, userId) != null) { 7877 // Revoke the runtime permission and clear the flags. 7878 origPermissions.revokeRuntimePermission(bp, userId); 7879 origPermissions.updatePermissionFlags(bp, userId, 7880 PackageManager.MASK_PERMISSION_FLAGS, 0); 7881 // If we revoked a permission permission, we have to write. 7882 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7883 changedRuntimePermissionUserIds, userId); 7884 } 7885 } 7886 // Grant an install permission. 7887 if (permissionsState.grantInstallPermission(bp) != 7888 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7889 changedInstallPermission = true; 7890 } 7891 } break; 7892 7893 case GRANT_INSTALL_LEGACY: { 7894 // Grant an install permission. 7895 if (permissionsState.grantInstallPermission(bp) != 7896 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7897 changedInstallPermission = true; 7898 } 7899 } break; 7900 7901 case GRANT_RUNTIME: { 7902 // Grant previously granted runtime permissions. 7903 for (int userId : UserManagerService.getInstance().getUserIds()) { 7904 PermissionState permissionState = origPermissions 7905 .getRuntimePermissionState(bp.name, userId); 7906 final int flags = permissionState != null 7907 ? permissionState.getFlags() : 0; 7908 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7909 if (permissionsState.grantRuntimePermission(bp, userId) == 7910 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7911 // If we cannot put the permission as it was, we have to write. 7912 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7913 changedRuntimePermissionUserIds, userId); 7914 } 7915 } 7916 // Propagate the permission flags. 7917 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 7918 } 7919 } break; 7920 7921 case GRANT_UPGRADE: { 7922 // Grant runtime permissions for a previously held install permission. 7923 PermissionState permissionState = origPermissions 7924 .getInstallPermissionState(bp.name); 7925 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7926 7927 if (origPermissions.revokeInstallPermission(bp) 7928 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 7929 // We will be transferring the permission flags, so clear them. 7930 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7931 PackageManager.MASK_PERMISSION_FLAGS, 0); 7932 changedInstallPermission = true; 7933 } 7934 7935 // If the permission is not to be promoted to runtime we ignore it and 7936 // also its other flags as they are not applicable to install permissions. 7937 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7938 for (int userId : currentUserIds) { 7939 if (permissionsState.grantRuntimePermission(bp, userId) != 7940 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7941 // Transfer the permission flags. 7942 permissionsState.updatePermissionFlags(bp, userId, 7943 flags, flags); 7944 // If we granted the permission, we have to write. 7945 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7946 changedRuntimePermissionUserIds, userId); 7947 } 7948 } 7949 } 7950 } break; 7951 7952 default: { 7953 if (packageOfInterest == null 7954 || packageOfInterest.equals(pkg.packageName)) { 7955 Slog.w(TAG, "Not granting permission " + perm 7956 + " to package " + pkg.packageName 7957 + " because it was previously installed without"); 7958 } 7959 } break; 7960 } 7961 } else { 7962 if (permissionsState.revokeInstallPermission(bp) != 7963 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7964 // Also drop the permission flags. 7965 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7966 PackageManager.MASK_PERMISSION_FLAGS, 0); 7967 changedInstallPermission = true; 7968 Slog.i(TAG, "Un-granting permission " + perm 7969 + " from package " + pkg.packageName 7970 + " (protectionLevel=" + bp.protectionLevel 7971 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7972 + ")"); 7973 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7974 // Don't print warning for app op permissions, since it is fine for them 7975 // not to be granted, there is a UI for the user to decide. 7976 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7977 Slog.w(TAG, "Not granting permission " + perm 7978 + " to package " + pkg.packageName 7979 + " (protectionLevel=" + bp.protectionLevel 7980 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7981 + ")"); 7982 } 7983 } 7984 } 7985 } 7986 7987 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7988 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7989 // This is the first that we have heard about this package, so the 7990 // permissions we have now selected are fixed until explicitly 7991 // changed. 7992 ps.installPermissionsFixed = true; 7993 } 7994 7995 // Persist the runtime permissions state for users with changes. 7996 for (int userId : changedRuntimePermissionUserIds) { 7997 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 7998 } 7999 } 8000 8001 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8002 boolean allowed = false; 8003 final int NP = PackageParser.NEW_PERMISSIONS.length; 8004 for (int ip=0; ip<NP; ip++) { 8005 final PackageParser.NewPermissionInfo npi 8006 = PackageParser.NEW_PERMISSIONS[ip]; 8007 if (npi.name.equals(perm) 8008 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8009 allowed = true; 8010 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8011 + pkg.packageName); 8012 break; 8013 } 8014 } 8015 return allowed; 8016 } 8017 8018 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8019 BasePermission bp, PermissionsState origPermissions) { 8020 boolean allowed; 8021 allowed = (compareSignatures( 8022 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8023 == PackageManager.SIGNATURE_MATCH) 8024 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8025 == PackageManager.SIGNATURE_MATCH); 8026 if (!allowed && (bp.protectionLevel 8027 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8028 if (isSystemApp(pkg)) { 8029 // For updated system applications, a system permission 8030 // is granted only if it had been defined by the original application. 8031 if (pkg.isUpdatedSystemApp()) { 8032 final PackageSetting sysPs = mSettings 8033 .getDisabledSystemPkgLPr(pkg.packageName); 8034 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8035 // If the original was granted this permission, we take 8036 // that grant decision as read and propagate it to the 8037 // update. 8038 if (sysPs.isPrivileged()) { 8039 allowed = true; 8040 } 8041 } else { 8042 // The system apk may have been updated with an older 8043 // version of the one on the data partition, but which 8044 // granted a new system permission that it didn't have 8045 // before. In this case we do want to allow the app to 8046 // now get the new permission if the ancestral apk is 8047 // privileged to get it. 8048 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8049 for (int j=0; 8050 j<sysPs.pkg.requestedPermissions.size(); j++) { 8051 if (perm.equals( 8052 sysPs.pkg.requestedPermissions.get(j))) { 8053 allowed = true; 8054 break; 8055 } 8056 } 8057 } 8058 } 8059 } else { 8060 allowed = isPrivilegedApp(pkg); 8061 } 8062 } 8063 } 8064 if (!allowed && (bp.protectionLevel 8065 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8066 // For development permissions, a development permission 8067 // is granted only if it was already granted. 8068 allowed = origPermissions.hasInstallPermission(perm); 8069 } 8070 return allowed; 8071 } 8072 8073 final class ActivityIntentResolver 8074 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8075 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8076 boolean defaultOnly, int userId) { 8077 if (!sUserManager.exists(userId)) return null; 8078 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8079 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8080 } 8081 8082 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8083 int userId) { 8084 if (!sUserManager.exists(userId)) return null; 8085 mFlags = flags; 8086 return super.queryIntent(intent, resolvedType, 8087 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8088 } 8089 8090 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8091 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8092 if (!sUserManager.exists(userId)) return null; 8093 if (packageActivities == null) { 8094 return null; 8095 } 8096 mFlags = flags; 8097 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8098 final int N = packageActivities.size(); 8099 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8100 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8101 8102 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8103 for (int i = 0; i < N; ++i) { 8104 intentFilters = packageActivities.get(i).intents; 8105 if (intentFilters != null && intentFilters.size() > 0) { 8106 PackageParser.ActivityIntentInfo[] array = 8107 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8108 intentFilters.toArray(array); 8109 listCut.add(array); 8110 } 8111 } 8112 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8113 } 8114 8115 public final void addActivity(PackageParser.Activity a, String type) { 8116 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8117 mActivities.put(a.getComponentName(), a); 8118 if (DEBUG_SHOW_INFO) 8119 Log.v( 8120 TAG, " " + type + " " + 8121 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8122 if (DEBUG_SHOW_INFO) 8123 Log.v(TAG, " Class=" + a.info.name); 8124 final int NI = a.intents.size(); 8125 for (int j=0; j<NI; j++) { 8126 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8127 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8128 intent.setPriority(0); 8129 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8130 + a.className + " with priority > 0, forcing to 0"); 8131 } 8132 if (DEBUG_SHOW_INFO) { 8133 Log.v(TAG, " IntentFilter:"); 8134 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8135 } 8136 if (!intent.debugCheck()) { 8137 Log.w(TAG, "==> For Activity " + a.info.name); 8138 } 8139 addFilter(intent); 8140 } 8141 } 8142 8143 public final void removeActivity(PackageParser.Activity a, String type) { 8144 mActivities.remove(a.getComponentName()); 8145 if (DEBUG_SHOW_INFO) { 8146 Log.v(TAG, " " + type + " " 8147 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8148 : a.info.name) + ":"); 8149 Log.v(TAG, " Class=" + a.info.name); 8150 } 8151 final int NI = a.intents.size(); 8152 for (int j=0; j<NI; j++) { 8153 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8154 if (DEBUG_SHOW_INFO) { 8155 Log.v(TAG, " IntentFilter:"); 8156 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8157 } 8158 removeFilter(intent); 8159 } 8160 } 8161 8162 @Override 8163 protected boolean allowFilterResult( 8164 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8165 ActivityInfo filterAi = filter.activity.info; 8166 for (int i=dest.size()-1; i>=0; i--) { 8167 ActivityInfo destAi = dest.get(i).activityInfo; 8168 if (destAi.name == filterAi.name 8169 && destAi.packageName == filterAi.packageName) { 8170 return false; 8171 } 8172 } 8173 return true; 8174 } 8175 8176 @Override 8177 protected ActivityIntentInfo[] newArray(int size) { 8178 return new ActivityIntentInfo[size]; 8179 } 8180 8181 @Override 8182 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8183 if (!sUserManager.exists(userId)) return true; 8184 PackageParser.Package p = filter.activity.owner; 8185 if (p != null) { 8186 PackageSetting ps = (PackageSetting)p.mExtras; 8187 if (ps != null) { 8188 // System apps are never considered stopped for purposes of 8189 // filtering, because there may be no way for the user to 8190 // actually re-launch them. 8191 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8192 && ps.getStopped(userId); 8193 } 8194 } 8195 return false; 8196 } 8197 8198 @Override 8199 protected boolean isPackageForFilter(String packageName, 8200 PackageParser.ActivityIntentInfo info) { 8201 return packageName.equals(info.activity.owner.packageName); 8202 } 8203 8204 @Override 8205 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8206 int match, int userId) { 8207 if (!sUserManager.exists(userId)) return null; 8208 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8209 return null; 8210 } 8211 final PackageParser.Activity activity = info.activity; 8212 if (mSafeMode && (activity.info.applicationInfo.flags 8213 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8214 return null; 8215 } 8216 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8217 if (ps == null) { 8218 return null; 8219 } 8220 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8221 ps.readUserState(userId), userId); 8222 if (ai == null) { 8223 return null; 8224 } 8225 final ResolveInfo res = new ResolveInfo(); 8226 res.activityInfo = ai; 8227 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8228 res.filter = info; 8229 } 8230 if (info != null) { 8231 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8232 } 8233 res.priority = info.getPriority(); 8234 res.preferredOrder = activity.owner.mPreferredOrder; 8235 //System.out.println("Result: " + res.activityInfo.className + 8236 // " = " + res.priority); 8237 res.match = match; 8238 res.isDefault = info.hasDefault; 8239 res.labelRes = info.labelRes; 8240 res.nonLocalizedLabel = info.nonLocalizedLabel; 8241 if (userNeedsBadging(userId)) { 8242 res.noResourceId = true; 8243 } else { 8244 res.icon = info.icon; 8245 } 8246 res.iconResourceId = info.icon; 8247 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8248 return res; 8249 } 8250 8251 @Override 8252 protected void sortResults(List<ResolveInfo> results) { 8253 Collections.sort(results, mResolvePrioritySorter); 8254 } 8255 8256 @Override 8257 protected void dumpFilter(PrintWriter out, String prefix, 8258 PackageParser.ActivityIntentInfo filter) { 8259 out.print(prefix); out.print( 8260 Integer.toHexString(System.identityHashCode(filter.activity))); 8261 out.print(' '); 8262 filter.activity.printComponentShortName(out); 8263 out.print(" filter "); 8264 out.println(Integer.toHexString(System.identityHashCode(filter))); 8265 } 8266 8267 @Override 8268 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8269 return filter.activity; 8270 } 8271 8272 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8273 PackageParser.Activity activity = (PackageParser.Activity)label; 8274 out.print(prefix); out.print( 8275 Integer.toHexString(System.identityHashCode(activity))); 8276 out.print(' '); 8277 activity.printComponentShortName(out); 8278 if (count > 1) { 8279 out.print(" ("); out.print(count); out.print(" filters)"); 8280 } 8281 out.println(); 8282 } 8283 8284// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8285// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8286// final List<ResolveInfo> retList = Lists.newArrayList(); 8287// while (i.hasNext()) { 8288// final ResolveInfo resolveInfo = i.next(); 8289// if (isEnabledLP(resolveInfo.activityInfo)) { 8290// retList.add(resolveInfo); 8291// } 8292// } 8293// return retList; 8294// } 8295 8296 // Keys are String (activity class name), values are Activity. 8297 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8298 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8299 private int mFlags; 8300 } 8301 8302 private final class ServiceIntentResolver 8303 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8304 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8305 boolean defaultOnly, int userId) { 8306 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8307 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8308 } 8309 8310 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8311 int userId) { 8312 if (!sUserManager.exists(userId)) return null; 8313 mFlags = flags; 8314 return super.queryIntent(intent, resolvedType, 8315 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8316 } 8317 8318 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8319 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8320 if (!sUserManager.exists(userId)) return null; 8321 if (packageServices == null) { 8322 return null; 8323 } 8324 mFlags = flags; 8325 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8326 final int N = packageServices.size(); 8327 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8328 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8329 8330 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8331 for (int i = 0; i < N; ++i) { 8332 intentFilters = packageServices.get(i).intents; 8333 if (intentFilters != null && intentFilters.size() > 0) { 8334 PackageParser.ServiceIntentInfo[] array = 8335 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8336 intentFilters.toArray(array); 8337 listCut.add(array); 8338 } 8339 } 8340 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8341 } 8342 8343 public final void addService(PackageParser.Service s) { 8344 mServices.put(s.getComponentName(), s); 8345 if (DEBUG_SHOW_INFO) { 8346 Log.v(TAG, " " 8347 + (s.info.nonLocalizedLabel != null 8348 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8349 Log.v(TAG, " Class=" + s.info.name); 8350 } 8351 final int NI = s.intents.size(); 8352 int j; 8353 for (j=0; j<NI; j++) { 8354 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8355 if (DEBUG_SHOW_INFO) { 8356 Log.v(TAG, " IntentFilter:"); 8357 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8358 } 8359 if (!intent.debugCheck()) { 8360 Log.w(TAG, "==> For Service " + s.info.name); 8361 } 8362 addFilter(intent); 8363 } 8364 } 8365 8366 public final void removeService(PackageParser.Service s) { 8367 mServices.remove(s.getComponentName()); 8368 if (DEBUG_SHOW_INFO) { 8369 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8370 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8371 Log.v(TAG, " Class=" + s.info.name); 8372 } 8373 final int NI = s.intents.size(); 8374 int j; 8375 for (j=0; j<NI; j++) { 8376 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8377 if (DEBUG_SHOW_INFO) { 8378 Log.v(TAG, " IntentFilter:"); 8379 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8380 } 8381 removeFilter(intent); 8382 } 8383 } 8384 8385 @Override 8386 protected boolean allowFilterResult( 8387 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8388 ServiceInfo filterSi = filter.service.info; 8389 for (int i=dest.size()-1; i>=0; i--) { 8390 ServiceInfo destAi = dest.get(i).serviceInfo; 8391 if (destAi.name == filterSi.name 8392 && destAi.packageName == filterSi.packageName) { 8393 return false; 8394 } 8395 } 8396 return true; 8397 } 8398 8399 @Override 8400 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8401 return new PackageParser.ServiceIntentInfo[size]; 8402 } 8403 8404 @Override 8405 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8406 if (!sUserManager.exists(userId)) return true; 8407 PackageParser.Package p = filter.service.owner; 8408 if (p != null) { 8409 PackageSetting ps = (PackageSetting)p.mExtras; 8410 if (ps != null) { 8411 // System apps are never considered stopped for purposes of 8412 // filtering, because there may be no way for the user to 8413 // actually re-launch them. 8414 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8415 && ps.getStopped(userId); 8416 } 8417 } 8418 return false; 8419 } 8420 8421 @Override 8422 protected boolean isPackageForFilter(String packageName, 8423 PackageParser.ServiceIntentInfo info) { 8424 return packageName.equals(info.service.owner.packageName); 8425 } 8426 8427 @Override 8428 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8429 int match, int userId) { 8430 if (!sUserManager.exists(userId)) return null; 8431 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8432 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8433 return null; 8434 } 8435 final PackageParser.Service service = info.service; 8436 if (mSafeMode && (service.info.applicationInfo.flags 8437 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8438 return null; 8439 } 8440 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8441 if (ps == null) { 8442 return null; 8443 } 8444 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8445 ps.readUserState(userId), userId); 8446 if (si == null) { 8447 return null; 8448 } 8449 final ResolveInfo res = new ResolveInfo(); 8450 res.serviceInfo = si; 8451 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8452 res.filter = filter; 8453 } 8454 res.priority = info.getPriority(); 8455 res.preferredOrder = service.owner.mPreferredOrder; 8456 res.match = match; 8457 res.isDefault = info.hasDefault; 8458 res.labelRes = info.labelRes; 8459 res.nonLocalizedLabel = info.nonLocalizedLabel; 8460 res.icon = info.icon; 8461 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8462 return res; 8463 } 8464 8465 @Override 8466 protected void sortResults(List<ResolveInfo> results) { 8467 Collections.sort(results, mResolvePrioritySorter); 8468 } 8469 8470 @Override 8471 protected void dumpFilter(PrintWriter out, String prefix, 8472 PackageParser.ServiceIntentInfo filter) { 8473 out.print(prefix); out.print( 8474 Integer.toHexString(System.identityHashCode(filter.service))); 8475 out.print(' '); 8476 filter.service.printComponentShortName(out); 8477 out.print(" filter "); 8478 out.println(Integer.toHexString(System.identityHashCode(filter))); 8479 } 8480 8481 @Override 8482 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8483 return filter.service; 8484 } 8485 8486 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8487 PackageParser.Service service = (PackageParser.Service)label; 8488 out.print(prefix); out.print( 8489 Integer.toHexString(System.identityHashCode(service))); 8490 out.print(' '); 8491 service.printComponentShortName(out); 8492 if (count > 1) { 8493 out.print(" ("); out.print(count); out.print(" filters)"); 8494 } 8495 out.println(); 8496 } 8497 8498// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8499// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8500// final List<ResolveInfo> retList = Lists.newArrayList(); 8501// while (i.hasNext()) { 8502// final ResolveInfo resolveInfo = (ResolveInfo) i; 8503// if (isEnabledLP(resolveInfo.serviceInfo)) { 8504// retList.add(resolveInfo); 8505// } 8506// } 8507// return retList; 8508// } 8509 8510 // Keys are String (activity class name), values are Activity. 8511 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8512 = new ArrayMap<ComponentName, PackageParser.Service>(); 8513 private int mFlags; 8514 }; 8515 8516 private final class ProviderIntentResolver 8517 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8518 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8519 boolean defaultOnly, int userId) { 8520 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8521 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8522 } 8523 8524 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8525 int userId) { 8526 if (!sUserManager.exists(userId)) 8527 return null; 8528 mFlags = flags; 8529 return super.queryIntent(intent, resolvedType, 8530 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8531 } 8532 8533 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8534 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8535 if (!sUserManager.exists(userId)) 8536 return null; 8537 if (packageProviders == null) { 8538 return null; 8539 } 8540 mFlags = flags; 8541 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8542 final int N = packageProviders.size(); 8543 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8544 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8545 8546 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8547 for (int i = 0; i < N; ++i) { 8548 intentFilters = packageProviders.get(i).intents; 8549 if (intentFilters != null && intentFilters.size() > 0) { 8550 PackageParser.ProviderIntentInfo[] array = 8551 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8552 intentFilters.toArray(array); 8553 listCut.add(array); 8554 } 8555 } 8556 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8557 } 8558 8559 public final void addProvider(PackageParser.Provider p) { 8560 if (mProviders.containsKey(p.getComponentName())) { 8561 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8562 return; 8563 } 8564 8565 mProviders.put(p.getComponentName(), p); 8566 if (DEBUG_SHOW_INFO) { 8567 Log.v(TAG, " " 8568 + (p.info.nonLocalizedLabel != null 8569 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8570 Log.v(TAG, " Class=" + p.info.name); 8571 } 8572 final int NI = p.intents.size(); 8573 int j; 8574 for (j = 0; j < NI; j++) { 8575 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8576 if (DEBUG_SHOW_INFO) { 8577 Log.v(TAG, " IntentFilter:"); 8578 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8579 } 8580 if (!intent.debugCheck()) { 8581 Log.w(TAG, "==> For Provider " + p.info.name); 8582 } 8583 addFilter(intent); 8584 } 8585 } 8586 8587 public final void removeProvider(PackageParser.Provider p) { 8588 mProviders.remove(p.getComponentName()); 8589 if (DEBUG_SHOW_INFO) { 8590 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8591 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8592 Log.v(TAG, " Class=" + p.info.name); 8593 } 8594 final int NI = p.intents.size(); 8595 int j; 8596 for (j = 0; j < NI; j++) { 8597 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8598 if (DEBUG_SHOW_INFO) { 8599 Log.v(TAG, " IntentFilter:"); 8600 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8601 } 8602 removeFilter(intent); 8603 } 8604 } 8605 8606 @Override 8607 protected boolean allowFilterResult( 8608 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8609 ProviderInfo filterPi = filter.provider.info; 8610 for (int i = dest.size() - 1; i >= 0; i--) { 8611 ProviderInfo destPi = dest.get(i).providerInfo; 8612 if (destPi.name == filterPi.name 8613 && destPi.packageName == filterPi.packageName) { 8614 return false; 8615 } 8616 } 8617 return true; 8618 } 8619 8620 @Override 8621 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8622 return new PackageParser.ProviderIntentInfo[size]; 8623 } 8624 8625 @Override 8626 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8627 if (!sUserManager.exists(userId)) 8628 return true; 8629 PackageParser.Package p = filter.provider.owner; 8630 if (p != null) { 8631 PackageSetting ps = (PackageSetting) p.mExtras; 8632 if (ps != null) { 8633 // System apps are never considered stopped for purposes of 8634 // filtering, because there may be no way for the user to 8635 // actually re-launch them. 8636 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8637 && ps.getStopped(userId); 8638 } 8639 } 8640 return false; 8641 } 8642 8643 @Override 8644 protected boolean isPackageForFilter(String packageName, 8645 PackageParser.ProviderIntentInfo info) { 8646 return packageName.equals(info.provider.owner.packageName); 8647 } 8648 8649 @Override 8650 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8651 int match, int userId) { 8652 if (!sUserManager.exists(userId)) 8653 return null; 8654 final PackageParser.ProviderIntentInfo info = filter; 8655 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8656 return null; 8657 } 8658 final PackageParser.Provider provider = info.provider; 8659 if (mSafeMode && (provider.info.applicationInfo.flags 8660 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8661 return null; 8662 } 8663 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8664 if (ps == null) { 8665 return null; 8666 } 8667 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8668 ps.readUserState(userId), userId); 8669 if (pi == null) { 8670 return null; 8671 } 8672 final ResolveInfo res = new ResolveInfo(); 8673 res.providerInfo = pi; 8674 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8675 res.filter = filter; 8676 } 8677 res.priority = info.getPriority(); 8678 res.preferredOrder = provider.owner.mPreferredOrder; 8679 res.match = match; 8680 res.isDefault = info.hasDefault; 8681 res.labelRes = info.labelRes; 8682 res.nonLocalizedLabel = info.nonLocalizedLabel; 8683 res.icon = info.icon; 8684 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8685 return res; 8686 } 8687 8688 @Override 8689 protected void sortResults(List<ResolveInfo> results) { 8690 Collections.sort(results, mResolvePrioritySorter); 8691 } 8692 8693 @Override 8694 protected void dumpFilter(PrintWriter out, String prefix, 8695 PackageParser.ProviderIntentInfo filter) { 8696 out.print(prefix); 8697 out.print( 8698 Integer.toHexString(System.identityHashCode(filter.provider))); 8699 out.print(' '); 8700 filter.provider.printComponentShortName(out); 8701 out.print(" filter "); 8702 out.println(Integer.toHexString(System.identityHashCode(filter))); 8703 } 8704 8705 @Override 8706 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8707 return filter.provider; 8708 } 8709 8710 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8711 PackageParser.Provider provider = (PackageParser.Provider)label; 8712 out.print(prefix); out.print( 8713 Integer.toHexString(System.identityHashCode(provider))); 8714 out.print(' '); 8715 provider.printComponentShortName(out); 8716 if (count > 1) { 8717 out.print(" ("); out.print(count); out.print(" filters)"); 8718 } 8719 out.println(); 8720 } 8721 8722 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8723 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8724 private int mFlags; 8725 }; 8726 8727 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8728 new Comparator<ResolveInfo>() { 8729 public int compare(ResolveInfo r1, ResolveInfo r2) { 8730 int v1 = r1.priority; 8731 int v2 = r2.priority; 8732 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8733 if (v1 != v2) { 8734 return (v1 > v2) ? -1 : 1; 8735 } 8736 v1 = r1.preferredOrder; 8737 v2 = r2.preferredOrder; 8738 if (v1 != v2) { 8739 return (v1 > v2) ? -1 : 1; 8740 } 8741 if (r1.isDefault != r2.isDefault) { 8742 return r1.isDefault ? -1 : 1; 8743 } 8744 v1 = r1.match; 8745 v2 = r2.match; 8746 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8747 if (v1 != v2) { 8748 return (v1 > v2) ? -1 : 1; 8749 } 8750 if (r1.system != r2.system) { 8751 return r1.system ? -1 : 1; 8752 } 8753 return 0; 8754 } 8755 }; 8756 8757 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8758 new Comparator<ProviderInfo>() { 8759 public int compare(ProviderInfo p1, ProviderInfo p2) { 8760 final int v1 = p1.initOrder; 8761 final int v2 = p2.initOrder; 8762 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8763 } 8764 }; 8765 8766 final void sendPackageBroadcast(final String action, final String pkg, 8767 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8768 final int[] userIds) { 8769 mHandler.post(new Runnable() { 8770 @Override 8771 public void run() { 8772 try { 8773 final IActivityManager am = ActivityManagerNative.getDefault(); 8774 if (am == null) return; 8775 final int[] resolvedUserIds; 8776 if (userIds == null) { 8777 resolvedUserIds = am.getRunningUserIds(); 8778 } else { 8779 resolvedUserIds = userIds; 8780 } 8781 for (int id : resolvedUserIds) { 8782 final Intent intent = new Intent(action, 8783 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8784 if (extras != null) { 8785 intent.putExtras(extras); 8786 } 8787 if (targetPkg != null) { 8788 intent.setPackage(targetPkg); 8789 } 8790 // Modify the UID when posting to other users 8791 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8792 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8793 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8794 intent.putExtra(Intent.EXTRA_UID, uid); 8795 } 8796 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8797 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8798 if (DEBUG_BROADCASTS) { 8799 RuntimeException here = new RuntimeException("here"); 8800 here.fillInStackTrace(); 8801 Slog.d(TAG, "Sending to user " + id + ": " 8802 + intent.toShortString(false, true, false, false) 8803 + " " + intent.getExtras(), here); 8804 } 8805 am.broadcastIntent(null, intent, null, finishedReceiver, 8806 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8807 null, finishedReceiver != null, false, id); 8808 } 8809 } catch (RemoteException ex) { 8810 } 8811 } 8812 }); 8813 } 8814 8815 /** 8816 * Check if the external storage media is available. This is true if there 8817 * is a mounted external storage medium or if the external storage is 8818 * emulated. 8819 */ 8820 private boolean isExternalMediaAvailable() { 8821 return mMediaMounted || Environment.isExternalStorageEmulated(); 8822 } 8823 8824 @Override 8825 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8826 // writer 8827 synchronized (mPackages) { 8828 if (!isExternalMediaAvailable()) { 8829 // If the external storage is no longer mounted at this point, 8830 // the caller may not have been able to delete all of this 8831 // packages files and can not delete any more. Bail. 8832 return null; 8833 } 8834 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8835 if (lastPackage != null) { 8836 pkgs.remove(lastPackage); 8837 } 8838 if (pkgs.size() > 0) { 8839 return pkgs.get(0); 8840 } 8841 } 8842 return null; 8843 } 8844 8845 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8846 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8847 userId, andCode ? 1 : 0, packageName); 8848 if (mSystemReady) { 8849 msg.sendToTarget(); 8850 } else { 8851 if (mPostSystemReadyMessages == null) { 8852 mPostSystemReadyMessages = new ArrayList<>(); 8853 } 8854 mPostSystemReadyMessages.add(msg); 8855 } 8856 } 8857 8858 void startCleaningPackages() { 8859 // reader 8860 synchronized (mPackages) { 8861 if (!isExternalMediaAvailable()) { 8862 return; 8863 } 8864 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8865 return; 8866 } 8867 } 8868 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8869 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8870 IActivityManager am = ActivityManagerNative.getDefault(); 8871 if (am != null) { 8872 try { 8873 am.startService(null, intent, null, UserHandle.USER_OWNER); 8874 } catch (RemoteException e) { 8875 } 8876 } 8877 } 8878 8879 @Override 8880 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8881 int installFlags, String installerPackageName, VerificationParams verificationParams, 8882 String packageAbiOverride) { 8883 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8884 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8885 } 8886 8887 @Override 8888 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8889 int installFlags, String installerPackageName, VerificationParams verificationParams, 8890 String packageAbiOverride, int userId) { 8891 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8892 8893 final int callingUid = Binder.getCallingUid(); 8894 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8895 8896 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8897 try { 8898 if (observer != null) { 8899 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8900 } 8901 } catch (RemoteException re) { 8902 } 8903 return; 8904 } 8905 8906 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8907 installFlags |= PackageManager.INSTALL_FROM_ADB; 8908 8909 } else { 8910 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8911 // about installerPackageName. 8912 8913 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8914 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8915 } 8916 8917 UserHandle user; 8918 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8919 user = UserHandle.ALL; 8920 } else { 8921 user = new UserHandle(userId); 8922 } 8923 8924 // Only system components can circumvent runtime permissions when installing. 8925 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8926 && mContext.checkCallingOrSelfPermission(Manifest.permission 8927 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8928 throw new SecurityException("You need the " 8929 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8930 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8931 } 8932 8933 verificationParams.setInstallerUid(callingUid); 8934 8935 final File originFile = new File(originPath); 8936 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8937 8938 final Message msg = mHandler.obtainMessage(INIT_COPY); 8939 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8940 null, verificationParams, user, packageAbiOverride); 8941 mHandler.sendMessage(msg); 8942 } 8943 8944 void installStage(String packageName, File stagedDir, String stagedCid, 8945 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8946 String installerPackageName, int installerUid, UserHandle user) { 8947 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8948 params.referrerUri, installerUid, null); 8949 8950 final OriginInfo origin; 8951 if (stagedDir != null) { 8952 origin = OriginInfo.fromStagedFile(stagedDir); 8953 } else { 8954 origin = OriginInfo.fromStagedContainer(stagedCid); 8955 } 8956 8957 final Message msg = mHandler.obtainMessage(INIT_COPY); 8958 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8959 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8960 mHandler.sendMessage(msg); 8961 } 8962 8963 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8964 Bundle extras = new Bundle(1); 8965 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8966 8967 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8968 packageName, extras, null, null, new int[] {userId}); 8969 try { 8970 IActivityManager am = ActivityManagerNative.getDefault(); 8971 final boolean isSystem = 8972 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8973 if (isSystem && am.isUserRunning(userId, false)) { 8974 // The just-installed/enabled app is bundled on the system, so presumed 8975 // to be able to run automatically without needing an explicit launch. 8976 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8977 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8978 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8979 .setPackage(packageName); 8980 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8981 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 8982 } 8983 } catch (RemoteException e) { 8984 // shouldn't happen 8985 Slog.w(TAG, "Unable to bootstrap installed package", e); 8986 } 8987 } 8988 8989 @Override 8990 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8991 int userId) { 8992 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8993 PackageSetting pkgSetting; 8994 final int uid = Binder.getCallingUid(); 8995 enforceCrossUserPermission(uid, userId, true, true, 8996 "setApplicationHiddenSetting for user " + userId); 8997 8998 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8999 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9000 return false; 9001 } 9002 9003 long callingId = Binder.clearCallingIdentity(); 9004 try { 9005 boolean sendAdded = false; 9006 boolean sendRemoved = false; 9007 // writer 9008 synchronized (mPackages) { 9009 pkgSetting = mSettings.mPackages.get(packageName); 9010 if (pkgSetting == null) { 9011 return false; 9012 } 9013 if (pkgSetting.getHidden(userId) != hidden) { 9014 pkgSetting.setHidden(hidden, userId); 9015 mSettings.writePackageRestrictionsLPr(userId); 9016 if (hidden) { 9017 sendRemoved = true; 9018 } else { 9019 sendAdded = true; 9020 } 9021 } 9022 } 9023 if (sendAdded) { 9024 sendPackageAddedForUser(packageName, pkgSetting, userId); 9025 return true; 9026 } 9027 if (sendRemoved) { 9028 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9029 "hiding pkg"); 9030 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9031 } 9032 } finally { 9033 Binder.restoreCallingIdentity(callingId); 9034 } 9035 return false; 9036 } 9037 9038 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9039 int userId) { 9040 final PackageRemovedInfo info = new PackageRemovedInfo(); 9041 info.removedPackage = packageName; 9042 info.removedUsers = new int[] {userId}; 9043 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9044 info.sendBroadcast(false, false, false); 9045 } 9046 9047 /** 9048 * Returns true if application is not found or there was an error. Otherwise it returns 9049 * the hidden state of the package for the given user. 9050 */ 9051 @Override 9052 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9053 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9054 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9055 false, "getApplicationHidden for user " + userId); 9056 PackageSetting pkgSetting; 9057 long callingId = Binder.clearCallingIdentity(); 9058 try { 9059 // writer 9060 synchronized (mPackages) { 9061 pkgSetting = mSettings.mPackages.get(packageName); 9062 if (pkgSetting == null) { 9063 return true; 9064 } 9065 return pkgSetting.getHidden(userId); 9066 } 9067 } finally { 9068 Binder.restoreCallingIdentity(callingId); 9069 } 9070 } 9071 9072 /** 9073 * @hide 9074 */ 9075 @Override 9076 public int installExistingPackageAsUser(String packageName, int userId) { 9077 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9078 null); 9079 PackageSetting pkgSetting; 9080 final int uid = Binder.getCallingUid(); 9081 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9082 + userId); 9083 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9084 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9085 } 9086 9087 long callingId = Binder.clearCallingIdentity(); 9088 try { 9089 boolean sendAdded = false; 9090 9091 // writer 9092 synchronized (mPackages) { 9093 pkgSetting = mSettings.mPackages.get(packageName); 9094 if (pkgSetting == null) { 9095 return PackageManager.INSTALL_FAILED_INVALID_URI; 9096 } 9097 if (!pkgSetting.getInstalled(userId)) { 9098 pkgSetting.setInstalled(true, userId); 9099 pkgSetting.setHidden(false, userId); 9100 mSettings.writePackageRestrictionsLPr(userId); 9101 sendAdded = true; 9102 } 9103 } 9104 9105 if (sendAdded) { 9106 sendPackageAddedForUser(packageName, pkgSetting, userId); 9107 } 9108 } finally { 9109 Binder.restoreCallingIdentity(callingId); 9110 } 9111 9112 return PackageManager.INSTALL_SUCCEEDED; 9113 } 9114 9115 boolean isUserRestricted(int userId, String restrictionKey) { 9116 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9117 if (restrictions.getBoolean(restrictionKey, false)) { 9118 Log.w(TAG, "User is restricted: " + restrictionKey); 9119 return true; 9120 } 9121 return false; 9122 } 9123 9124 @Override 9125 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9126 mContext.enforceCallingOrSelfPermission( 9127 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9128 "Only package verification agents can verify applications"); 9129 9130 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9131 final PackageVerificationResponse response = new PackageVerificationResponse( 9132 verificationCode, Binder.getCallingUid()); 9133 msg.arg1 = id; 9134 msg.obj = response; 9135 mHandler.sendMessage(msg); 9136 } 9137 9138 @Override 9139 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9140 long millisecondsToDelay) { 9141 mContext.enforceCallingOrSelfPermission( 9142 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9143 "Only package verification agents can extend verification timeouts"); 9144 9145 final PackageVerificationState state = mPendingVerification.get(id); 9146 final PackageVerificationResponse response = new PackageVerificationResponse( 9147 verificationCodeAtTimeout, Binder.getCallingUid()); 9148 9149 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9150 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9151 } 9152 if (millisecondsToDelay < 0) { 9153 millisecondsToDelay = 0; 9154 } 9155 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9156 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9157 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9158 } 9159 9160 if ((state != null) && !state.timeoutExtended()) { 9161 state.extendTimeout(); 9162 9163 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9164 msg.arg1 = id; 9165 msg.obj = response; 9166 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9167 } 9168 } 9169 9170 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9171 int verificationCode, UserHandle user) { 9172 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9173 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9174 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9175 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9176 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9177 9178 mContext.sendBroadcastAsUser(intent, user, 9179 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9180 } 9181 9182 private ComponentName matchComponentForVerifier(String packageName, 9183 List<ResolveInfo> receivers) { 9184 ActivityInfo targetReceiver = null; 9185 9186 final int NR = receivers.size(); 9187 for (int i = 0; i < NR; i++) { 9188 final ResolveInfo info = receivers.get(i); 9189 if (info.activityInfo == null) { 9190 continue; 9191 } 9192 9193 if (packageName.equals(info.activityInfo.packageName)) { 9194 targetReceiver = info.activityInfo; 9195 break; 9196 } 9197 } 9198 9199 if (targetReceiver == null) { 9200 return null; 9201 } 9202 9203 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9204 } 9205 9206 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9207 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9208 if (pkgInfo.verifiers.length == 0) { 9209 return null; 9210 } 9211 9212 final int N = pkgInfo.verifiers.length; 9213 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9214 for (int i = 0; i < N; i++) { 9215 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9216 9217 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9218 receivers); 9219 if (comp == null) { 9220 continue; 9221 } 9222 9223 final int verifierUid = getUidForVerifier(verifierInfo); 9224 if (verifierUid == -1) { 9225 continue; 9226 } 9227 9228 if (DEBUG_VERIFY) { 9229 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9230 + " with the correct signature"); 9231 } 9232 sufficientVerifiers.add(comp); 9233 verificationState.addSufficientVerifier(verifierUid); 9234 } 9235 9236 return sufficientVerifiers; 9237 } 9238 9239 private int getUidForVerifier(VerifierInfo verifierInfo) { 9240 synchronized (mPackages) { 9241 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9242 if (pkg == null) { 9243 return -1; 9244 } else if (pkg.mSignatures.length != 1) { 9245 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9246 + " has more than one signature; ignoring"); 9247 return -1; 9248 } 9249 9250 /* 9251 * If the public key of the package's signature does not match 9252 * our expected public key, then this is a different package and 9253 * we should skip. 9254 */ 9255 9256 final byte[] expectedPublicKey; 9257 try { 9258 final Signature verifierSig = pkg.mSignatures[0]; 9259 final PublicKey publicKey = verifierSig.getPublicKey(); 9260 expectedPublicKey = publicKey.getEncoded(); 9261 } catch (CertificateException e) { 9262 return -1; 9263 } 9264 9265 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9266 9267 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9268 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9269 + " does not have the expected public key; ignoring"); 9270 return -1; 9271 } 9272 9273 return pkg.applicationInfo.uid; 9274 } 9275 } 9276 9277 @Override 9278 public void finishPackageInstall(int token) { 9279 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9280 9281 if (DEBUG_INSTALL) { 9282 Slog.v(TAG, "BM finishing package install for " + token); 9283 } 9284 9285 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9286 mHandler.sendMessage(msg); 9287 } 9288 9289 /** 9290 * Get the verification agent timeout. 9291 * 9292 * @return verification timeout in milliseconds 9293 */ 9294 private long getVerificationTimeout() { 9295 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9296 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9297 DEFAULT_VERIFICATION_TIMEOUT); 9298 } 9299 9300 /** 9301 * Get the default verification agent response code. 9302 * 9303 * @return default verification response code 9304 */ 9305 private int getDefaultVerificationResponse() { 9306 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9307 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9308 DEFAULT_VERIFICATION_RESPONSE); 9309 } 9310 9311 /** 9312 * Check whether or not package verification has been enabled. 9313 * 9314 * @return true if verification should be performed 9315 */ 9316 private boolean isVerificationEnabled(int userId, int installFlags) { 9317 if (!DEFAULT_VERIFY_ENABLE) { 9318 return false; 9319 } 9320 9321 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9322 9323 // Check if installing from ADB 9324 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9325 // Do not run verification in a test harness environment 9326 if (ActivityManager.isRunningInTestHarness()) { 9327 return false; 9328 } 9329 if (ensureVerifyAppsEnabled) { 9330 return true; 9331 } 9332 // Check if the developer does not want package verification for ADB installs 9333 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9334 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9335 return false; 9336 } 9337 } 9338 9339 if (ensureVerifyAppsEnabled) { 9340 return true; 9341 } 9342 9343 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9344 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9345 } 9346 9347 @Override 9348 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9349 throws RemoteException { 9350 mContext.enforceCallingOrSelfPermission( 9351 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9352 "Only intentfilter verification agents can verify applications"); 9353 9354 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9355 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9356 Binder.getCallingUid(), verificationCode, failedDomains); 9357 msg.arg1 = id; 9358 msg.obj = response; 9359 mHandler.sendMessage(msg); 9360 } 9361 9362 @Override 9363 public int getIntentVerificationStatus(String packageName, int userId) { 9364 synchronized (mPackages) { 9365 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9366 } 9367 } 9368 9369 @Override 9370 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9371 boolean result = false; 9372 synchronized (mPackages) { 9373 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9374 } 9375 if (result) { 9376 scheduleWritePackageRestrictionsLocked(userId); 9377 } 9378 return result; 9379 } 9380 9381 @Override 9382 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9383 synchronized (mPackages) { 9384 return mSettings.getIntentFilterVerificationsLPr(packageName); 9385 } 9386 } 9387 9388 @Override 9389 public List<IntentFilter> getAllIntentFilters(String packageName) { 9390 if (TextUtils.isEmpty(packageName)) { 9391 return Collections.<IntentFilter>emptyList(); 9392 } 9393 synchronized (mPackages) { 9394 PackageParser.Package pkg = mPackages.get(packageName); 9395 if (pkg == null || pkg.activities == null) { 9396 return Collections.<IntentFilter>emptyList(); 9397 } 9398 final int count = pkg.activities.size(); 9399 ArrayList<IntentFilter> result = new ArrayList<>(); 9400 for (int n=0; n<count; n++) { 9401 PackageParser.Activity activity = pkg.activities.get(n); 9402 if (activity.intents != null || activity.intents.size() > 0) { 9403 result.addAll(activity.intents); 9404 } 9405 } 9406 return result; 9407 } 9408 } 9409 9410 @Override 9411 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9412 synchronized (mPackages) { 9413 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9414 if (packageName != null) { 9415 result |= updateIntentVerificationStatus(packageName, 9416 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9417 UserHandle.myUserId()); 9418 } 9419 return result; 9420 } 9421 } 9422 9423 @Override 9424 public String getDefaultBrowserPackageName(int userId) { 9425 synchronized (mPackages) { 9426 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9427 } 9428 } 9429 9430 /** 9431 * Get the "allow unknown sources" setting. 9432 * 9433 * @return the current "allow unknown sources" setting 9434 */ 9435 private int getUnknownSourcesSettings() { 9436 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9437 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9438 -1); 9439 } 9440 9441 @Override 9442 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9443 final int uid = Binder.getCallingUid(); 9444 // writer 9445 synchronized (mPackages) { 9446 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9447 if (targetPackageSetting == null) { 9448 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9449 } 9450 9451 PackageSetting installerPackageSetting; 9452 if (installerPackageName != null) { 9453 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9454 if (installerPackageSetting == null) { 9455 throw new IllegalArgumentException("Unknown installer package: " 9456 + installerPackageName); 9457 } 9458 } else { 9459 installerPackageSetting = null; 9460 } 9461 9462 Signature[] callerSignature; 9463 Object obj = mSettings.getUserIdLPr(uid); 9464 if (obj != null) { 9465 if (obj instanceof SharedUserSetting) { 9466 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9467 } else if (obj instanceof PackageSetting) { 9468 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9469 } else { 9470 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9471 } 9472 } else { 9473 throw new SecurityException("Unknown calling uid " + uid); 9474 } 9475 9476 // Verify: can't set installerPackageName to a package that is 9477 // not signed with the same cert as the caller. 9478 if (installerPackageSetting != null) { 9479 if (compareSignatures(callerSignature, 9480 installerPackageSetting.signatures.mSignatures) 9481 != PackageManager.SIGNATURE_MATCH) { 9482 throw new SecurityException( 9483 "Caller does not have same cert as new installer package " 9484 + installerPackageName); 9485 } 9486 } 9487 9488 // Verify: if target already has an installer package, it must 9489 // be signed with the same cert as the caller. 9490 if (targetPackageSetting.installerPackageName != null) { 9491 PackageSetting setting = mSettings.mPackages.get( 9492 targetPackageSetting.installerPackageName); 9493 // If the currently set package isn't valid, then it's always 9494 // okay to change it. 9495 if (setting != null) { 9496 if (compareSignatures(callerSignature, 9497 setting.signatures.mSignatures) 9498 != PackageManager.SIGNATURE_MATCH) { 9499 throw new SecurityException( 9500 "Caller does not have same cert as old installer package " 9501 + targetPackageSetting.installerPackageName); 9502 } 9503 } 9504 } 9505 9506 // Okay! 9507 targetPackageSetting.installerPackageName = installerPackageName; 9508 scheduleWriteSettingsLocked(); 9509 } 9510 } 9511 9512 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9513 // Queue up an async operation since the package installation may take a little while. 9514 mHandler.post(new Runnable() { 9515 public void run() { 9516 mHandler.removeCallbacks(this); 9517 // Result object to be returned 9518 PackageInstalledInfo res = new PackageInstalledInfo(); 9519 res.returnCode = currentStatus; 9520 res.uid = -1; 9521 res.pkg = null; 9522 res.removedInfo = new PackageRemovedInfo(); 9523 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9524 args.doPreInstall(res.returnCode); 9525 synchronized (mInstallLock) { 9526 installPackageLI(args, res); 9527 } 9528 args.doPostInstall(res.returnCode, res.uid); 9529 } 9530 9531 // A restore should be performed at this point if (a) the install 9532 // succeeded, (b) the operation is not an update, and (c) the new 9533 // package has not opted out of backup participation. 9534 final boolean update = res.removedInfo.removedPackage != null; 9535 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9536 boolean doRestore = !update 9537 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9538 9539 // Set up the post-install work request bookkeeping. This will be used 9540 // and cleaned up by the post-install event handling regardless of whether 9541 // there's a restore pass performed. Token values are >= 1. 9542 int token; 9543 if (mNextInstallToken < 0) mNextInstallToken = 1; 9544 token = mNextInstallToken++; 9545 9546 PostInstallData data = new PostInstallData(args, res); 9547 mRunningInstalls.put(token, data); 9548 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9549 9550 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9551 // Pass responsibility to the Backup Manager. It will perform a 9552 // restore if appropriate, then pass responsibility back to the 9553 // Package Manager to run the post-install observer callbacks 9554 // and broadcasts. 9555 IBackupManager bm = IBackupManager.Stub.asInterface( 9556 ServiceManager.getService(Context.BACKUP_SERVICE)); 9557 if (bm != null) { 9558 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9559 + " to BM for possible restore"); 9560 try { 9561 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9562 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9563 } else { 9564 doRestore = false; 9565 } 9566 } catch (RemoteException e) { 9567 // can't happen; the backup manager is local 9568 } catch (Exception e) { 9569 Slog.e(TAG, "Exception trying to enqueue restore", e); 9570 doRestore = false; 9571 } 9572 } else { 9573 Slog.e(TAG, "Backup Manager not found!"); 9574 doRestore = false; 9575 } 9576 } 9577 9578 if (!doRestore) { 9579 // No restore possible, or the Backup Manager was mysteriously not 9580 // available -- just fire the post-install work request directly. 9581 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9582 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9583 mHandler.sendMessage(msg); 9584 } 9585 } 9586 }); 9587 } 9588 9589 private abstract class HandlerParams { 9590 private static final int MAX_RETRIES = 4; 9591 9592 /** 9593 * Number of times startCopy() has been attempted and had a non-fatal 9594 * error. 9595 */ 9596 private int mRetries = 0; 9597 9598 /** User handle for the user requesting the information or installation. */ 9599 private final UserHandle mUser; 9600 9601 HandlerParams(UserHandle user) { 9602 mUser = user; 9603 } 9604 9605 UserHandle getUser() { 9606 return mUser; 9607 } 9608 9609 final boolean startCopy() { 9610 boolean res; 9611 try { 9612 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9613 9614 if (++mRetries > MAX_RETRIES) { 9615 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9616 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9617 handleServiceError(); 9618 return false; 9619 } else { 9620 handleStartCopy(); 9621 res = true; 9622 } 9623 } catch (RemoteException e) { 9624 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9625 mHandler.sendEmptyMessage(MCS_RECONNECT); 9626 res = false; 9627 } 9628 handleReturnCode(); 9629 return res; 9630 } 9631 9632 final void serviceError() { 9633 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9634 handleServiceError(); 9635 handleReturnCode(); 9636 } 9637 9638 abstract void handleStartCopy() throws RemoteException; 9639 abstract void handleServiceError(); 9640 abstract void handleReturnCode(); 9641 } 9642 9643 class MeasureParams extends HandlerParams { 9644 private final PackageStats mStats; 9645 private boolean mSuccess; 9646 9647 private final IPackageStatsObserver mObserver; 9648 9649 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9650 super(new UserHandle(stats.userHandle)); 9651 mObserver = observer; 9652 mStats = stats; 9653 } 9654 9655 @Override 9656 public String toString() { 9657 return "MeasureParams{" 9658 + Integer.toHexString(System.identityHashCode(this)) 9659 + " " + mStats.packageName + "}"; 9660 } 9661 9662 @Override 9663 void handleStartCopy() throws RemoteException { 9664 synchronized (mInstallLock) { 9665 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9666 } 9667 9668 if (mSuccess) { 9669 final boolean mounted; 9670 if (Environment.isExternalStorageEmulated()) { 9671 mounted = true; 9672 } else { 9673 final String status = Environment.getExternalStorageState(); 9674 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9675 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9676 } 9677 9678 if (mounted) { 9679 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9680 9681 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9682 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9683 9684 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9685 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9686 9687 // Always subtract cache size, since it's a subdirectory 9688 mStats.externalDataSize -= mStats.externalCacheSize; 9689 9690 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9691 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9692 9693 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9694 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9695 } 9696 } 9697 } 9698 9699 @Override 9700 void handleReturnCode() { 9701 if (mObserver != null) { 9702 try { 9703 mObserver.onGetStatsCompleted(mStats, mSuccess); 9704 } catch (RemoteException e) { 9705 Slog.i(TAG, "Observer no longer exists."); 9706 } 9707 } 9708 } 9709 9710 @Override 9711 void handleServiceError() { 9712 Slog.e(TAG, "Could not measure application " + mStats.packageName 9713 + " external storage"); 9714 } 9715 } 9716 9717 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9718 throws RemoteException { 9719 long result = 0; 9720 for (File path : paths) { 9721 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9722 } 9723 return result; 9724 } 9725 9726 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9727 for (File path : paths) { 9728 try { 9729 mcs.clearDirectory(path.getAbsolutePath()); 9730 } catch (RemoteException e) { 9731 } 9732 } 9733 } 9734 9735 static class OriginInfo { 9736 /** 9737 * Location where install is coming from, before it has been 9738 * copied/renamed into place. This could be a single monolithic APK 9739 * file, or a cluster directory. This location may be untrusted. 9740 */ 9741 final File file; 9742 final String cid; 9743 9744 /** 9745 * Flag indicating that {@link #file} or {@link #cid} has already been 9746 * staged, meaning downstream users don't need to defensively copy the 9747 * contents. 9748 */ 9749 final boolean staged; 9750 9751 /** 9752 * Flag indicating that {@link #file} or {@link #cid} is an already 9753 * installed app that is being moved. 9754 */ 9755 final boolean existing; 9756 9757 final String resolvedPath; 9758 final File resolvedFile; 9759 9760 static OriginInfo fromNothing() { 9761 return new OriginInfo(null, null, false, false); 9762 } 9763 9764 static OriginInfo fromUntrustedFile(File file) { 9765 return new OriginInfo(file, null, false, false); 9766 } 9767 9768 static OriginInfo fromExistingFile(File file) { 9769 return new OriginInfo(file, null, false, true); 9770 } 9771 9772 static OriginInfo fromStagedFile(File file) { 9773 return new OriginInfo(file, null, true, false); 9774 } 9775 9776 static OriginInfo fromStagedContainer(String cid) { 9777 return new OriginInfo(null, cid, true, false); 9778 } 9779 9780 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9781 this.file = file; 9782 this.cid = cid; 9783 this.staged = staged; 9784 this.existing = existing; 9785 9786 if (cid != null) { 9787 resolvedPath = PackageHelper.getSdDir(cid); 9788 resolvedFile = new File(resolvedPath); 9789 } else if (file != null) { 9790 resolvedPath = file.getAbsolutePath(); 9791 resolvedFile = file; 9792 } else { 9793 resolvedPath = null; 9794 resolvedFile = null; 9795 } 9796 } 9797 } 9798 9799 class MoveInfo { 9800 final int moveId; 9801 final String fromUuid; 9802 final String toUuid; 9803 final String packageName; 9804 final String dataAppName; 9805 final int appId; 9806 final String seinfo; 9807 9808 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9809 String dataAppName, int appId, String seinfo) { 9810 this.moveId = moveId; 9811 this.fromUuid = fromUuid; 9812 this.toUuid = toUuid; 9813 this.packageName = packageName; 9814 this.dataAppName = dataAppName; 9815 this.appId = appId; 9816 this.seinfo = seinfo; 9817 } 9818 } 9819 9820 class InstallParams extends HandlerParams { 9821 final OriginInfo origin; 9822 final MoveInfo move; 9823 final IPackageInstallObserver2 observer; 9824 int installFlags; 9825 final String installerPackageName; 9826 final String volumeUuid; 9827 final VerificationParams verificationParams; 9828 private InstallArgs mArgs; 9829 private int mRet; 9830 final String packageAbiOverride; 9831 9832 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9833 int installFlags, String installerPackageName, String volumeUuid, 9834 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9835 super(user); 9836 this.origin = origin; 9837 this.move = move; 9838 this.observer = observer; 9839 this.installFlags = installFlags; 9840 this.installerPackageName = installerPackageName; 9841 this.volumeUuid = volumeUuid; 9842 this.verificationParams = verificationParams; 9843 this.packageAbiOverride = packageAbiOverride; 9844 } 9845 9846 @Override 9847 public String toString() { 9848 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9849 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9850 } 9851 9852 public ManifestDigest getManifestDigest() { 9853 if (verificationParams == null) { 9854 return null; 9855 } 9856 return verificationParams.getManifestDigest(); 9857 } 9858 9859 private int installLocationPolicy(PackageInfoLite pkgLite) { 9860 String packageName = pkgLite.packageName; 9861 int installLocation = pkgLite.installLocation; 9862 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9863 // reader 9864 synchronized (mPackages) { 9865 PackageParser.Package pkg = mPackages.get(packageName); 9866 if (pkg != null) { 9867 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9868 // Check for downgrading. 9869 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9870 try { 9871 checkDowngrade(pkg, pkgLite); 9872 } catch (PackageManagerException e) { 9873 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9874 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9875 } 9876 } 9877 // Check for updated system application. 9878 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9879 if (onSd) { 9880 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9881 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9882 } 9883 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9884 } else { 9885 if (onSd) { 9886 // Install flag overrides everything. 9887 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9888 } 9889 // If current upgrade specifies particular preference 9890 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9891 // Application explicitly specified internal. 9892 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9893 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9894 // App explictly prefers external. Let policy decide 9895 } else { 9896 // Prefer previous location 9897 if (isExternal(pkg)) { 9898 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9899 } 9900 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9901 } 9902 } 9903 } else { 9904 // Invalid install. Return error code 9905 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9906 } 9907 } 9908 } 9909 // All the special cases have been taken care of. 9910 // Return result based on recommended install location. 9911 if (onSd) { 9912 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9913 } 9914 return pkgLite.recommendedInstallLocation; 9915 } 9916 9917 /* 9918 * Invoke remote method to get package information and install 9919 * location values. Override install location based on default 9920 * policy if needed and then create install arguments based 9921 * on the install location. 9922 */ 9923 public void handleStartCopy() throws RemoteException { 9924 int ret = PackageManager.INSTALL_SUCCEEDED; 9925 9926 // If we're already staged, we've firmly committed to an install location 9927 if (origin.staged) { 9928 if (origin.file != null) { 9929 installFlags |= PackageManager.INSTALL_INTERNAL; 9930 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9931 } else if (origin.cid != null) { 9932 installFlags |= PackageManager.INSTALL_EXTERNAL; 9933 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9934 } else { 9935 throw new IllegalStateException("Invalid stage location"); 9936 } 9937 } 9938 9939 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9940 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9941 9942 PackageInfoLite pkgLite = null; 9943 9944 if (onInt && onSd) { 9945 // Check if both bits are set. 9946 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9947 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9948 } else { 9949 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9950 packageAbiOverride); 9951 9952 /* 9953 * If we have too little free space, try to free cache 9954 * before giving up. 9955 */ 9956 if (!origin.staged && pkgLite.recommendedInstallLocation 9957 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9958 // TODO: focus freeing disk space on the target device 9959 final StorageManager storage = StorageManager.from(mContext); 9960 final long lowThreshold = storage.getStorageLowBytes( 9961 Environment.getDataDirectory()); 9962 9963 final long sizeBytes = mContainerService.calculateInstalledSize( 9964 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9965 9966 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9967 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9968 installFlags, packageAbiOverride); 9969 } 9970 9971 /* 9972 * The cache free must have deleted the file we 9973 * downloaded to install. 9974 * 9975 * TODO: fix the "freeCache" call to not delete 9976 * the file we care about. 9977 */ 9978 if (pkgLite.recommendedInstallLocation 9979 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9980 pkgLite.recommendedInstallLocation 9981 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9982 } 9983 } 9984 } 9985 9986 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9987 int loc = pkgLite.recommendedInstallLocation; 9988 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9989 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9990 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9991 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9992 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9993 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9994 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9995 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9996 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9997 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9998 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9999 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10000 } else { 10001 // Override with defaults if needed. 10002 loc = installLocationPolicy(pkgLite); 10003 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10004 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10005 } else if (!onSd && !onInt) { 10006 // Override install location with flags 10007 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10008 // Set the flag to install on external media. 10009 installFlags |= PackageManager.INSTALL_EXTERNAL; 10010 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10011 } else { 10012 // Make sure the flag for installing on external 10013 // media is unset 10014 installFlags |= PackageManager.INSTALL_INTERNAL; 10015 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10016 } 10017 } 10018 } 10019 } 10020 10021 final InstallArgs args = createInstallArgs(this); 10022 mArgs = args; 10023 10024 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10025 /* 10026 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10027 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10028 */ 10029 int userIdentifier = getUser().getIdentifier(); 10030 if (userIdentifier == UserHandle.USER_ALL 10031 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10032 userIdentifier = UserHandle.USER_OWNER; 10033 } 10034 10035 /* 10036 * Determine if we have any installed package verifiers. If we 10037 * do, then we'll defer to them to verify the packages. 10038 */ 10039 final int requiredUid = mRequiredVerifierPackage == null ? -1 10040 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10041 if (!origin.existing && requiredUid != -1 10042 && isVerificationEnabled(userIdentifier, installFlags)) { 10043 final Intent verification = new Intent( 10044 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10045 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10046 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10047 PACKAGE_MIME_TYPE); 10048 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10049 10050 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10051 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10052 0 /* TODO: Which userId? */); 10053 10054 if (DEBUG_VERIFY) { 10055 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10056 + verification.toString() + " with " + pkgLite.verifiers.length 10057 + " optional verifiers"); 10058 } 10059 10060 final int verificationId = mPendingVerificationToken++; 10061 10062 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10063 10064 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10065 installerPackageName); 10066 10067 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10068 installFlags); 10069 10070 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10071 pkgLite.packageName); 10072 10073 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10074 pkgLite.versionCode); 10075 10076 if (verificationParams != null) { 10077 if (verificationParams.getVerificationURI() != null) { 10078 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10079 verificationParams.getVerificationURI()); 10080 } 10081 if (verificationParams.getOriginatingURI() != null) { 10082 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10083 verificationParams.getOriginatingURI()); 10084 } 10085 if (verificationParams.getReferrer() != null) { 10086 verification.putExtra(Intent.EXTRA_REFERRER, 10087 verificationParams.getReferrer()); 10088 } 10089 if (verificationParams.getOriginatingUid() >= 0) { 10090 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10091 verificationParams.getOriginatingUid()); 10092 } 10093 if (verificationParams.getInstallerUid() >= 0) { 10094 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10095 verificationParams.getInstallerUid()); 10096 } 10097 } 10098 10099 final PackageVerificationState verificationState = new PackageVerificationState( 10100 requiredUid, args); 10101 10102 mPendingVerification.append(verificationId, verificationState); 10103 10104 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10105 receivers, verificationState); 10106 10107 /* 10108 * If any sufficient verifiers were listed in the package 10109 * manifest, attempt to ask them. 10110 */ 10111 if (sufficientVerifiers != null) { 10112 final int N = sufficientVerifiers.size(); 10113 if (N == 0) { 10114 Slog.i(TAG, "Additional verifiers required, but none installed."); 10115 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10116 } else { 10117 for (int i = 0; i < N; i++) { 10118 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10119 10120 final Intent sufficientIntent = new Intent(verification); 10121 sufficientIntent.setComponent(verifierComponent); 10122 10123 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10124 } 10125 } 10126 } 10127 10128 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10129 mRequiredVerifierPackage, receivers); 10130 if (ret == PackageManager.INSTALL_SUCCEEDED 10131 && mRequiredVerifierPackage != null) { 10132 /* 10133 * Send the intent to the required verification agent, 10134 * but only start the verification timeout after the 10135 * target BroadcastReceivers have run. 10136 */ 10137 verification.setComponent(requiredVerifierComponent); 10138 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10139 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10140 new BroadcastReceiver() { 10141 @Override 10142 public void onReceive(Context context, Intent intent) { 10143 final Message msg = mHandler 10144 .obtainMessage(CHECK_PENDING_VERIFICATION); 10145 msg.arg1 = verificationId; 10146 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10147 } 10148 }, null, 0, null, null); 10149 10150 /* 10151 * We don't want the copy to proceed until verification 10152 * succeeds, so null out this field. 10153 */ 10154 mArgs = null; 10155 } 10156 } else { 10157 /* 10158 * No package verification is enabled, so immediately start 10159 * the remote call to initiate copy using temporary file. 10160 */ 10161 ret = args.copyApk(mContainerService, true); 10162 } 10163 } 10164 10165 mRet = ret; 10166 } 10167 10168 @Override 10169 void handleReturnCode() { 10170 // If mArgs is null, then MCS couldn't be reached. When it 10171 // reconnects, it will try again to install. At that point, this 10172 // will succeed. 10173 if (mArgs != null) { 10174 processPendingInstall(mArgs, mRet); 10175 } 10176 } 10177 10178 @Override 10179 void handleServiceError() { 10180 mArgs = createInstallArgs(this); 10181 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10182 } 10183 10184 public boolean isForwardLocked() { 10185 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10186 } 10187 } 10188 10189 /** 10190 * Used during creation of InstallArgs 10191 * 10192 * @param installFlags package installation flags 10193 * @return true if should be installed on external storage 10194 */ 10195 private static boolean installOnExternalAsec(int installFlags) { 10196 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10197 return false; 10198 } 10199 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10200 return true; 10201 } 10202 return false; 10203 } 10204 10205 /** 10206 * Used during creation of InstallArgs 10207 * 10208 * @param installFlags package installation flags 10209 * @return true if should be installed as forward locked 10210 */ 10211 private static boolean installForwardLocked(int installFlags) { 10212 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10213 } 10214 10215 private InstallArgs createInstallArgs(InstallParams params) { 10216 if (params.move != null) { 10217 return new MoveInstallArgs(params); 10218 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10219 return new AsecInstallArgs(params); 10220 } else { 10221 return new FileInstallArgs(params); 10222 } 10223 } 10224 10225 /** 10226 * Create args that describe an existing installed package. Typically used 10227 * when cleaning up old installs, or used as a move source. 10228 */ 10229 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10230 String resourcePath, String[] instructionSets) { 10231 final boolean isInAsec; 10232 if (installOnExternalAsec(installFlags)) { 10233 /* Apps on SD card are always in ASEC containers. */ 10234 isInAsec = true; 10235 } else if (installForwardLocked(installFlags) 10236 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10237 /* 10238 * Forward-locked apps are only in ASEC containers if they're the 10239 * new style 10240 */ 10241 isInAsec = true; 10242 } else { 10243 isInAsec = false; 10244 } 10245 10246 if (isInAsec) { 10247 return new AsecInstallArgs(codePath, instructionSets, 10248 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10249 } else { 10250 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10251 } 10252 } 10253 10254 static abstract class InstallArgs { 10255 /** @see InstallParams#origin */ 10256 final OriginInfo origin; 10257 /** @see InstallParams#move */ 10258 final MoveInfo move; 10259 10260 final IPackageInstallObserver2 observer; 10261 // Always refers to PackageManager flags only 10262 final int installFlags; 10263 final String installerPackageName; 10264 final String volumeUuid; 10265 final ManifestDigest manifestDigest; 10266 final UserHandle user; 10267 final String abiOverride; 10268 10269 // The list of instruction sets supported by this app. This is currently 10270 // only used during the rmdex() phase to clean up resources. We can get rid of this 10271 // if we move dex files under the common app path. 10272 /* nullable */ String[] instructionSets; 10273 10274 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10275 int installFlags, String installerPackageName, String volumeUuid, 10276 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10277 String abiOverride) { 10278 this.origin = origin; 10279 this.move = move; 10280 this.installFlags = installFlags; 10281 this.observer = observer; 10282 this.installerPackageName = installerPackageName; 10283 this.volumeUuid = volumeUuid; 10284 this.manifestDigest = manifestDigest; 10285 this.user = user; 10286 this.instructionSets = instructionSets; 10287 this.abiOverride = abiOverride; 10288 } 10289 10290 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10291 abstract int doPreInstall(int status); 10292 10293 /** 10294 * Rename package into final resting place. All paths on the given 10295 * scanned package should be updated to reflect the rename. 10296 */ 10297 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10298 abstract int doPostInstall(int status, int uid); 10299 10300 /** @see PackageSettingBase#codePathString */ 10301 abstract String getCodePath(); 10302 /** @see PackageSettingBase#resourcePathString */ 10303 abstract String getResourcePath(); 10304 10305 // Need installer lock especially for dex file removal. 10306 abstract void cleanUpResourcesLI(); 10307 abstract boolean doPostDeleteLI(boolean delete); 10308 10309 /** 10310 * Called before the source arguments are copied. This is used mostly 10311 * for MoveParams when it needs to read the source file to put it in the 10312 * destination. 10313 */ 10314 int doPreCopy() { 10315 return PackageManager.INSTALL_SUCCEEDED; 10316 } 10317 10318 /** 10319 * Called after the source arguments are copied. This is used mostly for 10320 * MoveParams when it needs to read the source file to put it in the 10321 * destination. 10322 * 10323 * @return 10324 */ 10325 int doPostCopy(int uid) { 10326 return PackageManager.INSTALL_SUCCEEDED; 10327 } 10328 10329 protected boolean isFwdLocked() { 10330 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10331 } 10332 10333 protected boolean isExternalAsec() { 10334 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10335 } 10336 10337 UserHandle getUser() { 10338 return user; 10339 } 10340 } 10341 10342 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10343 if (!allCodePaths.isEmpty()) { 10344 if (instructionSets == null) { 10345 throw new IllegalStateException("instructionSet == null"); 10346 } 10347 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10348 for (String codePath : allCodePaths) { 10349 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10350 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10351 if (retCode < 0) { 10352 Slog.w(TAG, "Couldn't remove dex file for package: " 10353 + " at location " + codePath + ", retcode=" + retCode); 10354 // we don't consider this to be a failure of the core package deletion 10355 } 10356 } 10357 } 10358 } 10359 } 10360 10361 /** 10362 * Logic to handle installation of non-ASEC applications, including copying 10363 * and renaming logic. 10364 */ 10365 class FileInstallArgs extends InstallArgs { 10366 private File codeFile; 10367 private File resourceFile; 10368 10369 // Example topology: 10370 // /data/app/com.example/base.apk 10371 // /data/app/com.example/split_foo.apk 10372 // /data/app/com.example/lib/arm/libfoo.so 10373 // /data/app/com.example/lib/arm64/libfoo.so 10374 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10375 10376 /** New install */ 10377 FileInstallArgs(InstallParams params) { 10378 super(params.origin, params.move, params.observer, params.installFlags, 10379 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10380 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10381 if (isFwdLocked()) { 10382 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10383 } 10384 } 10385 10386 /** Existing install */ 10387 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10388 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10389 null); 10390 this.codeFile = (codePath != null) ? new File(codePath) : null; 10391 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10392 } 10393 10394 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10395 if (origin.staged) { 10396 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10397 codeFile = origin.file; 10398 resourceFile = origin.file; 10399 return PackageManager.INSTALL_SUCCEEDED; 10400 } 10401 10402 try { 10403 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10404 codeFile = tempDir; 10405 resourceFile = tempDir; 10406 } catch (IOException e) { 10407 Slog.w(TAG, "Failed to create copy file: " + e); 10408 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10409 } 10410 10411 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10412 @Override 10413 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10414 if (!FileUtils.isValidExtFilename(name)) { 10415 throw new IllegalArgumentException("Invalid filename: " + name); 10416 } 10417 try { 10418 final File file = new File(codeFile, name); 10419 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10420 O_RDWR | O_CREAT, 0644); 10421 Os.chmod(file.getAbsolutePath(), 0644); 10422 return new ParcelFileDescriptor(fd); 10423 } catch (ErrnoException e) { 10424 throw new RemoteException("Failed to open: " + e.getMessage()); 10425 } 10426 } 10427 }; 10428 10429 int ret = PackageManager.INSTALL_SUCCEEDED; 10430 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10431 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10432 Slog.e(TAG, "Failed to copy package"); 10433 return ret; 10434 } 10435 10436 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10437 NativeLibraryHelper.Handle handle = null; 10438 try { 10439 handle = NativeLibraryHelper.Handle.create(codeFile); 10440 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10441 abiOverride); 10442 } catch (IOException e) { 10443 Slog.e(TAG, "Copying native libraries failed", e); 10444 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10445 } finally { 10446 IoUtils.closeQuietly(handle); 10447 } 10448 10449 return ret; 10450 } 10451 10452 int doPreInstall(int status) { 10453 if (status != PackageManager.INSTALL_SUCCEEDED) { 10454 cleanUp(); 10455 } 10456 return status; 10457 } 10458 10459 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10460 if (status != PackageManager.INSTALL_SUCCEEDED) { 10461 cleanUp(); 10462 return false; 10463 } 10464 10465 final File targetDir = codeFile.getParentFile(); 10466 final File beforeCodeFile = codeFile; 10467 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10468 10469 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10470 try { 10471 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10472 } catch (ErrnoException e) { 10473 Slog.w(TAG, "Failed to rename", e); 10474 return false; 10475 } 10476 10477 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10478 Slog.w(TAG, "Failed to restorecon"); 10479 return false; 10480 } 10481 10482 // Reflect the rename internally 10483 codeFile = afterCodeFile; 10484 resourceFile = afterCodeFile; 10485 10486 // Reflect the rename in scanned details 10487 pkg.codePath = afterCodeFile.getAbsolutePath(); 10488 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10489 pkg.baseCodePath); 10490 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10491 pkg.splitCodePaths); 10492 10493 // Reflect the rename in app info 10494 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10495 pkg.applicationInfo.setCodePath(pkg.codePath); 10496 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10497 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10498 pkg.applicationInfo.setResourcePath(pkg.codePath); 10499 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10500 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10501 10502 return true; 10503 } 10504 10505 int doPostInstall(int status, int uid) { 10506 if (status != PackageManager.INSTALL_SUCCEEDED) { 10507 cleanUp(); 10508 } 10509 return status; 10510 } 10511 10512 @Override 10513 String getCodePath() { 10514 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10515 } 10516 10517 @Override 10518 String getResourcePath() { 10519 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10520 } 10521 10522 private boolean cleanUp() { 10523 if (codeFile == null || !codeFile.exists()) { 10524 return false; 10525 } 10526 10527 if (codeFile.isDirectory()) { 10528 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10529 } else { 10530 codeFile.delete(); 10531 } 10532 10533 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10534 resourceFile.delete(); 10535 } 10536 10537 return true; 10538 } 10539 10540 void cleanUpResourcesLI() { 10541 // Try enumerating all code paths before deleting 10542 List<String> allCodePaths = Collections.EMPTY_LIST; 10543 if (codeFile != null && codeFile.exists()) { 10544 try { 10545 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10546 allCodePaths = pkg.getAllCodePaths(); 10547 } catch (PackageParserException e) { 10548 // Ignored; we tried our best 10549 } 10550 } 10551 10552 cleanUp(); 10553 removeDexFiles(allCodePaths, instructionSets); 10554 } 10555 10556 boolean doPostDeleteLI(boolean delete) { 10557 // XXX err, shouldn't we respect the delete flag? 10558 cleanUpResourcesLI(); 10559 return true; 10560 } 10561 } 10562 10563 private boolean isAsecExternal(String cid) { 10564 final String asecPath = PackageHelper.getSdFilesystem(cid); 10565 return !asecPath.startsWith(mAsecInternalPath); 10566 } 10567 10568 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10569 PackageManagerException { 10570 if (copyRet < 0) { 10571 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10572 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10573 throw new PackageManagerException(copyRet, message); 10574 } 10575 } 10576 } 10577 10578 /** 10579 * Extract the MountService "container ID" from the full code path of an 10580 * .apk. 10581 */ 10582 static String cidFromCodePath(String fullCodePath) { 10583 int eidx = fullCodePath.lastIndexOf("/"); 10584 String subStr1 = fullCodePath.substring(0, eidx); 10585 int sidx = subStr1.lastIndexOf("/"); 10586 return subStr1.substring(sidx+1, eidx); 10587 } 10588 10589 /** 10590 * Logic to handle installation of ASEC applications, including copying and 10591 * renaming logic. 10592 */ 10593 class AsecInstallArgs extends InstallArgs { 10594 static final String RES_FILE_NAME = "pkg.apk"; 10595 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10596 10597 String cid; 10598 String packagePath; 10599 String resourcePath; 10600 10601 /** New install */ 10602 AsecInstallArgs(InstallParams params) { 10603 super(params.origin, params.move, params.observer, params.installFlags, 10604 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10605 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10606 } 10607 10608 /** Existing install */ 10609 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10610 boolean isExternal, boolean isForwardLocked) { 10611 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10612 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10613 instructionSets, null); 10614 // Hackily pretend we're still looking at a full code path 10615 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10616 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10617 } 10618 10619 // Extract cid from fullCodePath 10620 int eidx = fullCodePath.lastIndexOf("/"); 10621 String subStr1 = fullCodePath.substring(0, eidx); 10622 int sidx = subStr1.lastIndexOf("/"); 10623 cid = subStr1.substring(sidx+1, eidx); 10624 setMountPath(subStr1); 10625 } 10626 10627 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10628 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10629 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10630 instructionSets, null); 10631 this.cid = cid; 10632 setMountPath(PackageHelper.getSdDir(cid)); 10633 } 10634 10635 void createCopyFile() { 10636 cid = mInstallerService.allocateExternalStageCidLegacy(); 10637 } 10638 10639 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10640 if (origin.staged) { 10641 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10642 cid = origin.cid; 10643 setMountPath(PackageHelper.getSdDir(cid)); 10644 return PackageManager.INSTALL_SUCCEEDED; 10645 } 10646 10647 if (temp) { 10648 createCopyFile(); 10649 } else { 10650 /* 10651 * Pre-emptively destroy the container since it's destroyed if 10652 * copying fails due to it existing anyway. 10653 */ 10654 PackageHelper.destroySdDir(cid); 10655 } 10656 10657 final String newMountPath = imcs.copyPackageToContainer( 10658 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10659 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10660 10661 if (newMountPath != null) { 10662 setMountPath(newMountPath); 10663 return PackageManager.INSTALL_SUCCEEDED; 10664 } else { 10665 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10666 } 10667 } 10668 10669 @Override 10670 String getCodePath() { 10671 return packagePath; 10672 } 10673 10674 @Override 10675 String getResourcePath() { 10676 return resourcePath; 10677 } 10678 10679 int doPreInstall(int status) { 10680 if (status != PackageManager.INSTALL_SUCCEEDED) { 10681 // Destroy container 10682 PackageHelper.destroySdDir(cid); 10683 } else { 10684 boolean mounted = PackageHelper.isContainerMounted(cid); 10685 if (!mounted) { 10686 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10687 Process.SYSTEM_UID); 10688 if (newMountPath != null) { 10689 setMountPath(newMountPath); 10690 } else { 10691 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10692 } 10693 } 10694 } 10695 return status; 10696 } 10697 10698 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10699 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10700 String newMountPath = null; 10701 if (PackageHelper.isContainerMounted(cid)) { 10702 // Unmount the container 10703 if (!PackageHelper.unMountSdDir(cid)) { 10704 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10705 return false; 10706 } 10707 } 10708 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10709 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10710 " which might be stale. Will try to clean up."); 10711 // Clean up the stale container and proceed to recreate. 10712 if (!PackageHelper.destroySdDir(newCacheId)) { 10713 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10714 return false; 10715 } 10716 // Successfully cleaned up stale container. Try to rename again. 10717 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10718 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10719 + " inspite of cleaning it up."); 10720 return false; 10721 } 10722 } 10723 if (!PackageHelper.isContainerMounted(newCacheId)) { 10724 Slog.w(TAG, "Mounting container " + newCacheId); 10725 newMountPath = PackageHelper.mountSdDir(newCacheId, 10726 getEncryptKey(), Process.SYSTEM_UID); 10727 } else { 10728 newMountPath = PackageHelper.getSdDir(newCacheId); 10729 } 10730 if (newMountPath == null) { 10731 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10732 return false; 10733 } 10734 Log.i(TAG, "Succesfully renamed " + cid + 10735 " to " + newCacheId + 10736 " at new path: " + newMountPath); 10737 cid = newCacheId; 10738 10739 final File beforeCodeFile = new File(packagePath); 10740 setMountPath(newMountPath); 10741 final File afterCodeFile = new File(packagePath); 10742 10743 // Reflect the rename in scanned details 10744 pkg.codePath = afterCodeFile.getAbsolutePath(); 10745 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10746 pkg.baseCodePath); 10747 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10748 pkg.splitCodePaths); 10749 10750 // Reflect the rename in app info 10751 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10752 pkg.applicationInfo.setCodePath(pkg.codePath); 10753 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10754 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10755 pkg.applicationInfo.setResourcePath(pkg.codePath); 10756 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10757 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10758 10759 return true; 10760 } 10761 10762 private void setMountPath(String mountPath) { 10763 final File mountFile = new File(mountPath); 10764 10765 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10766 if (monolithicFile.exists()) { 10767 packagePath = monolithicFile.getAbsolutePath(); 10768 if (isFwdLocked()) { 10769 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10770 } else { 10771 resourcePath = packagePath; 10772 } 10773 } else { 10774 packagePath = mountFile.getAbsolutePath(); 10775 resourcePath = packagePath; 10776 } 10777 } 10778 10779 int doPostInstall(int status, int uid) { 10780 if (status != PackageManager.INSTALL_SUCCEEDED) { 10781 cleanUp(); 10782 } else { 10783 final int groupOwner; 10784 final String protectedFile; 10785 if (isFwdLocked()) { 10786 groupOwner = UserHandle.getSharedAppGid(uid); 10787 protectedFile = RES_FILE_NAME; 10788 } else { 10789 groupOwner = -1; 10790 protectedFile = null; 10791 } 10792 10793 if (uid < Process.FIRST_APPLICATION_UID 10794 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10795 Slog.e(TAG, "Failed to finalize " + cid); 10796 PackageHelper.destroySdDir(cid); 10797 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10798 } 10799 10800 boolean mounted = PackageHelper.isContainerMounted(cid); 10801 if (!mounted) { 10802 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10803 } 10804 } 10805 return status; 10806 } 10807 10808 private void cleanUp() { 10809 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10810 10811 // Destroy secure container 10812 PackageHelper.destroySdDir(cid); 10813 } 10814 10815 private List<String> getAllCodePaths() { 10816 final File codeFile = new File(getCodePath()); 10817 if (codeFile != null && codeFile.exists()) { 10818 try { 10819 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10820 return pkg.getAllCodePaths(); 10821 } catch (PackageParserException e) { 10822 // Ignored; we tried our best 10823 } 10824 } 10825 return Collections.EMPTY_LIST; 10826 } 10827 10828 void cleanUpResourcesLI() { 10829 // Enumerate all code paths before deleting 10830 cleanUpResourcesLI(getAllCodePaths()); 10831 } 10832 10833 private void cleanUpResourcesLI(List<String> allCodePaths) { 10834 cleanUp(); 10835 removeDexFiles(allCodePaths, instructionSets); 10836 } 10837 10838 String getPackageName() { 10839 return getAsecPackageName(cid); 10840 } 10841 10842 boolean doPostDeleteLI(boolean delete) { 10843 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10844 final List<String> allCodePaths = getAllCodePaths(); 10845 boolean mounted = PackageHelper.isContainerMounted(cid); 10846 if (mounted) { 10847 // Unmount first 10848 if (PackageHelper.unMountSdDir(cid)) { 10849 mounted = false; 10850 } 10851 } 10852 if (!mounted && delete) { 10853 cleanUpResourcesLI(allCodePaths); 10854 } 10855 return !mounted; 10856 } 10857 10858 @Override 10859 int doPreCopy() { 10860 if (isFwdLocked()) { 10861 if (!PackageHelper.fixSdPermissions(cid, 10862 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10863 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10864 } 10865 } 10866 10867 return PackageManager.INSTALL_SUCCEEDED; 10868 } 10869 10870 @Override 10871 int doPostCopy(int uid) { 10872 if (isFwdLocked()) { 10873 if (uid < Process.FIRST_APPLICATION_UID 10874 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10875 RES_FILE_NAME)) { 10876 Slog.e(TAG, "Failed to finalize " + cid); 10877 PackageHelper.destroySdDir(cid); 10878 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10879 } 10880 } 10881 10882 return PackageManager.INSTALL_SUCCEEDED; 10883 } 10884 } 10885 10886 /** 10887 * Logic to handle movement of existing installed applications. 10888 */ 10889 class MoveInstallArgs extends InstallArgs { 10890 private File codeFile; 10891 private File resourceFile; 10892 10893 /** New install */ 10894 MoveInstallArgs(InstallParams params) { 10895 super(params.origin, params.move, params.observer, params.installFlags, 10896 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10897 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10898 } 10899 10900 int copyApk(IMediaContainerService imcs, boolean temp) { 10901 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10902 + move.fromUuid + " to " + move.toUuid); 10903 synchronized (mInstaller) { 10904 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10905 move.dataAppName, move.appId, move.seinfo) != 0) { 10906 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10907 } 10908 } 10909 10910 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10911 resourceFile = codeFile; 10912 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10913 10914 return PackageManager.INSTALL_SUCCEEDED; 10915 } 10916 10917 int doPreInstall(int status) { 10918 if (status != PackageManager.INSTALL_SUCCEEDED) { 10919 cleanUp(); 10920 } 10921 return status; 10922 } 10923 10924 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10925 if (status != PackageManager.INSTALL_SUCCEEDED) { 10926 cleanUp(); 10927 return false; 10928 } 10929 10930 // Reflect the move in app info 10931 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10932 pkg.applicationInfo.setCodePath(pkg.codePath); 10933 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10934 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10935 pkg.applicationInfo.setResourcePath(pkg.codePath); 10936 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10937 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10938 10939 return true; 10940 } 10941 10942 int doPostInstall(int status, int uid) { 10943 if (status != PackageManager.INSTALL_SUCCEEDED) { 10944 cleanUp(); 10945 } 10946 return status; 10947 } 10948 10949 @Override 10950 String getCodePath() { 10951 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10952 } 10953 10954 @Override 10955 String getResourcePath() { 10956 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10957 } 10958 10959 private boolean cleanUp() { 10960 if (codeFile == null || !codeFile.exists()) { 10961 return false; 10962 } 10963 10964 if (codeFile.isDirectory()) { 10965 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10966 } else { 10967 codeFile.delete(); 10968 } 10969 10970 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10971 resourceFile.delete(); 10972 } 10973 10974 return true; 10975 } 10976 10977 void cleanUpResourcesLI() { 10978 cleanUp(); 10979 } 10980 10981 boolean doPostDeleteLI(boolean delete) { 10982 // XXX err, shouldn't we respect the delete flag? 10983 cleanUpResourcesLI(); 10984 return true; 10985 } 10986 } 10987 10988 static String getAsecPackageName(String packageCid) { 10989 int idx = packageCid.lastIndexOf("-"); 10990 if (idx == -1) { 10991 return packageCid; 10992 } 10993 return packageCid.substring(0, idx); 10994 } 10995 10996 // Utility method used to create code paths based on package name and available index. 10997 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10998 String idxStr = ""; 10999 int idx = 1; 11000 // Fall back to default value of idx=1 if prefix is not 11001 // part of oldCodePath 11002 if (oldCodePath != null) { 11003 String subStr = oldCodePath; 11004 // Drop the suffix right away 11005 if (suffix != null && subStr.endsWith(suffix)) { 11006 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11007 } 11008 // If oldCodePath already contains prefix find out the 11009 // ending index to either increment or decrement. 11010 int sidx = subStr.lastIndexOf(prefix); 11011 if (sidx != -1) { 11012 subStr = subStr.substring(sidx + prefix.length()); 11013 if (subStr != null) { 11014 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11015 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11016 } 11017 try { 11018 idx = Integer.parseInt(subStr); 11019 if (idx <= 1) { 11020 idx++; 11021 } else { 11022 idx--; 11023 } 11024 } catch(NumberFormatException e) { 11025 } 11026 } 11027 } 11028 } 11029 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11030 return prefix + idxStr; 11031 } 11032 11033 private File getNextCodePath(File targetDir, String packageName) { 11034 int suffix = 1; 11035 File result; 11036 do { 11037 result = new File(targetDir, packageName + "-" + suffix); 11038 suffix++; 11039 } while (result.exists()); 11040 return result; 11041 } 11042 11043 // Utility method that returns the relative package path with respect 11044 // to the installation directory. Like say for /data/data/com.test-1.apk 11045 // string com.test-1 is returned. 11046 static String deriveCodePathName(String codePath) { 11047 if (codePath == null) { 11048 return null; 11049 } 11050 final File codeFile = new File(codePath); 11051 final String name = codeFile.getName(); 11052 if (codeFile.isDirectory()) { 11053 return name; 11054 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11055 final int lastDot = name.lastIndexOf('.'); 11056 return name.substring(0, lastDot); 11057 } else { 11058 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11059 return null; 11060 } 11061 } 11062 11063 class PackageInstalledInfo { 11064 String name; 11065 int uid; 11066 // The set of users that originally had this package installed. 11067 int[] origUsers; 11068 // The set of users that now have this package installed. 11069 int[] newUsers; 11070 PackageParser.Package pkg; 11071 int returnCode; 11072 String returnMsg; 11073 PackageRemovedInfo removedInfo; 11074 11075 public void setError(int code, String msg) { 11076 returnCode = code; 11077 returnMsg = msg; 11078 Slog.w(TAG, msg); 11079 } 11080 11081 public void setError(String msg, PackageParserException e) { 11082 returnCode = e.error; 11083 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11084 Slog.w(TAG, msg, e); 11085 } 11086 11087 public void setError(String msg, PackageManagerException e) { 11088 returnCode = e.error; 11089 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11090 Slog.w(TAG, msg, e); 11091 } 11092 11093 // In some error cases we want to convey more info back to the observer 11094 String origPackage; 11095 String origPermission; 11096 } 11097 11098 /* 11099 * Install a non-existing package. 11100 */ 11101 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11102 UserHandle user, String installerPackageName, String volumeUuid, 11103 PackageInstalledInfo res) { 11104 // Remember this for later, in case we need to rollback this install 11105 String pkgName = pkg.packageName; 11106 11107 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11108 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11109 UserHandle.USER_OWNER).exists(); 11110 synchronized(mPackages) { 11111 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11112 // A package with the same name is already installed, though 11113 // it has been renamed to an older name. The package we 11114 // are trying to install should be installed as an update to 11115 // the existing one, but that has not been requested, so bail. 11116 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11117 + " without first uninstalling package running as " 11118 + mSettings.mRenamedPackages.get(pkgName)); 11119 return; 11120 } 11121 if (mPackages.containsKey(pkgName)) { 11122 // Don't allow installation over an existing package with the same name. 11123 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11124 + " without first uninstalling."); 11125 return; 11126 } 11127 } 11128 11129 try { 11130 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11131 System.currentTimeMillis(), user); 11132 11133 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11134 // delete the partially installed application. the data directory will have to be 11135 // restored if it was already existing 11136 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11137 // remove package from internal structures. Note that we want deletePackageX to 11138 // delete the package data and cache directories that it created in 11139 // scanPackageLocked, unless those directories existed before we even tried to 11140 // install. 11141 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11142 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11143 res.removedInfo, true); 11144 } 11145 11146 } catch (PackageManagerException e) { 11147 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11148 } 11149 } 11150 11151 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11152 // Can't rotate keys during boot or if sharedUser. 11153 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11154 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11155 return false; 11156 } 11157 // app is using upgradeKeySets; make sure all are valid 11158 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11159 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11160 for (int i = 0; i < upgradeKeySets.length; i++) { 11161 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11162 Slog.wtf(TAG, "Package " 11163 + (oldPs.name != null ? oldPs.name : "<null>") 11164 + " contains upgrade-key-set reference to unknown key-set: " 11165 + upgradeKeySets[i] 11166 + " reverting to signatures check."); 11167 return false; 11168 } 11169 } 11170 return true; 11171 } 11172 11173 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11174 // Upgrade keysets are being used. Determine if new package has a superset of the 11175 // required keys. 11176 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11177 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11178 for (int i = 0; i < upgradeKeySets.length; i++) { 11179 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11180 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11181 return true; 11182 } 11183 } 11184 return false; 11185 } 11186 11187 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11188 UserHandle user, String installerPackageName, String volumeUuid, 11189 PackageInstalledInfo res) { 11190 final PackageParser.Package oldPackage; 11191 final String pkgName = pkg.packageName; 11192 final int[] allUsers; 11193 final boolean[] perUserInstalled; 11194 final boolean weFroze; 11195 11196 // First find the old package info and check signatures 11197 synchronized(mPackages) { 11198 oldPackage = mPackages.get(pkgName); 11199 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11200 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11201 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11202 if(!checkUpgradeKeySetLP(ps, pkg)) { 11203 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11204 "New package not signed by keys specified by upgrade-keysets: " 11205 + pkgName); 11206 return; 11207 } 11208 } else { 11209 // default to original signature matching 11210 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11211 != PackageManager.SIGNATURE_MATCH) { 11212 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11213 "New package has a different signature: " + pkgName); 11214 return; 11215 } 11216 } 11217 11218 // In case of rollback, remember per-user/profile install state 11219 allUsers = sUserManager.getUserIds(); 11220 perUserInstalled = new boolean[allUsers.length]; 11221 for (int i = 0; i < allUsers.length; i++) { 11222 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11223 } 11224 11225 // Mark the app as frozen to prevent launching during the upgrade 11226 // process, and then kill all running instances 11227 if (!ps.frozen) { 11228 ps.frozen = true; 11229 weFroze = true; 11230 } else { 11231 weFroze = false; 11232 } 11233 } 11234 11235 // Now that we're guarded by frozen state, kill app during upgrade 11236 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11237 11238 try { 11239 boolean sysPkg = (isSystemApp(oldPackage)); 11240 if (sysPkg) { 11241 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11242 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11243 } else { 11244 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11245 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11246 } 11247 } finally { 11248 // Regardless of success or failure of upgrade steps above, always 11249 // unfreeze the package if we froze it 11250 if (weFroze) { 11251 unfreezePackage(pkgName); 11252 } 11253 } 11254 } 11255 11256 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11257 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11258 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11259 String volumeUuid, PackageInstalledInfo res) { 11260 String pkgName = deletedPackage.packageName; 11261 boolean deletedPkg = true; 11262 boolean updatedSettings = false; 11263 11264 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11265 + deletedPackage); 11266 long origUpdateTime; 11267 if (pkg.mExtras != null) { 11268 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11269 } else { 11270 origUpdateTime = 0; 11271 } 11272 11273 // First delete the existing package while retaining the data directory 11274 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11275 res.removedInfo, true)) { 11276 // If the existing package wasn't successfully deleted 11277 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11278 deletedPkg = false; 11279 } else { 11280 // Successfully deleted the old package; proceed with replace. 11281 11282 // If deleted package lived in a container, give users a chance to 11283 // relinquish resources before killing. 11284 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11285 if (DEBUG_INSTALL) { 11286 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11287 } 11288 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11289 final ArrayList<String> pkgList = new ArrayList<String>(1); 11290 pkgList.add(deletedPackage.applicationInfo.packageName); 11291 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11292 } 11293 11294 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11295 try { 11296 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11297 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11298 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11299 perUserInstalled, res, user); 11300 updatedSettings = true; 11301 } catch (PackageManagerException e) { 11302 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11303 } 11304 } 11305 11306 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11307 // remove package from internal structures. Note that we want deletePackageX to 11308 // delete the package data and cache directories that it created in 11309 // scanPackageLocked, unless those directories existed before we even tried to 11310 // install. 11311 if(updatedSettings) { 11312 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11313 deletePackageLI( 11314 pkgName, null, true, allUsers, perUserInstalled, 11315 PackageManager.DELETE_KEEP_DATA, 11316 res.removedInfo, true); 11317 } 11318 // Since we failed to install the new package we need to restore the old 11319 // package that we deleted. 11320 if (deletedPkg) { 11321 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11322 File restoreFile = new File(deletedPackage.codePath); 11323 // Parse old package 11324 boolean oldExternal = isExternal(deletedPackage); 11325 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11326 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11327 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11328 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11329 try { 11330 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11331 } catch (PackageManagerException e) { 11332 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11333 + e.getMessage()); 11334 return; 11335 } 11336 // Restore of old package succeeded. Update permissions. 11337 // writer 11338 synchronized (mPackages) { 11339 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11340 UPDATE_PERMISSIONS_ALL); 11341 // can downgrade to reader 11342 mSettings.writeLPr(); 11343 } 11344 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11345 } 11346 } 11347 } 11348 11349 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11350 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11351 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11352 String volumeUuid, PackageInstalledInfo res) { 11353 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11354 + ", old=" + deletedPackage); 11355 boolean disabledSystem = false; 11356 boolean updatedSettings = false; 11357 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11358 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11359 != 0) { 11360 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11361 } 11362 String packageName = deletedPackage.packageName; 11363 if (packageName == null) { 11364 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11365 "Attempt to delete null packageName."); 11366 return; 11367 } 11368 PackageParser.Package oldPkg; 11369 PackageSetting oldPkgSetting; 11370 // reader 11371 synchronized (mPackages) { 11372 oldPkg = mPackages.get(packageName); 11373 oldPkgSetting = mSettings.mPackages.get(packageName); 11374 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11375 (oldPkgSetting == null)) { 11376 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11377 "Couldn't find package:" + packageName + " information"); 11378 return; 11379 } 11380 } 11381 11382 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11383 res.removedInfo.removedPackage = packageName; 11384 // Remove existing system package 11385 removePackageLI(oldPkgSetting, true); 11386 // writer 11387 synchronized (mPackages) { 11388 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11389 if (!disabledSystem && deletedPackage != null) { 11390 // We didn't need to disable the .apk as a current system package, 11391 // which means we are replacing another update that is already 11392 // installed. We need to make sure to delete the older one's .apk. 11393 res.removedInfo.args = createInstallArgsForExisting(0, 11394 deletedPackage.applicationInfo.getCodePath(), 11395 deletedPackage.applicationInfo.getResourcePath(), 11396 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11397 } else { 11398 res.removedInfo.args = null; 11399 } 11400 } 11401 11402 // Successfully disabled the old package. Now proceed with re-installation 11403 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11404 11405 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11406 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11407 11408 PackageParser.Package newPackage = null; 11409 try { 11410 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11411 if (newPackage.mExtras != null) { 11412 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11413 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11414 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11415 11416 // is the update attempting to change shared user? that isn't going to work... 11417 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11418 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11419 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11420 + " to " + newPkgSetting.sharedUser); 11421 updatedSettings = true; 11422 } 11423 } 11424 11425 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11426 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11427 perUserInstalled, res, user); 11428 updatedSettings = true; 11429 } 11430 11431 } catch (PackageManagerException e) { 11432 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11433 } 11434 11435 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11436 // Re installation failed. Restore old information 11437 // Remove new pkg information 11438 if (newPackage != null) { 11439 removeInstalledPackageLI(newPackage, true); 11440 } 11441 // Add back the old system package 11442 try { 11443 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11444 } catch (PackageManagerException e) { 11445 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11446 } 11447 // Restore the old system information in Settings 11448 synchronized (mPackages) { 11449 if (disabledSystem) { 11450 mSettings.enableSystemPackageLPw(packageName); 11451 } 11452 if (updatedSettings) { 11453 mSettings.setInstallerPackageName(packageName, 11454 oldPkgSetting.installerPackageName); 11455 } 11456 mSettings.writeLPr(); 11457 } 11458 } 11459 } 11460 11461 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11462 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11463 UserHandle user) { 11464 String pkgName = newPackage.packageName; 11465 synchronized (mPackages) { 11466 //write settings. the installStatus will be incomplete at this stage. 11467 //note that the new package setting would have already been 11468 //added to mPackages. It hasn't been persisted yet. 11469 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11470 mSettings.writeLPr(); 11471 } 11472 11473 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11474 11475 synchronized (mPackages) { 11476 updatePermissionsLPw(newPackage.packageName, newPackage, 11477 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11478 ? UPDATE_PERMISSIONS_ALL : 0)); 11479 // For system-bundled packages, we assume that installing an upgraded version 11480 // of the package implies that the user actually wants to run that new code, 11481 // so we enable the package. 11482 PackageSetting ps = mSettings.mPackages.get(pkgName); 11483 if (ps != null) { 11484 if (isSystemApp(newPackage)) { 11485 // NB: implicit assumption that system package upgrades apply to all users 11486 if (DEBUG_INSTALL) { 11487 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11488 } 11489 if (res.origUsers != null) { 11490 for (int userHandle : res.origUsers) { 11491 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11492 userHandle, installerPackageName); 11493 } 11494 } 11495 // Also convey the prior install/uninstall state 11496 if (allUsers != null && perUserInstalled != null) { 11497 for (int i = 0; i < allUsers.length; i++) { 11498 if (DEBUG_INSTALL) { 11499 Slog.d(TAG, " user " + allUsers[i] 11500 + " => " + perUserInstalled[i]); 11501 } 11502 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11503 } 11504 // these install state changes will be persisted in the 11505 // upcoming call to mSettings.writeLPr(). 11506 } 11507 } 11508 // It's implied that when a user requests installation, they want the app to be 11509 // installed and enabled. 11510 int userId = user.getIdentifier(); 11511 if (userId != UserHandle.USER_ALL) { 11512 ps.setInstalled(true, userId); 11513 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11514 } 11515 } 11516 res.name = pkgName; 11517 res.uid = newPackage.applicationInfo.uid; 11518 res.pkg = newPackage; 11519 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11520 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11521 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11522 //to update install status 11523 mSettings.writeLPr(); 11524 } 11525 } 11526 11527 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11528 final int installFlags = args.installFlags; 11529 final String installerPackageName = args.installerPackageName; 11530 final String volumeUuid = args.volumeUuid; 11531 final File tmpPackageFile = new File(args.getCodePath()); 11532 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11533 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11534 || (args.volumeUuid != null)); 11535 boolean replace = false; 11536 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11537 // Result object to be returned 11538 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11539 11540 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11541 // Retrieve PackageSettings and parse package 11542 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11543 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11544 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11545 PackageParser pp = new PackageParser(); 11546 pp.setSeparateProcesses(mSeparateProcesses); 11547 pp.setDisplayMetrics(mMetrics); 11548 11549 final PackageParser.Package pkg; 11550 try { 11551 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11552 } catch (PackageParserException e) { 11553 res.setError("Failed parse during installPackageLI", e); 11554 return; 11555 } 11556 11557 // Mark that we have an install time CPU ABI override. 11558 pkg.cpuAbiOverride = args.abiOverride; 11559 11560 String pkgName = res.name = pkg.packageName; 11561 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11562 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11563 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11564 return; 11565 } 11566 } 11567 11568 try { 11569 pp.collectCertificates(pkg, parseFlags); 11570 pp.collectManifestDigest(pkg); 11571 } catch (PackageParserException e) { 11572 res.setError("Failed collect during installPackageLI", e); 11573 return; 11574 } 11575 11576 /* If the installer passed in a manifest digest, compare it now. */ 11577 if (args.manifestDigest != null) { 11578 if (DEBUG_INSTALL) { 11579 final String parsedManifest = pkg.manifestDigest == null ? "null" 11580 : pkg.manifestDigest.toString(); 11581 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11582 + parsedManifest); 11583 } 11584 11585 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11586 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11587 return; 11588 } 11589 } else if (DEBUG_INSTALL) { 11590 final String parsedManifest = pkg.manifestDigest == null 11591 ? "null" : pkg.manifestDigest.toString(); 11592 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11593 } 11594 11595 // Get rid of all references to package scan path via parser. 11596 pp = null; 11597 String oldCodePath = null; 11598 boolean systemApp = false; 11599 synchronized (mPackages) { 11600 // Check if installing already existing package 11601 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11602 String oldName = mSettings.mRenamedPackages.get(pkgName); 11603 if (pkg.mOriginalPackages != null 11604 && pkg.mOriginalPackages.contains(oldName) 11605 && mPackages.containsKey(oldName)) { 11606 // This package is derived from an original package, 11607 // and this device has been updating from that original 11608 // name. We must continue using the original name, so 11609 // rename the new package here. 11610 pkg.setPackageName(oldName); 11611 pkgName = pkg.packageName; 11612 replace = true; 11613 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11614 + oldName + " pkgName=" + pkgName); 11615 } else if (mPackages.containsKey(pkgName)) { 11616 // This package, under its official name, already exists 11617 // on the device; we should replace it. 11618 replace = true; 11619 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11620 } 11621 11622 // Prevent apps opting out from runtime permissions 11623 if (replace) { 11624 PackageParser.Package oldPackage = mPackages.get(pkgName); 11625 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11626 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11627 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11628 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11629 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11630 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11631 + " doesn't support runtime permissions but the old" 11632 + " target SDK " + oldTargetSdk + " does."); 11633 return; 11634 } 11635 } 11636 } 11637 11638 PackageSetting ps = mSettings.mPackages.get(pkgName); 11639 if (ps != null) { 11640 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11641 11642 // Quick sanity check that we're signed correctly if updating; 11643 // we'll check this again later when scanning, but we want to 11644 // bail early here before tripping over redefined permissions. 11645 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11646 if (!checkUpgradeKeySetLP(ps, pkg)) { 11647 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11648 + pkg.packageName + " upgrade keys do not match the " 11649 + "previously installed version"); 11650 return; 11651 } 11652 } else { 11653 try { 11654 verifySignaturesLP(ps, pkg); 11655 } catch (PackageManagerException e) { 11656 res.setError(e.error, e.getMessage()); 11657 return; 11658 } 11659 } 11660 11661 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11662 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11663 systemApp = (ps.pkg.applicationInfo.flags & 11664 ApplicationInfo.FLAG_SYSTEM) != 0; 11665 } 11666 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11667 } 11668 11669 // Check whether the newly-scanned package wants to define an already-defined perm 11670 int N = pkg.permissions.size(); 11671 for (int i = N-1; i >= 0; i--) { 11672 PackageParser.Permission perm = pkg.permissions.get(i); 11673 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11674 if (bp != null) { 11675 // If the defining package is signed with our cert, it's okay. This 11676 // also includes the "updating the same package" case, of course. 11677 // "updating same package" could also involve key-rotation. 11678 final boolean sigsOk; 11679 if (bp.sourcePackage.equals(pkg.packageName) 11680 && (bp.packageSetting instanceof PackageSetting) 11681 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11682 scanFlags))) { 11683 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11684 } else { 11685 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11686 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11687 } 11688 if (!sigsOk) { 11689 // If the owning package is the system itself, we log but allow 11690 // install to proceed; we fail the install on all other permission 11691 // redefinitions. 11692 if (!bp.sourcePackage.equals("android")) { 11693 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11694 + pkg.packageName + " attempting to redeclare permission " 11695 + perm.info.name + " already owned by " + bp.sourcePackage); 11696 res.origPermission = perm.info.name; 11697 res.origPackage = bp.sourcePackage; 11698 return; 11699 } else { 11700 Slog.w(TAG, "Package " + pkg.packageName 11701 + " attempting to redeclare system permission " 11702 + perm.info.name + "; ignoring new declaration"); 11703 pkg.permissions.remove(i); 11704 } 11705 } 11706 } 11707 } 11708 11709 } 11710 11711 if (systemApp && onExternal) { 11712 // Disable updates to system apps on sdcard 11713 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11714 "Cannot install updates to system apps on sdcard"); 11715 return; 11716 } 11717 11718 if (args.move != null) { 11719 // We did an in-place move, so dex is ready to roll 11720 scanFlags |= SCAN_NO_DEX; 11721 scanFlags |= SCAN_MOVE; 11722 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11723 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11724 scanFlags |= SCAN_NO_DEX; 11725 11726 try { 11727 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11728 true /* extract libs */); 11729 } catch (PackageManagerException pme) { 11730 Slog.e(TAG, "Error deriving application ABI", pme); 11731 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11732 return; 11733 } 11734 11735 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11736 int result = mPackageDexOptimizer 11737 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11738 false /* defer */, false /* inclDependencies */); 11739 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11740 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11741 return; 11742 } 11743 } 11744 11745 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11746 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11747 return; 11748 } 11749 11750 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11751 11752 if (replace) { 11753 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11754 installerPackageName, volumeUuid, res); 11755 } else { 11756 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11757 args.user, installerPackageName, volumeUuid, res); 11758 } 11759 synchronized (mPackages) { 11760 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11761 if (ps != null) { 11762 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11763 } 11764 } 11765 } 11766 11767 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11768 if (mIntentFilterVerifierComponent == null) { 11769 Slog.w(TAG, "No IntentFilter verification will not be done as " 11770 + "there is no IntentFilterVerifier available!"); 11771 return; 11772 } 11773 11774 final int verifierUid = getPackageUid( 11775 mIntentFilterVerifierComponent.getPackageName(), 11776 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11777 11778 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11779 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11780 msg.obj = pkg; 11781 msg.arg1 = userId; 11782 msg.arg2 = verifierUid; 11783 11784 mHandler.sendMessage(msg); 11785 } 11786 11787 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11788 PackageParser.Package pkg) { 11789 int size = pkg.activities.size(); 11790 if (size == 0) { 11791 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11792 "No activity, so no need to verify any IntentFilter!"); 11793 return; 11794 } 11795 11796 final boolean hasDomainURLs = hasDomainURLs(pkg); 11797 if (!hasDomainURLs) { 11798 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11799 "No domain URLs, so no need to verify any IntentFilter!"); 11800 return; 11801 } 11802 11803 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11804 + " if any IntentFilter from the " + size 11805 + " Activities needs verification ..."); 11806 11807 final int verificationId = mIntentFilterVerificationToken++; 11808 int count = 0; 11809 final String packageName = pkg.packageName; 11810 boolean needToVerify = false; 11811 11812 synchronized (mPackages) { 11813 // If any filters need to be verified, then all need to be. 11814 for (PackageParser.Activity a : pkg.activities) { 11815 for (ActivityIntentInfo filter : a.intents) { 11816 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 11817 if (DEBUG_DOMAIN_VERIFICATION) { 11818 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 11819 } 11820 needToVerify = true; 11821 break; 11822 } 11823 } 11824 } 11825 if (needToVerify) { 11826 for (PackageParser.Activity a : pkg.activities) { 11827 for (ActivityIntentInfo filter : a.intents) { 11828 boolean needsFilterVerification = filter.hasWebDataURI(); 11829 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11830 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11831 "Verification needed for IntentFilter:" + filter.toString()); 11832 mIntentFilterVerifier.addOneIntentFilterVerification( 11833 verifierUid, userId, verificationId, filter, packageName); 11834 count++; 11835 } 11836 } 11837 } 11838 } 11839 } 11840 11841 if (count > 0) { 11842 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 11843 + " IntentFilter verification" + (count > 1 ? "s" : "") 11844 + " for userId:" + userId); 11845 mIntentFilterVerifier.startVerifications(userId); 11846 } else { 11847 if (DEBUG_DOMAIN_VERIFICATION) { 11848 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 11849 } 11850 } 11851 } 11852 11853 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11854 final ComponentName cn = filter.activity.getComponentName(); 11855 final String packageName = cn.getPackageName(); 11856 11857 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11858 packageName); 11859 if (ivi == null) { 11860 return true; 11861 } 11862 int status = ivi.getStatus(); 11863 switch (status) { 11864 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11865 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11866 return true; 11867 11868 default: 11869 // Nothing to do 11870 return false; 11871 } 11872 } 11873 11874 private static boolean isMultiArch(PackageSetting ps) { 11875 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11876 } 11877 11878 private static boolean isMultiArch(ApplicationInfo info) { 11879 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11880 } 11881 11882 private static boolean isExternal(PackageParser.Package pkg) { 11883 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11884 } 11885 11886 private static boolean isExternal(PackageSetting ps) { 11887 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11888 } 11889 11890 private static boolean isExternal(ApplicationInfo info) { 11891 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11892 } 11893 11894 private static boolean isSystemApp(PackageParser.Package pkg) { 11895 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11896 } 11897 11898 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11899 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11900 } 11901 11902 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11903 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11904 } 11905 11906 private static boolean isSystemApp(PackageSetting ps) { 11907 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11908 } 11909 11910 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11911 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11912 } 11913 11914 private int packageFlagsToInstallFlags(PackageSetting ps) { 11915 int installFlags = 0; 11916 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11917 // This existing package was an external ASEC install when we have 11918 // the external flag without a UUID 11919 installFlags |= PackageManager.INSTALL_EXTERNAL; 11920 } 11921 if (ps.isForwardLocked()) { 11922 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11923 } 11924 return installFlags; 11925 } 11926 11927 private void deleteTempPackageFiles() { 11928 final FilenameFilter filter = new FilenameFilter() { 11929 public boolean accept(File dir, String name) { 11930 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11931 } 11932 }; 11933 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11934 file.delete(); 11935 } 11936 } 11937 11938 @Override 11939 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11940 int flags) { 11941 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11942 flags); 11943 } 11944 11945 @Override 11946 public void deletePackage(final String packageName, 11947 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11948 mContext.enforceCallingOrSelfPermission( 11949 android.Manifest.permission.DELETE_PACKAGES, null); 11950 final int uid = Binder.getCallingUid(); 11951 if (UserHandle.getUserId(uid) != userId) { 11952 mContext.enforceCallingPermission( 11953 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11954 "deletePackage for user " + userId); 11955 } 11956 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11957 try { 11958 observer.onPackageDeleted(packageName, 11959 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11960 } catch (RemoteException re) { 11961 } 11962 return; 11963 } 11964 11965 boolean uninstallBlocked = false; 11966 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11967 int[] users = sUserManager.getUserIds(); 11968 for (int i = 0; i < users.length; ++i) { 11969 if (getBlockUninstallForUser(packageName, users[i])) { 11970 uninstallBlocked = true; 11971 break; 11972 } 11973 } 11974 } else { 11975 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11976 } 11977 if (uninstallBlocked) { 11978 try { 11979 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11980 null); 11981 } catch (RemoteException re) { 11982 } 11983 return; 11984 } 11985 11986 if (DEBUG_REMOVE) { 11987 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11988 } 11989 // Queue up an async operation since the package deletion may take a little while. 11990 mHandler.post(new Runnable() { 11991 public void run() { 11992 mHandler.removeCallbacks(this); 11993 final int returnCode = deletePackageX(packageName, userId, flags); 11994 if (observer != null) { 11995 try { 11996 observer.onPackageDeleted(packageName, returnCode, null); 11997 } catch (RemoteException e) { 11998 Log.i(TAG, "Observer no longer exists."); 11999 } //end catch 12000 } //end if 12001 } //end run 12002 }); 12003 } 12004 12005 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12006 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12007 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12008 try { 12009 if (dpm != null) { 12010 if (dpm.isDeviceOwner(packageName)) { 12011 return true; 12012 } 12013 int[] users; 12014 if (userId == UserHandle.USER_ALL) { 12015 users = sUserManager.getUserIds(); 12016 } else { 12017 users = new int[]{userId}; 12018 } 12019 for (int i = 0; i < users.length; ++i) { 12020 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12021 return true; 12022 } 12023 } 12024 } 12025 } catch (RemoteException e) { 12026 } 12027 return false; 12028 } 12029 12030 /** 12031 * This method is an internal method that could be get invoked either 12032 * to delete an installed package or to clean up a failed installation. 12033 * After deleting an installed package, a broadcast is sent to notify any 12034 * listeners that the package has been installed. For cleaning up a failed 12035 * installation, the broadcast is not necessary since the package's 12036 * installation wouldn't have sent the initial broadcast either 12037 * The key steps in deleting a package are 12038 * deleting the package information in internal structures like mPackages, 12039 * deleting the packages base directories through installd 12040 * updating mSettings to reflect current status 12041 * persisting settings for later use 12042 * sending a broadcast if necessary 12043 */ 12044 private int deletePackageX(String packageName, int userId, int flags) { 12045 final PackageRemovedInfo info = new PackageRemovedInfo(); 12046 final boolean res; 12047 12048 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12049 ? UserHandle.ALL : new UserHandle(userId); 12050 12051 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12052 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12053 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12054 } 12055 12056 boolean removedForAllUsers = false; 12057 boolean systemUpdate = false; 12058 12059 // for the uninstall-updates case and restricted profiles, remember the per- 12060 // userhandle installed state 12061 int[] allUsers; 12062 boolean[] perUserInstalled; 12063 synchronized (mPackages) { 12064 PackageSetting ps = mSettings.mPackages.get(packageName); 12065 allUsers = sUserManager.getUserIds(); 12066 perUserInstalled = new boolean[allUsers.length]; 12067 for (int i = 0; i < allUsers.length; i++) { 12068 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12069 } 12070 } 12071 12072 synchronized (mInstallLock) { 12073 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12074 res = deletePackageLI(packageName, removeForUser, 12075 true, allUsers, perUserInstalled, 12076 flags | REMOVE_CHATTY, info, true); 12077 systemUpdate = info.isRemovedPackageSystemUpdate; 12078 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12079 removedForAllUsers = true; 12080 } 12081 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12082 + " removedForAllUsers=" + removedForAllUsers); 12083 } 12084 12085 if (res) { 12086 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12087 12088 // If the removed package was a system update, the old system package 12089 // was re-enabled; we need to broadcast this information 12090 if (systemUpdate) { 12091 Bundle extras = new Bundle(1); 12092 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12093 ? info.removedAppId : info.uid); 12094 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12095 12096 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12097 extras, null, null, null); 12098 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12099 extras, null, null, null); 12100 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12101 null, packageName, null, null); 12102 } 12103 } 12104 // Force a gc here. 12105 Runtime.getRuntime().gc(); 12106 // Delete the resources here after sending the broadcast to let 12107 // other processes clean up before deleting resources. 12108 if (info.args != null) { 12109 synchronized (mInstallLock) { 12110 info.args.doPostDeleteLI(true); 12111 } 12112 } 12113 12114 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12115 } 12116 12117 class PackageRemovedInfo { 12118 String removedPackage; 12119 int uid = -1; 12120 int removedAppId = -1; 12121 int[] removedUsers = null; 12122 boolean isRemovedPackageSystemUpdate = false; 12123 // Clean up resources deleted packages. 12124 InstallArgs args = null; 12125 12126 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12127 Bundle extras = new Bundle(1); 12128 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12129 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12130 if (replacing) { 12131 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12132 } 12133 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12134 if (removedPackage != null) { 12135 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12136 extras, null, null, removedUsers); 12137 if (fullRemove && !replacing) { 12138 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12139 extras, null, null, removedUsers); 12140 } 12141 } 12142 if (removedAppId >= 0) { 12143 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12144 removedUsers); 12145 } 12146 } 12147 } 12148 12149 /* 12150 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12151 * flag is not set, the data directory is removed as well. 12152 * make sure this flag is set for partially installed apps. If not its meaningless to 12153 * delete a partially installed application. 12154 */ 12155 private void removePackageDataLI(PackageSetting ps, 12156 int[] allUserHandles, boolean[] perUserInstalled, 12157 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12158 String packageName = ps.name; 12159 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12160 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12161 // Retrieve object to delete permissions for shared user later on 12162 final PackageSetting deletedPs; 12163 // reader 12164 synchronized (mPackages) { 12165 deletedPs = mSettings.mPackages.get(packageName); 12166 if (outInfo != null) { 12167 outInfo.removedPackage = packageName; 12168 outInfo.removedUsers = deletedPs != null 12169 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12170 : null; 12171 } 12172 } 12173 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12174 removeDataDirsLI(ps.volumeUuid, packageName); 12175 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12176 } 12177 // writer 12178 synchronized (mPackages) { 12179 if (deletedPs != null) { 12180 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12181 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12182 clearDefaultBrowserIfNeeded(packageName); 12183 if (outInfo != null) { 12184 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12185 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12186 } 12187 updatePermissionsLPw(deletedPs.name, null, 0); 12188 if (deletedPs.sharedUser != null) { 12189 // Remove permissions associated with package. Since runtime 12190 // permissions are per user we have to kill the removed package 12191 // or packages running under the shared user of the removed 12192 // package if revoking the permissions requested only by the removed 12193 // package is successful and this causes a change in gids. 12194 for (int userId : UserManagerService.getInstance().getUserIds()) { 12195 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12196 userId); 12197 if (userIdToKill == UserHandle.USER_ALL 12198 || userIdToKill >= UserHandle.USER_OWNER) { 12199 // If gids changed for this user, kill all affected packages. 12200 mHandler.post(new Runnable() { 12201 @Override 12202 public void run() { 12203 // This has to happen with no lock held. 12204 killSettingPackagesForUser(deletedPs, userIdToKill, 12205 KILL_APP_REASON_GIDS_CHANGED); 12206 } 12207 }); 12208 break; 12209 } 12210 } 12211 } 12212 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12213 } 12214 // make sure to preserve per-user disabled state if this removal was just 12215 // a downgrade of a system app to the factory package 12216 if (allUserHandles != null && perUserInstalled != null) { 12217 if (DEBUG_REMOVE) { 12218 Slog.d(TAG, "Propagating install state across downgrade"); 12219 } 12220 for (int i = 0; i < allUserHandles.length; i++) { 12221 if (DEBUG_REMOVE) { 12222 Slog.d(TAG, " user " + allUserHandles[i] 12223 + " => " + perUserInstalled[i]); 12224 } 12225 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12226 } 12227 } 12228 } 12229 // can downgrade to reader 12230 if (writeSettings) { 12231 // Save settings now 12232 mSettings.writeLPr(); 12233 } 12234 } 12235 if (outInfo != null) { 12236 // A user ID was deleted here. Go through all users and remove it 12237 // from KeyStore. 12238 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12239 } 12240 } 12241 12242 static boolean locationIsPrivileged(File path) { 12243 try { 12244 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12245 .getCanonicalPath(); 12246 return path.getCanonicalPath().startsWith(privilegedAppDir); 12247 } catch (IOException e) { 12248 Slog.e(TAG, "Unable to access code path " + path); 12249 } 12250 return false; 12251 } 12252 12253 /* 12254 * Tries to delete system package. 12255 */ 12256 private boolean deleteSystemPackageLI(PackageSetting newPs, 12257 int[] allUserHandles, boolean[] perUserInstalled, 12258 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12259 final boolean applyUserRestrictions 12260 = (allUserHandles != null) && (perUserInstalled != null); 12261 PackageSetting disabledPs = null; 12262 // Confirm if the system package has been updated 12263 // An updated system app can be deleted. This will also have to restore 12264 // the system pkg from system partition 12265 // reader 12266 synchronized (mPackages) { 12267 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12268 } 12269 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12270 + " disabledPs=" + disabledPs); 12271 if (disabledPs == null) { 12272 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12273 return false; 12274 } else if (DEBUG_REMOVE) { 12275 Slog.d(TAG, "Deleting system pkg from data partition"); 12276 } 12277 if (DEBUG_REMOVE) { 12278 if (applyUserRestrictions) { 12279 Slog.d(TAG, "Remembering install states:"); 12280 for (int i = 0; i < allUserHandles.length; i++) { 12281 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12282 } 12283 } 12284 } 12285 // Delete the updated package 12286 outInfo.isRemovedPackageSystemUpdate = true; 12287 if (disabledPs.versionCode < newPs.versionCode) { 12288 // Delete data for downgrades 12289 flags &= ~PackageManager.DELETE_KEEP_DATA; 12290 } else { 12291 // Preserve data by setting flag 12292 flags |= PackageManager.DELETE_KEEP_DATA; 12293 } 12294 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12295 allUserHandles, perUserInstalled, outInfo, writeSettings); 12296 if (!ret) { 12297 return false; 12298 } 12299 // writer 12300 synchronized (mPackages) { 12301 // Reinstate the old system package 12302 mSettings.enableSystemPackageLPw(newPs.name); 12303 // Remove any native libraries from the upgraded package. 12304 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12305 } 12306 // Install the system package 12307 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12308 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12309 if (locationIsPrivileged(disabledPs.codePath)) { 12310 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12311 } 12312 12313 final PackageParser.Package newPkg; 12314 try { 12315 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12316 } catch (PackageManagerException e) { 12317 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12318 return false; 12319 } 12320 12321 // writer 12322 synchronized (mPackages) { 12323 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12324 updatePermissionsLPw(newPkg.packageName, newPkg, 12325 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12326 if (applyUserRestrictions) { 12327 if (DEBUG_REMOVE) { 12328 Slog.d(TAG, "Propagating install state across reinstall"); 12329 } 12330 for (int i = 0; i < allUserHandles.length; i++) { 12331 if (DEBUG_REMOVE) { 12332 Slog.d(TAG, " user " + allUserHandles[i] 12333 + " => " + perUserInstalled[i]); 12334 } 12335 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12336 } 12337 // Regardless of writeSettings we need to ensure that this restriction 12338 // state propagation is persisted 12339 mSettings.writeAllUsersPackageRestrictionsLPr(); 12340 } 12341 // can downgrade to reader here 12342 if (writeSettings) { 12343 mSettings.writeLPr(); 12344 } 12345 } 12346 return true; 12347 } 12348 12349 private boolean deleteInstalledPackageLI(PackageSetting ps, 12350 boolean deleteCodeAndResources, int flags, 12351 int[] allUserHandles, boolean[] perUserInstalled, 12352 PackageRemovedInfo outInfo, boolean writeSettings) { 12353 if (outInfo != null) { 12354 outInfo.uid = ps.appId; 12355 } 12356 12357 // Delete package data from internal structures and also remove data if flag is set 12358 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12359 12360 // Delete application code and resources 12361 if (deleteCodeAndResources && (outInfo != null)) { 12362 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12363 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12364 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12365 } 12366 return true; 12367 } 12368 12369 @Override 12370 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12371 int userId) { 12372 mContext.enforceCallingOrSelfPermission( 12373 android.Manifest.permission.DELETE_PACKAGES, null); 12374 synchronized (mPackages) { 12375 PackageSetting ps = mSettings.mPackages.get(packageName); 12376 if (ps == null) { 12377 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12378 return false; 12379 } 12380 if (!ps.getInstalled(userId)) { 12381 // Can't block uninstall for an app that is not installed or enabled. 12382 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12383 return false; 12384 } 12385 ps.setBlockUninstall(blockUninstall, userId); 12386 mSettings.writePackageRestrictionsLPr(userId); 12387 } 12388 return true; 12389 } 12390 12391 @Override 12392 public boolean getBlockUninstallForUser(String packageName, int userId) { 12393 synchronized (mPackages) { 12394 PackageSetting ps = mSettings.mPackages.get(packageName); 12395 if (ps == null) { 12396 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12397 return false; 12398 } 12399 return ps.getBlockUninstall(userId); 12400 } 12401 } 12402 12403 /* 12404 * This method handles package deletion in general 12405 */ 12406 private boolean deletePackageLI(String packageName, UserHandle user, 12407 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12408 int flags, PackageRemovedInfo outInfo, 12409 boolean writeSettings) { 12410 if (packageName == null) { 12411 Slog.w(TAG, "Attempt to delete null packageName."); 12412 return false; 12413 } 12414 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12415 PackageSetting ps; 12416 boolean dataOnly = false; 12417 int removeUser = -1; 12418 int appId = -1; 12419 synchronized (mPackages) { 12420 ps = mSettings.mPackages.get(packageName); 12421 if (ps == null) { 12422 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12423 return false; 12424 } 12425 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12426 && user.getIdentifier() != UserHandle.USER_ALL) { 12427 // The caller is asking that the package only be deleted for a single 12428 // user. To do this, we just mark its uninstalled state and delete 12429 // its data. If this is a system app, we only allow this to happen if 12430 // they have set the special DELETE_SYSTEM_APP which requests different 12431 // semantics than normal for uninstalling system apps. 12432 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12433 ps.setUserState(user.getIdentifier(), 12434 COMPONENT_ENABLED_STATE_DEFAULT, 12435 false, //installed 12436 true, //stopped 12437 true, //notLaunched 12438 false, //hidden 12439 null, null, null, 12440 false, // blockUninstall 12441 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12442 if (!isSystemApp(ps)) { 12443 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12444 // Other user still have this package installed, so all 12445 // we need to do is clear this user's data and save that 12446 // it is uninstalled. 12447 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12448 removeUser = user.getIdentifier(); 12449 appId = ps.appId; 12450 scheduleWritePackageRestrictionsLocked(removeUser); 12451 } else { 12452 // We need to set it back to 'installed' so the uninstall 12453 // broadcasts will be sent correctly. 12454 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12455 ps.setInstalled(true, user.getIdentifier()); 12456 } 12457 } else { 12458 // This is a system app, so we assume that the 12459 // other users still have this package installed, so all 12460 // we need to do is clear this user's data and save that 12461 // it is uninstalled. 12462 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12463 removeUser = user.getIdentifier(); 12464 appId = ps.appId; 12465 scheduleWritePackageRestrictionsLocked(removeUser); 12466 } 12467 } 12468 } 12469 12470 if (removeUser >= 0) { 12471 // From above, we determined that we are deleting this only 12472 // for a single user. Continue the work here. 12473 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12474 if (outInfo != null) { 12475 outInfo.removedPackage = packageName; 12476 outInfo.removedAppId = appId; 12477 outInfo.removedUsers = new int[] {removeUser}; 12478 } 12479 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12480 removeKeystoreDataIfNeeded(removeUser, appId); 12481 schedulePackageCleaning(packageName, removeUser, false); 12482 synchronized (mPackages) { 12483 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12484 scheduleWritePackageRestrictionsLocked(removeUser); 12485 } 12486 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12487 removeUser); 12488 } 12489 return true; 12490 } 12491 12492 if (dataOnly) { 12493 // Delete application data first 12494 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12495 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12496 return true; 12497 } 12498 12499 boolean ret = false; 12500 if (isSystemApp(ps)) { 12501 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12502 // When an updated system application is deleted we delete the existing resources as well and 12503 // fall back to existing code in system partition 12504 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12505 flags, outInfo, writeSettings); 12506 } else { 12507 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12508 // Kill application pre-emptively especially for apps on sd. 12509 killApplication(packageName, ps.appId, "uninstall pkg"); 12510 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12511 allUserHandles, perUserInstalled, 12512 outInfo, writeSettings); 12513 } 12514 12515 return ret; 12516 } 12517 12518 private final class ClearStorageConnection implements ServiceConnection { 12519 IMediaContainerService mContainerService; 12520 12521 @Override 12522 public void onServiceConnected(ComponentName name, IBinder service) { 12523 synchronized (this) { 12524 mContainerService = IMediaContainerService.Stub.asInterface(service); 12525 notifyAll(); 12526 } 12527 } 12528 12529 @Override 12530 public void onServiceDisconnected(ComponentName name) { 12531 } 12532 } 12533 12534 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12535 final boolean mounted; 12536 if (Environment.isExternalStorageEmulated()) { 12537 mounted = true; 12538 } else { 12539 final String status = Environment.getExternalStorageState(); 12540 12541 mounted = status.equals(Environment.MEDIA_MOUNTED) 12542 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12543 } 12544 12545 if (!mounted) { 12546 return; 12547 } 12548 12549 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12550 int[] users; 12551 if (userId == UserHandle.USER_ALL) { 12552 users = sUserManager.getUserIds(); 12553 } else { 12554 users = new int[] { userId }; 12555 } 12556 final ClearStorageConnection conn = new ClearStorageConnection(); 12557 if (mContext.bindServiceAsUser( 12558 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12559 try { 12560 for (int curUser : users) { 12561 long timeout = SystemClock.uptimeMillis() + 5000; 12562 synchronized (conn) { 12563 long now = SystemClock.uptimeMillis(); 12564 while (conn.mContainerService == null && now < timeout) { 12565 try { 12566 conn.wait(timeout - now); 12567 } catch (InterruptedException e) { 12568 } 12569 } 12570 } 12571 if (conn.mContainerService == null) { 12572 return; 12573 } 12574 12575 final UserEnvironment userEnv = new UserEnvironment(curUser); 12576 clearDirectory(conn.mContainerService, 12577 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12578 if (allData) { 12579 clearDirectory(conn.mContainerService, 12580 userEnv.buildExternalStorageAppDataDirs(packageName)); 12581 clearDirectory(conn.mContainerService, 12582 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12583 } 12584 } 12585 } finally { 12586 mContext.unbindService(conn); 12587 } 12588 } 12589 } 12590 12591 @Override 12592 public void clearApplicationUserData(final String packageName, 12593 final IPackageDataObserver observer, final int userId) { 12594 mContext.enforceCallingOrSelfPermission( 12595 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12596 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12597 // Queue up an async operation since the package deletion may take a little while. 12598 mHandler.post(new Runnable() { 12599 public void run() { 12600 mHandler.removeCallbacks(this); 12601 final boolean succeeded; 12602 synchronized (mInstallLock) { 12603 succeeded = clearApplicationUserDataLI(packageName, userId); 12604 } 12605 clearExternalStorageDataSync(packageName, userId, true); 12606 if (succeeded) { 12607 // invoke DeviceStorageMonitor's update method to clear any notifications 12608 DeviceStorageMonitorInternal 12609 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12610 if (dsm != null) { 12611 dsm.checkMemory(); 12612 } 12613 } 12614 if(observer != null) { 12615 try { 12616 observer.onRemoveCompleted(packageName, succeeded); 12617 } catch (RemoteException e) { 12618 Log.i(TAG, "Observer no longer exists."); 12619 } 12620 } //end if observer 12621 } //end run 12622 }); 12623 } 12624 12625 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12626 if (packageName == null) { 12627 Slog.w(TAG, "Attempt to delete null packageName."); 12628 return false; 12629 } 12630 12631 // Try finding details about the requested package 12632 PackageParser.Package pkg; 12633 synchronized (mPackages) { 12634 pkg = mPackages.get(packageName); 12635 if (pkg == null) { 12636 final PackageSetting ps = mSettings.mPackages.get(packageName); 12637 if (ps != null) { 12638 pkg = ps.pkg; 12639 } 12640 } 12641 12642 if (pkg == null) { 12643 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12644 return false; 12645 } 12646 12647 PackageSetting ps = (PackageSetting) pkg.mExtras; 12648 PermissionsState permissionsState = ps.getPermissionsState(); 12649 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12650 } 12651 12652 // Always delete data directories for package, even if we found no other 12653 // record of app. This helps users recover from UID mismatches without 12654 // resorting to a full data wipe. 12655 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12656 if (retCode < 0) { 12657 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12658 return false; 12659 } 12660 12661 final int appId = pkg.applicationInfo.uid; 12662 removeKeystoreDataIfNeeded(userId, appId); 12663 12664 // Create a native library symlink only if we have native libraries 12665 // and if the native libraries are 32 bit libraries. We do not provide 12666 // this symlink for 64 bit libraries. 12667 if (pkg.applicationInfo.primaryCpuAbi != null && 12668 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12669 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12670 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12671 nativeLibPath, userId) < 0) { 12672 Slog.w(TAG, "Failed linking native library dir"); 12673 return false; 12674 } 12675 } 12676 12677 return true; 12678 } 12679 12680 12681 /** 12682 * Revokes granted runtime permissions and clears resettable flags 12683 * which are flags that can be set by a user interaction. 12684 * 12685 * @param permissionsState The permission state to reset. 12686 * @param userId The device user for which to do a reset. 12687 */ 12688 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12689 PermissionsState permissionsState, int userId) { 12690 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12691 | PackageManager.FLAG_PERMISSION_USER_FIXED 12692 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12693 12694 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 12695 } 12696 12697 /** 12698 * Revokes granted runtime permissions and clears all flags. 12699 * 12700 * @param permissionsState The permission state to reset. 12701 * @param userId The device user for which to do a reset. 12702 */ 12703 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 12704 PermissionsState permissionsState, int userId) { 12705 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 12706 PackageManager.MASK_PERMISSION_FLAGS); 12707 } 12708 12709 /** 12710 * Revokes granted runtime permissions and clears certain flags. 12711 * 12712 * @param permissionsState The permission state to reset. 12713 * @param userId The device user for which to do a reset. 12714 * @param flags The flags that is going to be reset. 12715 */ 12716 private void revokeRuntimePermissionsAndClearFlagsLocked( 12717 PermissionsState permissionsState, int userId, int flags) { 12718 boolean needsWrite = false; 12719 12720 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12721 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12722 if (bp != null) { 12723 permissionsState.revokeRuntimePermission(bp, userId); 12724 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 12725 needsWrite = true; 12726 } 12727 } 12728 12729 // Ensure default permissions are never cleared. 12730 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 12731 12732 if (needsWrite) { 12733 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12734 } 12735 } 12736 12737 /** 12738 * Remove entries from the keystore daemon. Will only remove it if the 12739 * {@code appId} is valid. 12740 */ 12741 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12742 if (appId < 0) { 12743 return; 12744 } 12745 12746 final KeyStore keyStore = KeyStore.getInstance(); 12747 if (keyStore != null) { 12748 if (userId == UserHandle.USER_ALL) { 12749 for (final int individual : sUserManager.getUserIds()) { 12750 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12751 } 12752 } else { 12753 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12754 } 12755 } else { 12756 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12757 } 12758 } 12759 12760 @Override 12761 public void deleteApplicationCacheFiles(final String packageName, 12762 final IPackageDataObserver observer) { 12763 mContext.enforceCallingOrSelfPermission( 12764 android.Manifest.permission.DELETE_CACHE_FILES, null); 12765 // Queue up an async operation since the package deletion may take a little while. 12766 final int userId = UserHandle.getCallingUserId(); 12767 mHandler.post(new Runnable() { 12768 public void run() { 12769 mHandler.removeCallbacks(this); 12770 final boolean succeded; 12771 synchronized (mInstallLock) { 12772 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12773 } 12774 clearExternalStorageDataSync(packageName, userId, false); 12775 if (observer != null) { 12776 try { 12777 observer.onRemoveCompleted(packageName, succeded); 12778 } catch (RemoteException e) { 12779 Log.i(TAG, "Observer no longer exists."); 12780 } 12781 } //end if observer 12782 } //end run 12783 }); 12784 } 12785 12786 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12787 if (packageName == null) { 12788 Slog.w(TAG, "Attempt to delete null packageName."); 12789 return false; 12790 } 12791 PackageParser.Package p; 12792 synchronized (mPackages) { 12793 p = mPackages.get(packageName); 12794 } 12795 if (p == null) { 12796 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12797 return false; 12798 } 12799 final ApplicationInfo applicationInfo = p.applicationInfo; 12800 if (applicationInfo == null) { 12801 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12802 return false; 12803 } 12804 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12805 if (retCode < 0) { 12806 Slog.w(TAG, "Couldn't remove cache files for package: " 12807 + packageName + " u" + userId); 12808 return false; 12809 } 12810 return true; 12811 } 12812 12813 @Override 12814 public void getPackageSizeInfo(final String packageName, int userHandle, 12815 final IPackageStatsObserver observer) { 12816 mContext.enforceCallingOrSelfPermission( 12817 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12818 if (packageName == null) { 12819 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12820 } 12821 12822 PackageStats stats = new PackageStats(packageName, userHandle); 12823 12824 /* 12825 * Queue up an async operation since the package measurement may take a 12826 * little while. 12827 */ 12828 Message msg = mHandler.obtainMessage(INIT_COPY); 12829 msg.obj = new MeasureParams(stats, observer); 12830 mHandler.sendMessage(msg); 12831 } 12832 12833 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12834 PackageStats pStats) { 12835 if (packageName == null) { 12836 Slog.w(TAG, "Attempt to get size of null packageName."); 12837 return false; 12838 } 12839 PackageParser.Package p; 12840 boolean dataOnly = false; 12841 String libDirRoot = null; 12842 String asecPath = null; 12843 PackageSetting ps = null; 12844 synchronized (mPackages) { 12845 p = mPackages.get(packageName); 12846 ps = mSettings.mPackages.get(packageName); 12847 if(p == null) { 12848 dataOnly = true; 12849 if((ps == null) || (ps.pkg == null)) { 12850 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12851 return false; 12852 } 12853 p = ps.pkg; 12854 } 12855 if (ps != null) { 12856 libDirRoot = ps.legacyNativeLibraryPathString; 12857 } 12858 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12859 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12860 if (secureContainerId != null) { 12861 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12862 } 12863 } 12864 } 12865 String publicSrcDir = null; 12866 if(!dataOnly) { 12867 final ApplicationInfo applicationInfo = p.applicationInfo; 12868 if (applicationInfo == null) { 12869 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12870 return false; 12871 } 12872 if (p.isForwardLocked()) { 12873 publicSrcDir = applicationInfo.getBaseResourcePath(); 12874 } 12875 } 12876 // TODO: extend to measure size of split APKs 12877 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12878 // not just the first level. 12879 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12880 // just the primary. 12881 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12882 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12883 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12884 if (res < 0) { 12885 return false; 12886 } 12887 12888 // Fix-up for forward-locked applications in ASEC containers. 12889 if (!isExternal(p)) { 12890 pStats.codeSize += pStats.externalCodeSize; 12891 pStats.externalCodeSize = 0L; 12892 } 12893 12894 return true; 12895 } 12896 12897 12898 @Override 12899 public void addPackageToPreferred(String packageName) { 12900 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12901 } 12902 12903 @Override 12904 public void removePackageFromPreferred(String packageName) { 12905 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12906 } 12907 12908 @Override 12909 public List<PackageInfo> getPreferredPackages(int flags) { 12910 return new ArrayList<PackageInfo>(); 12911 } 12912 12913 private int getUidTargetSdkVersionLockedLPr(int uid) { 12914 Object obj = mSettings.getUserIdLPr(uid); 12915 if (obj instanceof SharedUserSetting) { 12916 final SharedUserSetting sus = (SharedUserSetting) obj; 12917 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12918 final Iterator<PackageSetting> it = sus.packages.iterator(); 12919 while (it.hasNext()) { 12920 final PackageSetting ps = it.next(); 12921 if (ps.pkg != null) { 12922 int v = ps.pkg.applicationInfo.targetSdkVersion; 12923 if (v < vers) vers = v; 12924 } 12925 } 12926 return vers; 12927 } else if (obj instanceof PackageSetting) { 12928 final PackageSetting ps = (PackageSetting) obj; 12929 if (ps.pkg != null) { 12930 return ps.pkg.applicationInfo.targetSdkVersion; 12931 } 12932 } 12933 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12934 } 12935 12936 @Override 12937 public void addPreferredActivity(IntentFilter filter, int match, 12938 ComponentName[] set, ComponentName activity, int userId) { 12939 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12940 "Adding preferred"); 12941 } 12942 12943 private void addPreferredActivityInternal(IntentFilter filter, int match, 12944 ComponentName[] set, ComponentName activity, boolean always, int userId, 12945 String opname) { 12946 // writer 12947 int callingUid = Binder.getCallingUid(); 12948 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12949 if (filter.countActions() == 0) { 12950 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12951 return; 12952 } 12953 synchronized (mPackages) { 12954 if (mContext.checkCallingOrSelfPermission( 12955 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12956 != PackageManager.PERMISSION_GRANTED) { 12957 if (getUidTargetSdkVersionLockedLPr(callingUid) 12958 < Build.VERSION_CODES.FROYO) { 12959 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12960 + callingUid); 12961 return; 12962 } 12963 mContext.enforceCallingOrSelfPermission( 12964 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12965 } 12966 12967 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12968 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12969 + userId + ":"); 12970 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12971 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12972 scheduleWritePackageRestrictionsLocked(userId); 12973 } 12974 } 12975 12976 @Override 12977 public void replacePreferredActivity(IntentFilter filter, int match, 12978 ComponentName[] set, ComponentName activity, int userId) { 12979 if (filter.countActions() != 1) { 12980 throw new IllegalArgumentException( 12981 "replacePreferredActivity expects filter to have only 1 action."); 12982 } 12983 if (filter.countDataAuthorities() != 0 12984 || filter.countDataPaths() != 0 12985 || filter.countDataSchemes() > 1 12986 || filter.countDataTypes() != 0) { 12987 throw new IllegalArgumentException( 12988 "replacePreferredActivity expects filter to have no data authorities, " + 12989 "paths, or types; and at most one scheme."); 12990 } 12991 12992 final int callingUid = Binder.getCallingUid(); 12993 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12994 synchronized (mPackages) { 12995 if (mContext.checkCallingOrSelfPermission( 12996 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12997 != PackageManager.PERMISSION_GRANTED) { 12998 if (getUidTargetSdkVersionLockedLPr(callingUid) 12999 < Build.VERSION_CODES.FROYO) { 13000 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13001 + Binder.getCallingUid()); 13002 return; 13003 } 13004 mContext.enforceCallingOrSelfPermission( 13005 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13006 } 13007 13008 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13009 if (pir != null) { 13010 // Get all of the existing entries that exactly match this filter. 13011 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13012 if (existing != null && existing.size() == 1) { 13013 PreferredActivity cur = existing.get(0); 13014 if (DEBUG_PREFERRED) { 13015 Slog.i(TAG, "Checking replace of preferred:"); 13016 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13017 if (!cur.mPref.mAlways) { 13018 Slog.i(TAG, " -- CUR; not mAlways!"); 13019 } else { 13020 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13021 Slog.i(TAG, " -- CUR: mSet=" 13022 + Arrays.toString(cur.mPref.mSetComponents)); 13023 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13024 Slog.i(TAG, " -- NEW: mMatch=" 13025 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13026 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13027 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13028 } 13029 } 13030 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13031 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13032 && cur.mPref.sameSet(set)) { 13033 // Setting the preferred activity to what it happens to be already 13034 if (DEBUG_PREFERRED) { 13035 Slog.i(TAG, "Replacing with same preferred activity " 13036 + cur.mPref.mShortComponent + " for user " 13037 + userId + ":"); 13038 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13039 } 13040 return; 13041 } 13042 } 13043 13044 if (existing != null) { 13045 if (DEBUG_PREFERRED) { 13046 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13047 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13048 } 13049 for (int i = 0; i < existing.size(); i++) { 13050 PreferredActivity pa = existing.get(i); 13051 if (DEBUG_PREFERRED) { 13052 Slog.i(TAG, "Removing existing preferred activity " 13053 + pa.mPref.mComponent + ":"); 13054 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13055 } 13056 pir.removeFilter(pa); 13057 } 13058 } 13059 } 13060 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13061 "Replacing preferred"); 13062 } 13063 } 13064 13065 @Override 13066 public void clearPackagePreferredActivities(String packageName) { 13067 final int uid = Binder.getCallingUid(); 13068 // writer 13069 synchronized (mPackages) { 13070 PackageParser.Package pkg = mPackages.get(packageName); 13071 if (pkg == null || pkg.applicationInfo.uid != uid) { 13072 if (mContext.checkCallingOrSelfPermission( 13073 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13074 != PackageManager.PERMISSION_GRANTED) { 13075 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13076 < Build.VERSION_CODES.FROYO) { 13077 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13078 + Binder.getCallingUid()); 13079 return; 13080 } 13081 mContext.enforceCallingOrSelfPermission( 13082 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13083 } 13084 } 13085 13086 int user = UserHandle.getCallingUserId(); 13087 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13088 scheduleWritePackageRestrictionsLocked(user); 13089 } 13090 } 13091 } 13092 13093 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13094 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13095 ArrayList<PreferredActivity> removed = null; 13096 boolean changed = false; 13097 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13098 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13099 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13100 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13101 continue; 13102 } 13103 Iterator<PreferredActivity> it = pir.filterIterator(); 13104 while (it.hasNext()) { 13105 PreferredActivity pa = it.next(); 13106 // Mark entry for removal only if it matches the package name 13107 // and the entry is of type "always". 13108 if (packageName == null || 13109 (pa.mPref.mComponent.getPackageName().equals(packageName) 13110 && pa.mPref.mAlways)) { 13111 if (removed == null) { 13112 removed = new ArrayList<PreferredActivity>(); 13113 } 13114 removed.add(pa); 13115 } 13116 } 13117 if (removed != null) { 13118 for (int j=0; j<removed.size(); j++) { 13119 PreferredActivity pa = removed.get(j); 13120 pir.removeFilter(pa); 13121 } 13122 changed = true; 13123 } 13124 } 13125 return changed; 13126 } 13127 13128 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13129 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13130 if (userId == UserHandle.USER_ALL) { 13131 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13132 sUserManager.getUserIds())) { 13133 for (int oneUserId : sUserManager.getUserIds()) { 13134 scheduleWritePackageRestrictionsLocked(oneUserId); 13135 } 13136 } 13137 } else { 13138 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13139 scheduleWritePackageRestrictionsLocked(userId); 13140 } 13141 } 13142 } 13143 13144 13145 void clearDefaultBrowserIfNeeded(String packageName) { 13146 for (int oneUserId : sUserManager.getUserIds()) { 13147 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13148 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13149 if (packageName.equals(defaultBrowserPackageName)) { 13150 setDefaultBrowserPackageName(null, oneUserId); 13151 } 13152 } 13153 } 13154 13155 @Override 13156 public void resetPreferredActivities(int userId) { 13157 /* TODO: Actually use userId. Why is it being passed in? */ 13158 mContext.enforceCallingOrSelfPermission( 13159 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13160 // writer 13161 synchronized (mPackages) { 13162 int user = UserHandle.getCallingUserId(); 13163 clearPackagePreferredActivitiesLPw(null, user); 13164 mSettings.readDefaultPreferredAppsLPw(this, user); 13165 scheduleWritePackageRestrictionsLocked(user); 13166 } 13167 } 13168 13169 @Override 13170 public int getPreferredActivities(List<IntentFilter> outFilters, 13171 List<ComponentName> outActivities, String packageName) { 13172 13173 int num = 0; 13174 final int userId = UserHandle.getCallingUserId(); 13175 // reader 13176 synchronized (mPackages) { 13177 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13178 if (pir != null) { 13179 final Iterator<PreferredActivity> it = pir.filterIterator(); 13180 while (it.hasNext()) { 13181 final PreferredActivity pa = it.next(); 13182 if (packageName == null 13183 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13184 && pa.mPref.mAlways)) { 13185 if (outFilters != null) { 13186 outFilters.add(new IntentFilter(pa)); 13187 } 13188 if (outActivities != null) { 13189 outActivities.add(pa.mPref.mComponent); 13190 } 13191 } 13192 } 13193 } 13194 } 13195 13196 return num; 13197 } 13198 13199 @Override 13200 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13201 int userId) { 13202 int callingUid = Binder.getCallingUid(); 13203 if (callingUid != Process.SYSTEM_UID) { 13204 throw new SecurityException( 13205 "addPersistentPreferredActivity can only be run by the system"); 13206 } 13207 if (filter.countActions() == 0) { 13208 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13209 return; 13210 } 13211 synchronized (mPackages) { 13212 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13213 " :"); 13214 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13215 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13216 new PersistentPreferredActivity(filter, activity)); 13217 scheduleWritePackageRestrictionsLocked(userId); 13218 } 13219 } 13220 13221 @Override 13222 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13223 int callingUid = Binder.getCallingUid(); 13224 if (callingUid != Process.SYSTEM_UID) { 13225 throw new SecurityException( 13226 "clearPackagePersistentPreferredActivities can only be run by the system"); 13227 } 13228 ArrayList<PersistentPreferredActivity> removed = null; 13229 boolean changed = false; 13230 synchronized (mPackages) { 13231 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13232 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13233 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13234 .valueAt(i); 13235 if (userId != thisUserId) { 13236 continue; 13237 } 13238 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13239 while (it.hasNext()) { 13240 PersistentPreferredActivity ppa = it.next(); 13241 // Mark entry for removal only if it matches the package name. 13242 if (ppa.mComponent.getPackageName().equals(packageName)) { 13243 if (removed == null) { 13244 removed = new ArrayList<PersistentPreferredActivity>(); 13245 } 13246 removed.add(ppa); 13247 } 13248 } 13249 if (removed != null) { 13250 for (int j=0; j<removed.size(); j++) { 13251 PersistentPreferredActivity ppa = removed.get(j); 13252 ppir.removeFilter(ppa); 13253 } 13254 changed = true; 13255 } 13256 } 13257 13258 if (changed) { 13259 scheduleWritePackageRestrictionsLocked(userId); 13260 } 13261 } 13262 } 13263 13264 /** 13265 * Non-Binder method, support for the backup/restore mechanism: write the 13266 * full set of preferred activities in its canonical XML format. Returns true 13267 * on success; false otherwise. 13268 */ 13269 @Override 13270 public byte[] getPreferredActivityBackup(int userId) { 13271 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13272 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13273 } 13274 13275 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13276 try { 13277 final XmlSerializer serializer = new FastXmlSerializer(); 13278 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13279 serializer.startDocument(null, true); 13280 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13281 13282 synchronized (mPackages) { 13283 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13284 } 13285 13286 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13287 serializer.endDocument(); 13288 serializer.flush(); 13289 } catch (Exception e) { 13290 if (DEBUG_BACKUP) { 13291 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13292 } 13293 return null; 13294 } 13295 13296 return dataStream.toByteArray(); 13297 } 13298 13299 @Override 13300 public void restorePreferredActivities(byte[] backup, int userId) { 13301 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13302 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13303 } 13304 13305 try { 13306 final XmlPullParser parser = Xml.newPullParser(); 13307 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13308 13309 int type; 13310 while ((type = parser.next()) != XmlPullParser.START_TAG 13311 && type != XmlPullParser.END_DOCUMENT) { 13312 } 13313 if (type != XmlPullParser.START_TAG) { 13314 // oops didn't find a start tag?! 13315 if (DEBUG_BACKUP) { 13316 Slog.e(TAG, "Didn't find start tag during restore"); 13317 } 13318 return; 13319 } 13320 13321 // this is supposed to be TAG_PREFERRED_BACKUP 13322 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13323 if (DEBUG_BACKUP) { 13324 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13325 } 13326 return; 13327 } 13328 13329 // skip interfering stuff, then we're aligned with the backing implementation 13330 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13331 synchronized (mPackages) { 13332 mSettings.readPreferredActivitiesLPw(parser, userId); 13333 } 13334 } catch (Exception e) { 13335 if (DEBUG_BACKUP) { 13336 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13337 } 13338 } 13339 } 13340 13341 @Override 13342 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13343 int sourceUserId, int targetUserId, int flags) { 13344 mContext.enforceCallingOrSelfPermission( 13345 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13346 int callingUid = Binder.getCallingUid(); 13347 enforceOwnerRights(ownerPackage, callingUid); 13348 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13349 if (intentFilter.countActions() == 0) { 13350 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13351 return; 13352 } 13353 synchronized (mPackages) { 13354 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13355 ownerPackage, targetUserId, flags); 13356 CrossProfileIntentResolver resolver = 13357 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13358 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13359 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13360 if (existing != null) { 13361 int size = existing.size(); 13362 for (int i = 0; i < size; i++) { 13363 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13364 return; 13365 } 13366 } 13367 } 13368 resolver.addFilter(newFilter); 13369 scheduleWritePackageRestrictionsLocked(sourceUserId); 13370 } 13371 } 13372 13373 @Override 13374 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13375 mContext.enforceCallingOrSelfPermission( 13376 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13377 int callingUid = Binder.getCallingUid(); 13378 enforceOwnerRights(ownerPackage, callingUid); 13379 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13380 synchronized (mPackages) { 13381 CrossProfileIntentResolver resolver = 13382 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13383 ArraySet<CrossProfileIntentFilter> set = 13384 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13385 for (CrossProfileIntentFilter filter : set) { 13386 if (filter.getOwnerPackage().equals(ownerPackage)) { 13387 resolver.removeFilter(filter); 13388 } 13389 } 13390 scheduleWritePackageRestrictionsLocked(sourceUserId); 13391 } 13392 } 13393 13394 // Enforcing that callingUid is owning pkg on userId 13395 private void enforceOwnerRights(String pkg, int callingUid) { 13396 // The system owns everything. 13397 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13398 return; 13399 } 13400 int callingUserId = UserHandle.getUserId(callingUid); 13401 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13402 if (pi == null) { 13403 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13404 + callingUserId); 13405 } 13406 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13407 throw new SecurityException("Calling uid " + callingUid 13408 + " does not own package " + pkg); 13409 } 13410 } 13411 13412 @Override 13413 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13414 Intent intent = new Intent(Intent.ACTION_MAIN); 13415 intent.addCategory(Intent.CATEGORY_HOME); 13416 13417 final int callingUserId = UserHandle.getCallingUserId(); 13418 List<ResolveInfo> list = queryIntentActivities(intent, null, 13419 PackageManager.GET_META_DATA, callingUserId); 13420 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13421 true, false, false, callingUserId); 13422 13423 allHomeCandidates.clear(); 13424 if (list != null) { 13425 for (ResolveInfo ri : list) { 13426 allHomeCandidates.add(ri); 13427 } 13428 } 13429 return (preferred == null || preferred.activityInfo == null) 13430 ? null 13431 : new ComponentName(preferred.activityInfo.packageName, 13432 preferred.activityInfo.name); 13433 } 13434 13435 @Override 13436 public void setApplicationEnabledSetting(String appPackageName, 13437 int newState, int flags, int userId, String callingPackage) { 13438 if (!sUserManager.exists(userId)) return; 13439 if (callingPackage == null) { 13440 callingPackage = Integer.toString(Binder.getCallingUid()); 13441 } 13442 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13443 } 13444 13445 @Override 13446 public void setComponentEnabledSetting(ComponentName componentName, 13447 int newState, int flags, int userId) { 13448 if (!sUserManager.exists(userId)) return; 13449 setEnabledSetting(componentName.getPackageName(), 13450 componentName.getClassName(), newState, flags, userId, null); 13451 } 13452 13453 private void setEnabledSetting(final String packageName, String className, int newState, 13454 final int flags, int userId, String callingPackage) { 13455 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13456 || newState == COMPONENT_ENABLED_STATE_ENABLED 13457 || newState == COMPONENT_ENABLED_STATE_DISABLED 13458 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13459 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13460 throw new IllegalArgumentException("Invalid new component state: " 13461 + newState); 13462 } 13463 PackageSetting pkgSetting; 13464 final int uid = Binder.getCallingUid(); 13465 final int permission = mContext.checkCallingOrSelfPermission( 13466 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13467 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13468 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13469 boolean sendNow = false; 13470 boolean isApp = (className == null); 13471 String componentName = isApp ? packageName : className; 13472 int packageUid = -1; 13473 ArrayList<String> components; 13474 13475 // writer 13476 synchronized (mPackages) { 13477 pkgSetting = mSettings.mPackages.get(packageName); 13478 if (pkgSetting == null) { 13479 if (className == null) { 13480 throw new IllegalArgumentException( 13481 "Unknown package: " + packageName); 13482 } 13483 throw new IllegalArgumentException( 13484 "Unknown component: " + packageName 13485 + "/" + className); 13486 } 13487 // Allow root and verify that userId is not being specified by a different user 13488 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13489 throw new SecurityException( 13490 "Permission Denial: attempt to change component state from pid=" 13491 + Binder.getCallingPid() 13492 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13493 } 13494 if (className == null) { 13495 // We're dealing with an application/package level state change 13496 if (pkgSetting.getEnabled(userId) == newState) { 13497 // Nothing to do 13498 return; 13499 } 13500 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13501 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13502 // Don't care about who enables an app. 13503 callingPackage = null; 13504 } 13505 pkgSetting.setEnabled(newState, userId, callingPackage); 13506 // pkgSetting.pkg.mSetEnabled = newState; 13507 } else { 13508 // We're dealing with a component level state change 13509 // First, verify that this is a valid class name. 13510 PackageParser.Package pkg = pkgSetting.pkg; 13511 if (pkg == null || !pkg.hasComponentClassName(className)) { 13512 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13513 throw new IllegalArgumentException("Component class " + className 13514 + " does not exist in " + packageName); 13515 } else { 13516 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13517 + className + " does not exist in " + packageName); 13518 } 13519 } 13520 switch (newState) { 13521 case COMPONENT_ENABLED_STATE_ENABLED: 13522 if (!pkgSetting.enableComponentLPw(className, userId)) { 13523 return; 13524 } 13525 break; 13526 case COMPONENT_ENABLED_STATE_DISABLED: 13527 if (!pkgSetting.disableComponentLPw(className, userId)) { 13528 return; 13529 } 13530 break; 13531 case COMPONENT_ENABLED_STATE_DEFAULT: 13532 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13533 return; 13534 } 13535 break; 13536 default: 13537 Slog.e(TAG, "Invalid new component state: " + newState); 13538 return; 13539 } 13540 } 13541 scheduleWritePackageRestrictionsLocked(userId); 13542 components = mPendingBroadcasts.get(userId, packageName); 13543 final boolean newPackage = components == null; 13544 if (newPackage) { 13545 components = new ArrayList<String>(); 13546 } 13547 if (!components.contains(componentName)) { 13548 components.add(componentName); 13549 } 13550 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13551 sendNow = true; 13552 // Purge entry from pending broadcast list if another one exists already 13553 // since we are sending one right away. 13554 mPendingBroadcasts.remove(userId, packageName); 13555 } else { 13556 if (newPackage) { 13557 mPendingBroadcasts.put(userId, packageName, components); 13558 } 13559 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13560 // Schedule a message 13561 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13562 } 13563 } 13564 } 13565 13566 long callingId = Binder.clearCallingIdentity(); 13567 try { 13568 if (sendNow) { 13569 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13570 sendPackageChangedBroadcast(packageName, 13571 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13572 } 13573 } finally { 13574 Binder.restoreCallingIdentity(callingId); 13575 } 13576 } 13577 13578 private void sendPackageChangedBroadcast(String packageName, 13579 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13580 if (DEBUG_INSTALL) 13581 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13582 + componentNames); 13583 Bundle extras = new Bundle(4); 13584 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13585 String nameList[] = new String[componentNames.size()]; 13586 componentNames.toArray(nameList); 13587 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13588 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13589 extras.putInt(Intent.EXTRA_UID, packageUid); 13590 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13591 new int[] {UserHandle.getUserId(packageUid)}); 13592 } 13593 13594 @Override 13595 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13596 if (!sUserManager.exists(userId)) return; 13597 final int uid = Binder.getCallingUid(); 13598 final int permission = mContext.checkCallingOrSelfPermission( 13599 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13600 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13601 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13602 // writer 13603 synchronized (mPackages) { 13604 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13605 allowedByPermission, uid, userId)) { 13606 scheduleWritePackageRestrictionsLocked(userId); 13607 } 13608 } 13609 } 13610 13611 @Override 13612 public String getInstallerPackageName(String packageName) { 13613 // reader 13614 synchronized (mPackages) { 13615 return mSettings.getInstallerPackageNameLPr(packageName); 13616 } 13617 } 13618 13619 @Override 13620 public int getApplicationEnabledSetting(String packageName, int userId) { 13621 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13622 int uid = Binder.getCallingUid(); 13623 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13624 // reader 13625 synchronized (mPackages) { 13626 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13627 } 13628 } 13629 13630 @Override 13631 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13632 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13633 int uid = Binder.getCallingUid(); 13634 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13635 // reader 13636 synchronized (mPackages) { 13637 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13638 } 13639 } 13640 13641 @Override 13642 public void enterSafeMode() { 13643 enforceSystemOrRoot("Only the system can request entering safe mode"); 13644 13645 if (!mSystemReady) { 13646 mSafeMode = true; 13647 } 13648 } 13649 13650 @Override 13651 public void systemReady() { 13652 mSystemReady = true; 13653 13654 // Read the compatibilty setting when the system is ready. 13655 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13656 mContext.getContentResolver(), 13657 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13658 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13659 if (DEBUG_SETTINGS) { 13660 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13661 } 13662 13663 synchronized (mPackages) { 13664 // Verify that all of the preferred activity components actually 13665 // exist. It is possible for applications to be updated and at 13666 // that point remove a previously declared activity component that 13667 // had been set as a preferred activity. We try to clean this up 13668 // the next time we encounter that preferred activity, but it is 13669 // possible for the user flow to never be able to return to that 13670 // situation so here we do a sanity check to make sure we haven't 13671 // left any junk around. 13672 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13673 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13674 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13675 removed.clear(); 13676 for (PreferredActivity pa : pir.filterSet()) { 13677 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13678 removed.add(pa); 13679 } 13680 } 13681 if (removed.size() > 0) { 13682 for (int r=0; r<removed.size(); r++) { 13683 PreferredActivity pa = removed.get(r); 13684 Slog.w(TAG, "Removing dangling preferred activity: " 13685 + pa.mPref.mComponent); 13686 pir.removeFilter(pa); 13687 } 13688 mSettings.writePackageRestrictionsLPr( 13689 mSettings.mPreferredActivities.keyAt(i)); 13690 } 13691 } 13692 } 13693 sUserManager.systemReady(); 13694 13695 // If we upgraded grant all default permissions before kicking off. 13696 if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) { 13697 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 13698 for (int userId : UserManagerService.getInstance().getUserIds()) { 13699 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13700 } 13701 } 13702 13703 // Kick off any messages waiting for system ready 13704 if (mPostSystemReadyMessages != null) { 13705 for (Message msg : mPostSystemReadyMessages) { 13706 msg.sendToTarget(); 13707 } 13708 mPostSystemReadyMessages = null; 13709 } 13710 13711 // Watch for external volumes that come and go over time 13712 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13713 storage.registerListener(mStorageListener); 13714 13715 mInstallerService.systemReady(); 13716 mPackageDexOptimizer.systemReady(); 13717 } 13718 13719 @Override 13720 public boolean isSafeMode() { 13721 return mSafeMode; 13722 } 13723 13724 @Override 13725 public boolean hasSystemUidErrors() { 13726 return mHasSystemUidErrors; 13727 } 13728 13729 static String arrayToString(int[] array) { 13730 StringBuffer buf = new StringBuffer(128); 13731 buf.append('['); 13732 if (array != null) { 13733 for (int i=0; i<array.length; i++) { 13734 if (i > 0) buf.append(", "); 13735 buf.append(array[i]); 13736 } 13737 } 13738 buf.append(']'); 13739 return buf.toString(); 13740 } 13741 13742 static class DumpState { 13743 public static final int DUMP_LIBS = 1 << 0; 13744 public static final int DUMP_FEATURES = 1 << 1; 13745 public static final int DUMP_RESOLVERS = 1 << 2; 13746 public static final int DUMP_PERMISSIONS = 1 << 3; 13747 public static final int DUMP_PACKAGES = 1 << 4; 13748 public static final int DUMP_SHARED_USERS = 1 << 5; 13749 public static final int DUMP_MESSAGES = 1 << 6; 13750 public static final int DUMP_PROVIDERS = 1 << 7; 13751 public static final int DUMP_VERIFIERS = 1 << 8; 13752 public static final int DUMP_PREFERRED = 1 << 9; 13753 public static final int DUMP_PREFERRED_XML = 1 << 10; 13754 public static final int DUMP_KEYSETS = 1 << 11; 13755 public static final int DUMP_VERSION = 1 << 12; 13756 public static final int DUMP_INSTALLS = 1 << 13; 13757 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13758 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13759 13760 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13761 13762 private int mTypes; 13763 13764 private int mOptions; 13765 13766 private boolean mTitlePrinted; 13767 13768 private SharedUserSetting mSharedUser; 13769 13770 public boolean isDumping(int type) { 13771 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13772 return true; 13773 } 13774 13775 return (mTypes & type) != 0; 13776 } 13777 13778 public void setDump(int type) { 13779 mTypes |= type; 13780 } 13781 13782 public boolean isOptionEnabled(int option) { 13783 return (mOptions & option) != 0; 13784 } 13785 13786 public void setOptionEnabled(int option) { 13787 mOptions |= option; 13788 } 13789 13790 public boolean onTitlePrinted() { 13791 final boolean printed = mTitlePrinted; 13792 mTitlePrinted = true; 13793 return printed; 13794 } 13795 13796 public boolean getTitlePrinted() { 13797 return mTitlePrinted; 13798 } 13799 13800 public void setTitlePrinted(boolean enabled) { 13801 mTitlePrinted = enabled; 13802 } 13803 13804 public SharedUserSetting getSharedUser() { 13805 return mSharedUser; 13806 } 13807 13808 public void setSharedUser(SharedUserSetting user) { 13809 mSharedUser = user; 13810 } 13811 } 13812 13813 @Override 13814 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13815 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13816 != PackageManager.PERMISSION_GRANTED) { 13817 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13818 + Binder.getCallingPid() 13819 + ", uid=" + Binder.getCallingUid() 13820 + " without permission " 13821 + android.Manifest.permission.DUMP); 13822 return; 13823 } 13824 13825 DumpState dumpState = new DumpState(); 13826 boolean fullPreferred = false; 13827 boolean checkin = false; 13828 13829 String packageName = null; 13830 13831 int opti = 0; 13832 while (opti < args.length) { 13833 String opt = args[opti]; 13834 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13835 break; 13836 } 13837 opti++; 13838 13839 if ("-a".equals(opt)) { 13840 // Right now we only know how to print all. 13841 } else if ("-h".equals(opt)) { 13842 pw.println("Package manager dump options:"); 13843 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13844 pw.println(" --checkin: dump for a checkin"); 13845 pw.println(" -f: print details of intent filters"); 13846 pw.println(" -h: print this help"); 13847 pw.println(" cmd may be one of:"); 13848 pw.println(" l[ibraries]: list known shared libraries"); 13849 pw.println(" f[ibraries]: list device features"); 13850 pw.println(" k[eysets]: print known keysets"); 13851 pw.println(" r[esolvers]: dump intent resolvers"); 13852 pw.println(" perm[issions]: dump permissions"); 13853 pw.println(" pref[erred]: print preferred package settings"); 13854 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13855 pw.println(" prov[iders]: dump content providers"); 13856 pw.println(" p[ackages]: dump installed packages"); 13857 pw.println(" s[hared-users]: dump shared user IDs"); 13858 pw.println(" m[essages]: print collected runtime messages"); 13859 pw.println(" v[erifiers]: print package verifier info"); 13860 pw.println(" version: print database version info"); 13861 pw.println(" write: write current settings now"); 13862 pw.println(" <package.name>: info about given package"); 13863 pw.println(" installs: details about install sessions"); 13864 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13865 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13866 return; 13867 } else if ("--checkin".equals(opt)) { 13868 checkin = true; 13869 } else if ("-f".equals(opt)) { 13870 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13871 } else { 13872 pw.println("Unknown argument: " + opt + "; use -h for help"); 13873 } 13874 } 13875 13876 // Is the caller requesting to dump a particular piece of data? 13877 if (opti < args.length) { 13878 String cmd = args[opti]; 13879 opti++; 13880 // Is this a package name? 13881 if ("android".equals(cmd) || cmd.contains(".")) { 13882 packageName = cmd; 13883 // When dumping a single package, we always dump all of its 13884 // filter information since the amount of data will be reasonable. 13885 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13886 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13887 dumpState.setDump(DumpState.DUMP_LIBS); 13888 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13889 dumpState.setDump(DumpState.DUMP_FEATURES); 13890 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13891 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13892 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13893 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13894 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13895 dumpState.setDump(DumpState.DUMP_PREFERRED); 13896 } else if ("preferred-xml".equals(cmd)) { 13897 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13898 if (opti < args.length && "--full".equals(args[opti])) { 13899 fullPreferred = true; 13900 opti++; 13901 } 13902 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13903 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13904 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13905 dumpState.setDump(DumpState.DUMP_PACKAGES); 13906 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13907 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13908 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13909 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13910 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13911 dumpState.setDump(DumpState.DUMP_MESSAGES); 13912 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13913 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13914 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13915 || "intent-filter-verifiers".equals(cmd)) { 13916 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13917 } else if ("version".equals(cmd)) { 13918 dumpState.setDump(DumpState.DUMP_VERSION); 13919 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13920 dumpState.setDump(DumpState.DUMP_KEYSETS); 13921 } else if ("installs".equals(cmd)) { 13922 dumpState.setDump(DumpState.DUMP_INSTALLS); 13923 } else if ("write".equals(cmd)) { 13924 synchronized (mPackages) { 13925 mSettings.writeLPr(); 13926 pw.println("Settings written."); 13927 return; 13928 } 13929 } 13930 } 13931 13932 if (checkin) { 13933 pw.println("vers,1"); 13934 } 13935 13936 // reader 13937 synchronized (mPackages) { 13938 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13939 if (!checkin) { 13940 if (dumpState.onTitlePrinted()) 13941 pw.println(); 13942 pw.println("Database versions:"); 13943 pw.print(" SDK Version:"); 13944 pw.print(" internal="); 13945 pw.print(mSettings.mInternalSdkPlatform); 13946 pw.print(" external="); 13947 pw.println(mSettings.mExternalSdkPlatform); 13948 pw.print(" DB Version:"); 13949 pw.print(" internal="); 13950 pw.print(mSettings.mInternalDatabaseVersion); 13951 pw.print(" external="); 13952 pw.println(mSettings.mExternalDatabaseVersion); 13953 } 13954 } 13955 13956 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13957 if (!checkin) { 13958 if (dumpState.onTitlePrinted()) 13959 pw.println(); 13960 pw.println("Verifiers:"); 13961 pw.print(" Required: "); 13962 pw.print(mRequiredVerifierPackage); 13963 pw.print(" (uid="); 13964 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13965 pw.println(")"); 13966 } else if (mRequiredVerifierPackage != null) { 13967 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13968 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13969 } 13970 } 13971 13972 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13973 packageName == null) { 13974 if (mIntentFilterVerifierComponent != null) { 13975 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13976 if (!checkin) { 13977 if (dumpState.onTitlePrinted()) 13978 pw.println(); 13979 pw.println("Intent Filter Verifier:"); 13980 pw.print(" Using: "); 13981 pw.print(verifierPackageName); 13982 pw.print(" (uid="); 13983 pw.print(getPackageUid(verifierPackageName, 0)); 13984 pw.println(")"); 13985 } else if (verifierPackageName != null) { 13986 pw.print("ifv,"); pw.print(verifierPackageName); 13987 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13988 } 13989 } else { 13990 pw.println(); 13991 pw.println("No Intent Filter Verifier available!"); 13992 } 13993 } 13994 13995 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13996 boolean printedHeader = false; 13997 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13998 while (it.hasNext()) { 13999 String name = it.next(); 14000 SharedLibraryEntry ent = mSharedLibraries.get(name); 14001 if (!checkin) { 14002 if (!printedHeader) { 14003 if (dumpState.onTitlePrinted()) 14004 pw.println(); 14005 pw.println("Libraries:"); 14006 printedHeader = true; 14007 } 14008 pw.print(" "); 14009 } else { 14010 pw.print("lib,"); 14011 } 14012 pw.print(name); 14013 if (!checkin) { 14014 pw.print(" -> "); 14015 } 14016 if (ent.path != null) { 14017 if (!checkin) { 14018 pw.print("(jar) "); 14019 pw.print(ent.path); 14020 } else { 14021 pw.print(",jar,"); 14022 pw.print(ent.path); 14023 } 14024 } else { 14025 if (!checkin) { 14026 pw.print("(apk) "); 14027 pw.print(ent.apk); 14028 } else { 14029 pw.print(",apk,"); 14030 pw.print(ent.apk); 14031 } 14032 } 14033 pw.println(); 14034 } 14035 } 14036 14037 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14038 if (dumpState.onTitlePrinted()) 14039 pw.println(); 14040 if (!checkin) { 14041 pw.println("Features:"); 14042 } 14043 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14044 while (it.hasNext()) { 14045 String name = it.next(); 14046 if (!checkin) { 14047 pw.print(" "); 14048 } else { 14049 pw.print("feat,"); 14050 } 14051 pw.println(name); 14052 } 14053 } 14054 14055 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14056 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14057 : "Activity Resolver Table:", " ", packageName, 14058 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14059 dumpState.setTitlePrinted(true); 14060 } 14061 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14062 : "Receiver Resolver Table:", " ", packageName, 14063 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14064 dumpState.setTitlePrinted(true); 14065 } 14066 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14067 : "Service Resolver Table:", " ", packageName, 14068 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14069 dumpState.setTitlePrinted(true); 14070 } 14071 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14072 : "Provider Resolver Table:", " ", packageName, 14073 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14074 dumpState.setTitlePrinted(true); 14075 } 14076 } 14077 14078 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14079 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14080 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14081 int user = mSettings.mPreferredActivities.keyAt(i); 14082 if (pir.dump(pw, 14083 dumpState.getTitlePrinted() 14084 ? "\nPreferred Activities User " + user + ":" 14085 : "Preferred Activities User " + user + ":", " ", 14086 packageName, true, false)) { 14087 dumpState.setTitlePrinted(true); 14088 } 14089 } 14090 } 14091 14092 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14093 pw.flush(); 14094 FileOutputStream fout = new FileOutputStream(fd); 14095 BufferedOutputStream str = new BufferedOutputStream(fout); 14096 XmlSerializer serializer = new FastXmlSerializer(); 14097 try { 14098 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14099 serializer.startDocument(null, true); 14100 serializer.setFeature( 14101 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14102 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14103 serializer.endDocument(); 14104 serializer.flush(); 14105 } catch (IllegalArgumentException e) { 14106 pw.println("Failed writing: " + e); 14107 } catch (IllegalStateException e) { 14108 pw.println("Failed writing: " + e); 14109 } catch (IOException e) { 14110 pw.println("Failed writing: " + e); 14111 } 14112 } 14113 14114 if (!checkin 14115 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14116 && packageName == null) { 14117 pw.println(); 14118 int count = mSettings.mPackages.size(); 14119 if (count == 0) { 14120 pw.println("No domain preferred apps!"); 14121 pw.println(); 14122 } else { 14123 final String prefix = " "; 14124 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14125 if (allPackageSettings.size() == 0) { 14126 pw.println("No domain preferred apps!"); 14127 pw.println(); 14128 } else { 14129 pw.println("Domain preferred apps status:"); 14130 pw.println(); 14131 count = 0; 14132 for (PackageSetting ps : allPackageSettings) { 14133 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14134 if (ivi == null || ivi.getPackageName() == null) continue; 14135 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14136 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14137 pw.println(prefix + "Status: " + ivi.getStatusString()); 14138 pw.println(); 14139 count++; 14140 } 14141 if (count == 0) { 14142 pw.println(prefix + "No domain preferred app status!"); 14143 pw.println(); 14144 } 14145 for (int userId : sUserManager.getUserIds()) { 14146 pw.println("Domain preferred apps for User " + userId + ":"); 14147 pw.println(); 14148 count = 0; 14149 for (PackageSetting ps : allPackageSettings) { 14150 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14151 if (ivi == null || ivi.getPackageName() == null) { 14152 continue; 14153 } 14154 final int status = ps.getDomainVerificationStatusForUser(userId); 14155 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14156 continue; 14157 } 14158 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14159 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14160 String statusStr = IntentFilterVerificationInfo. 14161 getStatusStringFromValue(status); 14162 pw.println(prefix + "Status: " + statusStr); 14163 pw.println(); 14164 count++; 14165 } 14166 if (count == 0) { 14167 pw.println(prefix + "No domain preferred apps!"); 14168 pw.println(); 14169 } 14170 } 14171 } 14172 } 14173 } 14174 14175 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14176 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14177 if (packageName == null) { 14178 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14179 if (iperm == 0) { 14180 if (dumpState.onTitlePrinted()) 14181 pw.println(); 14182 pw.println("AppOp Permissions:"); 14183 } 14184 pw.print(" AppOp Permission "); 14185 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14186 pw.println(":"); 14187 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14188 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14189 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14190 } 14191 } 14192 } 14193 } 14194 14195 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14196 boolean printedSomething = false; 14197 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14198 if (packageName != null && !packageName.equals(p.info.packageName)) { 14199 continue; 14200 } 14201 if (!printedSomething) { 14202 if (dumpState.onTitlePrinted()) 14203 pw.println(); 14204 pw.println("Registered ContentProviders:"); 14205 printedSomething = true; 14206 } 14207 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14208 pw.print(" "); pw.println(p.toString()); 14209 } 14210 printedSomething = false; 14211 for (Map.Entry<String, PackageParser.Provider> entry : 14212 mProvidersByAuthority.entrySet()) { 14213 PackageParser.Provider p = entry.getValue(); 14214 if (packageName != null && !packageName.equals(p.info.packageName)) { 14215 continue; 14216 } 14217 if (!printedSomething) { 14218 if (dumpState.onTitlePrinted()) 14219 pw.println(); 14220 pw.println("ContentProvider Authorities:"); 14221 printedSomething = true; 14222 } 14223 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14224 pw.print(" "); pw.println(p.toString()); 14225 if (p.info != null && p.info.applicationInfo != null) { 14226 final String appInfo = p.info.applicationInfo.toString(); 14227 pw.print(" applicationInfo="); pw.println(appInfo); 14228 } 14229 } 14230 } 14231 14232 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14233 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14234 } 14235 14236 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14237 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14238 } 14239 14240 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14241 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14242 } 14243 14244 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14245 // XXX should handle packageName != null by dumping only install data that 14246 // the given package is involved with. 14247 if (dumpState.onTitlePrinted()) pw.println(); 14248 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14249 } 14250 14251 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14252 if (dumpState.onTitlePrinted()) pw.println(); 14253 mSettings.dumpReadMessagesLPr(pw, dumpState); 14254 14255 pw.println(); 14256 pw.println("Package warning messages:"); 14257 BufferedReader in = null; 14258 String line = null; 14259 try { 14260 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14261 while ((line = in.readLine()) != null) { 14262 if (line.contains("ignored: updated version")) continue; 14263 pw.println(line); 14264 } 14265 } catch (IOException ignored) { 14266 } finally { 14267 IoUtils.closeQuietly(in); 14268 } 14269 } 14270 14271 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14272 BufferedReader in = null; 14273 String line = null; 14274 try { 14275 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14276 while ((line = in.readLine()) != null) { 14277 if (line.contains("ignored: updated version")) continue; 14278 pw.print("msg,"); 14279 pw.println(line); 14280 } 14281 } catch (IOException ignored) { 14282 } finally { 14283 IoUtils.closeQuietly(in); 14284 } 14285 } 14286 } 14287 } 14288 14289 // ------- apps on sdcard specific code ------- 14290 static final boolean DEBUG_SD_INSTALL = false; 14291 14292 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14293 14294 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14295 14296 private boolean mMediaMounted = false; 14297 14298 static String getEncryptKey() { 14299 try { 14300 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14301 SD_ENCRYPTION_KEYSTORE_NAME); 14302 if (sdEncKey == null) { 14303 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14304 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14305 if (sdEncKey == null) { 14306 Slog.e(TAG, "Failed to create encryption keys"); 14307 return null; 14308 } 14309 } 14310 return sdEncKey; 14311 } catch (NoSuchAlgorithmException nsae) { 14312 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14313 return null; 14314 } catch (IOException ioe) { 14315 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14316 return null; 14317 } 14318 } 14319 14320 /* 14321 * Update media status on PackageManager. 14322 */ 14323 @Override 14324 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14325 int callingUid = Binder.getCallingUid(); 14326 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14327 throw new SecurityException("Media status can only be updated by the system"); 14328 } 14329 // reader; this apparently protects mMediaMounted, but should probably 14330 // be a different lock in that case. 14331 synchronized (mPackages) { 14332 Log.i(TAG, "Updating external media status from " 14333 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14334 + (mediaStatus ? "mounted" : "unmounted")); 14335 if (DEBUG_SD_INSTALL) 14336 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14337 + ", mMediaMounted=" + mMediaMounted); 14338 if (mediaStatus == mMediaMounted) { 14339 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14340 : 0, -1); 14341 mHandler.sendMessage(msg); 14342 return; 14343 } 14344 mMediaMounted = mediaStatus; 14345 } 14346 // Queue up an async operation since the package installation may take a 14347 // little while. 14348 mHandler.post(new Runnable() { 14349 public void run() { 14350 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14351 } 14352 }); 14353 } 14354 14355 /** 14356 * Called by MountService when the initial ASECs to scan are available. 14357 * Should block until all the ASEC containers are finished being scanned. 14358 */ 14359 public void scanAvailableAsecs() { 14360 updateExternalMediaStatusInner(true, false, false); 14361 if (mShouldRestoreconData) { 14362 SELinuxMMAC.setRestoreconDone(); 14363 mShouldRestoreconData = false; 14364 } 14365 } 14366 14367 /* 14368 * Collect information of applications on external media, map them against 14369 * existing containers and update information based on current mount status. 14370 * Please note that we always have to report status if reportStatus has been 14371 * set to true especially when unloading packages. 14372 */ 14373 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14374 boolean externalStorage) { 14375 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14376 int[] uidArr = EmptyArray.INT; 14377 14378 final String[] list = PackageHelper.getSecureContainerList(); 14379 if (ArrayUtils.isEmpty(list)) { 14380 Log.i(TAG, "No secure containers found"); 14381 } else { 14382 // Process list of secure containers and categorize them 14383 // as active or stale based on their package internal state. 14384 14385 // reader 14386 synchronized (mPackages) { 14387 for (String cid : list) { 14388 // Leave stages untouched for now; installer service owns them 14389 if (PackageInstallerService.isStageName(cid)) continue; 14390 14391 if (DEBUG_SD_INSTALL) 14392 Log.i(TAG, "Processing container " + cid); 14393 String pkgName = getAsecPackageName(cid); 14394 if (pkgName == null) { 14395 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14396 continue; 14397 } 14398 if (DEBUG_SD_INSTALL) 14399 Log.i(TAG, "Looking for pkg : " + pkgName); 14400 14401 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14402 if (ps == null) { 14403 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14404 continue; 14405 } 14406 14407 /* 14408 * Skip packages that are not external if we're unmounting 14409 * external storage. 14410 */ 14411 if (externalStorage && !isMounted && !isExternal(ps)) { 14412 continue; 14413 } 14414 14415 final AsecInstallArgs args = new AsecInstallArgs(cid, 14416 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14417 // The package status is changed only if the code path 14418 // matches between settings and the container id. 14419 if (ps.codePathString != null 14420 && ps.codePathString.startsWith(args.getCodePath())) { 14421 if (DEBUG_SD_INSTALL) { 14422 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14423 + " at code path: " + ps.codePathString); 14424 } 14425 14426 // We do have a valid package installed on sdcard 14427 processCids.put(args, ps.codePathString); 14428 final int uid = ps.appId; 14429 if (uid != -1) { 14430 uidArr = ArrayUtils.appendInt(uidArr, uid); 14431 } 14432 } else { 14433 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14434 + ps.codePathString); 14435 } 14436 } 14437 } 14438 14439 Arrays.sort(uidArr); 14440 } 14441 14442 // Process packages with valid entries. 14443 if (isMounted) { 14444 if (DEBUG_SD_INSTALL) 14445 Log.i(TAG, "Loading packages"); 14446 loadMediaPackages(processCids, uidArr); 14447 startCleaningPackages(); 14448 mInstallerService.onSecureContainersAvailable(); 14449 } else { 14450 if (DEBUG_SD_INSTALL) 14451 Log.i(TAG, "Unloading packages"); 14452 unloadMediaPackages(processCids, uidArr, reportStatus); 14453 } 14454 } 14455 14456 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14457 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14458 final int size = infos.size(); 14459 final String[] packageNames = new String[size]; 14460 final int[] packageUids = new int[size]; 14461 for (int i = 0; i < size; i++) { 14462 final ApplicationInfo info = infos.get(i); 14463 packageNames[i] = info.packageName; 14464 packageUids[i] = info.uid; 14465 } 14466 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14467 finishedReceiver); 14468 } 14469 14470 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14471 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14472 sendResourcesChangedBroadcast(mediaStatus, replacing, 14473 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14474 } 14475 14476 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14477 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14478 int size = pkgList.length; 14479 if (size > 0) { 14480 // Send broadcasts here 14481 Bundle extras = new Bundle(); 14482 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14483 if (uidArr != null) { 14484 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14485 } 14486 if (replacing) { 14487 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14488 } 14489 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14490 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14491 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14492 } 14493 } 14494 14495 /* 14496 * Look at potentially valid container ids from processCids If package 14497 * information doesn't match the one on record or package scanning fails, 14498 * the cid is added to list of removeCids. We currently don't delete stale 14499 * containers. 14500 */ 14501 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14502 ArrayList<String> pkgList = new ArrayList<String>(); 14503 Set<AsecInstallArgs> keys = processCids.keySet(); 14504 14505 for (AsecInstallArgs args : keys) { 14506 String codePath = processCids.get(args); 14507 if (DEBUG_SD_INSTALL) 14508 Log.i(TAG, "Loading container : " + args.cid); 14509 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14510 try { 14511 // Make sure there are no container errors first. 14512 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14513 Slog.e(TAG, "Failed to mount cid : " + args.cid 14514 + " when installing from sdcard"); 14515 continue; 14516 } 14517 // Check code path here. 14518 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14519 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14520 + " does not match one in settings " + codePath); 14521 continue; 14522 } 14523 // Parse package 14524 int parseFlags = mDefParseFlags; 14525 if (args.isExternalAsec()) { 14526 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14527 } 14528 if (args.isFwdLocked()) { 14529 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14530 } 14531 14532 synchronized (mInstallLock) { 14533 PackageParser.Package pkg = null; 14534 try { 14535 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14536 } catch (PackageManagerException e) { 14537 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14538 } 14539 // Scan the package 14540 if (pkg != null) { 14541 /* 14542 * TODO why is the lock being held? doPostInstall is 14543 * called in other places without the lock. This needs 14544 * to be straightened out. 14545 */ 14546 // writer 14547 synchronized (mPackages) { 14548 retCode = PackageManager.INSTALL_SUCCEEDED; 14549 pkgList.add(pkg.packageName); 14550 // Post process args 14551 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14552 pkg.applicationInfo.uid); 14553 } 14554 } else { 14555 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14556 } 14557 } 14558 14559 } finally { 14560 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14561 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14562 } 14563 } 14564 } 14565 // writer 14566 synchronized (mPackages) { 14567 // If the platform SDK has changed since the last time we booted, 14568 // we need to re-grant app permission to catch any new ones that 14569 // appear. This is really a hack, and means that apps can in some 14570 // cases get permissions that the user didn't initially explicitly 14571 // allow... it would be nice to have some better way to handle 14572 // this situation. 14573 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14574 if (regrantPermissions) 14575 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14576 + mSdkVersion + "; regranting permissions for external storage"); 14577 mSettings.mExternalSdkPlatform = mSdkVersion; 14578 14579 // Make sure group IDs have been assigned, and any permission 14580 // changes in other apps are accounted for 14581 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14582 | (regrantPermissions 14583 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14584 : 0)); 14585 14586 mSettings.updateExternalDatabaseVersion(); 14587 14588 // can downgrade to reader 14589 // Persist settings 14590 mSettings.writeLPr(); 14591 } 14592 // Send a broadcast to let everyone know we are done processing 14593 if (pkgList.size() > 0) { 14594 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14595 } 14596 } 14597 14598 /* 14599 * Utility method to unload a list of specified containers 14600 */ 14601 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14602 // Just unmount all valid containers. 14603 for (AsecInstallArgs arg : cidArgs) { 14604 synchronized (mInstallLock) { 14605 arg.doPostDeleteLI(false); 14606 } 14607 } 14608 } 14609 14610 /* 14611 * Unload packages mounted on external media. This involves deleting package 14612 * data from internal structures, sending broadcasts about diabled packages, 14613 * gc'ing to free up references, unmounting all secure containers 14614 * corresponding to packages on external media, and posting a 14615 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14616 * that we always have to post this message if status has been requested no 14617 * matter what. 14618 */ 14619 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14620 final boolean reportStatus) { 14621 if (DEBUG_SD_INSTALL) 14622 Log.i(TAG, "unloading media packages"); 14623 ArrayList<String> pkgList = new ArrayList<String>(); 14624 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14625 final Set<AsecInstallArgs> keys = processCids.keySet(); 14626 for (AsecInstallArgs args : keys) { 14627 String pkgName = args.getPackageName(); 14628 if (DEBUG_SD_INSTALL) 14629 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14630 // Delete package internally 14631 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14632 synchronized (mInstallLock) { 14633 boolean res = deletePackageLI(pkgName, null, false, null, null, 14634 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14635 if (res) { 14636 pkgList.add(pkgName); 14637 } else { 14638 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14639 failedList.add(args); 14640 } 14641 } 14642 } 14643 14644 // reader 14645 synchronized (mPackages) { 14646 // We didn't update the settings after removing each package; 14647 // write them now for all packages. 14648 mSettings.writeLPr(); 14649 } 14650 14651 // We have to absolutely send UPDATED_MEDIA_STATUS only 14652 // after confirming that all the receivers processed the ordered 14653 // broadcast when packages get disabled, force a gc to clean things up. 14654 // and unload all the containers. 14655 if (pkgList.size() > 0) { 14656 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14657 new IIntentReceiver.Stub() { 14658 public void performReceive(Intent intent, int resultCode, String data, 14659 Bundle extras, boolean ordered, boolean sticky, 14660 int sendingUser) throws RemoteException { 14661 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14662 reportStatus ? 1 : 0, 1, keys); 14663 mHandler.sendMessage(msg); 14664 } 14665 }); 14666 } else { 14667 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14668 keys); 14669 mHandler.sendMessage(msg); 14670 } 14671 } 14672 14673 private void loadPrivatePackages(VolumeInfo vol) { 14674 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14675 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14676 synchronized (mInstallLock) { 14677 synchronized (mPackages) { 14678 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14679 for (PackageSetting ps : packages) { 14680 final PackageParser.Package pkg; 14681 try { 14682 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14683 loaded.add(pkg.applicationInfo); 14684 } catch (PackageManagerException e) { 14685 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14686 } 14687 } 14688 14689 // TODO: regrant any permissions that changed based since original install 14690 14691 mSettings.writeLPr(); 14692 } 14693 } 14694 14695 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14696 sendResourcesChangedBroadcast(true, false, loaded, null); 14697 } 14698 14699 private void unloadPrivatePackages(VolumeInfo vol) { 14700 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14701 synchronized (mInstallLock) { 14702 synchronized (mPackages) { 14703 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14704 for (PackageSetting ps : packages) { 14705 if (ps.pkg == null) continue; 14706 14707 final ApplicationInfo info = ps.pkg.applicationInfo; 14708 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14709 if (deletePackageLI(ps.name, null, false, null, null, 14710 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14711 unloaded.add(info); 14712 } else { 14713 Slog.w(TAG, "Failed to unload " + ps.codePath); 14714 } 14715 } 14716 14717 mSettings.writeLPr(); 14718 } 14719 } 14720 14721 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14722 sendResourcesChangedBroadcast(false, false, unloaded, null); 14723 } 14724 14725 private void unfreezePackage(String packageName) { 14726 synchronized (mPackages) { 14727 final PackageSetting ps = mSettings.mPackages.get(packageName); 14728 if (ps != null) { 14729 ps.frozen = false; 14730 } 14731 } 14732 } 14733 14734 @Override 14735 public int movePackage(final String packageName, final String volumeUuid) { 14736 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14737 14738 final int moveId = mNextMoveId.getAndIncrement(); 14739 try { 14740 movePackageInternal(packageName, volumeUuid, moveId); 14741 } catch (PackageManagerException e) { 14742 Slog.w(TAG, "Failed to move " + packageName, e); 14743 mMoveCallbacks.notifyStatusChanged(moveId, 14744 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14745 } 14746 return moveId; 14747 } 14748 14749 private void movePackageInternal(final String packageName, final String volumeUuid, 14750 final int moveId) throws PackageManagerException { 14751 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14752 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14753 final PackageManager pm = mContext.getPackageManager(); 14754 14755 final boolean currentAsec; 14756 final String currentVolumeUuid; 14757 final File codeFile; 14758 final String installerPackageName; 14759 final String packageAbiOverride; 14760 final int appId; 14761 final String seinfo; 14762 final String label; 14763 14764 // reader 14765 synchronized (mPackages) { 14766 final PackageParser.Package pkg = mPackages.get(packageName); 14767 final PackageSetting ps = mSettings.mPackages.get(packageName); 14768 if (pkg == null || ps == null) { 14769 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14770 } 14771 14772 if (pkg.applicationInfo.isSystemApp()) { 14773 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14774 "Cannot move system application"); 14775 } 14776 14777 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14778 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14779 "Package already moved to " + volumeUuid); 14780 } 14781 14782 final File probe = new File(pkg.codePath); 14783 final File probeOat = new File(probe, "oat"); 14784 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14785 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14786 "Move only supported for modern cluster style installs"); 14787 } 14788 14789 if (ps.frozen) { 14790 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14791 "Failed to move already frozen package"); 14792 } 14793 ps.frozen = true; 14794 14795 currentAsec = pkg.applicationInfo.isForwardLocked() 14796 || pkg.applicationInfo.isExternalAsec(); 14797 currentVolumeUuid = ps.volumeUuid; 14798 codeFile = new File(pkg.codePath); 14799 installerPackageName = ps.installerPackageName; 14800 packageAbiOverride = ps.cpuAbiOverrideString; 14801 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14802 seinfo = pkg.applicationInfo.seinfo; 14803 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14804 } 14805 14806 // Now that we're guarded by frozen state, kill app during move 14807 killApplication(packageName, appId, "move pkg"); 14808 14809 final Bundle extras = new Bundle(); 14810 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14811 extras.putString(Intent.EXTRA_TITLE, label); 14812 mMoveCallbacks.notifyCreated(moveId, extras); 14813 14814 int installFlags; 14815 final boolean moveCompleteApp; 14816 final File measurePath; 14817 14818 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14819 installFlags = INSTALL_INTERNAL; 14820 moveCompleteApp = !currentAsec; 14821 measurePath = Environment.getDataAppDirectory(volumeUuid); 14822 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14823 installFlags = INSTALL_EXTERNAL; 14824 moveCompleteApp = false; 14825 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14826 } else { 14827 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14828 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14829 || !volume.isMountedWritable()) { 14830 unfreezePackage(packageName); 14831 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14832 "Move location not mounted private volume"); 14833 } 14834 14835 Preconditions.checkState(!currentAsec); 14836 14837 installFlags = INSTALL_INTERNAL; 14838 moveCompleteApp = true; 14839 measurePath = Environment.getDataAppDirectory(volumeUuid); 14840 } 14841 14842 final PackageStats stats = new PackageStats(null, -1); 14843 synchronized (mInstaller) { 14844 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14845 unfreezePackage(packageName); 14846 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14847 "Failed to measure package size"); 14848 } 14849 } 14850 14851 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14852 + stats.dataSize); 14853 14854 final long startFreeBytes = measurePath.getFreeSpace(); 14855 final long sizeBytes; 14856 if (moveCompleteApp) { 14857 sizeBytes = stats.codeSize + stats.dataSize; 14858 } else { 14859 sizeBytes = stats.codeSize; 14860 } 14861 14862 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14863 unfreezePackage(packageName); 14864 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14865 "Not enough free space to move"); 14866 } 14867 14868 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14869 14870 final CountDownLatch installedLatch = new CountDownLatch(1); 14871 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14872 @Override 14873 public void onUserActionRequired(Intent intent) throws RemoteException { 14874 throw new IllegalStateException(); 14875 } 14876 14877 @Override 14878 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14879 Bundle extras) throws RemoteException { 14880 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14881 + PackageManager.installStatusToString(returnCode, msg)); 14882 14883 installedLatch.countDown(); 14884 14885 // Regardless of success or failure of the move operation, 14886 // always unfreeze the package 14887 unfreezePackage(packageName); 14888 14889 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14890 switch (status) { 14891 case PackageInstaller.STATUS_SUCCESS: 14892 mMoveCallbacks.notifyStatusChanged(moveId, 14893 PackageManager.MOVE_SUCCEEDED); 14894 break; 14895 case PackageInstaller.STATUS_FAILURE_STORAGE: 14896 mMoveCallbacks.notifyStatusChanged(moveId, 14897 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14898 break; 14899 default: 14900 mMoveCallbacks.notifyStatusChanged(moveId, 14901 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14902 break; 14903 } 14904 } 14905 }; 14906 14907 final MoveInfo move; 14908 if (moveCompleteApp) { 14909 // Kick off a thread to report progress estimates 14910 new Thread() { 14911 @Override 14912 public void run() { 14913 while (true) { 14914 try { 14915 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14916 break; 14917 } 14918 } catch (InterruptedException ignored) { 14919 } 14920 14921 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14922 final int progress = 10 + (int) MathUtils.constrain( 14923 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14924 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14925 } 14926 } 14927 }.start(); 14928 14929 final String dataAppName = codeFile.getName(); 14930 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14931 dataAppName, appId, seinfo); 14932 } else { 14933 move = null; 14934 } 14935 14936 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14937 14938 final Message msg = mHandler.obtainMessage(INIT_COPY); 14939 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14940 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14941 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14942 mHandler.sendMessage(msg); 14943 } 14944 14945 @Override 14946 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14947 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14948 14949 final int realMoveId = mNextMoveId.getAndIncrement(); 14950 final Bundle extras = new Bundle(); 14951 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14952 mMoveCallbacks.notifyCreated(realMoveId, extras); 14953 14954 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14955 @Override 14956 public void onCreated(int moveId, Bundle extras) { 14957 // Ignored 14958 } 14959 14960 @Override 14961 public void onStatusChanged(int moveId, int status, long estMillis) { 14962 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14963 } 14964 }; 14965 14966 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14967 storage.setPrimaryStorageUuid(volumeUuid, callback); 14968 return realMoveId; 14969 } 14970 14971 @Override 14972 public int getMoveStatus(int moveId) { 14973 mContext.enforceCallingOrSelfPermission( 14974 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14975 return mMoveCallbacks.mLastStatus.get(moveId); 14976 } 14977 14978 @Override 14979 public void registerMoveCallback(IPackageMoveObserver callback) { 14980 mContext.enforceCallingOrSelfPermission( 14981 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14982 mMoveCallbacks.register(callback); 14983 } 14984 14985 @Override 14986 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14987 mContext.enforceCallingOrSelfPermission( 14988 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14989 mMoveCallbacks.unregister(callback); 14990 } 14991 14992 @Override 14993 public boolean setInstallLocation(int loc) { 14994 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14995 null); 14996 if (getInstallLocation() == loc) { 14997 return true; 14998 } 14999 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15000 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15001 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15002 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15003 return true; 15004 } 15005 return false; 15006 } 15007 15008 @Override 15009 public int getInstallLocation() { 15010 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15011 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15012 PackageHelper.APP_INSTALL_AUTO); 15013 } 15014 15015 /** Called by UserManagerService */ 15016 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15017 mDirtyUsers.remove(userHandle); 15018 mSettings.removeUserLPw(userHandle); 15019 mPendingBroadcasts.remove(userHandle); 15020 if (mInstaller != null) { 15021 // Technically, we shouldn't be doing this with the package lock 15022 // held. However, this is very rare, and there is already so much 15023 // other disk I/O going on, that we'll let it slide for now. 15024 final StorageManager storage = StorageManager.from(mContext); 15025 final List<VolumeInfo> vols = storage.getVolumes(); 15026 for (VolumeInfo vol : vols) { 15027 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15028 final String volumeUuid = vol.getFsUuid(); 15029 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15030 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15031 } 15032 } 15033 } 15034 mUserNeedsBadging.delete(userHandle); 15035 removeUnusedPackagesLILPw(userManager, userHandle); 15036 } 15037 15038 /** 15039 * We're removing userHandle and would like to remove any downloaded packages 15040 * that are no longer in use by any other user. 15041 * @param userHandle the user being removed 15042 */ 15043 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15044 final boolean DEBUG_CLEAN_APKS = false; 15045 int [] users = userManager.getUserIdsLPr(); 15046 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15047 while (psit.hasNext()) { 15048 PackageSetting ps = psit.next(); 15049 if (ps.pkg == null) { 15050 continue; 15051 } 15052 final String packageName = ps.pkg.packageName; 15053 // Skip over if system app 15054 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15055 continue; 15056 } 15057 if (DEBUG_CLEAN_APKS) { 15058 Slog.i(TAG, "Checking package " + packageName); 15059 } 15060 boolean keep = false; 15061 for (int i = 0; i < users.length; i++) { 15062 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15063 keep = true; 15064 if (DEBUG_CLEAN_APKS) { 15065 Slog.i(TAG, " Keeping package " + packageName + " for user " 15066 + users[i]); 15067 } 15068 break; 15069 } 15070 } 15071 if (!keep) { 15072 if (DEBUG_CLEAN_APKS) { 15073 Slog.i(TAG, " Removing package " + packageName); 15074 } 15075 mHandler.post(new Runnable() { 15076 public void run() { 15077 deletePackageX(packageName, userHandle, 0); 15078 } //end run 15079 }); 15080 } 15081 } 15082 } 15083 15084 /** Called by UserManagerService */ 15085 void createNewUserLILPw(int userHandle, File path) { 15086 if (mInstaller != null) { 15087 mInstaller.createUserConfig(userHandle); 15088 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15089 } 15090 } 15091 15092 void newUserCreatedLILPw(final int userHandle) { 15093 // We cannot grant the default permissions with a lock held as 15094 // we query providers from other components for default handlers 15095 // such as enabled IMEs, etc. 15096 mHandler.post(new Runnable() { 15097 @Override 15098 public void run() { 15099 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15100 } 15101 }); 15102 } 15103 15104 @Override 15105 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15106 mContext.enforceCallingOrSelfPermission( 15107 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15108 "Only package verification agents can read the verifier device identity"); 15109 15110 synchronized (mPackages) { 15111 return mSettings.getVerifierDeviceIdentityLPw(); 15112 } 15113 } 15114 15115 @Override 15116 public void setPermissionEnforced(String permission, boolean enforced) { 15117 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15118 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15119 synchronized (mPackages) { 15120 if (mSettings.mReadExternalStorageEnforced == null 15121 || mSettings.mReadExternalStorageEnforced != enforced) { 15122 mSettings.mReadExternalStorageEnforced = enforced; 15123 mSettings.writeLPr(); 15124 } 15125 } 15126 // kill any non-foreground processes so we restart them and 15127 // grant/revoke the GID. 15128 final IActivityManager am = ActivityManagerNative.getDefault(); 15129 if (am != null) { 15130 final long token = Binder.clearCallingIdentity(); 15131 try { 15132 am.killProcessesBelowForeground("setPermissionEnforcement"); 15133 } catch (RemoteException e) { 15134 } finally { 15135 Binder.restoreCallingIdentity(token); 15136 } 15137 } 15138 } else { 15139 throw new IllegalArgumentException("No selective enforcement for " + permission); 15140 } 15141 } 15142 15143 @Override 15144 @Deprecated 15145 public boolean isPermissionEnforced(String permission) { 15146 return true; 15147 } 15148 15149 @Override 15150 public boolean isStorageLow() { 15151 final long token = Binder.clearCallingIdentity(); 15152 try { 15153 final DeviceStorageMonitorInternal 15154 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15155 if (dsm != null) { 15156 return dsm.isMemoryLow(); 15157 } else { 15158 return false; 15159 } 15160 } finally { 15161 Binder.restoreCallingIdentity(token); 15162 } 15163 } 15164 15165 @Override 15166 public IPackageInstaller getPackageInstaller() { 15167 return mInstallerService; 15168 } 15169 15170 private boolean userNeedsBadging(int userId) { 15171 int index = mUserNeedsBadging.indexOfKey(userId); 15172 if (index < 0) { 15173 final UserInfo userInfo; 15174 final long token = Binder.clearCallingIdentity(); 15175 try { 15176 userInfo = sUserManager.getUserInfo(userId); 15177 } finally { 15178 Binder.restoreCallingIdentity(token); 15179 } 15180 final boolean b; 15181 if (userInfo != null && userInfo.isManagedProfile()) { 15182 b = true; 15183 } else { 15184 b = false; 15185 } 15186 mUserNeedsBadging.put(userId, b); 15187 return b; 15188 } 15189 return mUserNeedsBadging.valueAt(index); 15190 } 15191 15192 @Override 15193 public KeySet getKeySetByAlias(String packageName, String alias) { 15194 if (packageName == null || alias == null) { 15195 return null; 15196 } 15197 synchronized(mPackages) { 15198 final PackageParser.Package pkg = mPackages.get(packageName); 15199 if (pkg == null) { 15200 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15201 throw new IllegalArgumentException("Unknown package: " + packageName); 15202 } 15203 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15204 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15205 } 15206 } 15207 15208 @Override 15209 public KeySet getSigningKeySet(String packageName) { 15210 if (packageName == null) { 15211 return null; 15212 } 15213 synchronized(mPackages) { 15214 final PackageParser.Package pkg = mPackages.get(packageName); 15215 if (pkg == null) { 15216 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15217 throw new IllegalArgumentException("Unknown package: " + packageName); 15218 } 15219 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15220 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15221 throw new SecurityException("May not access signing KeySet of other apps."); 15222 } 15223 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15224 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15225 } 15226 } 15227 15228 @Override 15229 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15230 if (packageName == null || ks == null) { 15231 return false; 15232 } 15233 synchronized(mPackages) { 15234 final PackageParser.Package pkg = mPackages.get(packageName); 15235 if (pkg == null) { 15236 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15237 throw new IllegalArgumentException("Unknown package: " + packageName); 15238 } 15239 IBinder ksh = ks.getToken(); 15240 if (ksh instanceof KeySetHandle) { 15241 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15242 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15243 } 15244 return false; 15245 } 15246 } 15247 15248 @Override 15249 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15250 if (packageName == null || ks == null) { 15251 return false; 15252 } 15253 synchronized(mPackages) { 15254 final PackageParser.Package pkg = mPackages.get(packageName); 15255 if (pkg == null) { 15256 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15257 throw new IllegalArgumentException("Unknown package: " + packageName); 15258 } 15259 IBinder ksh = ks.getToken(); 15260 if (ksh instanceof KeySetHandle) { 15261 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15262 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15263 } 15264 return false; 15265 } 15266 } 15267 15268 public void getUsageStatsIfNoPackageUsageInfo() { 15269 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15270 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15271 if (usm == null) { 15272 throw new IllegalStateException("UsageStatsManager must be initialized"); 15273 } 15274 long now = System.currentTimeMillis(); 15275 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15276 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15277 String packageName = entry.getKey(); 15278 PackageParser.Package pkg = mPackages.get(packageName); 15279 if (pkg == null) { 15280 continue; 15281 } 15282 UsageStats usage = entry.getValue(); 15283 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15284 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15285 } 15286 } 15287 } 15288 15289 /** 15290 * Check and throw if the given before/after packages would be considered a 15291 * downgrade. 15292 */ 15293 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15294 throws PackageManagerException { 15295 if (after.versionCode < before.mVersionCode) { 15296 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15297 "Update version code " + after.versionCode + " is older than current " 15298 + before.mVersionCode); 15299 } else if (after.versionCode == before.mVersionCode) { 15300 if (after.baseRevisionCode < before.baseRevisionCode) { 15301 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15302 "Update base revision code " + after.baseRevisionCode 15303 + " is older than current " + before.baseRevisionCode); 15304 } 15305 15306 if (!ArrayUtils.isEmpty(after.splitNames)) { 15307 for (int i = 0; i < after.splitNames.length; i++) { 15308 final String splitName = after.splitNames[i]; 15309 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15310 if (j != -1) { 15311 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15312 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15313 "Update split " + splitName + " revision code " 15314 + after.splitRevisionCodes[i] + " is older than current " 15315 + before.splitRevisionCodes[j]); 15316 } 15317 } 15318 } 15319 } 15320 } 15321 } 15322 15323 private static class MoveCallbacks extends Handler { 15324 private static final int MSG_CREATED = 1; 15325 private static final int MSG_STATUS_CHANGED = 2; 15326 15327 private final RemoteCallbackList<IPackageMoveObserver> 15328 mCallbacks = new RemoteCallbackList<>(); 15329 15330 private final SparseIntArray mLastStatus = new SparseIntArray(); 15331 15332 public MoveCallbacks(Looper looper) { 15333 super(looper); 15334 } 15335 15336 public void register(IPackageMoveObserver callback) { 15337 mCallbacks.register(callback); 15338 } 15339 15340 public void unregister(IPackageMoveObserver callback) { 15341 mCallbacks.unregister(callback); 15342 } 15343 15344 @Override 15345 public void handleMessage(Message msg) { 15346 final SomeArgs args = (SomeArgs) msg.obj; 15347 final int n = mCallbacks.beginBroadcast(); 15348 for (int i = 0; i < n; i++) { 15349 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15350 try { 15351 invokeCallback(callback, msg.what, args); 15352 } catch (RemoteException ignored) { 15353 } 15354 } 15355 mCallbacks.finishBroadcast(); 15356 args.recycle(); 15357 } 15358 15359 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15360 throws RemoteException { 15361 switch (what) { 15362 case MSG_CREATED: { 15363 callback.onCreated(args.argi1, (Bundle) args.arg2); 15364 break; 15365 } 15366 case MSG_STATUS_CHANGED: { 15367 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15368 break; 15369 } 15370 } 15371 } 15372 15373 private void notifyCreated(int moveId, Bundle extras) { 15374 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15375 15376 final SomeArgs args = SomeArgs.obtain(); 15377 args.argi1 = moveId; 15378 args.arg2 = extras; 15379 obtainMessage(MSG_CREATED, args).sendToTarget(); 15380 } 15381 15382 private void notifyStatusChanged(int moveId, int status) { 15383 notifyStatusChanged(moveId, status, -1); 15384 } 15385 15386 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15387 Slog.v(TAG, "Move " + moveId + " status " + status); 15388 15389 final SomeArgs args = SomeArgs.obtain(); 15390 args.argi1 = moveId; 15391 args.argi2 = status; 15392 args.arg3 = estMillis; 15393 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15394 15395 synchronized (mLastStatus) { 15396 mLastStatus.put(moveId, status); 15397 } 15398 } 15399 } 15400 15401 private final class OnPermissionChangeListeners extends Handler { 15402 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15403 15404 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15405 new RemoteCallbackList<>(); 15406 15407 public OnPermissionChangeListeners(Looper looper) { 15408 super(looper); 15409 } 15410 15411 @Override 15412 public void handleMessage(Message msg) { 15413 switch (msg.what) { 15414 case MSG_ON_PERMISSIONS_CHANGED: { 15415 final int uid = msg.arg1; 15416 handleOnPermissionsChanged(uid); 15417 } break; 15418 } 15419 } 15420 15421 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15422 mPermissionListeners.register(listener); 15423 15424 } 15425 15426 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15427 mPermissionListeners.unregister(listener); 15428 } 15429 15430 public void onPermissionsChanged(int uid) { 15431 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15432 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15433 } 15434 } 15435 15436 private void handleOnPermissionsChanged(int uid) { 15437 final int count = mPermissionListeners.beginBroadcast(); 15438 try { 15439 for (int i = 0; i < count; i++) { 15440 IOnPermissionsChangeListener callback = mPermissionListeners 15441 .getBroadcastItem(i); 15442 try { 15443 callback.onPermissionsChanged(uid); 15444 } catch (RemoteException e) { 15445 Log.e(TAG, "Permission listener is dead", e); 15446 } 15447 } 15448 } finally { 15449 mPermissionListeners.finishBroadcast(); 15450 } 15451 } 15452 } 15453 15454 private class PackageManagerInternalImpl extends PackageManagerInternal { 15455 @Override 15456 public void setLocationPackagesProvider(PackagesProvider provider) { 15457 synchronized (mPackages) { 15458 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15459 } 15460 } 15461 15462 @Override 15463 public void setImePackagesProvider(PackagesProvider provider) { 15464 synchronized (mPackages) { 15465 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15466 } 15467 } 15468 15469 @Override 15470 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15471 synchronized (mPackages) { 15472 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15473 } 15474 } 15475 } 15476} 15477