PackageManagerService.java revision adc1cf46045ae756d3a9ccbccf6b0f894e4c1edd
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 1596 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1597 SettingBase sb = (SettingBase) pkg.mExtras; 1598 if (sb == null) { 1599 return; 1600 } 1601 1602 PermissionsState permissionsState = sb.getPermissionsState(); 1603 1604 for (String permission : pkg.requestedPermissions) { 1605 BasePermission bp = mSettings.mPermissions.get(permission); 1606 if (bp != null && bp.isRuntime()) { 1607 permissionsState.grantRuntimePermission(bp, userId); 1608 } 1609 } 1610 } 1611 1612 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1613 Bundle extras = null; 1614 switch (res.returnCode) { 1615 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1616 extras = new Bundle(); 1617 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1618 res.origPermission); 1619 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1620 res.origPackage); 1621 break; 1622 } 1623 case PackageManager.INSTALL_SUCCEEDED: { 1624 extras = new Bundle(); 1625 extras.putBoolean(Intent.EXTRA_REPLACING, 1626 res.removedInfo != null && res.removedInfo.removedPackage != null); 1627 break; 1628 } 1629 } 1630 return extras; 1631 } 1632 1633 void scheduleWriteSettingsLocked() { 1634 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1635 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1636 } 1637 } 1638 1639 void scheduleWritePackageRestrictionsLocked(int userId) { 1640 if (!sUserManager.exists(userId)) return; 1641 mDirtyUsers.add(userId); 1642 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1643 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1644 } 1645 } 1646 1647 public static PackageManagerService main(Context context, Installer installer, 1648 boolean factoryTest, boolean onlyCore) { 1649 PackageManagerService m = new PackageManagerService(context, installer, 1650 factoryTest, onlyCore); 1651 ServiceManager.addService("package", m); 1652 return m; 1653 } 1654 1655 static String[] splitString(String str, char sep) { 1656 int count = 1; 1657 int i = 0; 1658 while ((i=str.indexOf(sep, i)) >= 0) { 1659 count++; 1660 i++; 1661 } 1662 1663 String[] res = new String[count]; 1664 i=0; 1665 count = 0; 1666 int lastI=0; 1667 while ((i=str.indexOf(sep, i)) >= 0) { 1668 res[count] = str.substring(lastI, i); 1669 count++; 1670 i++; 1671 lastI = i; 1672 } 1673 res[count] = str.substring(lastI, str.length()); 1674 return res; 1675 } 1676 1677 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1678 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1679 Context.DISPLAY_SERVICE); 1680 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1681 } 1682 1683 public PackageManagerService(Context context, Installer installer, 1684 boolean factoryTest, boolean onlyCore) { 1685 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1686 SystemClock.uptimeMillis()); 1687 1688 if (mSdkVersion <= 0) { 1689 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1690 } 1691 1692 mContext = context; 1693 mFactoryTest = factoryTest; 1694 mOnlyCore = onlyCore; 1695 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1696 mMetrics = new DisplayMetrics(); 1697 mSettings = new Settings(mPackages); 1698 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1699 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1700 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1701 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1702 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1703 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1704 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1705 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1706 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1707 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1708 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1709 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1710 1711 // TODO: add a property to control this? 1712 long dexOptLRUThresholdInMinutes; 1713 if (mLazyDexOpt) { 1714 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1715 } else { 1716 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1717 } 1718 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1719 1720 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1721 if (separateProcesses != null && separateProcesses.length() > 0) { 1722 if ("*".equals(separateProcesses)) { 1723 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1724 mSeparateProcesses = null; 1725 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1726 } else { 1727 mDefParseFlags = 0; 1728 mSeparateProcesses = separateProcesses.split(","); 1729 Slog.w(TAG, "Running with debug.separate_processes: " 1730 + separateProcesses); 1731 } 1732 } else { 1733 mDefParseFlags = 0; 1734 mSeparateProcesses = null; 1735 } 1736 1737 mInstaller = installer; 1738 mPackageDexOptimizer = new PackageDexOptimizer(this); 1739 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1740 1741 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1742 FgThread.get().getLooper()); 1743 1744 getDefaultDisplayMetrics(context, mMetrics); 1745 1746 SystemConfig systemConfig = SystemConfig.getInstance(); 1747 mGlobalGids = systemConfig.getGlobalGids(); 1748 mSystemPermissions = systemConfig.getSystemPermissions(); 1749 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1750 1751 synchronized (mInstallLock) { 1752 // writer 1753 synchronized (mPackages) { 1754 mHandlerThread = new ServiceThread(TAG, 1755 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1756 mHandlerThread.start(); 1757 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1758 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1759 1760 File dataDir = Environment.getDataDirectory(); 1761 mAppDataDir = new File(dataDir, "data"); 1762 mAppInstallDir = new File(dataDir, "app"); 1763 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1764 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1765 mUserAppDataDir = new File(dataDir, "user"); 1766 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1767 1768 sUserManager = new UserManagerService(context, this, 1769 mInstallLock, mPackages); 1770 1771 // Propagate permission configuration in to package manager. 1772 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1773 = systemConfig.getPermissions(); 1774 for (int i=0; i<permConfig.size(); i++) { 1775 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1776 BasePermission bp = mSettings.mPermissions.get(perm.name); 1777 if (bp == null) { 1778 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1779 mSettings.mPermissions.put(perm.name, bp); 1780 } 1781 if (perm.gids != null) { 1782 bp.setGids(perm.gids, perm.perUser); 1783 } 1784 } 1785 1786 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1787 for (int i=0; i<libConfig.size(); i++) { 1788 mSharedLibraries.put(libConfig.keyAt(i), 1789 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1790 } 1791 1792 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1793 1794 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1795 mSdkVersion, mOnlyCore); 1796 1797 String customResolverActivity = Resources.getSystem().getString( 1798 R.string.config_customResolverActivity); 1799 if (TextUtils.isEmpty(customResolverActivity)) { 1800 customResolverActivity = null; 1801 } else { 1802 mCustomResolverComponentName = ComponentName.unflattenFromString( 1803 customResolverActivity); 1804 } 1805 1806 long startTime = SystemClock.uptimeMillis(); 1807 1808 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1809 startTime); 1810 1811 // Set flag to monitor and not change apk file paths when 1812 // scanning install directories. 1813 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1814 1815 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1816 1817 /** 1818 * Add everything in the in the boot class path to the 1819 * list of process files because dexopt will have been run 1820 * if necessary during zygote startup. 1821 */ 1822 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1823 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1824 1825 if (bootClassPath != null) { 1826 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1827 for (String element : bootClassPathElements) { 1828 alreadyDexOpted.add(element); 1829 } 1830 } else { 1831 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1832 } 1833 1834 if (systemServerClassPath != null) { 1835 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1836 for (String element : systemServerClassPathElements) { 1837 alreadyDexOpted.add(element); 1838 } 1839 } else { 1840 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1841 } 1842 1843 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1844 final String[] dexCodeInstructionSets = 1845 getDexCodeInstructionSets( 1846 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1847 1848 /** 1849 * Ensure all external libraries have had dexopt run on them. 1850 */ 1851 if (mSharedLibraries.size() > 0) { 1852 // NOTE: For now, we're compiling these system "shared libraries" 1853 // (and framework jars) into all available architectures. It's possible 1854 // to compile them only when we come across an app that uses them (there's 1855 // already logic for that in scanPackageLI) but that adds some complexity. 1856 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1857 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1858 final String lib = libEntry.path; 1859 if (lib == null) { 1860 continue; 1861 } 1862 1863 try { 1864 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1865 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1866 alreadyDexOpted.add(lib); 1867 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1868 } 1869 } catch (FileNotFoundException e) { 1870 Slog.w(TAG, "Library not found: " + lib); 1871 } catch (IOException e) { 1872 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1873 + e.getMessage()); 1874 } 1875 } 1876 } 1877 } 1878 1879 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1880 1881 // Gross hack for now: we know this file doesn't contain any 1882 // code, so don't dexopt it to avoid the resulting log spew. 1883 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1884 1885 // Gross hack for now: we know this file is only part of 1886 // the boot class path for art, so don't dexopt it to 1887 // avoid the resulting log spew. 1888 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1889 1890 /** 1891 * There are a number of commands implemented in Java, which 1892 * we currently need to do the dexopt on so that they can be 1893 * run from a non-root shell. 1894 */ 1895 String[] frameworkFiles = frameworkDir.list(); 1896 if (frameworkFiles != null) { 1897 // TODO: We could compile these only for the most preferred ABI. We should 1898 // first double check that the dex files for these commands are not referenced 1899 // by other system apps. 1900 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1901 for (int i=0; i<frameworkFiles.length; i++) { 1902 File libPath = new File(frameworkDir, frameworkFiles[i]); 1903 String path = libPath.getPath(); 1904 // Skip the file if we already did it. 1905 if (alreadyDexOpted.contains(path)) { 1906 continue; 1907 } 1908 // Skip the file if it is not a type we want to dexopt. 1909 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1910 continue; 1911 } 1912 try { 1913 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1914 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1915 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1916 } 1917 } catch (FileNotFoundException e) { 1918 Slog.w(TAG, "Jar not found: " + path); 1919 } catch (IOException e) { 1920 Slog.w(TAG, "Exception reading jar: " + path, e); 1921 } 1922 } 1923 } 1924 } 1925 1926 // Collect vendor overlay packages. 1927 // (Do this before scanning any apps.) 1928 // For security and version matching reason, only consider 1929 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1930 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1931 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1932 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1933 1934 // Find base frameworks (resource packages without code). 1935 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1936 | PackageParser.PARSE_IS_SYSTEM_DIR 1937 | PackageParser.PARSE_IS_PRIVILEGED, 1938 scanFlags | SCAN_NO_DEX, 0); 1939 1940 // Collected privileged system packages. 1941 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1942 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1943 | PackageParser.PARSE_IS_SYSTEM_DIR 1944 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1945 1946 // Collect ordinary system packages. 1947 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1948 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1949 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1950 1951 // Collect all vendor packages. 1952 File vendorAppDir = new File("/vendor/app"); 1953 try { 1954 vendorAppDir = vendorAppDir.getCanonicalFile(); 1955 } catch (IOException e) { 1956 // failed to look up canonical path, continue with original one 1957 } 1958 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1959 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1960 1961 // Collect all OEM packages. 1962 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1963 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1964 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1965 1966 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1967 mInstaller.moveFiles(); 1968 1969 // Prune any system packages that no longer exist. 1970 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1971 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1972 if (!mOnlyCore) { 1973 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1974 while (psit.hasNext()) { 1975 PackageSetting ps = psit.next(); 1976 1977 /* 1978 * If this is not a system app, it can't be a 1979 * disable system app. 1980 */ 1981 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1982 continue; 1983 } 1984 1985 /* 1986 * If the package is scanned, it's not erased. 1987 */ 1988 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1989 if (scannedPkg != null) { 1990 /* 1991 * If the system app is both scanned and in the 1992 * disabled packages list, then it must have been 1993 * added via OTA. Remove it from the currently 1994 * scanned package so the previously user-installed 1995 * application can be scanned. 1996 */ 1997 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1998 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1999 + ps.name + "; removing system app. Last known codePath=" 2000 + ps.codePathString + ", installStatus=" + ps.installStatus 2001 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2002 + scannedPkg.mVersionCode); 2003 removePackageLI(ps, true); 2004 expectingBetter.put(ps.name, ps.codePath); 2005 } 2006 2007 continue; 2008 } 2009 2010 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2011 psit.remove(); 2012 logCriticalInfo(Log.WARN, "System package " + ps.name 2013 + " no longer exists; wiping its data"); 2014 removeDataDirsLI(null, ps.name); 2015 } else { 2016 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2017 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2018 possiblyDeletedUpdatedSystemApps.add(ps.name); 2019 } 2020 } 2021 } 2022 } 2023 2024 //look for any incomplete package installations 2025 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2026 //clean up list 2027 for(int i = 0; i < deletePkgsList.size(); i++) { 2028 //clean up here 2029 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2030 } 2031 //delete tmp files 2032 deleteTempPackageFiles(); 2033 2034 // Remove any shared userIDs that have no associated packages 2035 mSettings.pruneSharedUsersLPw(); 2036 2037 if (!mOnlyCore) { 2038 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2039 SystemClock.uptimeMillis()); 2040 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2041 2042 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2043 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2044 2045 /** 2046 * Remove disable package settings for any updated system 2047 * apps that were removed via an OTA. If they're not a 2048 * previously-updated app, remove them completely. 2049 * Otherwise, just revoke their system-level permissions. 2050 */ 2051 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2052 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2053 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2054 2055 String msg; 2056 if (deletedPkg == null) { 2057 msg = "Updated system package " + deletedAppName 2058 + " no longer exists; wiping its data"; 2059 removeDataDirsLI(null, deletedAppName); 2060 } else { 2061 msg = "Updated system app + " + deletedAppName 2062 + " no longer present; removing system privileges for " 2063 + deletedAppName; 2064 2065 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2066 2067 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2068 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2069 } 2070 logCriticalInfo(Log.WARN, msg); 2071 } 2072 2073 /** 2074 * Make sure all system apps that we expected to appear on 2075 * the userdata partition actually showed up. If they never 2076 * appeared, crawl back and revive the system version. 2077 */ 2078 for (int i = 0; i < expectingBetter.size(); i++) { 2079 final String packageName = expectingBetter.keyAt(i); 2080 if (!mPackages.containsKey(packageName)) { 2081 final File scanFile = expectingBetter.valueAt(i); 2082 2083 logCriticalInfo(Log.WARN, "Expected better " + packageName 2084 + " but never showed up; reverting to system"); 2085 2086 final int reparseFlags; 2087 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2088 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2089 | PackageParser.PARSE_IS_SYSTEM_DIR 2090 | PackageParser.PARSE_IS_PRIVILEGED; 2091 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2092 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2093 | PackageParser.PARSE_IS_SYSTEM_DIR; 2094 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2095 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2096 | PackageParser.PARSE_IS_SYSTEM_DIR; 2097 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2098 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2099 | PackageParser.PARSE_IS_SYSTEM_DIR; 2100 } else { 2101 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2102 continue; 2103 } 2104 2105 mSettings.enableSystemPackageLPw(packageName); 2106 2107 try { 2108 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2109 } catch (PackageManagerException e) { 2110 Slog.e(TAG, "Failed to parse original system package: " 2111 + e.getMessage()); 2112 } 2113 } 2114 } 2115 } 2116 2117 // Now that we know all of the shared libraries, update all clients to have 2118 // the correct library paths. 2119 updateAllSharedLibrariesLPw(); 2120 2121 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2122 // NOTE: We ignore potential failures here during a system scan (like 2123 // the rest of the commands above) because there's precious little we 2124 // can do about it. A settings error is reported, though. 2125 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2126 false /* force dexopt */, false /* defer dexopt */); 2127 } 2128 2129 // Now that we know all the packages we are keeping, 2130 // read and update their last usage times. 2131 mPackageUsage.readLP(); 2132 2133 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2134 SystemClock.uptimeMillis()); 2135 Slog.i(TAG, "Time to scan packages: " 2136 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2137 + " seconds"); 2138 2139 // If the platform SDK has changed since the last time we booted, 2140 // we need to re-grant app permission to catch any new ones that 2141 // appear. This is really a hack, and means that apps can in some 2142 // cases get permissions that the user didn't initially explicitly 2143 // allow... it would be nice to have some better way to handle 2144 // this situation. 2145 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2146 != mSdkVersion; 2147 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2148 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2149 + "; regranting permissions for internal storage"); 2150 mSettings.mInternalSdkPlatform = mSdkVersion; 2151 2152 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2153 | (regrantPermissions 2154 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2155 : 0)); 2156 2157 // If this is the first boot, and it is a normal boot, then 2158 // we need to initialize the default preferred apps. 2159 if (!mRestoredSettings && !onlyCore) { 2160 mSettings.readDefaultPreferredAppsLPw(this, 0); 2161 } 2162 2163 // If this is first boot after an OTA, and a normal boot, then 2164 // we need to clear code cache directories. 2165 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2166 if (mIsUpgrade && !onlyCore) { 2167 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2168 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2169 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2170 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2171 } 2172 mSettings.mFingerprint = Build.FINGERPRINT; 2173 } 2174 2175 primeDomainVerificationsLPw(); 2176 checkDefaultBrowser(); 2177 2178 // All the changes are done during package scanning. 2179 mSettings.updateInternalDatabaseVersion(); 2180 2181 // can downgrade to reader 2182 mSettings.writeLPr(); 2183 2184 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2185 SystemClock.uptimeMillis()); 2186 2187 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2188 2189 mInstallerService = new PackageInstallerService(context, this); 2190 2191 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2192 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2193 mIntentFilterVerifierComponent); 2194 2195 } // synchronized (mPackages) 2196 } // synchronized (mInstallLock) 2197 2198 // Now after opening every single application zip, make sure they 2199 // are all flushed. Not really needed, but keeps things nice and 2200 // tidy. 2201 Runtime.getRuntime().gc(); 2202 2203 // Expose private service for system components to use. 2204 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2205 } 2206 2207 @Override 2208 public boolean isFirstBoot() { 2209 return !mRestoredSettings; 2210 } 2211 2212 @Override 2213 public boolean isOnlyCoreApps() { 2214 return mOnlyCore; 2215 } 2216 2217 @Override 2218 public boolean isUpgrade() { 2219 return mIsUpgrade; 2220 } 2221 2222 private String getRequiredVerifierLPr() { 2223 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2224 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2225 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2226 2227 String requiredVerifier = null; 2228 2229 final int N = receivers.size(); 2230 for (int i = 0; i < N; i++) { 2231 final ResolveInfo info = receivers.get(i); 2232 2233 if (info.activityInfo == null) { 2234 continue; 2235 } 2236 2237 final String packageName = info.activityInfo.packageName; 2238 2239 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2240 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2241 continue; 2242 } 2243 2244 if (requiredVerifier != null) { 2245 throw new RuntimeException("There can be only one required verifier"); 2246 } 2247 2248 requiredVerifier = packageName; 2249 } 2250 2251 return requiredVerifier; 2252 } 2253 2254 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2255 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2256 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2257 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2258 2259 ComponentName verifierComponentName = null; 2260 2261 int priority = -1000; 2262 final int N = receivers.size(); 2263 for (int i = 0; i < N; i++) { 2264 final ResolveInfo info = receivers.get(i); 2265 2266 if (info.activityInfo == null) { 2267 continue; 2268 } 2269 2270 final String packageName = info.activityInfo.packageName; 2271 2272 final PackageSetting ps = mSettings.mPackages.get(packageName); 2273 if (ps == null) { 2274 continue; 2275 } 2276 2277 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2278 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2279 continue; 2280 } 2281 2282 // Select the IntentFilterVerifier with the highest priority 2283 if (priority < info.priority) { 2284 priority = info.priority; 2285 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2286 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2287 + verifierComponentName + " with priority: " + info.priority); 2288 } 2289 } 2290 2291 return verifierComponentName; 2292 } 2293 2294 private void primeDomainVerificationsLPw() { 2295 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2296 boolean updated = false; 2297 ArraySet<String> allHostsSet = new ArraySet<>(); 2298 for (PackageParser.Package pkg : mPackages.values()) { 2299 final String packageName = pkg.packageName; 2300 if (!hasDomainURLs(pkg)) { 2301 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2302 "package with no domain URLs: " + packageName); 2303 continue; 2304 } 2305 if (!pkg.isSystemApp()) { 2306 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2307 "No priming domain verifications for a non system package : " + 2308 packageName); 2309 continue; 2310 } 2311 for (PackageParser.Activity a : pkg.activities) { 2312 for (ActivityIntentInfo filter : a.intents) { 2313 if (hasValidDomains(filter)) { 2314 allHostsSet.addAll(filter.getHostsList()); 2315 } 2316 } 2317 } 2318 if (allHostsSet.size() == 0) { 2319 allHostsSet.add("*"); 2320 } 2321 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2322 IntentFilterVerificationInfo ivi = 2323 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2324 if (ivi != null) { 2325 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2326 "Priming domain verifications for package: " + packageName + 2327 " with hosts:" + ivi.getDomainsString()); 2328 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2329 updated = true; 2330 } 2331 else { 2332 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2333 "No priming domain verifications for package: " + packageName); 2334 } 2335 allHostsSet.clear(); 2336 } 2337 if (updated) { 2338 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2339 "Will need to write primed domain verifications"); 2340 } 2341 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2342 } 2343 2344 private void checkDefaultBrowser() { 2345 final int myUserId = UserHandle.myUserId(); 2346 final String packageName = getDefaultBrowserPackageName(myUserId); 2347 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2348 if (info == null) { 2349 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2350 packageName); 2351 setDefaultBrowserPackageName(null, myUserId); 2352 } 2353 } 2354 2355 @Override 2356 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2357 throws RemoteException { 2358 try { 2359 return super.onTransact(code, data, reply, flags); 2360 } catch (RuntimeException e) { 2361 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2362 Slog.wtf(TAG, "Package Manager Crash", e); 2363 } 2364 throw e; 2365 } 2366 } 2367 2368 void cleanupInstallFailedPackage(PackageSetting ps) { 2369 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2370 2371 removeDataDirsLI(ps.volumeUuid, ps.name); 2372 if (ps.codePath != null) { 2373 if (ps.codePath.isDirectory()) { 2374 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2375 } else { 2376 ps.codePath.delete(); 2377 } 2378 } 2379 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2380 if (ps.resourcePath.isDirectory()) { 2381 FileUtils.deleteContents(ps.resourcePath); 2382 } 2383 ps.resourcePath.delete(); 2384 } 2385 mSettings.removePackageLPw(ps.name); 2386 } 2387 2388 static int[] appendInts(int[] cur, int[] add) { 2389 if (add == null) return cur; 2390 if (cur == null) return add; 2391 final int N = add.length; 2392 for (int i=0; i<N; i++) { 2393 cur = appendInt(cur, add[i]); 2394 } 2395 return cur; 2396 } 2397 2398 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2399 if (!sUserManager.exists(userId)) return null; 2400 final PackageSetting ps = (PackageSetting) p.mExtras; 2401 if (ps == null) { 2402 return null; 2403 } 2404 2405 final PermissionsState permissionsState = ps.getPermissionsState(); 2406 2407 final int[] gids = permissionsState.computeGids(userId); 2408 final Set<String> permissions = permissionsState.getPermissions(userId); 2409 final PackageUserState state = ps.readUserState(userId); 2410 2411 return PackageParser.generatePackageInfo(p, gids, flags, 2412 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2413 } 2414 2415 @Override 2416 public boolean isPackageFrozen(String packageName) { 2417 synchronized (mPackages) { 2418 final PackageSetting ps = mSettings.mPackages.get(packageName); 2419 if (ps != null) { 2420 return ps.frozen; 2421 } 2422 } 2423 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2424 return true; 2425 } 2426 2427 @Override 2428 public boolean isPackageAvailable(String packageName, int userId) { 2429 if (!sUserManager.exists(userId)) return false; 2430 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2431 synchronized (mPackages) { 2432 PackageParser.Package p = mPackages.get(packageName); 2433 if (p != null) { 2434 final PackageSetting ps = (PackageSetting) p.mExtras; 2435 if (ps != null) { 2436 final PackageUserState state = ps.readUserState(userId); 2437 if (state != null) { 2438 return PackageParser.isAvailable(state); 2439 } 2440 } 2441 } 2442 } 2443 return false; 2444 } 2445 2446 @Override 2447 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2448 if (!sUserManager.exists(userId)) return null; 2449 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2450 // reader 2451 synchronized (mPackages) { 2452 PackageParser.Package p = mPackages.get(packageName); 2453 if (DEBUG_PACKAGE_INFO) 2454 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2455 if (p != null) { 2456 return generatePackageInfo(p, flags, userId); 2457 } 2458 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2459 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2460 } 2461 } 2462 return null; 2463 } 2464 2465 @Override 2466 public String[] currentToCanonicalPackageNames(String[] names) { 2467 String[] out = new String[names.length]; 2468 // reader 2469 synchronized (mPackages) { 2470 for (int i=names.length-1; i>=0; i--) { 2471 PackageSetting ps = mSettings.mPackages.get(names[i]); 2472 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2473 } 2474 } 2475 return out; 2476 } 2477 2478 @Override 2479 public String[] canonicalToCurrentPackageNames(String[] names) { 2480 String[] out = new String[names.length]; 2481 // reader 2482 synchronized (mPackages) { 2483 for (int i=names.length-1; i>=0; i--) { 2484 String cur = mSettings.mRenamedPackages.get(names[i]); 2485 out[i] = cur != null ? cur : names[i]; 2486 } 2487 } 2488 return out; 2489 } 2490 2491 @Override 2492 public int getPackageUid(String packageName, int userId) { 2493 if (!sUserManager.exists(userId)) return -1; 2494 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2495 2496 // reader 2497 synchronized (mPackages) { 2498 PackageParser.Package p = mPackages.get(packageName); 2499 if(p != null) { 2500 return UserHandle.getUid(userId, p.applicationInfo.uid); 2501 } 2502 PackageSetting ps = mSettings.mPackages.get(packageName); 2503 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2504 return -1; 2505 } 2506 p = ps.pkg; 2507 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2508 } 2509 } 2510 2511 @Override 2512 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2513 if (!sUserManager.exists(userId)) { 2514 return null; 2515 } 2516 2517 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2518 "getPackageGids"); 2519 2520 // reader 2521 synchronized (mPackages) { 2522 PackageParser.Package p = mPackages.get(packageName); 2523 if (DEBUG_PACKAGE_INFO) { 2524 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2525 } 2526 if (p != null) { 2527 PackageSetting ps = (PackageSetting) p.mExtras; 2528 return ps.getPermissionsState().computeGids(userId); 2529 } 2530 } 2531 2532 return null; 2533 } 2534 2535 static PermissionInfo generatePermissionInfo( 2536 BasePermission bp, int flags) { 2537 if (bp.perm != null) { 2538 return PackageParser.generatePermissionInfo(bp.perm, flags); 2539 } 2540 PermissionInfo pi = new PermissionInfo(); 2541 pi.name = bp.name; 2542 pi.packageName = bp.sourcePackage; 2543 pi.nonLocalizedLabel = bp.name; 2544 pi.protectionLevel = bp.protectionLevel; 2545 return pi; 2546 } 2547 2548 @Override 2549 public PermissionInfo getPermissionInfo(String name, int flags) { 2550 // reader 2551 synchronized (mPackages) { 2552 final BasePermission p = mSettings.mPermissions.get(name); 2553 if (p != null) { 2554 return generatePermissionInfo(p, flags); 2555 } 2556 return null; 2557 } 2558 } 2559 2560 @Override 2561 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2562 // reader 2563 synchronized (mPackages) { 2564 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2565 for (BasePermission p : mSettings.mPermissions.values()) { 2566 if (group == null) { 2567 if (p.perm == null || p.perm.info.group == null) { 2568 out.add(generatePermissionInfo(p, flags)); 2569 } 2570 } else { 2571 if (p.perm != null && group.equals(p.perm.info.group)) { 2572 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2573 } 2574 } 2575 } 2576 2577 if (out.size() > 0) { 2578 return out; 2579 } 2580 return mPermissionGroups.containsKey(group) ? out : null; 2581 } 2582 } 2583 2584 @Override 2585 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2586 // reader 2587 synchronized (mPackages) { 2588 return PackageParser.generatePermissionGroupInfo( 2589 mPermissionGroups.get(name), flags); 2590 } 2591 } 2592 2593 @Override 2594 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2595 // reader 2596 synchronized (mPackages) { 2597 final int N = mPermissionGroups.size(); 2598 ArrayList<PermissionGroupInfo> out 2599 = new ArrayList<PermissionGroupInfo>(N); 2600 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2601 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2602 } 2603 return out; 2604 } 2605 } 2606 2607 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2608 int userId) { 2609 if (!sUserManager.exists(userId)) return null; 2610 PackageSetting ps = mSettings.mPackages.get(packageName); 2611 if (ps != null) { 2612 if (ps.pkg == null) { 2613 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2614 flags, userId); 2615 if (pInfo != null) { 2616 return pInfo.applicationInfo; 2617 } 2618 return null; 2619 } 2620 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2621 ps.readUserState(userId), userId); 2622 } 2623 return null; 2624 } 2625 2626 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2627 int userId) { 2628 if (!sUserManager.exists(userId)) return null; 2629 PackageSetting ps = mSettings.mPackages.get(packageName); 2630 if (ps != null) { 2631 PackageParser.Package pkg = ps.pkg; 2632 if (pkg == null) { 2633 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2634 return null; 2635 } 2636 // Only data remains, so we aren't worried about code paths 2637 pkg = new PackageParser.Package(packageName); 2638 pkg.applicationInfo.packageName = packageName; 2639 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2640 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2641 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2642 packageName, userId).getAbsolutePath(); 2643 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2644 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2645 } 2646 return generatePackageInfo(pkg, flags, userId); 2647 } 2648 return null; 2649 } 2650 2651 @Override 2652 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2653 if (!sUserManager.exists(userId)) return null; 2654 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2655 // writer 2656 synchronized (mPackages) { 2657 PackageParser.Package p = mPackages.get(packageName); 2658 if (DEBUG_PACKAGE_INFO) Log.v( 2659 TAG, "getApplicationInfo " + packageName 2660 + ": " + p); 2661 if (p != null) { 2662 PackageSetting ps = mSettings.mPackages.get(packageName); 2663 if (ps == null) return null; 2664 // Note: isEnabledLP() does not apply here - always return info 2665 return PackageParser.generateApplicationInfo( 2666 p, flags, ps.readUserState(userId), userId); 2667 } 2668 if ("android".equals(packageName)||"system".equals(packageName)) { 2669 return mAndroidApplication; 2670 } 2671 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2672 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2673 } 2674 } 2675 return null; 2676 } 2677 2678 @Override 2679 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2680 final IPackageDataObserver observer) { 2681 mContext.enforceCallingOrSelfPermission( 2682 android.Manifest.permission.CLEAR_APP_CACHE, null); 2683 // Queue up an async operation since clearing cache may take a little while. 2684 mHandler.post(new Runnable() { 2685 public void run() { 2686 mHandler.removeCallbacks(this); 2687 int retCode = -1; 2688 synchronized (mInstallLock) { 2689 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2690 if (retCode < 0) { 2691 Slog.w(TAG, "Couldn't clear application caches"); 2692 } 2693 } 2694 if (observer != null) { 2695 try { 2696 observer.onRemoveCompleted(null, (retCode >= 0)); 2697 } catch (RemoteException e) { 2698 Slog.w(TAG, "RemoveException when invoking call back"); 2699 } 2700 } 2701 } 2702 }); 2703 } 2704 2705 @Override 2706 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2707 final IntentSender pi) { 2708 mContext.enforceCallingOrSelfPermission( 2709 android.Manifest.permission.CLEAR_APP_CACHE, null); 2710 // Queue up an async operation since clearing cache may take a little while. 2711 mHandler.post(new Runnable() { 2712 public void run() { 2713 mHandler.removeCallbacks(this); 2714 int retCode = -1; 2715 synchronized (mInstallLock) { 2716 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2717 if (retCode < 0) { 2718 Slog.w(TAG, "Couldn't clear application caches"); 2719 } 2720 } 2721 if(pi != null) { 2722 try { 2723 // Callback via pending intent 2724 int code = (retCode >= 0) ? 1 : 0; 2725 pi.sendIntent(null, code, null, 2726 null, null); 2727 } catch (SendIntentException e1) { 2728 Slog.i(TAG, "Failed to send pending intent"); 2729 } 2730 } 2731 } 2732 }); 2733 } 2734 2735 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2736 synchronized (mInstallLock) { 2737 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2738 throw new IOException("Failed to free enough space"); 2739 } 2740 } 2741 } 2742 2743 @Override 2744 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2745 if (!sUserManager.exists(userId)) return null; 2746 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2747 synchronized (mPackages) { 2748 PackageParser.Activity a = mActivities.mActivities.get(component); 2749 2750 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2751 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2752 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2753 if (ps == null) return null; 2754 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2755 userId); 2756 } 2757 if (mResolveComponentName.equals(component)) { 2758 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2759 new PackageUserState(), userId); 2760 } 2761 } 2762 return null; 2763 } 2764 2765 @Override 2766 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2767 String resolvedType) { 2768 synchronized (mPackages) { 2769 PackageParser.Activity a = mActivities.mActivities.get(component); 2770 if (a == null) { 2771 return false; 2772 } 2773 for (int i=0; i<a.intents.size(); i++) { 2774 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2775 intent.getData(), intent.getCategories(), TAG) >= 0) { 2776 return true; 2777 } 2778 } 2779 return false; 2780 } 2781 } 2782 2783 @Override 2784 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2785 if (!sUserManager.exists(userId)) return null; 2786 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2787 synchronized (mPackages) { 2788 PackageParser.Activity a = mReceivers.mActivities.get(component); 2789 if (DEBUG_PACKAGE_INFO) Log.v( 2790 TAG, "getReceiverInfo " + component + ": " + a); 2791 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2792 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2793 if (ps == null) return null; 2794 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2795 userId); 2796 } 2797 } 2798 return null; 2799 } 2800 2801 @Override 2802 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2803 if (!sUserManager.exists(userId)) return null; 2804 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2805 synchronized (mPackages) { 2806 PackageParser.Service s = mServices.mServices.get(component); 2807 if (DEBUG_PACKAGE_INFO) Log.v( 2808 TAG, "getServiceInfo " + component + ": " + s); 2809 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2810 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2811 if (ps == null) return null; 2812 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2813 userId); 2814 } 2815 } 2816 return null; 2817 } 2818 2819 @Override 2820 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2821 if (!sUserManager.exists(userId)) return null; 2822 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2823 synchronized (mPackages) { 2824 PackageParser.Provider p = mProviders.mProviders.get(component); 2825 if (DEBUG_PACKAGE_INFO) Log.v( 2826 TAG, "getProviderInfo " + component + ": " + p); 2827 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2828 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2829 if (ps == null) return null; 2830 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2831 userId); 2832 } 2833 } 2834 return null; 2835 } 2836 2837 @Override 2838 public String[] getSystemSharedLibraryNames() { 2839 Set<String> libSet; 2840 synchronized (mPackages) { 2841 libSet = mSharedLibraries.keySet(); 2842 int size = libSet.size(); 2843 if (size > 0) { 2844 String[] libs = new String[size]; 2845 libSet.toArray(libs); 2846 return libs; 2847 } 2848 } 2849 return null; 2850 } 2851 2852 /** 2853 * @hide 2854 */ 2855 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2856 synchronized (mPackages) { 2857 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2858 if (lib != null && lib.apk != null) { 2859 return mPackages.get(lib.apk); 2860 } 2861 } 2862 return null; 2863 } 2864 2865 @Override 2866 public FeatureInfo[] getSystemAvailableFeatures() { 2867 Collection<FeatureInfo> featSet; 2868 synchronized (mPackages) { 2869 featSet = mAvailableFeatures.values(); 2870 int size = featSet.size(); 2871 if (size > 0) { 2872 FeatureInfo[] features = new FeatureInfo[size+1]; 2873 featSet.toArray(features); 2874 FeatureInfo fi = new FeatureInfo(); 2875 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2876 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2877 features[size] = fi; 2878 return features; 2879 } 2880 } 2881 return null; 2882 } 2883 2884 @Override 2885 public boolean hasSystemFeature(String name) { 2886 synchronized (mPackages) { 2887 return mAvailableFeatures.containsKey(name); 2888 } 2889 } 2890 2891 private void checkValidCaller(int uid, int userId) { 2892 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2893 return; 2894 2895 throw new SecurityException("Caller uid=" + uid 2896 + " is not privileged to communicate with user=" + userId); 2897 } 2898 2899 @Override 2900 public int checkPermission(String permName, String pkgName, int userId) { 2901 if (!sUserManager.exists(userId)) { 2902 return PackageManager.PERMISSION_DENIED; 2903 } 2904 2905 synchronized (mPackages) { 2906 final PackageParser.Package p = mPackages.get(pkgName); 2907 if (p != null && p.mExtras != null) { 2908 final PackageSetting ps = (PackageSetting) p.mExtras; 2909 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2910 return PackageManager.PERMISSION_GRANTED; 2911 } 2912 } 2913 } 2914 2915 return PackageManager.PERMISSION_DENIED; 2916 } 2917 2918 @Override 2919 public int checkUidPermission(String permName, int uid) { 2920 final int userId = UserHandle.getUserId(uid); 2921 2922 if (!sUserManager.exists(userId)) { 2923 return PackageManager.PERMISSION_DENIED; 2924 } 2925 2926 synchronized (mPackages) { 2927 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2928 if (obj != null) { 2929 final SettingBase ps = (SettingBase) obj; 2930 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2931 return PackageManager.PERMISSION_GRANTED; 2932 } 2933 } else { 2934 ArraySet<String> perms = mSystemPermissions.get(uid); 2935 if (perms != null && perms.contains(permName)) { 2936 return PackageManager.PERMISSION_GRANTED; 2937 } 2938 } 2939 } 2940 2941 return PackageManager.PERMISSION_DENIED; 2942 } 2943 2944 /** 2945 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2946 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2947 * @param checkShell TODO(yamasani): 2948 * @param message the message to log on security exception 2949 */ 2950 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2951 boolean checkShell, String message) { 2952 if (userId < 0) { 2953 throw new IllegalArgumentException("Invalid userId " + userId); 2954 } 2955 if (checkShell) { 2956 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2957 } 2958 if (userId == UserHandle.getUserId(callingUid)) return; 2959 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2960 if (requireFullPermission) { 2961 mContext.enforceCallingOrSelfPermission( 2962 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2963 } else { 2964 try { 2965 mContext.enforceCallingOrSelfPermission( 2966 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2967 } catch (SecurityException se) { 2968 mContext.enforceCallingOrSelfPermission( 2969 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2970 } 2971 } 2972 } 2973 } 2974 2975 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2976 if (callingUid == Process.SHELL_UID) { 2977 if (userHandle >= 0 2978 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2979 throw new SecurityException("Shell does not have permission to access user " 2980 + userHandle); 2981 } else if (userHandle < 0) { 2982 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2983 + Debug.getCallers(3)); 2984 } 2985 } 2986 } 2987 2988 private BasePermission findPermissionTreeLP(String permName) { 2989 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2990 if (permName.startsWith(bp.name) && 2991 permName.length() > bp.name.length() && 2992 permName.charAt(bp.name.length()) == '.') { 2993 return bp; 2994 } 2995 } 2996 return null; 2997 } 2998 2999 private BasePermission checkPermissionTreeLP(String permName) { 3000 if (permName != null) { 3001 BasePermission bp = findPermissionTreeLP(permName); 3002 if (bp != null) { 3003 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3004 return bp; 3005 } 3006 throw new SecurityException("Calling uid " 3007 + Binder.getCallingUid() 3008 + " is not allowed to add to permission tree " 3009 + bp.name + " owned by uid " + bp.uid); 3010 } 3011 } 3012 throw new SecurityException("No permission tree found for " + permName); 3013 } 3014 3015 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3016 if (s1 == null) { 3017 return s2 == null; 3018 } 3019 if (s2 == null) { 3020 return false; 3021 } 3022 if (s1.getClass() != s2.getClass()) { 3023 return false; 3024 } 3025 return s1.equals(s2); 3026 } 3027 3028 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3029 if (pi1.icon != pi2.icon) return false; 3030 if (pi1.logo != pi2.logo) return false; 3031 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3032 if (!compareStrings(pi1.name, pi2.name)) return false; 3033 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3034 // We'll take care of setting this one. 3035 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3036 // These are not currently stored in settings. 3037 //if (!compareStrings(pi1.group, pi2.group)) return false; 3038 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3039 //if (pi1.labelRes != pi2.labelRes) return false; 3040 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3041 return true; 3042 } 3043 3044 int permissionInfoFootprint(PermissionInfo info) { 3045 int size = info.name.length(); 3046 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3047 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3048 return size; 3049 } 3050 3051 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3052 int size = 0; 3053 for (BasePermission perm : mSettings.mPermissions.values()) { 3054 if (perm.uid == tree.uid) { 3055 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3056 } 3057 } 3058 return size; 3059 } 3060 3061 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3062 // We calculate the max size of permissions defined by this uid and throw 3063 // if that plus the size of 'info' would exceed our stated maximum. 3064 if (tree.uid != Process.SYSTEM_UID) { 3065 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3066 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3067 throw new SecurityException("Permission tree size cap exceeded"); 3068 } 3069 } 3070 } 3071 3072 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3073 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3074 throw new SecurityException("Label must be specified in permission"); 3075 } 3076 BasePermission tree = checkPermissionTreeLP(info.name); 3077 BasePermission bp = mSettings.mPermissions.get(info.name); 3078 boolean added = bp == null; 3079 boolean changed = true; 3080 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3081 if (added) { 3082 enforcePermissionCapLocked(info, tree); 3083 bp = new BasePermission(info.name, tree.sourcePackage, 3084 BasePermission.TYPE_DYNAMIC); 3085 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3086 throw new SecurityException( 3087 "Not allowed to modify non-dynamic permission " 3088 + info.name); 3089 } else { 3090 if (bp.protectionLevel == fixedLevel 3091 && bp.perm.owner.equals(tree.perm.owner) 3092 && bp.uid == tree.uid 3093 && comparePermissionInfos(bp.perm.info, info)) { 3094 changed = false; 3095 } 3096 } 3097 bp.protectionLevel = fixedLevel; 3098 info = new PermissionInfo(info); 3099 info.protectionLevel = fixedLevel; 3100 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3101 bp.perm.info.packageName = tree.perm.info.packageName; 3102 bp.uid = tree.uid; 3103 if (added) { 3104 mSettings.mPermissions.put(info.name, bp); 3105 } 3106 if (changed) { 3107 if (!async) { 3108 mSettings.writeLPr(); 3109 } else { 3110 scheduleWriteSettingsLocked(); 3111 } 3112 } 3113 return added; 3114 } 3115 3116 @Override 3117 public boolean addPermission(PermissionInfo info) { 3118 synchronized (mPackages) { 3119 return addPermissionLocked(info, false); 3120 } 3121 } 3122 3123 @Override 3124 public boolean addPermissionAsync(PermissionInfo info) { 3125 synchronized (mPackages) { 3126 return addPermissionLocked(info, true); 3127 } 3128 } 3129 3130 @Override 3131 public void removePermission(String name) { 3132 synchronized (mPackages) { 3133 checkPermissionTreeLP(name); 3134 BasePermission bp = mSettings.mPermissions.get(name); 3135 if (bp != null) { 3136 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3137 throw new SecurityException( 3138 "Not allowed to modify non-dynamic permission " 3139 + name); 3140 } 3141 mSettings.mPermissions.remove(name); 3142 mSettings.writeLPr(); 3143 } 3144 } 3145 } 3146 3147 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3148 BasePermission bp) { 3149 int index = pkg.requestedPermissions.indexOf(bp.name); 3150 if (index == -1) { 3151 throw new SecurityException("Package " + pkg.packageName 3152 + " has not requested permission " + bp.name); 3153 } 3154 if (!bp.isRuntime()) { 3155 throw new SecurityException("Permission " + bp.name 3156 + " is not a changeable permission type"); 3157 } 3158 } 3159 3160 @Override 3161 public void grantRuntimePermission(String packageName, String name, final int userId) { 3162 if (!sUserManager.exists(userId)) { 3163 Log.e(TAG, "No such user:" + userId); 3164 return; 3165 } 3166 3167 mContext.enforceCallingOrSelfPermission( 3168 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3169 "grantRuntimePermission"); 3170 3171 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3172 "grantRuntimePermission"); 3173 3174 final SettingBase sb; 3175 3176 synchronized (mPackages) { 3177 final PackageParser.Package pkg = mPackages.get(packageName); 3178 if (pkg == null) { 3179 throw new IllegalArgumentException("Unknown package: " + packageName); 3180 } 3181 3182 final BasePermission bp = mSettings.mPermissions.get(name); 3183 if (bp == null) { 3184 throw new IllegalArgumentException("Unknown permission: " + name); 3185 } 3186 3187 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3188 3189 sb = (SettingBase) pkg.mExtras; 3190 if (sb == null) { 3191 throw new IllegalArgumentException("Unknown package: " + packageName); 3192 } 3193 3194 final PermissionsState permissionsState = sb.getPermissionsState(); 3195 3196 final int flags = permissionsState.getPermissionFlags(name, userId); 3197 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3198 throw new SecurityException("Cannot grant system fixed permission: " 3199 + name + " for package: " + packageName); 3200 } 3201 3202 final int result = permissionsState.grantRuntimePermission(bp, userId); 3203 switch (result) { 3204 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3205 return; 3206 } 3207 3208 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3209 mHandler.post(new Runnable() { 3210 @Override 3211 public void run() { 3212 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3213 } 3214 }); 3215 } break; 3216 } 3217 3218 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3219 3220 // Not critical if that is lost - app has to request again. 3221 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3222 } 3223 } 3224 3225 @Override 3226 public void revokeRuntimePermission(String packageName, String name, int userId) { 3227 if (!sUserManager.exists(userId)) { 3228 Log.e(TAG, "No such user:" + userId); 3229 return; 3230 } 3231 3232 mContext.enforceCallingOrSelfPermission( 3233 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3234 "revokeRuntimePermission"); 3235 3236 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3237 "revokeRuntimePermission"); 3238 3239 final SettingBase sb; 3240 3241 synchronized (mPackages) { 3242 final PackageParser.Package pkg = mPackages.get(packageName); 3243 if (pkg == null) { 3244 throw new IllegalArgumentException("Unknown package: " + packageName); 3245 } 3246 3247 final BasePermission bp = mSettings.mPermissions.get(name); 3248 if (bp == null) { 3249 throw new IllegalArgumentException("Unknown permission: " + name); 3250 } 3251 3252 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3253 3254 sb = (SettingBase) pkg.mExtras; 3255 if (sb == null) { 3256 throw new IllegalArgumentException("Unknown package: " + packageName); 3257 } 3258 3259 final PermissionsState permissionsState = sb.getPermissionsState(); 3260 3261 final int flags = permissionsState.getPermissionFlags(name, userId); 3262 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3263 throw new SecurityException("Cannot revoke system fixed permission: " 3264 + name + " for package: " + packageName); 3265 } 3266 3267 if (permissionsState.revokeRuntimePermission(bp, userId) == 3268 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3269 return; 3270 } 3271 3272 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3273 3274 // Critical, after this call app should never have the permission. 3275 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3276 } 3277 3278 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3279 } 3280 3281 @Override 3282 public int getPermissionFlags(String name, String packageName, int userId) { 3283 if (!sUserManager.exists(userId)) { 3284 return 0; 3285 } 3286 3287 mContext.enforceCallingOrSelfPermission( 3288 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3289 "getPermissionFlags"); 3290 3291 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3292 "getPermissionFlags"); 3293 3294 synchronized (mPackages) { 3295 final PackageParser.Package pkg = mPackages.get(packageName); 3296 if (pkg == null) { 3297 throw new IllegalArgumentException("Unknown package: " + packageName); 3298 } 3299 3300 final BasePermission bp = mSettings.mPermissions.get(name); 3301 if (bp == null) { 3302 throw new IllegalArgumentException("Unknown permission: " + name); 3303 } 3304 3305 SettingBase sb = (SettingBase) pkg.mExtras; 3306 if (sb == null) { 3307 throw new IllegalArgumentException("Unknown package: " + packageName); 3308 } 3309 3310 PermissionsState permissionsState = sb.getPermissionsState(); 3311 return permissionsState.getPermissionFlags(name, userId); 3312 } 3313 } 3314 3315 @Override 3316 public void updatePermissionFlags(String name, String packageName, int flagMask, 3317 int flagValues, int userId) { 3318 if (!sUserManager.exists(userId)) { 3319 return; 3320 } 3321 3322 mContext.enforceCallingOrSelfPermission( 3323 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3324 "updatePermissionFlags"); 3325 3326 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3327 "updatePermissionFlags"); 3328 3329 // Only the system can change policy and system fixed flags. 3330 if (getCallingUid() != Process.SYSTEM_UID) { 3331 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3332 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3333 3334 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3335 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3336 } 3337 3338 synchronized (mPackages) { 3339 final PackageParser.Package pkg = mPackages.get(packageName); 3340 if (pkg == null) { 3341 throw new IllegalArgumentException("Unknown package: " + packageName); 3342 } 3343 3344 final BasePermission bp = mSettings.mPermissions.get(name); 3345 if (bp == null) { 3346 throw new IllegalArgumentException("Unknown permission: " + name); 3347 } 3348 3349 SettingBase sb = (SettingBase) pkg.mExtras; 3350 if (sb == null) { 3351 throw new IllegalArgumentException("Unknown package: " + packageName); 3352 } 3353 3354 PermissionsState permissionsState = sb.getPermissionsState(); 3355 3356 // Only the package manager can change flags for system component permissions. 3357 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3358 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3359 return; 3360 } 3361 3362 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3363 // Install and runtime permissions are stored in different places, 3364 // so figure out what permission changed and persist the change. 3365 if (permissionsState.getInstallPermissionState(name) != null) { 3366 scheduleWriteSettingsLocked(); 3367 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3368 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3369 } 3370 } 3371 } 3372 } 3373 3374 @Override 3375 public boolean shouldShowRequestPermissionRationale(String permissionName, 3376 String packageName, int userId) { 3377 if (UserHandle.getCallingUserId() != userId) { 3378 mContext.enforceCallingPermission( 3379 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3380 "canShowRequestPermissionRationale for user " + userId); 3381 } 3382 3383 final int uid = getPackageUid(packageName, userId); 3384 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3385 return false; 3386 } 3387 3388 if (checkPermission(permissionName, packageName, userId) 3389 == PackageManager.PERMISSION_GRANTED) { 3390 return false; 3391 } 3392 3393 final int flags; 3394 3395 final long identity = Binder.clearCallingIdentity(); 3396 try { 3397 flags = getPermissionFlags(permissionName, 3398 packageName, userId); 3399 } finally { 3400 Binder.restoreCallingIdentity(identity); 3401 } 3402 3403 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3404 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3405 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3406 3407 if ((flags & fixedFlags) != 0) { 3408 return false; 3409 } 3410 3411 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3412 } 3413 3414 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3415 BasePermission bp = mSettings.mPermissions.get(permission); 3416 if (bp == null) { 3417 throw new SecurityException("Missing " + permission + " permission"); 3418 } 3419 3420 SettingBase sb = (SettingBase) pkg.mExtras; 3421 PermissionsState permissionsState = sb.getPermissionsState(); 3422 3423 if (permissionsState.grantInstallPermission(bp) != 3424 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3425 scheduleWriteSettingsLocked(); 3426 } 3427 } 3428 3429 @Override 3430 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3431 mContext.enforceCallingOrSelfPermission( 3432 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3433 "addOnPermissionsChangeListener"); 3434 3435 synchronized (mPackages) { 3436 mOnPermissionChangeListeners.addListenerLocked(listener); 3437 } 3438 } 3439 3440 @Override 3441 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3442 synchronized (mPackages) { 3443 mOnPermissionChangeListeners.removeListenerLocked(listener); 3444 } 3445 } 3446 3447 @Override 3448 public boolean isProtectedBroadcast(String actionName) { 3449 synchronized (mPackages) { 3450 return mProtectedBroadcasts.contains(actionName); 3451 } 3452 } 3453 3454 @Override 3455 public int checkSignatures(String pkg1, String pkg2) { 3456 synchronized (mPackages) { 3457 final PackageParser.Package p1 = mPackages.get(pkg1); 3458 final PackageParser.Package p2 = mPackages.get(pkg2); 3459 if (p1 == null || p1.mExtras == null 3460 || p2 == null || p2.mExtras == null) { 3461 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3462 } 3463 return compareSignatures(p1.mSignatures, p2.mSignatures); 3464 } 3465 } 3466 3467 @Override 3468 public int checkUidSignatures(int uid1, int uid2) { 3469 // Map to base uids. 3470 uid1 = UserHandle.getAppId(uid1); 3471 uid2 = UserHandle.getAppId(uid2); 3472 // reader 3473 synchronized (mPackages) { 3474 Signature[] s1; 3475 Signature[] s2; 3476 Object obj = mSettings.getUserIdLPr(uid1); 3477 if (obj != null) { 3478 if (obj instanceof SharedUserSetting) { 3479 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3480 } else if (obj instanceof PackageSetting) { 3481 s1 = ((PackageSetting)obj).signatures.mSignatures; 3482 } else { 3483 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3484 } 3485 } else { 3486 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3487 } 3488 obj = mSettings.getUserIdLPr(uid2); 3489 if (obj != null) { 3490 if (obj instanceof SharedUserSetting) { 3491 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3492 } else if (obj instanceof PackageSetting) { 3493 s2 = ((PackageSetting)obj).signatures.mSignatures; 3494 } else { 3495 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3496 } 3497 } else { 3498 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3499 } 3500 return compareSignatures(s1, s2); 3501 } 3502 } 3503 3504 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3505 final long identity = Binder.clearCallingIdentity(); 3506 try { 3507 if (sb instanceof SharedUserSetting) { 3508 SharedUserSetting sus = (SharedUserSetting) sb; 3509 final int packageCount = sus.packages.size(); 3510 for (int i = 0; i < packageCount; i++) { 3511 PackageSetting susPs = sus.packages.valueAt(i); 3512 if (userId == UserHandle.USER_ALL) { 3513 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3514 } else { 3515 final int uid = UserHandle.getUid(userId, susPs.appId); 3516 killUid(uid, reason); 3517 } 3518 } 3519 } else if (sb instanceof PackageSetting) { 3520 PackageSetting ps = (PackageSetting) sb; 3521 if (userId == UserHandle.USER_ALL) { 3522 killApplication(ps.pkg.packageName, ps.appId, reason); 3523 } else { 3524 final int uid = UserHandle.getUid(userId, ps.appId); 3525 killUid(uid, reason); 3526 } 3527 } 3528 } finally { 3529 Binder.restoreCallingIdentity(identity); 3530 } 3531 } 3532 3533 private static void killUid(int uid, String reason) { 3534 IActivityManager am = ActivityManagerNative.getDefault(); 3535 if (am != null) { 3536 try { 3537 am.killUid(uid, reason); 3538 } catch (RemoteException e) { 3539 /* ignore - same process */ 3540 } 3541 } 3542 } 3543 3544 /** 3545 * Compares two sets of signatures. Returns: 3546 * <br /> 3547 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3548 * <br /> 3549 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3550 * <br /> 3551 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3552 * <br /> 3553 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3554 * <br /> 3555 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3556 */ 3557 static int compareSignatures(Signature[] s1, Signature[] s2) { 3558 if (s1 == null) { 3559 return s2 == null 3560 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3561 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3562 } 3563 3564 if (s2 == null) { 3565 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3566 } 3567 3568 if (s1.length != s2.length) { 3569 return PackageManager.SIGNATURE_NO_MATCH; 3570 } 3571 3572 // Since both signature sets are of size 1, we can compare without HashSets. 3573 if (s1.length == 1) { 3574 return s1[0].equals(s2[0]) ? 3575 PackageManager.SIGNATURE_MATCH : 3576 PackageManager.SIGNATURE_NO_MATCH; 3577 } 3578 3579 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3580 for (Signature sig : s1) { 3581 set1.add(sig); 3582 } 3583 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3584 for (Signature sig : s2) { 3585 set2.add(sig); 3586 } 3587 // Make sure s2 contains all signatures in s1. 3588 if (set1.equals(set2)) { 3589 return PackageManager.SIGNATURE_MATCH; 3590 } 3591 return PackageManager.SIGNATURE_NO_MATCH; 3592 } 3593 3594 /** 3595 * If the database version for this type of package (internal storage or 3596 * external storage) is less than the version where package signatures 3597 * were updated, return true. 3598 */ 3599 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3600 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3601 DatabaseVersion.SIGNATURE_END_ENTITY)) 3602 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3603 DatabaseVersion.SIGNATURE_END_ENTITY)); 3604 } 3605 3606 /** 3607 * Used for backward compatibility to make sure any packages with 3608 * certificate chains get upgraded to the new style. {@code existingSigs} 3609 * will be in the old format (since they were stored on disk from before the 3610 * system upgrade) and {@code scannedSigs} will be in the newer format. 3611 */ 3612 private int compareSignaturesCompat(PackageSignatures existingSigs, 3613 PackageParser.Package scannedPkg) { 3614 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3615 return PackageManager.SIGNATURE_NO_MATCH; 3616 } 3617 3618 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3619 for (Signature sig : existingSigs.mSignatures) { 3620 existingSet.add(sig); 3621 } 3622 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3623 for (Signature sig : scannedPkg.mSignatures) { 3624 try { 3625 Signature[] chainSignatures = sig.getChainSignatures(); 3626 for (Signature chainSig : chainSignatures) { 3627 scannedCompatSet.add(chainSig); 3628 } 3629 } catch (CertificateEncodingException e) { 3630 scannedCompatSet.add(sig); 3631 } 3632 } 3633 /* 3634 * Make sure the expanded scanned set contains all signatures in the 3635 * existing one. 3636 */ 3637 if (scannedCompatSet.equals(existingSet)) { 3638 // Migrate the old signatures to the new scheme. 3639 existingSigs.assignSignatures(scannedPkg.mSignatures); 3640 // The new KeySets will be re-added later in the scanning process. 3641 synchronized (mPackages) { 3642 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3643 } 3644 return PackageManager.SIGNATURE_MATCH; 3645 } 3646 return PackageManager.SIGNATURE_NO_MATCH; 3647 } 3648 3649 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3650 if (isExternal(scannedPkg)) { 3651 return mSettings.isExternalDatabaseVersionOlderThan( 3652 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3653 } else { 3654 return mSettings.isInternalDatabaseVersionOlderThan( 3655 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3656 } 3657 } 3658 3659 private int compareSignaturesRecover(PackageSignatures existingSigs, 3660 PackageParser.Package scannedPkg) { 3661 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3662 return PackageManager.SIGNATURE_NO_MATCH; 3663 } 3664 3665 String msg = null; 3666 try { 3667 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3668 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3669 + scannedPkg.packageName); 3670 return PackageManager.SIGNATURE_MATCH; 3671 } 3672 } catch (CertificateException e) { 3673 msg = e.getMessage(); 3674 } 3675 3676 logCriticalInfo(Log.INFO, 3677 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3678 return PackageManager.SIGNATURE_NO_MATCH; 3679 } 3680 3681 @Override 3682 public String[] getPackagesForUid(int uid) { 3683 uid = UserHandle.getAppId(uid); 3684 // reader 3685 synchronized (mPackages) { 3686 Object obj = mSettings.getUserIdLPr(uid); 3687 if (obj instanceof SharedUserSetting) { 3688 final SharedUserSetting sus = (SharedUserSetting) obj; 3689 final int N = sus.packages.size(); 3690 final String[] res = new String[N]; 3691 final Iterator<PackageSetting> it = sus.packages.iterator(); 3692 int i = 0; 3693 while (it.hasNext()) { 3694 res[i++] = it.next().name; 3695 } 3696 return res; 3697 } else if (obj instanceof PackageSetting) { 3698 final PackageSetting ps = (PackageSetting) obj; 3699 return new String[] { ps.name }; 3700 } 3701 } 3702 return null; 3703 } 3704 3705 @Override 3706 public String getNameForUid(int uid) { 3707 // reader 3708 synchronized (mPackages) { 3709 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3710 if (obj instanceof SharedUserSetting) { 3711 final SharedUserSetting sus = (SharedUserSetting) obj; 3712 return sus.name + ":" + sus.userId; 3713 } else if (obj instanceof PackageSetting) { 3714 final PackageSetting ps = (PackageSetting) obj; 3715 return ps.name; 3716 } 3717 } 3718 return null; 3719 } 3720 3721 @Override 3722 public int getUidForSharedUser(String sharedUserName) { 3723 if(sharedUserName == null) { 3724 return -1; 3725 } 3726 // reader 3727 synchronized (mPackages) { 3728 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3729 if (suid == null) { 3730 return -1; 3731 } 3732 return suid.userId; 3733 } 3734 } 3735 3736 @Override 3737 public int getFlagsForUid(int uid) { 3738 synchronized (mPackages) { 3739 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3740 if (obj instanceof SharedUserSetting) { 3741 final SharedUserSetting sus = (SharedUserSetting) obj; 3742 return sus.pkgFlags; 3743 } else if (obj instanceof PackageSetting) { 3744 final PackageSetting ps = (PackageSetting) obj; 3745 return ps.pkgFlags; 3746 } 3747 } 3748 return 0; 3749 } 3750 3751 @Override 3752 public int getPrivateFlagsForUid(int uid) { 3753 synchronized (mPackages) { 3754 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3755 if (obj instanceof SharedUserSetting) { 3756 final SharedUserSetting sus = (SharedUserSetting) obj; 3757 return sus.pkgPrivateFlags; 3758 } else if (obj instanceof PackageSetting) { 3759 final PackageSetting ps = (PackageSetting) obj; 3760 return ps.pkgPrivateFlags; 3761 } 3762 } 3763 return 0; 3764 } 3765 3766 @Override 3767 public boolean isUidPrivileged(int uid) { 3768 uid = UserHandle.getAppId(uid); 3769 // reader 3770 synchronized (mPackages) { 3771 Object obj = mSettings.getUserIdLPr(uid); 3772 if (obj instanceof SharedUserSetting) { 3773 final SharedUserSetting sus = (SharedUserSetting) obj; 3774 final Iterator<PackageSetting> it = sus.packages.iterator(); 3775 while (it.hasNext()) { 3776 if (it.next().isPrivileged()) { 3777 return true; 3778 } 3779 } 3780 } else if (obj instanceof PackageSetting) { 3781 final PackageSetting ps = (PackageSetting) obj; 3782 return ps.isPrivileged(); 3783 } 3784 } 3785 return false; 3786 } 3787 3788 @Override 3789 public String[] getAppOpPermissionPackages(String permissionName) { 3790 synchronized (mPackages) { 3791 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3792 if (pkgs == null) { 3793 return null; 3794 } 3795 return pkgs.toArray(new String[pkgs.size()]); 3796 } 3797 } 3798 3799 @Override 3800 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3801 int flags, int userId) { 3802 if (!sUserManager.exists(userId)) return null; 3803 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3804 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3805 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3806 } 3807 3808 @Override 3809 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3810 IntentFilter filter, int match, ComponentName activity) { 3811 final int userId = UserHandle.getCallingUserId(); 3812 if (DEBUG_PREFERRED) { 3813 Log.v(TAG, "setLastChosenActivity intent=" + intent 3814 + " resolvedType=" + resolvedType 3815 + " flags=" + flags 3816 + " filter=" + filter 3817 + " match=" + match 3818 + " activity=" + activity); 3819 filter.dump(new PrintStreamPrinter(System.out), " "); 3820 } 3821 intent.setComponent(null); 3822 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3823 // Find any earlier preferred or last chosen entries and nuke them 3824 findPreferredActivity(intent, resolvedType, 3825 flags, query, 0, false, true, false, userId); 3826 // Add the new activity as the last chosen for this filter 3827 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3828 "Setting last chosen"); 3829 } 3830 3831 @Override 3832 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3833 final int userId = UserHandle.getCallingUserId(); 3834 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3835 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3836 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3837 false, false, false, userId); 3838 } 3839 3840 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3841 int flags, List<ResolveInfo> query, int userId) { 3842 if (query != null) { 3843 final int N = query.size(); 3844 if (N == 1) { 3845 return query.get(0); 3846 } else if (N > 1) { 3847 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3848 // If there is more than one activity with the same priority, 3849 // then let the user decide between them. 3850 ResolveInfo r0 = query.get(0); 3851 ResolveInfo r1 = query.get(1); 3852 if (DEBUG_INTENT_MATCHING || debug) { 3853 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3854 + r1.activityInfo.name + "=" + r1.priority); 3855 } 3856 // If the first activity has a higher priority, or a different 3857 // default, then it is always desireable to pick it. 3858 if (r0.priority != r1.priority 3859 || r0.preferredOrder != r1.preferredOrder 3860 || r0.isDefault != r1.isDefault) { 3861 return query.get(0); 3862 } 3863 // If we have saved a preference for a preferred activity for 3864 // this Intent, use that. 3865 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3866 flags, query, r0.priority, true, false, debug, userId); 3867 if (ri != null) { 3868 return ri; 3869 } 3870 if (userId != 0) { 3871 ri = new ResolveInfo(mResolveInfo); 3872 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3873 ri.activityInfo.applicationInfo = new ApplicationInfo( 3874 ri.activityInfo.applicationInfo); 3875 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3876 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3877 return ri; 3878 } 3879 return mResolveInfo; 3880 } 3881 } 3882 return null; 3883 } 3884 3885 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3886 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3887 final int N = query.size(); 3888 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3889 .get(userId); 3890 // Get the list of persistent preferred activities that handle the intent 3891 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3892 List<PersistentPreferredActivity> pprefs = ppir != null 3893 ? ppir.queryIntent(intent, resolvedType, 3894 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3895 : null; 3896 if (pprefs != null && pprefs.size() > 0) { 3897 final int M = pprefs.size(); 3898 for (int i=0; i<M; i++) { 3899 final PersistentPreferredActivity ppa = pprefs.get(i); 3900 if (DEBUG_PREFERRED || debug) { 3901 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3902 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3903 + "\n component=" + ppa.mComponent); 3904 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3905 } 3906 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3907 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3908 if (DEBUG_PREFERRED || debug) { 3909 Slog.v(TAG, "Found persistent preferred activity:"); 3910 if (ai != null) { 3911 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3912 } else { 3913 Slog.v(TAG, " null"); 3914 } 3915 } 3916 if (ai == null) { 3917 // This previously registered persistent preferred activity 3918 // component is no longer known. Ignore it and do NOT remove it. 3919 continue; 3920 } 3921 for (int j=0; j<N; j++) { 3922 final ResolveInfo ri = query.get(j); 3923 if (!ri.activityInfo.applicationInfo.packageName 3924 .equals(ai.applicationInfo.packageName)) { 3925 continue; 3926 } 3927 if (!ri.activityInfo.name.equals(ai.name)) { 3928 continue; 3929 } 3930 // Found a persistent preference that can handle the intent. 3931 if (DEBUG_PREFERRED || debug) { 3932 Slog.v(TAG, "Returning persistent preferred activity: " + 3933 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3934 } 3935 return ri; 3936 } 3937 } 3938 } 3939 return null; 3940 } 3941 3942 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3943 List<ResolveInfo> query, int priority, boolean always, 3944 boolean removeMatches, boolean debug, int userId) { 3945 if (!sUserManager.exists(userId)) return null; 3946 // writer 3947 synchronized (mPackages) { 3948 if (intent.getSelector() != null) { 3949 intent = intent.getSelector(); 3950 } 3951 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3952 3953 // Try to find a matching persistent preferred activity. 3954 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3955 debug, userId); 3956 3957 // If a persistent preferred activity matched, use it. 3958 if (pri != null) { 3959 return pri; 3960 } 3961 3962 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3963 // Get the list of preferred activities that handle the intent 3964 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3965 List<PreferredActivity> prefs = pir != null 3966 ? pir.queryIntent(intent, resolvedType, 3967 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3968 : null; 3969 if (prefs != null && prefs.size() > 0) { 3970 boolean changed = false; 3971 try { 3972 // First figure out how good the original match set is. 3973 // We will only allow preferred activities that came 3974 // from the same match quality. 3975 int match = 0; 3976 3977 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3978 3979 final int N = query.size(); 3980 for (int j=0; j<N; j++) { 3981 final ResolveInfo ri = query.get(j); 3982 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3983 + ": 0x" + Integer.toHexString(match)); 3984 if (ri.match > match) { 3985 match = ri.match; 3986 } 3987 } 3988 3989 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3990 + Integer.toHexString(match)); 3991 3992 match &= IntentFilter.MATCH_CATEGORY_MASK; 3993 final int M = prefs.size(); 3994 for (int i=0; i<M; i++) { 3995 final PreferredActivity pa = prefs.get(i); 3996 if (DEBUG_PREFERRED || debug) { 3997 Slog.v(TAG, "Checking PreferredActivity ds=" 3998 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3999 + "\n component=" + pa.mPref.mComponent); 4000 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4001 } 4002 if (pa.mPref.mMatch != match) { 4003 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4004 + Integer.toHexString(pa.mPref.mMatch)); 4005 continue; 4006 } 4007 // If it's not an "always" type preferred activity and that's what we're 4008 // looking for, skip it. 4009 if (always && !pa.mPref.mAlways) { 4010 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4011 continue; 4012 } 4013 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4014 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4015 if (DEBUG_PREFERRED || debug) { 4016 Slog.v(TAG, "Found preferred activity:"); 4017 if (ai != null) { 4018 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4019 } else { 4020 Slog.v(TAG, " null"); 4021 } 4022 } 4023 if (ai == null) { 4024 // This previously registered preferred activity 4025 // component is no longer known. Most likely an update 4026 // to the app was installed and in the new version this 4027 // component no longer exists. Clean it up by removing 4028 // it from the preferred activities list, and skip it. 4029 Slog.w(TAG, "Removing dangling preferred activity: " 4030 + pa.mPref.mComponent); 4031 pir.removeFilter(pa); 4032 changed = true; 4033 continue; 4034 } 4035 for (int j=0; j<N; j++) { 4036 final ResolveInfo ri = query.get(j); 4037 if (!ri.activityInfo.applicationInfo.packageName 4038 .equals(ai.applicationInfo.packageName)) { 4039 continue; 4040 } 4041 if (!ri.activityInfo.name.equals(ai.name)) { 4042 continue; 4043 } 4044 4045 if (removeMatches) { 4046 pir.removeFilter(pa); 4047 changed = true; 4048 if (DEBUG_PREFERRED) { 4049 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4050 } 4051 break; 4052 } 4053 4054 // Okay we found a previously set preferred or last chosen app. 4055 // If the result set is different from when this 4056 // was created, we need to clear it and re-ask the 4057 // user their preference, if we're looking for an "always" type entry. 4058 if (always && !pa.mPref.sameSet(query)) { 4059 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4060 + intent + " type " + resolvedType); 4061 if (DEBUG_PREFERRED) { 4062 Slog.v(TAG, "Removing preferred activity since set changed " 4063 + pa.mPref.mComponent); 4064 } 4065 pir.removeFilter(pa); 4066 // Re-add the filter as a "last chosen" entry (!always) 4067 PreferredActivity lastChosen = new PreferredActivity( 4068 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4069 pir.addFilter(lastChosen); 4070 changed = true; 4071 return null; 4072 } 4073 4074 // Yay! Either the set matched or we're looking for the last chosen 4075 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4076 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4077 return ri; 4078 } 4079 } 4080 } finally { 4081 if (changed) { 4082 if (DEBUG_PREFERRED) { 4083 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4084 } 4085 scheduleWritePackageRestrictionsLocked(userId); 4086 } 4087 } 4088 } 4089 } 4090 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4091 return null; 4092 } 4093 4094 /* 4095 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4096 */ 4097 @Override 4098 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4099 int targetUserId) { 4100 mContext.enforceCallingOrSelfPermission( 4101 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4102 List<CrossProfileIntentFilter> matches = 4103 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4104 if (matches != null) { 4105 int size = matches.size(); 4106 for (int i = 0; i < size; i++) { 4107 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4108 } 4109 } 4110 return false; 4111 } 4112 4113 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4114 String resolvedType, int userId) { 4115 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4116 if (resolver != null) { 4117 return resolver.queryIntent(intent, resolvedType, false, userId); 4118 } 4119 return null; 4120 } 4121 4122 @Override 4123 public List<ResolveInfo> queryIntentActivities(Intent intent, 4124 String resolvedType, int flags, int userId) { 4125 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4126 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4127 ComponentName comp = intent.getComponent(); 4128 if (comp == null) { 4129 if (intent.getSelector() != null) { 4130 intent = intent.getSelector(); 4131 comp = intent.getComponent(); 4132 } 4133 } 4134 4135 if (comp != null) { 4136 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4137 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4138 if (ai != null) { 4139 final ResolveInfo ri = new ResolveInfo(); 4140 ri.activityInfo = ai; 4141 list.add(ri); 4142 } 4143 return list; 4144 } 4145 4146 // reader 4147 synchronized (mPackages) { 4148 final String pkgName = intent.getPackage(); 4149 if (pkgName == null) { 4150 List<CrossProfileIntentFilter> matchingFilters = 4151 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4152 // Check for results that need to skip the current profile. 4153 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4154 resolvedType, flags, userId); 4155 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4156 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4157 result.add(resolveInfo); 4158 return filterIfNotPrimaryUser(result, userId); 4159 } 4160 4161 // Check for results in the current profile. 4162 List<ResolveInfo> result = mActivities.queryIntent( 4163 intent, resolvedType, flags, userId); 4164 4165 // Check for cross profile results. 4166 resolveInfo = queryCrossProfileIntents( 4167 matchingFilters, intent, resolvedType, flags, userId); 4168 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4169 result.add(resolveInfo); 4170 Collections.sort(result, mResolvePrioritySorter); 4171 } 4172 result = filterIfNotPrimaryUser(result, userId); 4173 if (result.size() > 1 && hasWebURI(intent)) { 4174 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4175 } 4176 return result; 4177 } 4178 final PackageParser.Package pkg = mPackages.get(pkgName); 4179 if (pkg != null) { 4180 return filterIfNotPrimaryUser( 4181 mActivities.queryIntentForPackage( 4182 intent, resolvedType, flags, pkg.activities, userId), 4183 userId); 4184 } 4185 return new ArrayList<ResolveInfo>(); 4186 } 4187 } 4188 4189 private boolean isUserEnabled(int userId) { 4190 long callingId = Binder.clearCallingIdentity(); 4191 try { 4192 UserInfo userInfo = sUserManager.getUserInfo(userId); 4193 return userInfo != null && userInfo.isEnabled(); 4194 } finally { 4195 Binder.restoreCallingIdentity(callingId); 4196 } 4197 } 4198 4199 /** 4200 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4201 * 4202 * @return filtered list 4203 */ 4204 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4205 if (userId == UserHandle.USER_OWNER) { 4206 return resolveInfos; 4207 } 4208 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4209 ResolveInfo info = resolveInfos.get(i); 4210 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4211 resolveInfos.remove(i); 4212 } 4213 } 4214 return resolveInfos; 4215 } 4216 4217 private static boolean hasWebURI(Intent intent) { 4218 if (intent.getData() == null) { 4219 return false; 4220 } 4221 final String scheme = intent.getScheme(); 4222 if (TextUtils.isEmpty(scheme)) { 4223 return false; 4224 } 4225 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4226 } 4227 4228 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4229 int flags, List<ResolveInfo> candidates) { 4230 if (DEBUG_PREFERRED) { 4231 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4232 candidates.size()); 4233 } 4234 4235 final int userId = UserHandle.getCallingUserId(); 4236 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4237 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4238 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4239 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4240 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4241 4242 synchronized (mPackages) { 4243 final int count = candidates.size(); 4244 // First, try to use the domain prefered App. Partition the candidates into four lists: 4245 // one for the final results, one for the "do not use ever", one for "undefined status" 4246 // and finally one for "Browser App type". 4247 for (int n=0; n<count; n++) { 4248 ResolveInfo info = candidates.get(n); 4249 String packageName = info.activityInfo.packageName; 4250 PackageSetting ps = mSettings.mPackages.get(packageName); 4251 if (ps != null) { 4252 // Add to the special match all list (Browser use case) 4253 if (info.handleAllWebDataURI) { 4254 matchAllList.add(info); 4255 continue; 4256 } 4257 // Try to get the status from User settings first 4258 int status = getDomainVerificationStatusLPr(ps, userId); 4259 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4260 alwaysList.add(info); 4261 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4262 neverList.add(info); 4263 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4264 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4265 undefinedList.add(info); 4266 } 4267 } 4268 } 4269 // First try to add the "always" if there is any 4270 if (alwaysList.size() > 0) { 4271 result.addAll(alwaysList); 4272 } else { 4273 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4274 result.addAll(undefinedList); 4275 // Also add Browsers (all of them or only the default one) 4276 if ((flags & MATCH_ALL) != 0) { 4277 result.addAll(matchAllList); 4278 } else { 4279 // Try to add the Default Browser if we can 4280 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4281 UserHandle.myUserId()); 4282 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4283 boolean defaultBrowserFound = false; 4284 final int browserCount = matchAllList.size(); 4285 for (int n=0; n<browserCount; n++) { 4286 ResolveInfo browser = matchAllList.get(n); 4287 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4288 result.add(browser); 4289 defaultBrowserFound = true; 4290 break; 4291 } 4292 } 4293 if (!defaultBrowserFound) { 4294 result.addAll(matchAllList); 4295 } 4296 } else { 4297 result.addAll(matchAllList); 4298 } 4299 } 4300 4301 // If there is nothing selected, add all candidates and remove the ones that the User 4302 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4303 if (result.size() == 0) { 4304 result.addAll(candidates); 4305 result.removeAll(neverList); 4306 } 4307 } 4308 } 4309 if (DEBUG_PREFERRED) { 4310 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4311 result.size()); 4312 } 4313 return result; 4314 } 4315 4316 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4317 int status = ps.getDomainVerificationStatusForUser(userId); 4318 // if none available, get the master status 4319 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4320 if (ps.getIntentFilterVerificationInfo() != null) { 4321 status = ps.getIntentFilterVerificationInfo().getStatus(); 4322 } 4323 } 4324 return status; 4325 } 4326 4327 private ResolveInfo querySkipCurrentProfileIntents( 4328 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4329 int flags, int sourceUserId) { 4330 if (matchingFilters != null) { 4331 int size = matchingFilters.size(); 4332 for (int i = 0; i < size; i ++) { 4333 CrossProfileIntentFilter filter = matchingFilters.get(i); 4334 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4335 // Checking if there are activities in the target user that can handle the 4336 // intent. 4337 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4338 flags, sourceUserId); 4339 if (resolveInfo != null) { 4340 return resolveInfo; 4341 } 4342 } 4343 } 4344 } 4345 return null; 4346 } 4347 4348 // Return matching ResolveInfo if any for skip current profile intent filters. 4349 private ResolveInfo queryCrossProfileIntents( 4350 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4351 int flags, int sourceUserId) { 4352 if (matchingFilters != null) { 4353 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4354 // match the same intent. For performance reasons, it is better not to 4355 // run queryIntent twice for the same userId 4356 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4357 int size = matchingFilters.size(); 4358 for (int i = 0; i < size; i++) { 4359 CrossProfileIntentFilter filter = matchingFilters.get(i); 4360 int targetUserId = filter.getTargetUserId(); 4361 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4362 && !alreadyTriedUserIds.get(targetUserId)) { 4363 // Checking if there are activities in the target user that can handle the 4364 // intent. 4365 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4366 flags, sourceUserId); 4367 if (resolveInfo != null) return resolveInfo; 4368 alreadyTriedUserIds.put(targetUserId, true); 4369 } 4370 } 4371 } 4372 return null; 4373 } 4374 4375 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4376 String resolvedType, int flags, int sourceUserId) { 4377 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4378 resolvedType, flags, filter.getTargetUserId()); 4379 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4380 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4381 } 4382 return null; 4383 } 4384 4385 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4386 int sourceUserId, int targetUserId) { 4387 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4388 String className; 4389 if (targetUserId == UserHandle.USER_OWNER) { 4390 className = FORWARD_INTENT_TO_USER_OWNER; 4391 } else { 4392 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4393 } 4394 ComponentName forwardingActivityComponentName = new ComponentName( 4395 mAndroidApplication.packageName, className); 4396 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4397 sourceUserId); 4398 if (targetUserId == UserHandle.USER_OWNER) { 4399 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4400 forwardingResolveInfo.noResourceId = true; 4401 } 4402 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4403 forwardingResolveInfo.priority = 0; 4404 forwardingResolveInfo.preferredOrder = 0; 4405 forwardingResolveInfo.match = 0; 4406 forwardingResolveInfo.isDefault = true; 4407 forwardingResolveInfo.filter = filter; 4408 forwardingResolveInfo.targetUserId = targetUserId; 4409 return forwardingResolveInfo; 4410 } 4411 4412 @Override 4413 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4414 Intent[] specifics, String[] specificTypes, Intent intent, 4415 String resolvedType, int flags, int userId) { 4416 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4417 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4418 false, "query intent activity options"); 4419 final String resultsAction = intent.getAction(); 4420 4421 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4422 | PackageManager.GET_RESOLVED_FILTER, userId); 4423 4424 if (DEBUG_INTENT_MATCHING) { 4425 Log.v(TAG, "Query " + intent + ": " + results); 4426 } 4427 4428 int specificsPos = 0; 4429 int N; 4430 4431 // todo: note that the algorithm used here is O(N^2). This 4432 // isn't a problem in our current environment, but if we start running 4433 // into situations where we have more than 5 or 10 matches then this 4434 // should probably be changed to something smarter... 4435 4436 // First we go through and resolve each of the specific items 4437 // that were supplied, taking care of removing any corresponding 4438 // duplicate items in the generic resolve list. 4439 if (specifics != null) { 4440 for (int i=0; i<specifics.length; i++) { 4441 final Intent sintent = specifics[i]; 4442 if (sintent == null) { 4443 continue; 4444 } 4445 4446 if (DEBUG_INTENT_MATCHING) { 4447 Log.v(TAG, "Specific #" + i + ": " + sintent); 4448 } 4449 4450 String action = sintent.getAction(); 4451 if (resultsAction != null && resultsAction.equals(action)) { 4452 // If this action was explicitly requested, then don't 4453 // remove things that have it. 4454 action = null; 4455 } 4456 4457 ResolveInfo ri = null; 4458 ActivityInfo ai = null; 4459 4460 ComponentName comp = sintent.getComponent(); 4461 if (comp == null) { 4462 ri = resolveIntent( 4463 sintent, 4464 specificTypes != null ? specificTypes[i] : null, 4465 flags, userId); 4466 if (ri == null) { 4467 continue; 4468 } 4469 if (ri == mResolveInfo) { 4470 // ACK! Must do something better with this. 4471 } 4472 ai = ri.activityInfo; 4473 comp = new ComponentName(ai.applicationInfo.packageName, 4474 ai.name); 4475 } else { 4476 ai = getActivityInfo(comp, flags, userId); 4477 if (ai == null) { 4478 continue; 4479 } 4480 } 4481 4482 // Look for any generic query activities that are duplicates 4483 // of this specific one, and remove them from the results. 4484 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4485 N = results.size(); 4486 int j; 4487 for (j=specificsPos; j<N; j++) { 4488 ResolveInfo sri = results.get(j); 4489 if ((sri.activityInfo.name.equals(comp.getClassName()) 4490 && sri.activityInfo.applicationInfo.packageName.equals( 4491 comp.getPackageName())) 4492 || (action != null && sri.filter.matchAction(action))) { 4493 results.remove(j); 4494 if (DEBUG_INTENT_MATCHING) Log.v( 4495 TAG, "Removing duplicate item from " + j 4496 + " due to specific " + specificsPos); 4497 if (ri == null) { 4498 ri = sri; 4499 } 4500 j--; 4501 N--; 4502 } 4503 } 4504 4505 // Add this specific item to its proper place. 4506 if (ri == null) { 4507 ri = new ResolveInfo(); 4508 ri.activityInfo = ai; 4509 } 4510 results.add(specificsPos, ri); 4511 ri.specificIndex = i; 4512 specificsPos++; 4513 } 4514 } 4515 4516 // Now we go through the remaining generic results and remove any 4517 // duplicate actions that are found here. 4518 N = results.size(); 4519 for (int i=specificsPos; i<N-1; i++) { 4520 final ResolveInfo rii = results.get(i); 4521 if (rii.filter == null) { 4522 continue; 4523 } 4524 4525 // Iterate over all of the actions of this result's intent 4526 // filter... typically this should be just one. 4527 final Iterator<String> it = rii.filter.actionsIterator(); 4528 if (it == null) { 4529 continue; 4530 } 4531 while (it.hasNext()) { 4532 final String action = it.next(); 4533 if (resultsAction != null && resultsAction.equals(action)) { 4534 // If this action was explicitly requested, then don't 4535 // remove things that have it. 4536 continue; 4537 } 4538 for (int j=i+1; j<N; j++) { 4539 final ResolveInfo rij = results.get(j); 4540 if (rij.filter != null && rij.filter.hasAction(action)) { 4541 results.remove(j); 4542 if (DEBUG_INTENT_MATCHING) Log.v( 4543 TAG, "Removing duplicate item from " + j 4544 + " due to action " + action + " at " + i); 4545 j--; 4546 N--; 4547 } 4548 } 4549 } 4550 4551 // If the caller didn't request filter information, drop it now 4552 // so we don't have to marshall/unmarshall it. 4553 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4554 rii.filter = null; 4555 } 4556 } 4557 4558 // Filter out the caller activity if so requested. 4559 if (caller != null) { 4560 N = results.size(); 4561 for (int i=0; i<N; i++) { 4562 ActivityInfo ainfo = results.get(i).activityInfo; 4563 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4564 && caller.getClassName().equals(ainfo.name)) { 4565 results.remove(i); 4566 break; 4567 } 4568 } 4569 } 4570 4571 // If the caller didn't request filter information, 4572 // drop them now so we don't have to 4573 // marshall/unmarshall it. 4574 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4575 N = results.size(); 4576 for (int i=0; i<N; i++) { 4577 results.get(i).filter = null; 4578 } 4579 } 4580 4581 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4582 return results; 4583 } 4584 4585 @Override 4586 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4587 int userId) { 4588 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4589 ComponentName comp = intent.getComponent(); 4590 if (comp == null) { 4591 if (intent.getSelector() != null) { 4592 intent = intent.getSelector(); 4593 comp = intent.getComponent(); 4594 } 4595 } 4596 if (comp != null) { 4597 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4598 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4599 if (ai != null) { 4600 ResolveInfo ri = new ResolveInfo(); 4601 ri.activityInfo = ai; 4602 list.add(ri); 4603 } 4604 return list; 4605 } 4606 4607 // reader 4608 synchronized (mPackages) { 4609 String pkgName = intent.getPackage(); 4610 if (pkgName == null) { 4611 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4612 } 4613 final PackageParser.Package pkg = mPackages.get(pkgName); 4614 if (pkg != null) { 4615 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4616 userId); 4617 } 4618 return null; 4619 } 4620 } 4621 4622 @Override 4623 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4624 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4625 if (!sUserManager.exists(userId)) return null; 4626 if (query != null) { 4627 if (query.size() >= 1) { 4628 // If there is more than one service with the same priority, 4629 // just arbitrarily pick the first one. 4630 return query.get(0); 4631 } 4632 } 4633 return null; 4634 } 4635 4636 @Override 4637 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4638 int userId) { 4639 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4640 ComponentName comp = intent.getComponent(); 4641 if (comp == null) { 4642 if (intent.getSelector() != null) { 4643 intent = intent.getSelector(); 4644 comp = intent.getComponent(); 4645 } 4646 } 4647 if (comp != null) { 4648 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4649 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4650 if (si != null) { 4651 final ResolveInfo ri = new ResolveInfo(); 4652 ri.serviceInfo = si; 4653 list.add(ri); 4654 } 4655 return list; 4656 } 4657 4658 // reader 4659 synchronized (mPackages) { 4660 String pkgName = intent.getPackage(); 4661 if (pkgName == null) { 4662 return mServices.queryIntent(intent, resolvedType, flags, userId); 4663 } 4664 final PackageParser.Package pkg = mPackages.get(pkgName); 4665 if (pkg != null) { 4666 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4667 userId); 4668 } 4669 return null; 4670 } 4671 } 4672 4673 @Override 4674 public List<ResolveInfo> queryIntentContentProviders( 4675 Intent intent, String resolvedType, int flags, int userId) { 4676 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4677 ComponentName comp = intent.getComponent(); 4678 if (comp == null) { 4679 if (intent.getSelector() != null) { 4680 intent = intent.getSelector(); 4681 comp = intent.getComponent(); 4682 } 4683 } 4684 if (comp != null) { 4685 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4686 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4687 if (pi != null) { 4688 final ResolveInfo ri = new ResolveInfo(); 4689 ri.providerInfo = pi; 4690 list.add(ri); 4691 } 4692 return list; 4693 } 4694 4695 // reader 4696 synchronized (mPackages) { 4697 String pkgName = intent.getPackage(); 4698 if (pkgName == null) { 4699 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4700 } 4701 final PackageParser.Package pkg = mPackages.get(pkgName); 4702 if (pkg != null) { 4703 return mProviders.queryIntentForPackage( 4704 intent, resolvedType, flags, pkg.providers, userId); 4705 } 4706 return null; 4707 } 4708 } 4709 4710 @Override 4711 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4712 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4713 4714 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4715 4716 // writer 4717 synchronized (mPackages) { 4718 ArrayList<PackageInfo> list; 4719 if (listUninstalled) { 4720 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4721 for (PackageSetting ps : mSettings.mPackages.values()) { 4722 PackageInfo pi; 4723 if (ps.pkg != null) { 4724 pi = generatePackageInfo(ps.pkg, flags, userId); 4725 } else { 4726 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4727 } 4728 if (pi != null) { 4729 list.add(pi); 4730 } 4731 } 4732 } else { 4733 list = new ArrayList<PackageInfo>(mPackages.size()); 4734 for (PackageParser.Package p : mPackages.values()) { 4735 PackageInfo pi = generatePackageInfo(p, flags, userId); 4736 if (pi != null) { 4737 list.add(pi); 4738 } 4739 } 4740 } 4741 4742 return new ParceledListSlice<PackageInfo>(list); 4743 } 4744 } 4745 4746 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4747 String[] permissions, boolean[] tmp, int flags, int userId) { 4748 int numMatch = 0; 4749 final PermissionsState permissionsState = ps.getPermissionsState(); 4750 for (int i=0; i<permissions.length; i++) { 4751 final String permission = permissions[i]; 4752 if (permissionsState.hasPermission(permission, userId)) { 4753 tmp[i] = true; 4754 numMatch++; 4755 } else { 4756 tmp[i] = false; 4757 } 4758 } 4759 if (numMatch == 0) { 4760 return; 4761 } 4762 PackageInfo pi; 4763 if (ps.pkg != null) { 4764 pi = generatePackageInfo(ps.pkg, flags, userId); 4765 } else { 4766 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4767 } 4768 // The above might return null in cases of uninstalled apps or install-state 4769 // skew across users/profiles. 4770 if (pi != null) { 4771 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4772 if (numMatch == permissions.length) { 4773 pi.requestedPermissions = permissions; 4774 } else { 4775 pi.requestedPermissions = new String[numMatch]; 4776 numMatch = 0; 4777 for (int i=0; i<permissions.length; i++) { 4778 if (tmp[i]) { 4779 pi.requestedPermissions[numMatch] = permissions[i]; 4780 numMatch++; 4781 } 4782 } 4783 } 4784 } 4785 list.add(pi); 4786 } 4787 } 4788 4789 @Override 4790 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4791 String[] permissions, int flags, int userId) { 4792 if (!sUserManager.exists(userId)) return null; 4793 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4794 4795 // writer 4796 synchronized (mPackages) { 4797 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4798 boolean[] tmpBools = new boolean[permissions.length]; 4799 if (listUninstalled) { 4800 for (PackageSetting ps : mSettings.mPackages.values()) { 4801 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4802 } 4803 } else { 4804 for (PackageParser.Package pkg : mPackages.values()) { 4805 PackageSetting ps = (PackageSetting)pkg.mExtras; 4806 if (ps != null) { 4807 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4808 userId); 4809 } 4810 } 4811 } 4812 4813 return new ParceledListSlice<PackageInfo>(list); 4814 } 4815 } 4816 4817 @Override 4818 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4819 if (!sUserManager.exists(userId)) return null; 4820 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4821 4822 // writer 4823 synchronized (mPackages) { 4824 ArrayList<ApplicationInfo> list; 4825 if (listUninstalled) { 4826 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4827 for (PackageSetting ps : mSettings.mPackages.values()) { 4828 ApplicationInfo ai; 4829 if (ps.pkg != null) { 4830 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4831 ps.readUserState(userId), userId); 4832 } else { 4833 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4834 } 4835 if (ai != null) { 4836 list.add(ai); 4837 } 4838 } 4839 } else { 4840 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4841 for (PackageParser.Package p : mPackages.values()) { 4842 if (p.mExtras != null) { 4843 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4844 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4845 if (ai != null) { 4846 list.add(ai); 4847 } 4848 } 4849 } 4850 } 4851 4852 return new ParceledListSlice<ApplicationInfo>(list); 4853 } 4854 } 4855 4856 public List<ApplicationInfo> getPersistentApplications(int flags) { 4857 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4858 4859 // reader 4860 synchronized (mPackages) { 4861 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4862 final int userId = UserHandle.getCallingUserId(); 4863 while (i.hasNext()) { 4864 final PackageParser.Package p = i.next(); 4865 if (p.applicationInfo != null 4866 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4867 && (!mSafeMode || isSystemApp(p))) { 4868 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4869 if (ps != null) { 4870 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4871 ps.readUserState(userId), userId); 4872 if (ai != null) { 4873 finalList.add(ai); 4874 } 4875 } 4876 } 4877 } 4878 } 4879 4880 return finalList; 4881 } 4882 4883 @Override 4884 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4885 if (!sUserManager.exists(userId)) return null; 4886 // reader 4887 synchronized (mPackages) { 4888 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4889 PackageSetting ps = provider != null 4890 ? mSettings.mPackages.get(provider.owner.packageName) 4891 : null; 4892 return ps != null 4893 && mSettings.isEnabledLPr(provider.info, flags, userId) 4894 && (!mSafeMode || (provider.info.applicationInfo.flags 4895 &ApplicationInfo.FLAG_SYSTEM) != 0) 4896 ? PackageParser.generateProviderInfo(provider, flags, 4897 ps.readUserState(userId), userId) 4898 : null; 4899 } 4900 } 4901 4902 /** 4903 * @deprecated 4904 */ 4905 @Deprecated 4906 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4907 // reader 4908 synchronized (mPackages) { 4909 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4910 .entrySet().iterator(); 4911 final int userId = UserHandle.getCallingUserId(); 4912 while (i.hasNext()) { 4913 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4914 PackageParser.Provider p = entry.getValue(); 4915 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4916 4917 if (ps != null && p.syncable 4918 && (!mSafeMode || (p.info.applicationInfo.flags 4919 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4920 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4921 ps.readUserState(userId), userId); 4922 if (info != null) { 4923 outNames.add(entry.getKey()); 4924 outInfo.add(info); 4925 } 4926 } 4927 } 4928 } 4929 } 4930 4931 @Override 4932 public List<ProviderInfo> queryContentProviders(String processName, 4933 int uid, int flags) { 4934 ArrayList<ProviderInfo> finalList = null; 4935 // reader 4936 synchronized (mPackages) { 4937 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4938 final int userId = processName != null ? 4939 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4940 while (i.hasNext()) { 4941 final PackageParser.Provider p = i.next(); 4942 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4943 if (ps != null && p.info.authority != null 4944 && (processName == null 4945 || (p.info.processName.equals(processName) 4946 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4947 && mSettings.isEnabledLPr(p.info, flags, userId) 4948 && (!mSafeMode 4949 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4950 if (finalList == null) { 4951 finalList = new ArrayList<ProviderInfo>(3); 4952 } 4953 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4954 ps.readUserState(userId), userId); 4955 if (info != null) { 4956 finalList.add(info); 4957 } 4958 } 4959 } 4960 } 4961 4962 if (finalList != null) { 4963 Collections.sort(finalList, mProviderInitOrderSorter); 4964 } 4965 4966 return finalList; 4967 } 4968 4969 @Override 4970 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4971 int flags) { 4972 // reader 4973 synchronized (mPackages) { 4974 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4975 return PackageParser.generateInstrumentationInfo(i, flags); 4976 } 4977 } 4978 4979 @Override 4980 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4981 int flags) { 4982 ArrayList<InstrumentationInfo> finalList = 4983 new ArrayList<InstrumentationInfo>(); 4984 4985 // reader 4986 synchronized (mPackages) { 4987 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4988 while (i.hasNext()) { 4989 final PackageParser.Instrumentation p = i.next(); 4990 if (targetPackage == null 4991 || targetPackage.equals(p.info.targetPackage)) { 4992 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4993 flags); 4994 if (ii != null) { 4995 finalList.add(ii); 4996 } 4997 } 4998 } 4999 } 5000 5001 return finalList; 5002 } 5003 5004 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5005 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5006 if (overlays == null) { 5007 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5008 return; 5009 } 5010 for (PackageParser.Package opkg : overlays.values()) { 5011 // Not much to do if idmap fails: we already logged the error 5012 // and we certainly don't want to abort installation of pkg simply 5013 // because an overlay didn't fit properly. For these reasons, 5014 // ignore the return value of createIdmapForPackagePairLI. 5015 createIdmapForPackagePairLI(pkg, opkg); 5016 } 5017 } 5018 5019 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5020 PackageParser.Package opkg) { 5021 if (!opkg.mTrustedOverlay) { 5022 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5023 opkg.baseCodePath + ": overlay not trusted"); 5024 return false; 5025 } 5026 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5027 if (overlaySet == null) { 5028 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5029 opkg.baseCodePath + " but target package has no known overlays"); 5030 return false; 5031 } 5032 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5033 // TODO: generate idmap for split APKs 5034 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5035 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5036 + opkg.baseCodePath); 5037 return false; 5038 } 5039 PackageParser.Package[] overlayArray = 5040 overlaySet.values().toArray(new PackageParser.Package[0]); 5041 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5042 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5043 return p1.mOverlayPriority - p2.mOverlayPriority; 5044 } 5045 }; 5046 Arrays.sort(overlayArray, cmp); 5047 5048 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5049 int i = 0; 5050 for (PackageParser.Package p : overlayArray) { 5051 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5052 } 5053 return true; 5054 } 5055 5056 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5057 final File[] files = dir.listFiles(); 5058 if (ArrayUtils.isEmpty(files)) { 5059 Log.d(TAG, "No files in app dir " + dir); 5060 return; 5061 } 5062 5063 if (DEBUG_PACKAGE_SCANNING) { 5064 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5065 + " flags=0x" + Integer.toHexString(parseFlags)); 5066 } 5067 5068 for (File file : files) { 5069 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5070 && !PackageInstallerService.isStageName(file.getName()); 5071 if (!isPackage) { 5072 // Ignore entries which are not packages 5073 continue; 5074 } 5075 try { 5076 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5077 scanFlags, currentTime, null); 5078 } catch (PackageManagerException e) { 5079 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5080 5081 // Delete invalid userdata apps 5082 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5083 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5084 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5085 if (file.isDirectory()) { 5086 mInstaller.rmPackageDir(file.getAbsolutePath()); 5087 } else { 5088 file.delete(); 5089 } 5090 } 5091 } 5092 } 5093 } 5094 5095 private static File getSettingsProblemFile() { 5096 File dataDir = Environment.getDataDirectory(); 5097 File systemDir = new File(dataDir, "system"); 5098 File fname = new File(systemDir, "uiderrors.txt"); 5099 return fname; 5100 } 5101 5102 static void reportSettingsProblem(int priority, String msg) { 5103 logCriticalInfo(priority, msg); 5104 } 5105 5106 static void logCriticalInfo(int priority, String msg) { 5107 Slog.println(priority, TAG, msg); 5108 EventLogTags.writePmCriticalInfo(msg); 5109 try { 5110 File fname = getSettingsProblemFile(); 5111 FileOutputStream out = new FileOutputStream(fname, true); 5112 PrintWriter pw = new FastPrintWriter(out); 5113 SimpleDateFormat formatter = new SimpleDateFormat(); 5114 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5115 pw.println(dateString + ": " + msg); 5116 pw.close(); 5117 FileUtils.setPermissions( 5118 fname.toString(), 5119 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5120 -1, -1); 5121 } catch (java.io.IOException e) { 5122 } 5123 } 5124 5125 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5126 PackageParser.Package pkg, File srcFile, int parseFlags) 5127 throws PackageManagerException { 5128 if (ps != null 5129 && ps.codePath.equals(srcFile) 5130 && ps.timeStamp == srcFile.lastModified() 5131 && !isCompatSignatureUpdateNeeded(pkg) 5132 && !isRecoverSignatureUpdateNeeded(pkg)) { 5133 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5134 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5135 ArraySet<PublicKey> signingKs; 5136 synchronized (mPackages) { 5137 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5138 } 5139 if (ps.signatures.mSignatures != null 5140 && ps.signatures.mSignatures.length != 0 5141 && signingKs != null) { 5142 // Optimization: reuse the existing cached certificates 5143 // if the package appears to be unchanged. 5144 pkg.mSignatures = ps.signatures.mSignatures; 5145 pkg.mSigningKeys = signingKs; 5146 return; 5147 } 5148 5149 Slog.w(TAG, "PackageSetting for " + ps.name 5150 + " is missing signatures. Collecting certs again to recover them."); 5151 } else { 5152 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5153 } 5154 5155 try { 5156 pp.collectCertificates(pkg, parseFlags); 5157 pp.collectManifestDigest(pkg); 5158 } catch (PackageParserException e) { 5159 throw PackageManagerException.from(e); 5160 } 5161 } 5162 5163 /* 5164 * Scan a package and return the newly parsed package. 5165 * Returns null in case of errors and the error code is stored in mLastScanError 5166 */ 5167 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5168 long currentTime, UserHandle user) throws PackageManagerException { 5169 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5170 parseFlags |= mDefParseFlags; 5171 PackageParser pp = new PackageParser(); 5172 pp.setSeparateProcesses(mSeparateProcesses); 5173 pp.setOnlyCoreApps(mOnlyCore); 5174 pp.setDisplayMetrics(mMetrics); 5175 5176 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5177 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5178 } 5179 5180 final PackageParser.Package pkg; 5181 try { 5182 pkg = pp.parsePackage(scanFile, parseFlags); 5183 } catch (PackageParserException e) { 5184 throw PackageManagerException.from(e); 5185 } 5186 5187 PackageSetting ps = null; 5188 PackageSetting updatedPkg; 5189 // reader 5190 synchronized (mPackages) { 5191 // Look to see if we already know about this package. 5192 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5193 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5194 // This package has been renamed to its original name. Let's 5195 // use that. 5196 ps = mSettings.peekPackageLPr(oldName); 5197 } 5198 // If there was no original package, see one for the real package name. 5199 if (ps == null) { 5200 ps = mSettings.peekPackageLPr(pkg.packageName); 5201 } 5202 // Check to see if this package could be hiding/updating a system 5203 // package. Must look for it either under the original or real 5204 // package name depending on our state. 5205 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5206 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5207 } 5208 boolean updatedPkgBetter = false; 5209 // First check if this is a system package that may involve an update 5210 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5211 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5212 // it needs to drop FLAG_PRIVILEGED. 5213 if (locationIsPrivileged(scanFile)) { 5214 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5215 } else { 5216 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5217 } 5218 5219 if (ps != null && !ps.codePath.equals(scanFile)) { 5220 // The path has changed from what was last scanned... check the 5221 // version of the new path against what we have stored to determine 5222 // what to do. 5223 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5224 if (pkg.mVersionCode <= ps.versionCode) { 5225 // The system package has been updated and the code path does not match 5226 // Ignore entry. Skip it. 5227 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5228 + " ignored: updated version " + ps.versionCode 5229 + " better than this " + pkg.mVersionCode); 5230 if (!updatedPkg.codePath.equals(scanFile)) { 5231 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5232 + ps.name + " changing from " + updatedPkg.codePathString 5233 + " to " + scanFile); 5234 updatedPkg.codePath = scanFile; 5235 updatedPkg.codePathString = scanFile.toString(); 5236 updatedPkg.resourcePath = scanFile; 5237 updatedPkg.resourcePathString = scanFile.toString(); 5238 } 5239 updatedPkg.pkg = pkg; 5240 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5241 } else { 5242 // The current app on the system partition is better than 5243 // what we have updated to on the data partition; switch 5244 // back to the system partition version. 5245 // At this point, its safely assumed that package installation for 5246 // apps in system partition will go through. If not there won't be a working 5247 // version of the app 5248 // writer 5249 synchronized (mPackages) { 5250 // Just remove the loaded entries from package lists. 5251 mPackages.remove(ps.name); 5252 } 5253 5254 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5255 + " reverting from " + ps.codePathString 5256 + ": new version " + pkg.mVersionCode 5257 + " better than installed " + ps.versionCode); 5258 5259 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5260 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5261 synchronized (mInstallLock) { 5262 args.cleanUpResourcesLI(); 5263 } 5264 synchronized (mPackages) { 5265 mSettings.enableSystemPackageLPw(ps.name); 5266 } 5267 updatedPkgBetter = true; 5268 } 5269 } 5270 } 5271 5272 if (updatedPkg != null) { 5273 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5274 // initially 5275 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5276 5277 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5278 // flag set initially 5279 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5280 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5281 } 5282 } 5283 5284 // Verify certificates against what was last scanned 5285 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5286 5287 /* 5288 * A new system app appeared, but we already had a non-system one of the 5289 * same name installed earlier. 5290 */ 5291 boolean shouldHideSystemApp = false; 5292 if (updatedPkg == null && ps != null 5293 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5294 /* 5295 * Check to make sure the signatures match first. If they don't, 5296 * wipe the installed application and its data. 5297 */ 5298 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5299 != PackageManager.SIGNATURE_MATCH) { 5300 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5301 + " signatures don't match existing userdata copy; removing"); 5302 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5303 ps = null; 5304 } else { 5305 /* 5306 * If the newly-added system app is an older version than the 5307 * already installed version, hide it. It will be scanned later 5308 * and re-added like an update. 5309 */ 5310 if (pkg.mVersionCode <= ps.versionCode) { 5311 shouldHideSystemApp = true; 5312 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5313 + " but new version " + pkg.mVersionCode + " better than installed " 5314 + ps.versionCode + "; hiding system"); 5315 } else { 5316 /* 5317 * The newly found system app is a newer version that the 5318 * one previously installed. Simply remove the 5319 * already-installed application and replace it with our own 5320 * while keeping the application data. 5321 */ 5322 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5323 + " reverting from " + ps.codePathString + ": new version " 5324 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5325 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5326 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5327 synchronized (mInstallLock) { 5328 args.cleanUpResourcesLI(); 5329 } 5330 } 5331 } 5332 } 5333 5334 // The apk is forward locked (not public) if its code and resources 5335 // are kept in different files. (except for app in either system or 5336 // vendor path). 5337 // TODO grab this value from PackageSettings 5338 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5339 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5340 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5341 } 5342 } 5343 5344 // TODO: extend to support forward-locked splits 5345 String resourcePath = null; 5346 String baseResourcePath = null; 5347 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5348 if (ps != null && ps.resourcePathString != null) { 5349 resourcePath = ps.resourcePathString; 5350 baseResourcePath = ps.resourcePathString; 5351 } else { 5352 // Should not happen at all. Just log an error. 5353 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5354 } 5355 } else { 5356 resourcePath = pkg.codePath; 5357 baseResourcePath = pkg.baseCodePath; 5358 } 5359 5360 // Set application objects path explicitly. 5361 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5362 pkg.applicationInfo.setCodePath(pkg.codePath); 5363 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5364 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5365 pkg.applicationInfo.setResourcePath(resourcePath); 5366 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5367 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5368 5369 // Note that we invoke the following method only if we are about to unpack an application 5370 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5371 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5372 5373 /* 5374 * If the system app should be overridden by a previously installed 5375 * data, hide the system app now and let the /data/app scan pick it up 5376 * again. 5377 */ 5378 if (shouldHideSystemApp) { 5379 synchronized (mPackages) { 5380 /* 5381 * We have to grant systems permissions before we hide, because 5382 * grantPermissions will assume the package update is trying to 5383 * expand its permissions. 5384 */ 5385 grantPermissionsLPw(pkg, true, pkg.packageName); 5386 mSettings.disableSystemPackageLPw(pkg.packageName); 5387 } 5388 } 5389 5390 return scannedPkg; 5391 } 5392 5393 private static String fixProcessName(String defProcessName, 5394 String processName, int uid) { 5395 if (processName == null) { 5396 return defProcessName; 5397 } 5398 return processName; 5399 } 5400 5401 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5402 throws PackageManagerException { 5403 if (pkgSetting.signatures.mSignatures != null) { 5404 // Already existing package. Make sure signatures match 5405 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5406 == PackageManager.SIGNATURE_MATCH; 5407 if (!match) { 5408 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5409 == PackageManager.SIGNATURE_MATCH; 5410 } 5411 if (!match) { 5412 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5413 == PackageManager.SIGNATURE_MATCH; 5414 } 5415 if (!match) { 5416 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5417 + pkg.packageName + " signatures do not match the " 5418 + "previously installed version; ignoring!"); 5419 } 5420 } 5421 5422 // Check for shared user signatures 5423 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5424 // Already existing package. Make sure signatures match 5425 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5426 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5427 if (!match) { 5428 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5429 == PackageManager.SIGNATURE_MATCH; 5430 } 5431 if (!match) { 5432 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5433 == PackageManager.SIGNATURE_MATCH; 5434 } 5435 if (!match) { 5436 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5437 "Package " + pkg.packageName 5438 + " has no signatures that match those in shared user " 5439 + pkgSetting.sharedUser.name + "; ignoring!"); 5440 } 5441 } 5442 } 5443 5444 /** 5445 * Enforces that only the system UID or root's UID can call a method exposed 5446 * via Binder. 5447 * 5448 * @param message used as message if SecurityException is thrown 5449 * @throws SecurityException if the caller is not system or root 5450 */ 5451 private static final void enforceSystemOrRoot(String message) { 5452 final int uid = Binder.getCallingUid(); 5453 if (uid != Process.SYSTEM_UID && uid != 0) { 5454 throw new SecurityException(message); 5455 } 5456 } 5457 5458 @Override 5459 public void performBootDexOpt() { 5460 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5461 5462 // Before everything else, see whether we need to fstrim. 5463 try { 5464 IMountService ms = PackageHelper.getMountService(); 5465 if (ms != null) { 5466 final boolean isUpgrade = isUpgrade(); 5467 boolean doTrim = isUpgrade; 5468 if (doTrim) { 5469 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5470 } else { 5471 final long interval = android.provider.Settings.Global.getLong( 5472 mContext.getContentResolver(), 5473 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5474 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5475 if (interval > 0) { 5476 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5477 if (timeSinceLast > interval) { 5478 doTrim = true; 5479 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5480 + "; running immediately"); 5481 } 5482 } 5483 } 5484 if (doTrim) { 5485 if (!isFirstBoot()) { 5486 try { 5487 ActivityManagerNative.getDefault().showBootMessage( 5488 mContext.getResources().getString( 5489 R.string.android_upgrading_fstrim), true); 5490 } catch (RemoteException e) { 5491 } 5492 } 5493 ms.runMaintenance(); 5494 } 5495 } else { 5496 Slog.e(TAG, "Mount service unavailable!"); 5497 } 5498 } catch (RemoteException e) { 5499 // Can't happen; MountService is local 5500 } 5501 5502 final ArraySet<PackageParser.Package> pkgs; 5503 synchronized (mPackages) { 5504 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5505 } 5506 5507 if (pkgs != null) { 5508 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5509 // in case the device runs out of space. 5510 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5511 // Give priority to core apps. 5512 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5513 PackageParser.Package pkg = it.next(); 5514 if (pkg.coreApp) { 5515 if (DEBUG_DEXOPT) { 5516 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5517 } 5518 sortedPkgs.add(pkg); 5519 it.remove(); 5520 } 5521 } 5522 // Give priority to system apps that listen for pre boot complete. 5523 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5524 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5525 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5526 PackageParser.Package pkg = it.next(); 5527 if (pkgNames.contains(pkg.packageName)) { 5528 if (DEBUG_DEXOPT) { 5529 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5530 } 5531 sortedPkgs.add(pkg); 5532 it.remove(); 5533 } 5534 } 5535 // Give priority to system apps. 5536 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5537 PackageParser.Package pkg = it.next(); 5538 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5539 if (DEBUG_DEXOPT) { 5540 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5541 } 5542 sortedPkgs.add(pkg); 5543 it.remove(); 5544 } 5545 } 5546 // Give priority to updated system apps. 5547 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5548 PackageParser.Package pkg = it.next(); 5549 if (pkg.isUpdatedSystemApp()) { 5550 if (DEBUG_DEXOPT) { 5551 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5552 } 5553 sortedPkgs.add(pkg); 5554 it.remove(); 5555 } 5556 } 5557 // Give priority to apps that listen for boot complete. 5558 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5559 pkgNames = getPackageNamesForIntent(intent); 5560 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5561 PackageParser.Package pkg = it.next(); 5562 if (pkgNames.contains(pkg.packageName)) { 5563 if (DEBUG_DEXOPT) { 5564 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5565 } 5566 sortedPkgs.add(pkg); 5567 it.remove(); 5568 } 5569 } 5570 // Filter out packages that aren't recently used. 5571 filterRecentlyUsedApps(pkgs); 5572 // Add all remaining apps. 5573 for (PackageParser.Package pkg : pkgs) { 5574 if (DEBUG_DEXOPT) { 5575 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5576 } 5577 sortedPkgs.add(pkg); 5578 } 5579 5580 // If we want to be lazy, filter everything that wasn't recently used. 5581 if (mLazyDexOpt) { 5582 filterRecentlyUsedApps(sortedPkgs); 5583 } 5584 5585 int i = 0; 5586 int total = sortedPkgs.size(); 5587 File dataDir = Environment.getDataDirectory(); 5588 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5589 if (lowThreshold == 0) { 5590 throw new IllegalStateException("Invalid low memory threshold"); 5591 } 5592 for (PackageParser.Package pkg : sortedPkgs) { 5593 long usableSpace = dataDir.getUsableSpace(); 5594 if (usableSpace < lowThreshold) { 5595 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5596 break; 5597 } 5598 performBootDexOpt(pkg, ++i, total); 5599 } 5600 } 5601 } 5602 5603 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5604 // Filter out packages that aren't recently used. 5605 // 5606 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5607 // should do a full dexopt. 5608 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5609 int total = pkgs.size(); 5610 int skipped = 0; 5611 long now = System.currentTimeMillis(); 5612 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5613 PackageParser.Package pkg = i.next(); 5614 long then = pkg.mLastPackageUsageTimeInMills; 5615 if (then + mDexOptLRUThresholdInMills < now) { 5616 if (DEBUG_DEXOPT) { 5617 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5618 ((then == 0) ? "never" : new Date(then))); 5619 } 5620 i.remove(); 5621 skipped++; 5622 } 5623 } 5624 if (DEBUG_DEXOPT) { 5625 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5626 } 5627 } 5628 } 5629 5630 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5631 List<ResolveInfo> ris = null; 5632 try { 5633 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5634 intent, null, 0, UserHandle.USER_OWNER); 5635 } catch (RemoteException e) { 5636 } 5637 ArraySet<String> pkgNames = new ArraySet<String>(); 5638 if (ris != null) { 5639 for (ResolveInfo ri : ris) { 5640 pkgNames.add(ri.activityInfo.packageName); 5641 } 5642 } 5643 return pkgNames; 5644 } 5645 5646 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5647 if (DEBUG_DEXOPT) { 5648 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5649 } 5650 if (!isFirstBoot()) { 5651 try { 5652 ActivityManagerNative.getDefault().showBootMessage( 5653 mContext.getResources().getString(R.string.android_upgrading_apk, 5654 curr, total), true); 5655 } catch (RemoteException e) { 5656 } 5657 } 5658 PackageParser.Package p = pkg; 5659 synchronized (mInstallLock) { 5660 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5661 false /* force dex */, false /* defer */, true /* include dependencies */); 5662 } 5663 } 5664 5665 @Override 5666 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5667 return performDexOpt(packageName, instructionSet, false); 5668 } 5669 5670 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5671 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5672 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5673 if (!dexopt && !updateUsage) { 5674 // We aren't going to dexopt or update usage, so bail early. 5675 return false; 5676 } 5677 PackageParser.Package p; 5678 final String targetInstructionSet; 5679 synchronized (mPackages) { 5680 p = mPackages.get(packageName); 5681 if (p == null) { 5682 return false; 5683 } 5684 if (updateUsage) { 5685 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5686 } 5687 mPackageUsage.write(false); 5688 if (!dexopt) { 5689 // We aren't going to dexopt, so bail early. 5690 return false; 5691 } 5692 5693 targetInstructionSet = instructionSet != null ? instructionSet : 5694 getPrimaryInstructionSet(p.applicationInfo); 5695 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5696 return false; 5697 } 5698 } 5699 5700 synchronized (mInstallLock) { 5701 final String[] instructionSets = new String[] { targetInstructionSet }; 5702 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5703 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5704 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5705 } 5706 } 5707 5708 public ArraySet<String> getPackagesThatNeedDexOpt() { 5709 ArraySet<String> pkgs = null; 5710 synchronized (mPackages) { 5711 for (PackageParser.Package p : mPackages.values()) { 5712 if (DEBUG_DEXOPT) { 5713 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5714 } 5715 if (!p.mDexOptPerformed.isEmpty()) { 5716 continue; 5717 } 5718 if (pkgs == null) { 5719 pkgs = new ArraySet<String>(); 5720 } 5721 pkgs.add(p.packageName); 5722 } 5723 } 5724 return pkgs; 5725 } 5726 5727 public void shutdown() { 5728 mPackageUsage.write(true); 5729 } 5730 5731 @Override 5732 public void forceDexOpt(String packageName) { 5733 enforceSystemOrRoot("forceDexOpt"); 5734 5735 PackageParser.Package pkg; 5736 synchronized (mPackages) { 5737 pkg = mPackages.get(packageName); 5738 if (pkg == null) { 5739 throw new IllegalArgumentException("Missing package: " + packageName); 5740 } 5741 } 5742 5743 synchronized (mInstallLock) { 5744 final String[] instructionSets = new String[] { 5745 getPrimaryInstructionSet(pkg.applicationInfo) }; 5746 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5747 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5748 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5749 throw new IllegalStateException("Failed to dexopt: " + res); 5750 } 5751 } 5752 } 5753 5754 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5755 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5756 Slog.w(TAG, "Unable to update from " + oldPkg.name 5757 + " to " + newPkg.packageName 5758 + ": old package not in system partition"); 5759 return false; 5760 } else if (mPackages.get(oldPkg.name) != null) { 5761 Slog.w(TAG, "Unable to update from " + oldPkg.name 5762 + " to " + newPkg.packageName 5763 + ": old package still exists"); 5764 return false; 5765 } 5766 return true; 5767 } 5768 5769 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5770 int[] users = sUserManager.getUserIds(); 5771 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5772 if (res < 0) { 5773 return res; 5774 } 5775 for (int user : users) { 5776 if (user != 0) { 5777 res = mInstaller.createUserData(volumeUuid, packageName, 5778 UserHandle.getUid(user, uid), user, seinfo); 5779 if (res < 0) { 5780 return res; 5781 } 5782 } 5783 } 5784 return res; 5785 } 5786 5787 private int removeDataDirsLI(String volumeUuid, String packageName) { 5788 int[] users = sUserManager.getUserIds(); 5789 int res = 0; 5790 for (int user : users) { 5791 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5792 if (resInner < 0) { 5793 res = resInner; 5794 } 5795 } 5796 5797 return res; 5798 } 5799 5800 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5801 int[] users = sUserManager.getUserIds(); 5802 int res = 0; 5803 for (int user : users) { 5804 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5805 if (resInner < 0) { 5806 res = resInner; 5807 } 5808 } 5809 return res; 5810 } 5811 5812 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5813 PackageParser.Package changingLib) { 5814 if (file.path != null) { 5815 usesLibraryFiles.add(file.path); 5816 return; 5817 } 5818 PackageParser.Package p = mPackages.get(file.apk); 5819 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5820 // If we are doing this while in the middle of updating a library apk, 5821 // then we need to make sure to use that new apk for determining the 5822 // dependencies here. (We haven't yet finished committing the new apk 5823 // to the package manager state.) 5824 if (p == null || p.packageName.equals(changingLib.packageName)) { 5825 p = changingLib; 5826 } 5827 } 5828 if (p != null) { 5829 usesLibraryFiles.addAll(p.getAllCodePaths()); 5830 } 5831 } 5832 5833 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5834 PackageParser.Package changingLib) throws PackageManagerException { 5835 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5836 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5837 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5838 for (int i=0; i<N; i++) { 5839 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5840 if (file == null) { 5841 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5842 "Package " + pkg.packageName + " requires unavailable shared library " 5843 + pkg.usesLibraries.get(i) + "; failing!"); 5844 } 5845 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5846 } 5847 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5848 for (int i=0; i<N; i++) { 5849 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5850 if (file == null) { 5851 Slog.w(TAG, "Package " + pkg.packageName 5852 + " desires unavailable shared library " 5853 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5854 } else { 5855 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5856 } 5857 } 5858 N = usesLibraryFiles.size(); 5859 if (N > 0) { 5860 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5861 } else { 5862 pkg.usesLibraryFiles = null; 5863 } 5864 } 5865 } 5866 5867 private static boolean hasString(List<String> list, List<String> which) { 5868 if (list == null) { 5869 return false; 5870 } 5871 for (int i=list.size()-1; i>=0; i--) { 5872 for (int j=which.size()-1; j>=0; j--) { 5873 if (which.get(j).equals(list.get(i))) { 5874 return true; 5875 } 5876 } 5877 } 5878 return false; 5879 } 5880 5881 private void updateAllSharedLibrariesLPw() { 5882 for (PackageParser.Package pkg : mPackages.values()) { 5883 try { 5884 updateSharedLibrariesLPw(pkg, null); 5885 } catch (PackageManagerException e) { 5886 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5887 } 5888 } 5889 } 5890 5891 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5892 PackageParser.Package changingPkg) { 5893 ArrayList<PackageParser.Package> res = null; 5894 for (PackageParser.Package pkg : mPackages.values()) { 5895 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5896 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5897 if (res == null) { 5898 res = new ArrayList<PackageParser.Package>(); 5899 } 5900 res.add(pkg); 5901 try { 5902 updateSharedLibrariesLPw(pkg, changingPkg); 5903 } catch (PackageManagerException e) { 5904 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5905 } 5906 } 5907 } 5908 return res; 5909 } 5910 5911 /** 5912 * Derive the value of the {@code cpuAbiOverride} based on the provided 5913 * value and an optional stored value from the package settings. 5914 */ 5915 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5916 String cpuAbiOverride = null; 5917 5918 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5919 cpuAbiOverride = null; 5920 } else if (abiOverride != null) { 5921 cpuAbiOverride = abiOverride; 5922 } else if (settings != null) { 5923 cpuAbiOverride = settings.cpuAbiOverrideString; 5924 } 5925 5926 return cpuAbiOverride; 5927 } 5928 5929 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5930 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5931 boolean success = false; 5932 try { 5933 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5934 currentTime, user); 5935 success = true; 5936 return res; 5937 } finally { 5938 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5939 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5940 } 5941 } 5942 } 5943 5944 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5945 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5946 final File scanFile = new File(pkg.codePath); 5947 if (pkg.applicationInfo.getCodePath() == null || 5948 pkg.applicationInfo.getResourcePath() == null) { 5949 // Bail out. The resource and code paths haven't been set. 5950 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5951 "Code and resource paths haven't been set correctly"); 5952 } 5953 5954 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5955 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5956 } else { 5957 // Only allow system apps to be flagged as core apps. 5958 pkg.coreApp = false; 5959 } 5960 5961 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5962 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5963 } 5964 5965 if (mCustomResolverComponentName != null && 5966 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5967 setUpCustomResolverActivity(pkg); 5968 } 5969 5970 if (pkg.packageName.equals("android")) { 5971 synchronized (mPackages) { 5972 if (mAndroidApplication != null) { 5973 Slog.w(TAG, "*************************************************"); 5974 Slog.w(TAG, "Core android package being redefined. Skipping."); 5975 Slog.w(TAG, " file=" + scanFile); 5976 Slog.w(TAG, "*************************************************"); 5977 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5978 "Core android package being redefined. Skipping."); 5979 } 5980 5981 // Set up information for our fall-back user intent resolution activity. 5982 mPlatformPackage = pkg; 5983 pkg.mVersionCode = mSdkVersion; 5984 mAndroidApplication = pkg.applicationInfo; 5985 5986 if (!mResolverReplaced) { 5987 mResolveActivity.applicationInfo = mAndroidApplication; 5988 mResolveActivity.name = ResolverActivity.class.getName(); 5989 mResolveActivity.packageName = mAndroidApplication.packageName; 5990 mResolveActivity.processName = "system:ui"; 5991 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5992 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5993 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5994 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5995 mResolveActivity.exported = true; 5996 mResolveActivity.enabled = true; 5997 mResolveInfo.activityInfo = mResolveActivity; 5998 mResolveInfo.priority = 0; 5999 mResolveInfo.preferredOrder = 0; 6000 mResolveInfo.match = 0; 6001 mResolveComponentName = new ComponentName( 6002 mAndroidApplication.packageName, mResolveActivity.name); 6003 } 6004 } 6005 } 6006 6007 if (DEBUG_PACKAGE_SCANNING) { 6008 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6009 Log.d(TAG, "Scanning package " + pkg.packageName); 6010 } 6011 6012 if (mPackages.containsKey(pkg.packageName) 6013 || mSharedLibraries.containsKey(pkg.packageName)) { 6014 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6015 "Application package " + pkg.packageName 6016 + " already installed. Skipping duplicate."); 6017 } 6018 6019 // If we're only installing presumed-existing packages, require that the 6020 // scanned APK is both already known and at the path previously established 6021 // for it. Previously unknown packages we pick up normally, but if we have an 6022 // a priori expectation about this package's install presence, enforce it. 6023 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6024 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6025 if (known != null) { 6026 if (DEBUG_PACKAGE_SCANNING) { 6027 Log.d(TAG, "Examining " + pkg.codePath 6028 + " and requiring known paths " + known.codePathString 6029 + " & " + known.resourcePathString); 6030 } 6031 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6032 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6033 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6034 "Application package " + pkg.packageName 6035 + " found at " + pkg.applicationInfo.getCodePath() 6036 + " but expected at " + known.codePathString + "; ignoring."); 6037 } 6038 } 6039 } 6040 6041 // Initialize package source and resource directories 6042 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6043 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6044 6045 SharedUserSetting suid = null; 6046 PackageSetting pkgSetting = null; 6047 6048 if (!isSystemApp(pkg)) { 6049 // Only system apps can use these features. 6050 pkg.mOriginalPackages = null; 6051 pkg.mRealPackage = null; 6052 pkg.mAdoptPermissions = null; 6053 } 6054 6055 // writer 6056 synchronized (mPackages) { 6057 if (pkg.mSharedUserId != null) { 6058 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6059 if (suid == null) { 6060 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6061 "Creating application package " + pkg.packageName 6062 + " for shared user failed"); 6063 } 6064 if (DEBUG_PACKAGE_SCANNING) { 6065 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6066 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6067 + "): packages=" + suid.packages); 6068 } 6069 } 6070 6071 // Check if we are renaming from an original package name. 6072 PackageSetting origPackage = null; 6073 String realName = null; 6074 if (pkg.mOriginalPackages != null) { 6075 // This package may need to be renamed to a previously 6076 // installed name. Let's check on that... 6077 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6078 if (pkg.mOriginalPackages.contains(renamed)) { 6079 // This package had originally been installed as the 6080 // original name, and we have already taken care of 6081 // transitioning to the new one. Just update the new 6082 // one to continue using the old name. 6083 realName = pkg.mRealPackage; 6084 if (!pkg.packageName.equals(renamed)) { 6085 // Callers into this function may have already taken 6086 // care of renaming the package; only do it here if 6087 // it is not already done. 6088 pkg.setPackageName(renamed); 6089 } 6090 6091 } else { 6092 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6093 if ((origPackage = mSettings.peekPackageLPr( 6094 pkg.mOriginalPackages.get(i))) != null) { 6095 // We do have the package already installed under its 6096 // original name... should we use it? 6097 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6098 // New package is not compatible with original. 6099 origPackage = null; 6100 continue; 6101 } else if (origPackage.sharedUser != null) { 6102 // Make sure uid is compatible between packages. 6103 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6104 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6105 + " to " + pkg.packageName + ": old uid " 6106 + origPackage.sharedUser.name 6107 + " differs from " + pkg.mSharedUserId); 6108 origPackage = null; 6109 continue; 6110 } 6111 } else { 6112 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6113 + pkg.packageName + " to old name " + origPackage.name); 6114 } 6115 break; 6116 } 6117 } 6118 } 6119 } 6120 6121 if (mTransferedPackages.contains(pkg.packageName)) { 6122 Slog.w(TAG, "Package " + pkg.packageName 6123 + " was transferred to another, but its .apk remains"); 6124 } 6125 6126 // Just create the setting, don't add it yet. For already existing packages 6127 // the PkgSetting exists already and doesn't have to be created. 6128 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6129 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6130 pkg.applicationInfo.primaryCpuAbi, 6131 pkg.applicationInfo.secondaryCpuAbi, 6132 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6133 user, false); 6134 if (pkgSetting == null) { 6135 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6136 "Creating application package " + pkg.packageName + " failed"); 6137 } 6138 6139 if (pkgSetting.origPackage != null) { 6140 // If we are first transitioning from an original package, 6141 // fix up the new package's name now. We need to do this after 6142 // looking up the package under its new name, so getPackageLP 6143 // can take care of fiddling things correctly. 6144 pkg.setPackageName(origPackage.name); 6145 6146 // File a report about this. 6147 String msg = "New package " + pkgSetting.realName 6148 + " renamed to replace old package " + pkgSetting.name; 6149 reportSettingsProblem(Log.WARN, msg); 6150 6151 // Make a note of it. 6152 mTransferedPackages.add(origPackage.name); 6153 6154 // No longer need to retain this. 6155 pkgSetting.origPackage = null; 6156 } 6157 6158 if (realName != null) { 6159 // Make a note of it. 6160 mTransferedPackages.add(pkg.packageName); 6161 } 6162 6163 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6164 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6165 } 6166 6167 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6168 // Check all shared libraries and map to their actual file path. 6169 // We only do this here for apps not on a system dir, because those 6170 // are the only ones that can fail an install due to this. We 6171 // will take care of the system apps by updating all of their 6172 // library paths after the scan is done. 6173 updateSharedLibrariesLPw(pkg, null); 6174 } 6175 6176 if (mFoundPolicyFile) { 6177 SELinuxMMAC.assignSeinfoValue(pkg); 6178 } 6179 6180 pkg.applicationInfo.uid = pkgSetting.appId; 6181 pkg.mExtras = pkgSetting; 6182 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6183 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6184 // We just determined the app is signed correctly, so bring 6185 // over the latest parsed certs. 6186 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6187 } else { 6188 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6189 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6190 "Package " + pkg.packageName + " upgrade keys do not match the " 6191 + "previously installed version"); 6192 } else { 6193 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6194 String msg = "System package " + pkg.packageName 6195 + " signature changed; retaining data."; 6196 reportSettingsProblem(Log.WARN, msg); 6197 } 6198 } 6199 } else { 6200 try { 6201 verifySignaturesLP(pkgSetting, pkg); 6202 // We just determined the app is signed correctly, so bring 6203 // over the latest parsed certs. 6204 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6205 } catch (PackageManagerException e) { 6206 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6207 throw e; 6208 } 6209 // The signature has changed, but this package is in the system 6210 // image... let's recover! 6211 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6212 // However... if this package is part of a shared user, but it 6213 // doesn't match the signature of the shared user, let's fail. 6214 // What this means is that you can't change the signatures 6215 // associated with an overall shared user, which doesn't seem all 6216 // that unreasonable. 6217 if (pkgSetting.sharedUser != null) { 6218 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6219 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6220 throw new PackageManagerException( 6221 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6222 "Signature mismatch for shared user : " 6223 + pkgSetting.sharedUser); 6224 } 6225 } 6226 // File a report about this. 6227 String msg = "System package " + pkg.packageName 6228 + " signature changed; retaining data."; 6229 reportSettingsProblem(Log.WARN, msg); 6230 } 6231 } 6232 // Verify that this new package doesn't have any content providers 6233 // that conflict with existing packages. Only do this if the 6234 // package isn't already installed, since we don't want to break 6235 // things that are installed. 6236 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6237 final int N = pkg.providers.size(); 6238 int i; 6239 for (i=0; i<N; i++) { 6240 PackageParser.Provider p = pkg.providers.get(i); 6241 if (p.info.authority != null) { 6242 String names[] = p.info.authority.split(";"); 6243 for (int j = 0; j < names.length; j++) { 6244 if (mProvidersByAuthority.containsKey(names[j])) { 6245 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6246 final String otherPackageName = 6247 ((other != null && other.getComponentName() != null) ? 6248 other.getComponentName().getPackageName() : "?"); 6249 throw new PackageManagerException( 6250 INSTALL_FAILED_CONFLICTING_PROVIDER, 6251 "Can't install because provider name " + names[j] 6252 + " (in package " + pkg.applicationInfo.packageName 6253 + ") is already used by " + otherPackageName); 6254 } 6255 } 6256 } 6257 } 6258 } 6259 6260 if (pkg.mAdoptPermissions != null) { 6261 // This package wants to adopt ownership of permissions from 6262 // another package. 6263 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6264 final String origName = pkg.mAdoptPermissions.get(i); 6265 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6266 if (orig != null) { 6267 if (verifyPackageUpdateLPr(orig, pkg)) { 6268 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6269 + pkg.packageName); 6270 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6271 } 6272 } 6273 } 6274 } 6275 } 6276 6277 final String pkgName = pkg.packageName; 6278 6279 final long scanFileTime = scanFile.lastModified(); 6280 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6281 pkg.applicationInfo.processName = fixProcessName( 6282 pkg.applicationInfo.packageName, 6283 pkg.applicationInfo.processName, 6284 pkg.applicationInfo.uid); 6285 6286 File dataPath; 6287 if (mPlatformPackage == pkg) { 6288 // The system package is special. 6289 dataPath = new File(Environment.getDataDirectory(), "system"); 6290 6291 pkg.applicationInfo.dataDir = dataPath.getPath(); 6292 6293 } else { 6294 // This is a normal package, need to make its data directory. 6295 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6296 UserHandle.USER_OWNER); 6297 6298 boolean uidError = false; 6299 if (dataPath.exists()) { 6300 int currentUid = 0; 6301 try { 6302 StructStat stat = Os.stat(dataPath.getPath()); 6303 currentUid = stat.st_uid; 6304 } catch (ErrnoException e) { 6305 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6306 } 6307 6308 // If we have mismatched owners for the data path, we have a problem. 6309 if (currentUid != pkg.applicationInfo.uid) { 6310 boolean recovered = false; 6311 if (currentUid == 0) { 6312 // The directory somehow became owned by root. Wow. 6313 // This is probably because the system was stopped while 6314 // installd was in the middle of messing with its libs 6315 // directory. Ask installd to fix that. 6316 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6317 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6318 if (ret >= 0) { 6319 recovered = true; 6320 String msg = "Package " + pkg.packageName 6321 + " unexpectedly changed to uid 0; recovered to " + 6322 + pkg.applicationInfo.uid; 6323 reportSettingsProblem(Log.WARN, msg); 6324 } 6325 } 6326 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6327 || (scanFlags&SCAN_BOOTING) != 0)) { 6328 // If this is a system app, we can at least delete its 6329 // current data so the application will still work. 6330 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6331 if (ret >= 0) { 6332 // TODO: Kill the processes first 6333 // Old data gone! 6334 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6335 ? "System package " : "Third party package "; 6336 String msg = prefix + pkg.packageName 6337 + " has changed from uid: " 6338 + currentUid + " to " 6339 + pkg.applicationInfo.uid + "; old data erased"; 6340 reportSettingsProblem(Log.WARN, msg); 6341 recovered = true; 6342 6343 // And now re-install the app. 6344 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6345 pkg.applicationInfo.seinfo); 6346 if (ret == -1) { 6347 // Ack should not happen! 6348 msg = prefix + pkg.packageName 6349 + " could not have data directory re-created after delete."; 6350 reportSettingsProblem(Log.WARN, msg); 6351 throw new PackageManagerException( 6352 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6353 } 6354 } 6355 if (!recovered) { 6356 mHasSystemUidErrors = true; 6357 } 6358 } else if (!recovered) { 6359 // If we allow this install to proceed, we will be broken. 6360 // Abort, abort! 6361 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6362 "scanPackageLI"); 6363 } 6364 if (!recovered) { 6365 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6366 + pkg.applicationInfo.uid + "/fs_" 6367 + currentUid; 6368 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6369 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6370 String msg = "Package " + pkg.packageName 6371 + " has mismatched uid: " 6372 + currentUid + " on disk, " 6373 + pkg.applicationInfo.uid + " in settings"; 6374 // writer 6375 synchronized (mPackages) { 6376 mSettings.mReadMessages.append(msg); 6377 mSettings.mReadMessages.append('\n'); 6378 uidError = true; 6379 if (!pkgSetting.uidError) { 6380 reportSettingsProblem(Log.ERROR, msg); 6381 } 6382 } 6383 } 6384 } 6385 pkg.applicationInfo.dataDir = dataPath.getPath(); 6386 if (mShouldRestoreconData) { 6387 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6388 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6389 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6390 } 6391 } else { 6392 if (DEBUG_PACKAGE_SCANNING) { 6393 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6394 Log.v(TAG, "Want this data dir: " + dataPath); 6395 } 6396 //invoke installer to do the actual installation 6397 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6398 pkg.applicationInfo.seinfo); 6399 if (ret < 0) { 6400 // Error from installer 6401 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6402 "Unable to create data dirs [errorCode=" + ret + "]"); 6403 } 6404 6405 if (dataPath.exists()) { 6406 pkg.applicationInfo.dataDir = dataPath.getPath(); 6407 } else { 6408 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6409 pkg.applicationInfo.dataDir = null; 6410 } 6411 } 6412 6413 pkgSetting.uidError = uidError; 6414 } 6415 6416 final String path = scanFile.getPath(); 6417 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6418 6419 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6420 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6421 6422 // Some system apps still use directory structure for native libraries 6423 // in which case we might end up not detecting abi solely based on apk 6424 // structure. Try to detect abi based on directory structure. 6425 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6426 pkg.applicationInfo.primaryCpuAbi == null) { 6427 setBundledAppAbisAndRoots(pkg, pkgSetting); 6428 setNativeLibraryPaths(pkg); 6429 } 6430 6431 } else { 6432 if ((scanFlags & SCAN_MOVE) != 0) { 6433 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6434 // but we already have this packages package info in the PackageSetting. We just 6435 // use that and derive the native library path based on the new codepath. 6436 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6437 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6438 } 6439 6440 // Set native library paths again. For moves, the path will be updated based on the 6441 // ABIs we've determined above. For non-moves, the path will be updated based on the 6442 // ABIs we determined during compilation, but the path will depend on the final 6443 // package path (after the rename away from the stage path). 6444 setNativeLibraryPaths(pkg); 6445 } 6446 6447 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6448 final int[] userIds = sUserManager.getUserIds(); 6449 synchronized (mInstallLock) { 6450 // Create a native library symlink only if we have native libraries 6451 // and if the native libraries are 32 bit libraries. We do not provide 6452 // this symlink for 64 bit libraries. 6453 if (pkg.applicationInfo.primaryCpuAbi != null && 6454 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6455 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6456 for (int userId : userIds) { 6457 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6458 nativeLibPath, userId) < 0) { 6459 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6460 "Failed linking native library dir (user=" + userId + ")"); 6461 } 6462 } 6463 } 6464 } 6465 6466 // This is a special case for the "system" package, where the ABI is 6467 // dictated by the zygote configuration (and init.rc). We should keep track 6468 // of this ABI so that we can deal with "normal" applications that run under 6469 // the same UID correctly. 6470 if (mPlatformPackage == pkg) { 6471 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6472 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6473 } 6474 6475 // If there's a mismatch between the abi-override in the package setting 6476 // and the abiOverride specified for the install. Warn about this because we 6477 // would've already compiled the app without taking the package setting into 6478 // account. 6479 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6480 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6481 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6482 " for package: " + pkg.packageName); 6483 } 6484 } 6485 6486 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6487 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6488 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6489 6490 // Copy the derived override back to the parsed package, so that we can 6491 // update the package settings accordingly. 6492 pkg.cpuAbiOverride = cpuAbiOverride; 6493 6494 if (DEBUG_ABI_SELECTION) { 6495 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6496 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6497 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6498 } 6499 6500 // Push the derived path down into PackageSettings so we know what to 6501 // clean up at uninstall time. 6502 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6503 6504 if (DEBUG_ABI_SELECTION) { 6505 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6506 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6507 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6508 } 6509 6510 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6511 // We don't do this here during boot because we can do it all 6512 // at once after scanning all existing packages. 6513 // 6514 // We also do this *before* we perform dexopt on this package, so that 6515 // we can avoid redundant dexopts, and also to make sure we've got the 6516 // code and package path correct. 6517 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6518 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6519 } 6520 6521 if ((scanFlags & SCAN_NO_DEX) == 0) { 6522 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6523 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6524 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6525 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6526 } 6527 } 6528 if (mFactoryTest && pkg.requestedPermissions.contains( 6529 android.Manifest.permission.FACTORY_TEST)) { 6530 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6531 } 6532 6533 ArrayList<PackageParser.Package> clientLibPkgs = null; 6534 6535 // writer 6536 synchronized (mPackages) { 6537 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6538 // Only system apps can add new shared libraries. 6539 if (pkg.libraryNames != null) { 6540 for (int i=0; i<pkg.libraryNames.size(); i++) { 6541 String name = pkg.libraryNames.get(i); 6542 boolean allowed = false; 6543 if (pkg.isUpdatedSystemApp()) { 6544 // New library entries can only be added through the 6545 // system image. This is important to get rid of a lot 6546 // of nasty edge cases: for example if we allowed a non- 6547 // system update of the app to add a library, then uninstalling 6548 // the update would make the library go away, and assumptions 6549 // we made such as through app install filtering would now 6550 // have allowed apps on the device which aren't compatible 6551 // with it. Better to just have the restriction here, be 6552 // conservative, and create many fewer cases that can negatively 6553 // impact the user experience. 6554 final PackageSetting sysPs = mSettings 6555 .getDisabledSystemPkgLPr(pkg.packageName); 6556 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6557 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6558 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6559 allowed = true; 6560 allowed = true; 6561 break; 6562 } 6563 } 6564 } 6565 } else { 6566 allowed = true; 6567 } 6568 if (allowed) { 6569 if (!mSharedLibraries.containsKey(name)) { 6570 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6571 } else if (!name.equals(pkg.packageName)) { 6572 Slog.w(TAG, "Package " + pkg.packageName + " library " 6573 + name + " already exists; skipping"); 6574 } 6575 } else { 6576 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6577 + name + " that is not declared on system image; skipping"); 6578 } 6579 } 6580 if ((scanFlags&SCAN_BOOTING) == 0) { 6581 // If we are not booting, we need to update any applications 6582 // that are clients of our shared library. If we are booting, 6583 // this will all be done once the scan is complete. 6584 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6585 } 6586 } 6587 } 6588 } 6589 6590 // We also need to dexopt any apps that are dependent on this library. Note that 6591 // if these fail, we should abort the install since installing the library will 6592 // result in some apps being broken. 6593 if (clientLibPkgs != null) { 6594 if ((scanFlags & SCAN_NO_DEX) == 0) { 6595 for (int i = 0; i < clientLibPkgs.size(); i++) { 6596 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6597 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6598 null /* instruction sets */, forceDex, 6599 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6600 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6601 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6602 "scanPackageLI failed to dexopt clientLibPkgs"); 6603 } 6604 } 6605 } 6606 } 6607 6608 // Also need to kill any apps that are dependent on the library. 6609 if (clientLibPkgs != null) { 6610 for (int i=0; i<clientLibPkgs.size(); i++) { 6611 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6612 killApplication(clientPkg.applicationInfo.packageName, 6613 clientPkg.applicationInfo.uid, "update lib"); 6614 } 6615 } 6616 6617 // Make sure we're not adding any bogus keyset info 6618 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6619 ksms.assertScannedPackageValid(pkg); 6620 6621 // writer 6622 synchronized (mPackages) { 6623 // We don't expect installation to fail beyond this point 6624 6625 // Add the new setting to mSettings 6626 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6627 // Add the new setting to mPackages 6628 mPackages.put(pkg.applicationInfo.packageName, pkg); 6629 // Make sure we don't accidentally delete its data. 6630 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6631 while (iter.hasNext()) { 6632 PackageCleanItem item = iter.next(); 6633 if (pkgName.equals(item.packageName)) { 6634 iter.remove(); 6635 } 6636 } 6637 6638 // Take care of first install / last update times. 6639 if (currentTime != 0) { 6640 if (pkgSetting.firstInstallTime == 0) { 6641 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6642 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6643 pkgSetting.lastUpdateTime = currentTime; 6644 } 6645 } else if (pkgSetting.firstInstallTime == 0) { 6646 // We need *something*. Take time time stamp of the file. 6647 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6648 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6649 if (scanFileTime != pkgSetting.timeStamp) { 6650 // A package on the system image has changed; consider this 6651 // to be an update. 6652 pkgSetting.lastUpdateTime = scanFileTime; 6653 } 6654 } 6655 6656 // Add the package's KeySets to the global KeySetManagerService 6657 ksms.addScannedPackageLPw(pkg); 6658 6659 int N = pkg.providers.size(); 6660 StringBuilder r = null; 6661 int i; 6662 for (i=0; i<N; i++) { 6663 PackageParser.Provider p = pkg.providers.get(i); 6664 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6665 p.info.processName, pkg.applicationInfo.uid); 6666 mProviders.addProvider(p); 6667 p.syncable = p.info.isSyncable; 6668 if (p.info.authority != null) { 6669 String names[] = p.info.authority.split(";"); 6670 p.info.authority = null; 6671 for (int j = 0; j < names.length; j++) { 6672 if (j == 1 && p.syncable) { 6673 // We only want the first authority for a provider to possibly be 6674 // syncable, so if we already added this provider using a different 6675 // authority clear the syncable flag. We copy the provider before 6676 // changing it because the mProviders object contains a reference 6677 // to a provider that we don't want to change. 6678 // Only do this for the second authority since the resulting provider 6679 // object can be the same for all future authorities for this provider. 6680 p = new PackageParser.Provider(p); 6681 p.syncable = false; 6682 } 6683 if (!mProvidersByAuthority.containsKey(names[j])) { 6684 mProvidersByAuthority.put(names[j], p); 6685 if (p.info.authority == null) { 6686 p.info.authority = names[j]; 6687 } else { 6688 p.info.authority = p.info.authority + ";" + names[j]; 6689 } 6690 if (DEBUG_PACKAGE_SCANNING) { 6691 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6692 Log.d(TAG, "Registered content provider: " + names[j] 6693 + ", className = " + p.info.name + ", isSyncable = " 6694 + p.info.isSyncable); 6695 } 6696 } else { 6697 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6698 Slog.w(TAG, "Skipping provider name " + names[j] + 6699 " (in package " + pkg.applicationInfo.packageName + 6700 "): name already used by " 6701 + ((other != null && other.getComponentName() != null) 6702 ? other.getComponentName().getPackageName() : "?")); 6703 } 6704 } 6705 } 6706 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6707 if (r == null) { 6708 r = new StringBuilder(256); 6709 } else { 6710 r.append(' '); 6711 } 6712 r.append(p.info.name); 6713 } 6714 } 6715 if (r != null) { 6716 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6717 } 6718 6719 N = pkg.services.size(); 6720 r = null; 6721 for (i=0; i<N; i++) { 6722 PackageParser.Service s = pkg.services.get(i); 6723 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6724 s.info.processName, pkg.applicationInfo.uid); 6725 mServices.addService(s); 6726 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6727 if (r == null) { 6728 r = new StringBuilder(256); 6729 } else { 6730 r.append(' '); 6731 } 6732 r.append(s.info.name); 6733 } 6734 } 6735 if (r != null) { 6736 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6737 } 6738 6739 N = pkg.receivers.size(); 6740 r = null; 6741 for (i=0; i<N; i++) { 6742 PackageParser.Activity a = pkg.receivers.get(i); 6743 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6744 a.info.processName, pkg.applicationInfo.uid); 6745 mReceivers.addActivity(a, "receiver"); 6746 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6747 if (r == null) { 6748 r = new StringBuilder(256); 6749 } else { 6750 r.append(' '); 6751 } 6752 r.append(a.info.name); 6753 } 6754 } 6755 if (r != null) { 6756 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6757 } 6758 6759 N = pkg.activities.size(); 6760 r = null; 6761 for (i=0; i<N; i++) { 6762 PackageParser.Activity a = pkg.activities.get(i); 6763 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6764 a.info.processName, pkg.applicationInfo.uid); 6765 mActivities.addActivity(a, "activity"); 6766 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6767 if (r == null) { 6768 r = new StringBuilder(256); 6769 } else { 6770 r.append(' '); 6771 } 6772 r.append(a.info.name); 6773 } 6774 } 6775 if (r != null) { 6776 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6777 } 6778 6779 N = pkg.permissionGroups.size(); 6780 r = null; 6781 for (i=0; i<N; i++) { 6782 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6783 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6784 if (cur == null) { 6785 mPermissionGroups.put(pg.info.name, pg); 6786 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6787 if (r == null) { 6788 r = new StringBuilder(256); 6789 } else { 6790 r.append(' '); 6791 } 6792 r.append(pg.info.name); 6793 } 6794 } else { 6795 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6796 + pg.info.packageName + " ignored: original from " 6797 + cur.info.packageName); 6798 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6799 if (r == null) { 6800 r = new StringBuilder(256); 6801 } else { 6802 r.append(' '); 6803 } 6804 r.append("DUP:"); 6805 r.append(pg.info.name); 6806 } 6807 } 6808 } 6809 if (r != null) { 6810 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6811 } 6812 6813 N = pkg.permissions.size(); 6814 r = null; 6815 for (i=0; i<N; i++) { 6816 PackageParser.Permission p = pkg.permissions.get(i); 6817 6818 // Now that permission groups have a special meaning, we ignore permission 6819 // groups for legacy apps to prevent unexpected behavior. In particular, 6820 // permissions for one app being granted to someone just becuase they happen 6821 // to be in a group defined by another app (before this had no implications). 6822 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6823 p.group = mPermissionGroups.get(p.info.group); 6824 // Warn for a permission in an unknown group. 6825 if (p.info.group != null && p.group == null) { 6826 Slog.w(TAG, "Permission " + p.info.name + " from package " 6827 + p.info.packageName + " in an unknown group " + p.info.group); 6828 } 6829 } 6830 6831 ArrayMap<String, BasePermission> permissionMap = 6832 p.tree ? mSettings.mPermissionTrees 6833 : mSettings.mPermissions; 6834 BasePermission bp = permissionMap.get(p.info.name); 6835 6836 // Allow system apps to redefine non-system permissions 6837 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6838 final boolean currentOwnerIsSystem = (bp.perm != null 6839 && isSystemApp(bp.perm.owner)); 6840 if (isSystemApp(p.owner)) { 6841 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6842 // It's a built-in permission and no owner, take ownership now 6843 bp.packageSetting = pkgSetting; 6844 bp.perm = p; 6845 bp.uid = pkg.applicationInfo.uid; 6846 bp.sourcePackage = p.info.packageName; 6847 } else if (!currentOwnerIsSystem) { 6848 String msg = "New decl " + p.owner + " of permission " 6849 + p.info.name + " is system; overriding " + bp.sourcePackage; 6850 reportSettingsProblem(Log.WARN, msg); 6851 bp = null; 6852 } 6853 } 6854 } 6855 6856 if (bp == null) { 6857 bp = new BasePermission(p.info.name, p.info.packageName, 6858 BasePermission.TYPE_NORMAL); 6859 permissionMap.put(p.info.name, bp); 6860 } 6861 6862 if (bp.perm == null) { 6863 if (bp.sourcePackage == null 6864 || bp.sourcePackage.equals(p.info.packageName)) { 6865 BasePermission tree = findPermissionTreeLP(p.info.name); 6866 if (tree == null 6867 || tree.sourcePackage.equals(p.info.packageName)) { 6868 bp.packageSetting = pkgSetting; 6869 bp.perm = p; 6870 bp.uid = pkg.applicationInfo.uid; 6871 bp.sourcePackage = p.info.packageName; 6872 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6873 if (r == null) { 6874 r = new StringBuilder(256); 6875 } else { 6876 r.append(' '); 6877 } 6878 r.append(p.info.name); 6879 } 6880 } else { 6881 Slog.w(TAG, "Permission " + p.info.name + " from package " 6882 + p.info.packageName + " ignored: base tree " 6883 + tree.name + " is from package " 6884 + tree.sourcePackage); 6885 } 6886 } else { 6887 Slog.w(TAG, "Permission " + p.info.name + " from package " 6888 + p.info.packageName + " ignored: original from " 6889 + bp.sourcePackage); 6890 } 6891 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6892 if (r == null) { 6893 r = new StringBuilder(256); 6894 } else { 6895 r.append(' '); 6896 } 6897 r.append("DUP:"); 6898 r.append(p.info.name); 6899 } 6900 if (bp.perm == p) { 6901 bp.protectionLevel = p.info.protectionLevel; 6902 } 6903 } 6904 6905 if (r != null) { 6906 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6907 } 6908 6909 N = pkg.instrumentation.size(); 6910 r = null; 6911 for (i=0; i<N; i++) { 6912 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6913 a.info.packageName = pkg.applicationInfo.packageName; 6914 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6915 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6916 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6917 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6918 a.info.dataDir = pkg.applicationInfo.dataDir; 6919 6920 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6921 // need other information about the application, like the ABI and what not ? 6922 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6923 mInstrumentation.put(a.getComponentName(), a); 6924 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6925 if (r == null) { 6926 r = new StringBuilder(256); 6927 } else { 6928 r.append(' '); 6929 } 6930 r.append(a.info.name); 6931 } 6932 } 6933 if (r != null) { 6934 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6935 } 6936 6937 if (pkg.protectedBroadcasts != null) { 6938 N = pkg.protectedBroadcasts.size(); 6939 for (i=0; i<N; i++) { 6940 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6941 } 6942 } 6943 6944 pkgSetting.setTimeStamp(scanFileTime); 6945 6946 // Create idmap files for pairs of (packages, overlay packages). 6947 // Note: "android", ie framework-res.apk, is handled by native layers. 6948 if (pkg.mOverlayTarget != null) { 6949 // This is an overlay package. 6950 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6951 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6952 mOverlays.put(pkg.mOverlayTarget, 6953 new ArrayMap<String, PackageParser.Package>()); 6954 } 6955 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6956 map.put(pkg.packageName, pkg); 6957 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6958 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6959 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6960 "scanPackageLI failed to createIdmap"); 6961 } 6962 } 6963 } else if (mOverlays.containsKey(pkg.packageName) && 6964 !pkg.packageName.equals("android")) { 6965 // This is a regular package, with one or more known overlay packages. 6966 createIdmapsForPackageLI(pkg); 6967 } 6968 } 6969 6970 return pkg; 6971 } 6972 6973 /** 6974 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6975 * is derived purely on the basis of the contents of {@code scanFile} and 6976 * {@code cpuAbiOverride}. 6977 * 6978 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6979 */ 6980 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6981 String cpuAbiOverride, boolean extractLibs) 6982 throws PackageManagerException { 6983 // TODO: We can probably be smarter about this stuff. For installed apps, 6984 // we can calculate this information at install time once and for all. For 6985 // system apps, we can probably assume that this information doesn't change 6986 // after the first boot scan. As things stand, we do lots of unnecessary work. 6987 6988 // Give ourselves some initial paths; we'll come back for another 6989 // pass once we've determined ABI below. 6990 setNativeLibraryPaths(pkg); 6991 6992 // We would never need to extract libs for forward-locked and external packages, 6993 // since the container service will do it for us. We shouldn't attempt to 6994 // extract libs from system app when it was not updated. 6995 if (pkg.isForwardLocked() || isExternal(pkg) || 6996 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 6997 extractLibs = false; 6998 } 6999 7000 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7001 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7002 7003 NativeLibraryHelper.Handle handle = null; 7004 try { 7005 handle = NativeLibraryHelper.Handle.create(scanFile); 7006 // TODO(multiArch): This can be null for apps that didn't go through the 7007 // usual installation process. We can calculate it again, like we 7008 // do during install time. 7009 // 7010 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7011 // unnecessary. 7012 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7013 7014 // Null out the abis so that they can be recalculated. 7015 pkg.applicationInfo.primaryCpuAbi = null; 7016 pkg.applicationInfo.secondaryCpuAbi = null; 7017 if (isMultiArch(pkg.applicationInfo)) { 7018 // Warn if we've set an abiOverride for multi-lib packages.. 7019 // By definition, we need to copy both 32 and 64 bit libraries for 7020 // such packages. 7021 if (pkg.cpuAbiOverride != null 7022 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7023 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7024 } 7025 7026 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7027 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7028 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7029 if (extractLibs) { 7030 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7031 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7032 useIsaSpecificSubdirs); 7033 } else { 7034 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7035 } 7036 } 7037 7038 maybeThrowExceptionForMultiArchCopy( 7039 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7040 7041 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7042 if (extractLibs) { 7043 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7044 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7045 useIsaSpecificSubdirs); 7046 } else { 7047 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7048 } 7049 } 7050 7051 maybeThrowExceptionForMultiArchCopy( 7052 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7053 7054 if (abi64 >= 0) { 7055 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7056 } 7057 7058 if (abi32 >= 0) { 7059 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7060 if (abi64 >= 0) { 7061 pkg.applicationInfo.secondaryCpuAbi = abi; 7062 } else { 7063 pkg.applicationInfo.primaryCpuAbi = abi; 7064 } 7065 } 7066 } else { 7067 String[] abiList = (cpuAbiOverride != null) ? 7068 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7069 7070 // Enable gross and lame hacks for apps that are built with old 7071 // SDK tools. We must scan their APKs for renderscript bitcode and 7072 // not launch them if it's present. Don't bother checking on devices 7073 // that don't have 64 bit support. 7074 boolean needsRenderScriptOverride = false; 7075 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7076 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7077 abiList = Build.SUPPORTED_32_BIT_ABIS; 7078 needsRenderScriptOverride = true; 7079 } 7080 7081 final int copyRet; 7082 if (extractLibs) { 7083 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7084 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7085 } else { 7086 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7087 } 7088 7089 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7090 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7091 "Error unpackaging native libs for app, errorCode=" + copyRet); 7092 } 7093 7094 if (copyRet >= 0) { 7095 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7096 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7097 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7098 } else if (needsRenderScriptOverride) { 7099 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7100 } 7101 } 7102 } catch (IOException ioe) { 7103 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7104 } finally { 7105 IoUtils.closeQuietly(handle); 7106 } 7107 7108 // Now that we've calculated the ABIs and determined if it's an internal app, 7109 // we will go ahead and populate the nativeLibraryPath. 7110 setNativeLibraryPaths(pkg); 7111 } 7112 7113 /** 7114 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7115 * i.e, so that all packages can be run inside a single process if required. 7116 * 7117 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7118 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7119 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7120 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7121 * updating a package that belongs to a shared user. 7122 * 7123 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7124 * adds unnecessary complexity. 7125 */ 7126 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7127 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7128 String requiredInstructionSet = null; 7129 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7130 requiredInstructionSet = VMRuntime.getInstructionSet( 7131 scannedPackage.applicationInfo.primaryCpuAbi); 7132 } 7133 7134 PackageSetting requirer = null; 7135 for (PackageSetting ps : packagesForUser) { 7136 // If packagesForUser contains scannedPackage, we skip it. This will happen 7137 // when scannedPackage is an update of an existing package. Without this check, 7138 // we will never be able to change the ABI of any package belonging to a shared 7139 // user, even if it's compatible with other packages. 7140 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7141 if (ps.primaryCpuAbiString == null) { 7142 continue; 7143 } 7144 7145 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7146 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7147 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7148 // this but there's not much we can do. 7149 String errorMessage = "Instruction set mismatch, " 7150 + ((requirer == null) ? "[caller]" : requirer) 7151 + " requires " + requiredInstructionSet + " whereas " + ps 7152 + " requires " + instructionSet; 7153 Slog.w(TAG, errorMessage); 7154 } 7155 7156 if (requiredInstructionSet == null) { 7157 requiredInstructionSet = instructionSet; 7158 requirer = ps; 7159 } 7160 } 7161 } 7162 7163 if (requiredInstructionSet != null) { 7164 String adjustedAbi; 7165 if (requirer != null) { 7166 // requirer != null implies that either scannedPackage was null or that scannedPackage 7167 // did not require an ABI, in which case we have to adjust scannedPackage to match 7168 // the ABI of the set (which is the same as requirer's ABI) 7169 adjustedAbi = requirer.primaryCpuAbiString; 7170 if (scannedPackage != null) { 7171 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7172 } 7173 } else { 7174 // requirer == null implies that we're updating all ABIs in the set to 7175 // match scannedPackage. 7176 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7177 } 7178 7179 for (PackageSetting ps : packagesForUser) { 7180 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7181 if (ps.primaryCpuAbiString != null) { 7182 continue; 7183 } 7184 7185 ps.primaryCpuAbiString = adjustedAbi; 7186 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7187 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7188 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7189 7190 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7191 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7192 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7193 ps.primaryCpuAbiString = null; 7194 ps.pkg.applicationInfo.primaryCpuAbi = null; 7195 return; 7196 } else { 7197 mInstaller.rmdex(ps.codePathString, 7198 getDexCodeInstructionSet(getPreferredInstructionSet())); 7199 } 7200 } 7201 } 7202 } 7203 } 7204 } 7205 7206 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7207 synchronized (mPackages) { 7208 mResolverReplaced = true; 7209 // Set up information for custom user intent resolution activity. 7210 mResolveActivity.applicationInfo = pkg.applicationInfo; 7211 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7212 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7213 mResolveActivity.processName = pkg.applicationInfo.packageName; 7214 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7215 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7216 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7217 mResolveActivity.theme = 0; 7218 mResolveActivity.exported = true; 7219 mResolveActivity.enabled = true; 7220 mResolveInfo.activityInfo = mResolveActivity; 7221 mResolveInfo.priority = 0; 7222 mResolveInfo.preferredOrder = 0; 7223 mResolveInfo.match = 0; 7224 mResolveComponentName = mCustomResolverComponentName; 7225 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7226 mResolveComponentName); 7227 } 7228 } 7229 7230 private static String calculateBundledApkRoot(final String codePathString) { 7231 final File codePath = new File(codePathString); 7232 final File codeRoot; 7233 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7234 codeRoot = Environment.getRootDirectory(); 7235 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7236 codeRoot = Environment.getOemDirectory(); 7237 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7238 codeRoot = Environment.getVendorDirectory(); 7239 } else { 7240 // Unrecognized code path; take its top real segment as the apk root: 7241 // e.g. /something/app/blah.apk => /something 7242 try { 7243 File f = codePath.getCanonicalFile(); 7244 File parent = f.getParentFile(); // non-null because codePath is a file 7245 File tmp; 7246 while ((tmp = parent.getParentFile()) != null) { 7247 f = parent; 7248 parent = tmp; 7249 } 7250 codeRoot = f; 7251 Slog.w(TAG, "Unrecognized code path " 7252 + codePath + " - using " + codeRoot); 7253 } catch (IOException e) { 7254 // Can't canonicalize the code path -- shenanigans? 7255 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7256 return Environment.getRootDirectory().getPath(); 7257 } 7258 } 7259 return codeRoot.getPath(); 7260 } 7261 7262 /** 7263 * Derive and set the location of native libraries for the given package, 7264 * which varies depending on where and how the package was installed. 7265 */ 7266 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7267 final ApplicationInfo info = pkg.applicationInfo; 7268 final String codePath = pkg.codePath; 7269 final File codeFile = new File(codePath); 7270 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7271 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7272 7273 info.nativeLibraryRootDir = null; 7274 info.nativeLibraryRootRequiresIsa = false; 7275 info.nativeLibraryDir = null; 7276 info.secondaryNativeLibraryDir = null; 7277 7278 if (isApkFile(codeFile)) { 7279 // Monolithic install 7280 if (bundledApp) { 7281 // If "/system/lib64/apkname" exists, assume that is the per-package 7282 // native library directory to use; otherwise use "/system/lib/apkname". 7283 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7284 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7285 getPrimaryInstructionSet(info)); 7286 7287 // This is a bundled system app so choose the path based on the ABI. 7288 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7289 // is just the default path. 7290 final String apkName = deriveCodePathName(codePath); 7291 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7292 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7293 apkName).getAbsolutePath(); 7294 7295 if (info.secondaryCpuAbi != null) { 7296 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7297 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7298 secondaryLibDir, apkName).getAbsolutePath(); 7299 } 7300 } else if (asecApp) { 7301 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7302 .getAbsolutePath(); 7303 } else { 7304 final String apkName = deriveCodePathName(codePath); 7305 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7306 .getAbsolutePath(); 7307 } 7308 7309 info.nativeLibraryRootRequiresIsa = false; 7310 info.nativeLibraryDir = info.nativeLibraryRootDir; 7311 } else { 7312 // Cluster install 7313 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7314 info.nativeLibraryRootRequiresIsa = true; 7315 7316 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7317 getPrimaryInstructionSet(info)).getAbsolutePath(); 7318 7319 if (info.secondaryCpuAbi != null) { 7320 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7321 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7322 } 7323 } 7324 } 7325 7326 /** 7327 * Calculate the abis and roots for a bundled app. These can uniquely 7328 * be determined from the contents of the system partition, i.e whether 7329 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7330 * of this information, and instead assume that the system was built 7331 * sensibly. 7332 */ 7333 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7334 PackageSetting pkgSetting) { 7335 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7336 7337 // If "/system/lib64/apkname" exists, assume that is the per-package 7338 // native library directory to use; otherwise use "/system/lib/apkname". 7339 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7340 setBundledAppAbi(pkg, apkRoot, apkName); 7341 // pkgSetting might be null during rescan following uninstall of updates 7342 // to a bundled app, so accommodate that possibility. The settings in 7343 // that case will be established later from the parsed package. 7344 // 7345 // If the settings aren't null, sync them up with what we've just derived. 7346 // note that apkRoot isn't stored in the package settings. 7347 if (pkgSetting != null) { 7348 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7349 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7350 } 7351 } 7352 7353 /** 7354 * Deduces the ABI of a bundled app and sets the relevant fields on the 7355 * parsed pkg object. 7356 * 7357 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7358 * under which system libraries are installed. 7359 * @param apkName the name of the installed package. 7360 */ 7361 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7362 final File codeFile = new File(pkg.codePath); 7363 7364 final boolean has64BitLibs; 7365 final boolean has32BitLibs; 7366 if (isApkFile(codeFile)) { 7367 // Monolithic install 7368 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7369 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7370 } else { 7371 // Cluster install 7372 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7373 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7374 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7375 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7376 has64BitLibs = (new File(rootDir, isa)).exists(); 7377 } else { 7378 has64BitLibs = false; 7379 } 7380 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7381 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7382 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7383 has32BitLibs = (new File(rootDir, isa)).exists(); 7384 } else { 7385 has32BitLibs = false; 7386 } 7387 } 7388 7389 if (has64BitLibs && !has32BitLibs) { 7390 // The package has 64 bit libs, but not 32 bit libs. Its primary 7391 // ABI should be 64 bit. We can safely assume here that the bundled 7392 // native libraries correspond to the most preferred ABI in the list. 7393 7394 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7395 pkg.applicationInfo.secondaryCpuAbi = null; 7396 } else if (has32BitLibs && !has64BitLibs) { 7397 // The package has 32 bit libs but not 64 bit libs. Its primary 7398 // ABI should be 32 bit. 7399 7400 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7401 pkg.applicationInfo.secondaryCpuAbi = null; 7402 } else if (has32BitLibs && has64BitLibs) { 7403 // The application has both 64 and 32 bit bundled libraries. We check 7404 // here that the app declares multiArch support, and warn if it doesn't. 7405 // 7406 // We will be lenient here and record both ABIs. The primary will be the 7407 // ABI that's higher on the list, i.e, a device that's configured to prefer 7408 // 64 bit apps will see a 64 bit primary ABI, 7409 7410 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7411 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7412 } 7413 7414 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7415 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7416 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7417 } else { 7418 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7419 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7420 } 7421 } else { 7422 pkg.applicationInfo.primaryCpuAbi = null; 7423 pkg.applicationInfo.secondaryCpuAbi = null; 7424 } 7425 } 7426 7427 private void killApplication(String pkgName, int appId, String reason) { 7428 // Request the ActivityManager to kill the process(only for existing packages) 7429 // so that we do not end up in a confused state while the user is still using the older 7430 // version of the application while the new one gets installed. 7431 IActivityManager am = ActivityManagerNative.getDefault(); 7432 if (am != null) { 7433 try { 7434 am.killApplicationWithAppId(pkgName, appId, reason); 7435 } catch (RemoteException e) { 7436 } 7437 } 7438 } 7439 7440 void removePackageLI(PackageSetting ps, boolean chatty) { 7441 if (DEBUG_INSTALL) { 7442 if (chatty) 7443 Log.d(TAG, "Removing package " + ps.name); 7444 } 7445 7446 // writer 7447 synchronized (mPackages) { 7448 mPackages.remove(ps.name); 7449 final PackageParser.Package pkg = ps.pkg; 7450 if (pkg != null) { 7451 cleanPackageDataStructuresLILPw(pkg, chatty); 7452 } 7453 } 7454 } 7455 7456 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7457 if (DEBUG_INSTALL) { 7458 if (chatty) 7459 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7460 } 7461 7462 // writer 7463 synchronized (mPackages) { 7464 mPackages.remove(pkg.applicationInfo.packageName); 7465 cleanPackageDataStructuresLILPw(pkg, chatty); 7466 } 7467 } 7468 7469 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7470 int N = pkg.providers.size(); 7471 StringBuilder r = null; 7472 int i; 7473 for (i=0; i<N; i++) { 7474 PackageParser.Provider p = pkg.providers.get(i); 7475 mProviders.removeProvider(p); 7476 if (p.info.authority == null) { 7477 7478 /* There was another ContentProvider with this authority when 7479 * this app was installed so this authority is null, 7480 * Ignore it as we don't have to unregister the provider. 7481 */ 7482 continue; 7483 } 7484 String names[] = p.info.authority.split(";"); 7485 for (int j = 0; j < names.length; j++) { 7486 if (mProvidersByAuthority.get(names[j]) == p) { 7487 mProvidersByAuthority.remove(names[j]); 7488 if (DEBUG_REMOVE) { 7489 if (chatty) 7490 Log.d(TAG, "Unregistered content provider: " + names[j] 7491 + ", className = " + p.info.name + ", isSyncable = " 7492 + p.info.isSyncable); 7493 } 7494 } 7495 } 7496 if (DEBUG_REMOVE && chatty) { 7497 if (r == null) { 7498 r = new StringBuilder(256); 7499 } else { 7500 r.append(' '); 7501 } 7502 r.append(p.info.name); 7503 } 7504 } 7505 if (r != null) { 7506 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7507 } 7508 7509 N = pkg.services.size(); 7510 r = null; 7511 for (i=0; i<N; i++) { 7512 PackageParser.Service s = pkg.services.get(i); 7513 mServices.removeService(s); 7514 if (chatty) { 7515 if (r == null) { 7516 r = new StringBuilder(256); 7517 } else { 7518 r.append(' '); 7519 } 7520 r.append(s.info.name); 7521 } 7522 } 7523 if (r != null) { 7524 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7525 } 7526 7527 N = pkg.receivers.size(); 7528 r = null; 7529 for (i=0; i<N; i++) { 7530 PackageParser.Activity a = pkg.receivers.get(i); 7531 mReceivers.removeActivity(a, "receiver"); 7532 if (DEBUG_REMOVE && chatty) { 7533 if (r == null) { 7534 r = new StringBuilder(256); 7535 } else { 7536 r.append(' '); 7537 } 7538 r.append(a.info.name); 7539 } 7540 } 7541 if (r != null) { 7542 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7543 } 7544 7545 N = pkg.activities.size(); 7546 r = null; 7547 for (i=0; i<N; i++) { 7548 PackageParser.Activity a = pkg.activities.get(i); 7549 mActivities.removeActivity(a, "activity"); 7550 if (DEBUG_REMOVE && chatty) { 7551 if (r == null) { 7552 r = new StringBuilder(256); 7553 } else { 7554 r.append(' '); 7555 } 7556 r.append(a.info.name); 7557 } 7558 } 7559 if (r != null) { 7560 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7561 } 7562 7563 N = pkg.permissions.size(); 7564 r = null; 7565 for (i=0; i<N; i++) { 7566 PackageParser.Permission p = pkg.permissions.get(i); 7567 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7568 if (bp == null) { 7569 bp = mSettings.mPermissionTrees.get(p.info.name); 7570 } 7571 if (bp != null && bp.perm == p) { 7572 bp.perm = null; 7573 if (DEBUG_REMOVE && chatty) { 7574 if (r == null) { 7575 r = new StringBuilder(256); 7576 } else { 7577 r.append(' '); 7578 } 7579 r.append(p.info.name); 7580 } 7581 } 7582 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7583 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7584 if (appOpPerms != null) { 7585 appOpPerms.remove(pkg.packageName); 7586 } 7587 } 7588 } 7589 if (r != null) { 7590 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7591 } 7592 7593 N = pkg.requestedPermissions.size(); 7594 r = null; 7595 for (i=0; i<N; i++) { 7596 String perm = pkg.requestedPermissions.get(i); 7597 BasePermission bp = mSettings.mPermissions.get(perm); 7598 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7599 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7600 if (appOpPerms != null) { 7601 appOpPerms.remove(pkg.packageName); 7602 if (appOpPerms.isEmpty()) { 7603 mAppOpPermissionPackages.remove(perm); 7604 } 7605 } 7606 } 7607 } 7608 if (r != null) { 7609 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7610 } 7611 7612 N = pkg.instrumentation.size(); 7613 r = null; 7614 for (i=0; i<N; i++) { 7615 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7616 mInstrumentation.remove(a.getComponentName()); 7617 if (DEBUG_REMOVE && chatty) { 7618 if (r == null) { 7619 r = new StringBuilder(256); 7620 } else { 7621 r.append(' '); 7622 } 7623 r.append(a.info.name); 7624 } 7625 } 7626 if (r != null) { 7627 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7628 } 7629 7630 r = null; 7631 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7632 // Only system apps can hold shared libraries. 7633 if (pkg.libraryNames != null) { 7634 for (i=0; i<pkg.libraryNames.size(); i++) { 7635 String name = pkg.libraryNames.get(i); 7636 SharedLibraryEntry cur = mSharedLibraries.get(name); 7637 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7638 mSharedLibraries.remove(name); 7639 if (DEBUG_REMOVE && chatty) { 7640 if (r == null) { 7641 r = new StringBuilder(256); 7642 } else { 7643 r.append(' '); 7644 } 7645 r.append(name); 7646 } 7647 } 7648 } 7649 } 7650 } 7651 if (r != null) { 7652 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7653 } 7654 } 7655 7656 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7657 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7658 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7659 return true; 7660 } 7661 } 7662 return false; 7663 } 7664 7665 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7666 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7667 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7668 7669 private void updatePermissionsLPw(String changingPkg, 7670 PackageParser.Package pkgInfo, int flags) { 7671 // Make sure there are no dangling permission trees. 7672 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7673 while (it.hasNext()) { 7674 final BasePermission bp = it.next(); 7675 if (bp.packageSetting == null) { 7676 // We may not yet have parsed the package, so just see if 7677 // we still know about its settings. 7678 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7679 } 7680 if (bp.packageSetting == null) { 7681 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7682 + " from package " + bp.sourcePackage); 7683 it.remove(); 7684 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7685 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7686 Slog.i(TAG, "Removing old permission tree: " + bp.name 7687 + " from package " + bp.sourcePackage); 7688 flags |= UPDATE_PERMISSIONS_ALL; 7689 it.remove(); 7690 } 7691 } 7692 } 7693 7694 // Make sure all dynamic permissions have been assigned to a package, 7695 // and make sure there are no dangling permissions. 7696 it = mSettings.mPermissions.values().iterator(); 7697 while (it.hasNext()) { 7698 final BasePermission bp = it.next(); 7699 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7700 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7701 + bp.name + " pkg=" + bp.sourcePackage 7702 + " info=" + bp.pendingInfo); 7703 if (bp.packageSetting == null && bp.pendingInfo != null) { 7704 final BasePermission tree = findPermissionTreeLP(bp.name); 7705 if (tree != null && tree.perm != null) { 7706 bp.packageSetting = tree.packageSetting; 7707 bp.perm = new PackageParser.Permission(tree.perm.owner, 7708 new PermissionInfo(bp.pendingInfo)); 7709 bp.perm.info.packageName = tree.perm.info.packageName; 7710 bp.perm.info.name = bp.name; 7711 bp.uid = tree.uid; 7712 } 7713 } 7714 } 7715 if (bp.packageSetting == null) { 7716 // We may not yet have parsed the package, so just see if 7717 // we still know about its settings. 7718 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7719 } 7720 if (bp.packageSetting == null) { 7721 Slog.w(TAG, "Removing dangling permission: " + bp.name 7722 + " from package " + bp.sourcePackage); 7723 it.remove(); 7724 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7725 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7726 Slog.i(TAG, "Removing old permission: " + bp.name 7727 + " from package " + bp.sourcePackage); 7728 flags |= UPDATE_PERMISSIONS_ALL; 7729 it.remove(); 7730 } 7731 } 7732 } 7733 7734 // Now update the permissions for all packages, in particular 7735 // replace the granted permissions of the system packages. 7736 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7737 for (PackageParser.Package pkg : mPackages.values()) { 7738 if (pkg != pkgInfo) { 7739 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7740 changingPkg); 7741 } 7742 } 7743 } 7744 7745 if (pkgInfo != null) { 7746 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7747 } 7748 } 7749 7750 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7751 String packageOfInterest) { 7752 // IMPORTANT: There are two types of permissions: install and runtime. 7753 // Install time permissions are granted when the app is installed to 7754 // all device users and users added in the future. Runtime permissions 7755 // are granted at runtime explicitly to specific users. Normal and signature 7756 // protected permissions are install time permissions. Dangerous permissions 7757 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7758 // otherwise they are runtime permissions. This function does not manage 7759 // runtime permissions except for the case an app targeting Lollipop MR1 7760 // being upgraded to target a newer SDK, in which case dangerous permissions 7761 // are transformed from install time to runtime ones. 7762 7763 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7764 if (ps == null) { 7765 return; 7766 } 7767 7768 PermissionsState permissionsState = ps.getPermissionsState(); 7769 PermissionsState origPermissions = permissionsState; 7770 7771 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7772 7773 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7774 7775 boolean changedInstallPermission = false; 7776 7777 if (replace) { 7778 ps.installPermissionsFixed = false; 7779 if (!ps.isSharedUser()) { 7780 origPermissions = new PermissionsState(permissionsState); 7781 permissionsState.reset(); 7782 } 7783 } 7784 7785 permissionsState.setGlobalGids(mGlobalGids); 7786 7787 final int N = pkg.requestedPermissions.size(); 7788 for (int i=0; i<N; i++) { 7789 final String name = pkg.requestedPermissions.get(i); 7790 final BasePermission bp = mSettings.mPermissions.get(name); 7791 7792 if (DEBUG_INSTALL) { 7793 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7794 } 7795 7796 if (bp == null || bp.packageSetting == null) { 7797 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7798 Slog.w(TAG, "Unknown permission " + name 7799 + " in package " + pkg.packageName); 7800 } 7801 continue; 7802 } 7803 7804 final String perm = bp.name; 7805 boolean allowedSig = false; 7806 int grant = GRANT_DENIED; 7807 7808 // Keep track of app op permissions. 7809 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7810 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7811 if (pkgs == null) { 7812 pkgs = new ArraySet<>(); 7813 mAppOpPermissionPackages.put(bp.name, pkgs); 7814 } 7815 pkgs.add(pkg.packageName); 7816 } 7817 7818 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7819 switch (level) { 7820 case PermissionInfo.PROTECTION_NORMAL: { 7821 // For all apps normal permissions are install time ones. 7822 grant = GRANT_INSTALL; 7823 } break; 7824 7825 case PermissionInfo.PROTECTION_DANGEROUS: { 7826 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7827 // For legacy apps dangerous permissions are install time ones. 7828 grant = GRANT_INSTALL_LEGACY; 7829 } else if (origPermissions.hasInstallPermission(bp.name)) { 7830 // For legacy apps that became modern, install becomes runtime. 7831 grant = GRANT_UPGRADE; 7832 } else { 7833 // For modern apps keep runtime permissions unchanged. 7834 grant = GRANT_RUNTIME; 7835 } 7836 } break; 7837 7838 case PermissionInfo.PROTECTION_SIGNATURE: { 7839 // For all apps signature permissions are install time ones. 7840 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7841 if (allowedSig) { 7842 grant = GRANT_INSTALL; 7843 } 7844 } break; 7845 } 7846 7847 if (DEBUG_INSTALL) { 7848 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7849 } 7850 7851 if (grant != GRANT_DENIED) { 7852 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7853 // If this is an existing, non-system package, then 7854 // we can't add any new permissions to it. 7855 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7856 // Except... if this is a permission that was added 7857 // to the platform (note: need to only do this when 7858 // updating the platform). 7859 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7860 grant = GRANT_DENIED; 7861 } 7862 } 7863 } 7864 7865 switch (grant) { 7866 case GRANT_INSTALL: { 7867 // Revoke this as runtime permission to handle the case of 7868 // a runtime permission being downgraded to an install one. 7869 for (int userId : UserManagerService.getInstance().getUserIds()) { 7870 if (origPermissions.getRuntimePermissionState( 7871 bp.name, userId) != null) { 7872 // Revoke the runtime permission and clear the flags. 7873 origPermissions.revokeRuntimePermission(bp, userId); 7874 origPermissions.updatePermissionFlags(bp, userId, 7875 PackageManager.MASK_PERMISSION_FLAGS, 0); 7876 // If we revoked a permission permission, we have to write. 7877 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7878 changedRuntimePermissionUserIds, userId); 7879 } 7880 } 7881 // Grant an install permission. 7882 if (permissionsState.grantInstallPermission(bp) != 7883 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7884 changedInstallPermission = true; 7885 } 7886 } break; 7887 7888 case GRANT_INSTALL_LEGACY: { 7889 // Grant an install permission. 7890 if (permissionsState.grantInstallPermission(bp) != 7891 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7892 changedInstallPermission = true; 7893 } 7894 } break; 7895 7896 case GRANT_RUNTIME: { 7897 // Grant previously granted runtime permissions. 7898 for (int userId : UserManagerService.getInstance().getUserIds()) { 7899 PermissionState permissionState = origPermissions 7900 .getRuntimePermissionState(bp.name, userId); 7901 final int flags = permissionState != null 7902 ? permissionState.getFlags() : 0; 7903 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7904 if (permissionsState.grantRuntimePermission(bp, userId) == 7905 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7906 // If we cannot put the permission as it was, we have to write. 7907 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7908 changedRuntimePermissionUserIds, userId); 7909 } 7910 } 7911 // Propagate the permission flags. 7912 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 7913 } 7914 } break; 7915 7916 case GRANT_UPGRADE: { 7917 // Grant runtime permissions for a previously held install permission. 7918 PermissionState permissionState = origPermissions 7919 .getInstallPermissionState(bp.name); 7920 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7921 7922 if (origPermissions.revokeInstallPermission(bp) 7923 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 7924 // We will be transferring the permission flags, so clear them. 7925 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7926 PackageManager.MASK_PERMISSION_FLAGS, 0); 7927 changedInstallPermission = true; 7928 } 7929 7930 // If the permission is not to be promoted to runtime we ignore it and 7931 // also its other flags as they are not applicable to install permissions. 7932 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7933 for (int userId : currentUserIds) { 7934 if (permissionsState.grantRuntimePermission(bp, userId) != 7935 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7936 // Transfer the permission flags. 7937 permissionsState.updatePermissionFlags(bp, userId, 7938 flags, flags); 7939 // If we granted the permission, we have to write. 7940 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7941 changedRuntimePermissionUserIds, userId); 7942 } 7943 } 7944 } 7945 } break; 7946 7947 default: { 7948 if (packageOfInterest == null 7949 || packageOfInterest.equals(pkg.packageName)) { 7950 Slog.w(TAG, "Not granting permission " + perm 7951 + " to package " + pkg.packageName 7952 + " because it was previously installed without"); 7953 } 7954 } break; 7955 } 7956 } else { 7957 if (permissionsState.revokeInstallPermission(bp) != 7958 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7959 // Also drop the permission flags. 7960 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7961 PackageManager.MASK_PERMISSION_FLAGS, 0); 7962 changedInstallPermission = true; 7963 Slog.i(TAG, "Un-granting permission " + perm 7964 + " from package " + pkg.packageName 7965 + " (protectionLevel=" + bp.protectionLevel 7966 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7967 + ")"); 7968 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7969 // Don't print warning for app op permissions, since it is fine for them 7970 // not to be granted, there is a UI for the user to decide. 7971 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7972 Slog.w(TAG, "Not granting permission " + perm 7973 + " to package " + pkg.packageName 7974 + " (protectionLevel=" + bp.protectionLevel 7975 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7976 + ")"); 7977 } 7978 } 7979 } 7980 } 7981 7982 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7983 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7984 // This is the first that we have heard about this package, so the 7985 // permissions we have now selected are fixed until explicitly 7986 // changed. 7987 ps.installPermissionsFixed = true; 7988 } 7989 7990 // Persist the runtime permissions state for users with changes. 7991 for (int userId : changedRuntimePermissionUserIds) { 7992 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7993 } 7994 } 7995 7996 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7997 boolean allowed = false; 7998 final int NP = PackageParser.NEW_PERMISSIONS.length; 7999 for (int ip=0; ip<NP; ip++) { 8000 final PackageParser.NewPermissionInfo npi 8001 = PackageParser.NEW_PERMISSIONS[ip]; 8002 if (npi.name.equals(perm) 8003 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8004 allowed = true; 8005 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8006 + pkg.packageName); 8007 break; 8008 } 8009 } 8010 return allowed; 8011 } 8012 8013 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8014 BasePermission bp, PermissionsState origPermissions) { 8015 boolean allowed; 8016 allowed = (compareSignatures( 8017 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8018 == PackageManager.SIGNATURE_MATCH) 8019 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8020 == PackageManager.SIGNATURE_MATCH); 8021 if (!allowed && (bp.protectionLevel 8022 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8023 if (isSystemApp(pkg)) { 8024 // For updated system applications, a system permission 8025 // is granted only if it had been defined by the original application. 8026 if (pkg.isUpdatedSystemApp()) { 8027 final PackageSetting sysPs = mSettings 8028 .getDisabledSystemPkgLPr(pkg.packageName); 8029 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8030 // If the original was granted this permission, we take 8031 // that grant decision as read and propagate it to the 8032 // update. 8033 if (sysPs.isPrivileged()) { 8034 allowed = true; 8035 } 8036 } else { 8037 // The system apk may have been updated with an older 8038 // version of the one on the data partition, but which 8039 // granted a new system permission that it didn't have 8040 // before. In this case we do want to allow the app to 8041 // now get the new permission if the ancestral apk is 8042 // privileged to get it. 8043 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8044 for (int j=0; 8045 j<sysPs.pkg.requestedPermissions.size(); j++) { 8046 if (perm.equals( 8047 sysPs.pkg.requestedPermissions.get(j))) { 8048 allowed = true; 8049 break; 8050 } 8051 } 8052 } 8053 } 8054 } else { 8055 allowed = isPrivilegedApp(pkg); 8056 } 8057 } 8058 } 8059 if (!allowed && (bp.protectionLevel 8060 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8061 // For development permissions, a development permission 8062 // is granted only if it was already granted. 8063 allowed = origPermissions.hasInstallPermission(perm); 8064 } 8065 return allowed; 8066 } 8067 8068 final class ActivityIntentResolver 8069 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8070 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8071 boolean defaultOnly, int userId) { 8072 if (!sUserManager.exists(userId)) return null; 8073 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8074 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8075 } 8076 8077 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8078 int userId) { 8079 if (!sUserManager.exists(userId)) return null; 8080 mFlags = flags; 8081 return super.queryIntent(intent, resolvedType, 8082 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8083 } 8084 8085 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8086 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8087 if (!sUserManager.exists(userId)) return null; 8088 if (packageActivities == null) { 8089 return null; 8090 } 8091 mFlags = flags; 8092 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8093 final int N = packageActivities.size(); 8094 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8095 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8096 8097 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8098 for (int i = 0; i < N; ++i) { 8099 intentFilters = packageActivities.get(i).intents; 8100 if (intentFilters != null && intentFilters.size() > 0) { 8101 PackageParser.ActivityIntentInfo[] array = 8102 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8103 intentFilters.toArray(array); 8104 listCut.add(array); 8105 } 8106 } 8107 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8108 } 8109 8110 public final void addActivity(PackageParser.Activity a, String type) { 8111 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8112 mActivities.put(a.getComponentName(), a); 8113 if (DEBUG_SHOW_INFO) 8114 Log.v( 8115 TAG, " " + type + " " + 8116 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8117 if (DEBUG_SHOW_INFO) 8118 Log.v(TAG, " Class=" + a.info.name); 8119 final int NI = a.intents.size(); 8120 for (int j=0; j<NI; j++) { 8121 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8122 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8123 intent.setPriority(0); 8124 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8125 + a.className + " with priority > 0, forcing to 0"); 8126 } 8127 if (DEBUG_SHOW_INFO) { 8128 Log.v(TAG, " IntentFilter:"); 8129 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8130 } 8131 if (!intent.debugCheck()) { 8132 Log.w(TAG, "==> For Activity " + a.info.name); 8133 } 8134 addFilter(intent); 8135 } 8136 } 8137 8138 public final void removeActivity(PackageParser.Activity a, String type) { 8139 mActivities.remove(a.getComponentName()); 8140 if (DEBUG_SHOW_INFO) { 8141 Log.v(TAG, " " + type + " " 8142 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8143 : a.info.name) + ":"); 8144 Log.v(TAG, " Class=" + a.info.name); 8145 } 8146 final int NI = a.intents.size(); 8147 for (int j=0; j<NI; j++) { 8148 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8149 if (DEBUG_SHOW_INFO) { 8150 Log.v(TAG, " IntentFilter:"); 8151 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8152 } 8153 removeFilter(intent); 8154 } 8155 } 8156 8157 @Override 8158 protected boolean allowFilterResult( 8159 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8160 ActivityInfo filterAi = filter.activity.info; 8161 for (int i=dest.size()-1; i>=0; i--) { 8162 ActivityInfo destAi = dest.get(i).activityInfo; 8163 if (destAi.name == filterAi.name 8164 && destAi.packageName == filterAi.packageName) { 8165 return false; 8166 } 8167 } 8168 return true; 8169 } 8170 8171 @Override 8172 protected ActivityIntentInfo[] newArray(int size) { 8173 return new ActivityIntentInfo[size]; 8174 } 8175 8176 @Override 8177 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8178 if (!sUserManager.exists(userId)) return true; 8179 PackageParser.Package p = filter.activity.owner; 8180 if (p != null) { 8181 PackageSetting ps = (PackageSetting)p.mExtras; 8182 if (ps != null) { 8183 // System apps are never considered stopped for purposes of 8184 // filtering, because there may be no way for the user to 8185 // actually re-launch them. 8186 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8187 && ps.getStopped(userId); 8188 } 8189 } 8190 return false; 8191 } 8192 8193 @Override 8194 protected boolean isPackageForFilter(String packageName, 8195 PackageParser.ActivityIntentInfo info) { 8196 return packageName.equals(info.activity.owner.packageName); 8197 } 8198 8199 @Override 8200 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8201 int match, int userId) { 8202 if (!sUserManager.exists(userId)) return null; 8203 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8204 return null; 8205 } 8206 final PackageParser.Activity activity = info.activity; 8207 if (mSafeMode && (activity.info.applicationInfo.flags 8208 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8209 return null; 8210 } 8211 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8212 if (ps == null) { 8213 return null; 8214 } 8215 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8216 ps.readUserState(userId), userId); 8217 if (ai == null) { 8218 return null; 8219 } 8220 final ResolveInfo res = new ResolveInfo(); 8221 res.activityInfo = ai; 8222 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8223 res.filter = info; 8224 } 8225 if (info != null) { 8226 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8227 } 8228 res.priority = info.getPriority(); 8229 res.preferredOrder = activity.owner.mPreferredOrder; 8230 //System.out.println("Result: " + res.activityInfo.className + 8231 // " = " + res.priority); 8232 res.match = match; 8233 res.isDefault = info.hasDefault; 8234 res.labelRes = info.labelRes; 8235 res.nonLocalizedLabel = info.nonLocalizedLabel; 8236 if (userNeedsBadging(userId)) { 8237 res.noResourceId = true; 8238 } else { 8239 res.icon = info.icon; 8240 } 8241 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8242 return res; 8243 } 8244 8245 @Override 8246 protected void sortResults(List<ResolveInfo> results) { 8247 Collections.sort(results, mResolvePrioritySorter); 8248 } 8249 8250 @Override 8251 protected void dumpFilter(PrintWriter out, String prefix, 8252 PackageParser.ActivityIntentInfo filter) { 8253 out.print(prefix); out.print( 8254 Integer.toHexString(System.identityHashCode(filter.activity))); 8255 out.print(' '); 8256 filter.activity.printComponentShortName(out); 8257 out.print(" filter "); 8258 out.println(Integer.toHexString(System.identityHashCode(filter))); 8259 } 8260 8261 @Override 8262 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8263 return filter.activity; 8264 } 8265 8266 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8267 PackageParser.Activity activity = (PackageParser.Activity)label; 8268 out.print(prefix); out.print( 8269 Integer.toHexString(System.identityHashCode(activity))); 8270 out.print(' '); 8271 activity.printComponentShortName(out); 8272 if (count > 1) { 8273 out.print(" ("); out.print(count); out.print(" filters)"); 8274 } 8275 out.println(); 8276 } 8277 8278// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8279// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8280// final List<ResolveInfo> retList = Lists.newArrayList(); 8281// while (i.hasNext()) { 8282// final ResolveInfo resolveInfo = i.next(); 8283// if (isEnabledLP(resolveInfo.activityInfo)) { 8284// retList.add(resolveInfo); 8285// } 8286// } 8287// return retList; 8288// } 8289 8290 // Keys are String (activity class name), values are Activity. 8291 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8292 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8293 private int mFlags; 8294 } 8295 8296 private final class ServiceIntentResolver 8297 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8298 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8299 boolean defaultOnly, int userId) { 8300 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8301 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8302 } 8303 8304 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8305 int userId) { 8306 if (!sUserManager.exists(userId)) return null; 8307 mFlags = flags; 8308 return super.queryIntent(intent, resolvedType, 8309 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8310 } 8311 8312 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8313 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8314 if (!sUserManager.exists(userId)) return null; 8315 if (packageServices == null) { 8316 return null; 8317 } 8318 mFlags = flags; 8319 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8320 final int N = packageServices.size(); 8321 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8322 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8323 8324 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8325 for (int i = 0; i < N; ++i) { 8326 intentFilters = packageServices.get(i).intents; 8327 if (intentFilters != null && intentFilters.size() > 0) { 8328 PackageParser.ServiceIntentInfo[] array = 8329 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8330 intentFilters.toArray(array); 8331 listCut.add(array); 8332 } 8333 } 8334 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8335 } 8336 8337 public final void addService(PackageParser.Service s) { 8338 mServices.put(s.getComponentName(), s); 8339 if (DEBUG_SHOW_INFO) { 8340 Log.v(TAG, " " 8341 + (s.info.nonLocalizedLabel != null 8342 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8343 Log.v(TAG, " Class=" + s.info.name); 8344 } 8345 final int NI = s.intents.size(); 8346 int j; 8347 for (j=0; j<NI; j++) { 8348 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8349 if (DEBUG_SHOW_INFO) { 8350 Log.v(TAG, " IntentFilter:"); 8351 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8352 } 8353 if (!intent.debugCheck()) { 8354 Log.w(TAG, "==> For Service " + s.info.name); 8355 } 8356 addFilter(intent); 8357 } 8358 } 8359 8360 public final void removeService(PackageParser.Service s) { 8361 mServices.remove(s.getComponentName()); 8362 if (DEBUG_SHOW_INFO) { 8363 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8364 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8365 Log.v(TAG, " Class=" + s.info.name); 8366 } 8367 final int NI = s.intents.size(); 8368 int j; 8369 for (j=0; j<NI; j++) { 8370 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8371 if (DEBUG_SHOW_INFO) { 8372 Log.v(TAG, " IntentFilter:"); 8373 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8374 } 8375 removeFilter(intent); 8376 } 8377 } 8378 8379 @Override 8380 protected boolean allowFilterResult( 8381 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8382 ServiceInfo filterSi = filter.service.info; 8383 for (int i=dest.size()-1; i>=0; i--) { 8384 ServiceInfo destAi = dest.get(i).serviceInfo; 8385 if (destAi.name == filterSi.name 8386 && destAi.packageName == filterSi.packageName) { 8387 return false; 8388 } 8389 } 8390 return true; 8391 } 8392 8393 @Override 8394 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8395 return new PackageParser.ServiceIntentInfo[size]; 8396 } 8397 8398 @Override 8399 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8400 if (!sUserManager.exists(userId)) return true; 8401 PackageParser.Package p = filter.service.owner; 8402 if (p != null) { 8403 PackageSetting ps = (PackageSetting)p.mExtras; 8404 if (ps != null) { 8405 // System apps are never considered stopped for purposes of 8406 // filtering, because there may be no way for the user to 8407 // actually re-launch them. 8408 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8409 && ps.getStopped(userId); 8410 } 8411 } 8412 return false; 8413 } 8414 8415 @Override 8416 protected boolean isPackageForFilter(String packageName, 8417 PackageParser.ServiceIntentInfo info) { 8418 return packageName.equals(info.service.owner.packageName); 8419 } 8420 8421 @Override 8422 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8423 int match, int userId) { 8424 if (!sUserManager.exists(userId)) return null; 8425 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8426 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8427 return null; 8428 } 8429 final PackageParser.Service service = info.service; 8430 if (mSafeMode && (service.info.applicationInfo.flags 8431 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8432 return null; 8433 } 8434 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8435 if (ps == null) { 8436 return null; 8437 } 8438 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8439 ps.readUserState(userId), userId); 8440 if (si == null) { 8441 return null; 8442 } 8443 final ResolveInfo res = new ResolveInfo(); 8444 res.serviceInfo = si; 8445 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8446 res.filter = filter; 8447 } 8448 res.priority = info.getPriority(); 8449 res.preferredOrder = service.owner.mPreferredOrder; 8450 res.match = match; 8451 res.isDefault = info.hasDefault; 8452 res.labelRes = info.labelRes; 8453 res.nonLocalizedLabel = info.nonLocalizedLabel; 8454 res.icon = info.icon; 8455 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8456 return res; 8457 } 8458 8459 @Override 8460 protected void sortResults(List<ResolveInfo> results) { 8461 Collections.sort(results, mResolvePrioritySorter); 8462 } 8463 8464 @Override 8465 protected void dumpFilter(PrintWriter out, String prefix, 8466 PackageParser.ServiceIntentInfo filter) { 8467 out.print(prefix); out.print( 8468 Integer.toHexString(System.identityHashCode(filter.service))); 8469 out.print(' '); 8470 filter.service.printComponentShortName(out); 8471 out.print(" filter "); 8472 out.println(Integer.toHexString(System.identityHashCode(filter))); 8473 } 8474 8475 @Override 8476 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8477 return filter.service; 8478 } 8479 8480 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8481 PackageParser.Service service = (PackageParser.Service)label; 8482 out.print(prefix); out.print( 8483 Integer.toHexString(System.identityHashCode(service))); 8484 out.print(' '); 8485 service.printComponentShortName(out); 8486 if (count > 1) { 8487 out.print(" ("); out.print(count); out.print(" filters)"); 8488 } 8489 out.println(); 8490 } 8491 8492// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8493// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8494// final List<ResolveInfo> retList = Lists.newArrayList(); 8495// while (i.hasNext()) { 8496// final ResolveInfo resolveInfo = (ResolveInfo) i; 8497// if (isEnabledLP(resolveInfo.serviceInfo)) { 8498// retList.add(resolveInfo); 8499// } 8500// } 8501// return retList; 8502// } 8503 8504 // Keys are String (activity class name), values are Activity. 8505 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8506 = new ArrayMap<ComponentName, PackageParser.Service>(); 8507 private int mFlags; 8508 }; 8509 8510 private final class ProviderIntentResolver 8511 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8512 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8513 boolean defaultOnly, int userId) { 8514 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8515 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8516 } 8517 8518 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8519 int userId) { 8520 if (!sUserManager.exists(userId)) 8521 return null; 8522 mFlags = flags; 8523 return super.queryIntent(intent, resolvedType, 8524 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8525 } 8526 8527 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8528 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8529 if (!sUserManager.exists(userId)) 8530 return null; 8531 if (packageProviders == null) { 8532 return null; 8533 } 8534 mFlags = flags; 8535 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8536 final int N = packageProviders.size(); 8537 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8538 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8539 8540 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8541 for (int i = 0; i < N; ++i) { 8542 intentFilters = packageProviders.get(i).intents; 8543 if (intentFilters != null && intentFilters.size() > 0) { 8544 PackageParser.ProviderIntentInfo[] array = 8545 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8546 intentFilters.toArray(array); 8547 listCut.add(array); 8548 } 8549 } 8550 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8551 } 8552 8553 public final void addProvider(PackageParser.Provider p) { 8554 if (mProviders.containsKey(p.getComponentName())) { 8555 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8556 return; 8557 } 8558 8559 mProviders.put(p.getComponentName(), p); 8560 if (DEBUG_SHOW_INFO) { 8561 Log.v(TAG, " " 8562 + (p.info.nonLocalizedLabel != null 8563 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8564 Log.v(TAG, " Class=" + p.info.name); 8565 } 8566 final int NI = p.intents.size(); 8567 int j; 8568 for (j = 0; j < NI; j++) { 8569 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8570 if (DEBUG_SHOW_INFO) { 8571 Log.v(TAG, " IntentFilter:"); 8572 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8573 } 8574 if (!intent.debugCheck()) { 8575 Log.w(TAG, "==> For Provider " + p.info.name); 8576 } 8577 addFilter(intent); 8578 } 8579 } 8580 8581 public final void removeProvider(PackageParser.Provider p) { 8582 mProviders.remove(p.getComponentName()); 8583 if (DEBUG_SHOW_INFO) { 8584 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8585 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8586 Log.v(TAG, " Class=" + p.info.name); 8587 } 8588 final int NI = p.intents.size(); 8589 int j; 8590 for (j = 0; j < NI; j++) { 8591 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8592 if (DEBUG_SHOW_INFO) { 8593 Log.v(TAG, " IntentFilter:"); 8594 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8595 } 8596 removeFilter(intent); 8597 } 8598 } 8599 8600 @Override 8601 protected boolean allowFilterResult( 8602 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8603 ProviderInfo filterPi = filter.provider.info; 8604 for (int i = dest.size() - 1; i >= 0; i--) { 8605 ProviderInfo destPi = dest.get(i).providerInfo; 8606 if (destPi.name == filterPi.name 8607 && destPi.packageName == filterPi.packageName) { 8608 return false; 8609 } 8610 } 8611 return true; 8612 } 8613 8614 @Override 8615 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8616 return new PackageParser.ProviderIntentInfo[size]; 8617 } 8618 8619 @Override 8620 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8621 if (!sUserManager.exists(userId)) 8622 return true; 8623 PackageParser.Package p = filter.provider.owner; 8624 if (p != null) { 8625 PackageSetting ps = (PackageSetting) p.mExtras; 8626 if (ps != null) { 8627 // System apps are never considered stopped for purposes of 8628 // filtering, because there may be no way for the user to 8629 // actually re-launch them. 8630 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8631 && ps.getStopped(userId); 8632 } 8633 } 8634 return false; 8635 } 8636 8637 @Override 8638 protected boolean isPackageForFilter(String packageName, 8639 PackageParser.ProviderIntentInfo info) { 8640 return packageName.equals(info.provider.owner.packageName); 8641 } 8642 8643 @Override 8644 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8645 int match, int userId) { 8646 if (!sUserManager.exists(userId)) 8647 return null; 8648 final PackageParser.ProviderIntentInfo info = filter; 8649 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8650 return null; 8651 } 8652 final PackageParser.Provider provider = info.provider; 8653 if (mSafeMode && (provider.info.applicationInfo.flags 8654 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8655 return null; 8656 } 8657 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8658 if (ps == null) { 8659 return null; 8660 } 8661 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8662 ps.readUserState(userId), userId); 8663 if (pi == null) { 8664 return null; 8665 } 8666 final ResolveInfo res = new ResolveInfo(); 8667 res.providerInfo = pi; 8668 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8669 res.filter = filter; 8670 } 8671 res.priority = info.getPriority(); 8672 res.preferredOrder = provider.owner.mPreferredOrder; 8673 res.match = match; 8674 res.isDefault = info.hasDefault; 8675 res.labelRes = info.labelRes; 8676 res.nonLocalizedLabel = info.nonLocalizedLabel; 8677 res.icon = info.icon; 8678 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8679 return res; 8680 } 8681 8682 @Override 8683 protected void sortResults(List<ResolveInfo> results) { 8684 Collections.sort(results, mResolvePrioritySorter); 8685 } 8686 8687 @Override 8688 protected void dumpFilter(PrintWriter out, String prefix, 8689 PackageParser.ProviderIntentInfo filter) { 8690 out.print(prefix); 8691 out.print( 8692 Integer.toHexString(System.identityHashCode(filter.provider))); 8693 out.print(' '); 8694 filter.provider.printComponentShortName(out); 8695 out.print(" filter "); 8696 out.println(Integer.toHexString(System.identityHashCode(filter))); 8697 } 8698 8699 @Override 8700 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8701 return filter.provider; 8702 } 8703 8704 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8705 PackageParser.Provider provider = (PackageParser.Provider)label; 8706 out.print(prefix); out.print( 8707 Integer.toHexString(System.identityHashCode(provider))); 8708 out.print(' '); 8709 provider.printComponentShortName(out); 8710 if (count > 1) { 8711 out.print(" ("); out.print(count); out.print(" filters)"); 8712 } 8713 out.println(); 8714 } 8715 8716 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8717 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8718 private int mFlags; 8719 }; 8720 8721 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8722 new Comparator<ResolveInfo>() { 8723 public int compare(ResolveInfo r1, ResolveInfo r2) { 8724 int v1 = r1.priority; 8725 int v2 = r2.priority; 8726 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8727 if (v1 != v2) { 8728 return (v1 > v2) ? -1 : 1; 8729 } 8730 v1 = r1.preferredOrder; 8731 v2 = r2.preferredOrder; 8732 if (v1 != v2) { 8733 return (v1 > v2) ? -1 : 1; 8734 } 8735 if (r1.isDefault != r2.isDefault) { 8736 return r1.isDefault ? -1 : 1; 8737 } 8738 v1 = r1.match; 8739 v2 = r2.match; 8740 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8741 if (v1 != v2) { 8742 return (v1 > v2) ? -1 : 1; 8743 } 8744 if (r1.system != r2.system) { 8745 return r1.system ? -1 : 1; 8746 } 8747 return 0; 8748 } 8749 }; 8750 8751 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8752 new Comparator<ProviderInfo>() { 8753 public int compare(ProviderInfo p1, ProviderInfo p2) { 8754 final int v1 = p1.initOrder; 8755 final int v2 = p2.initOrder; 8756 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8757 } 8758 }; 8759 8760 final void sendPackageBroadcast(final String action, final String pkg, 8761 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8762 final int[] userIds) { 8763 mHandler.post(new Runnable() { 8764 @Override 8765 public void run() { 8766 try { 8767 final IActivityManager am = ActivityManagerNative.getDefault(); 8768 if (am == null) return; 8769 final int[] resolvedUserIds; 8770 if (userIds == null) { 8771 resolvedUserIds = am.getRunningUserIds(); 8772 } else { 8773 resolvedUserIds = userIds; 8774 } 8775 for (int id : resolvedUserIds) { 8776 final Intent intent = new Intent(action, 8777 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8778 if (extras != null) { 8779 intent.putExtras(extras); 8780 } 8781 if (targetPkg != null) { 8782 intent.setPackage(targetPkg); 8783 } 8784 // Modify the UID when posting to other users 8785 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8786 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8787 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8788 intent.putExtra(Intent.EXTRA_UID, uid); 8789 } 8790 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8791 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8792 if (DEBUG_BROADCASTS) { 8793 RuntimeException here = new RuntimeException("here"); 8794 here.fillInStackTrace(); 8795 Slog.d(TAG, "Sending to user " + id + ": " 8796 + intent.toShortString(false, true, false, false) 8797 + " " + intent.getExtras(), here); 8798 } 8799 am.broadcastIntent(null, intent, null, finishedReceiver, 8800 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8801 finishedReceiver != null, false, id); 8802 } 8803 } catch (RemoteException ex) { 8804 } 8805 } 8806 }); 8807 } 8808 8809 /** 8810 * Check if the external storage media is available. This is true if there 8811 * is a mounted external storage medium or if the external storage is 8812 * emulated. 8813 */ 8814 private boolean isExternalMediaAvailable() { 8815 return mMediaMounted || Environment.isExternalStorageEmulated(); 8816 } 8817 8818 @Override 8819 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8820 // writer 8821 synchronized (mPackages) { 8822 if (!isExternalMediaAvailable()) { 8823 // If the external storage is no longer mounted at this point, 8824 // the caller may not have been able to delete all of this 8825 // packages files and can not delete any more. Bail. 8826 return null; 8827 } 8828 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8829 if (lastPackage != null) { 8830 pkgs.remove(lastPackage); 8831 } 8832 if (pkgs.size() > 0) { 8833 return pkgs.get(0); 8834 } 8835 } 8836 return null; 8837 } 8838 8839 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8840 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8841 userId, andCode ? 1 : 0, packageName); 8842 if (mSystemReady) { 8843 msg.sendToTarget(); 8844 } else { 8845 if (mPostSystemReadyMessages == null) { 8846 mPostSystemReadyMessages = new ArrayList<>(); 8847 } 8848 mPostSystemReadyMessages.add(msg); 8849 } 8850 } 8851 8852 void startCleaningPackages() { 8853 // reader 8854 synchronized (mPackages) { 8855 if (!isExternalMediaAvailable()) { 8856 return; 8857 } 8858 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8859 return; 8860 } 8861 } 8862 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8863 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8864 IActivityManager am = ActivityManagerNative.getDefault(); 8865 if (am != null) { 8866 try { 8867 am.startService(null, intent, null, UserHandle.USER_OWNER); 8868 } catch (RemoteException e) { 8869 } 8870 } 8871 } 8872 8873 @Override 8874 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8875 int installFlags, String installerPackageName, VerificationParams verificationParams, 8876 String packageAbiOverride) { 8877 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8878 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8879 } 8880 8881 @Override 8882 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8883 int installFlags, String installerPackageName, VerificationParams verificationParams, 8884 String packageAbiOverride, int userId) { 8885 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8886 8887 final int callingUid = Binder.getCallingUid(); 8888 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8889 8890 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8891 try { 8892 if (observer != null) { 8893 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8894 } 8895 } catch (RemoteException re) { 8896 } 8897 return; 8898 } 8899 8900 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8901 installFlags |= PackageManager.INSTALL_FROM_ADB; 8902 8903 } else { 8904 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8905 // about installerPackageName. 8906 8907 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8908 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8909 } 8910 8911 UserHandle user; 8912 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8913 user = UserHandle.ALL; 8914 } else { 8915 user = new UserHandle(userId); 8916 } 8917 8918 // Only system components can circumvent runtime permissions when installing. 8919 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8920 && mContext.checkCallingOrSelfPermission(Manifest.permission 8921 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8922 throw new SecurityException("You need the " 8923 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8924 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8925 } 8926 8927 verificationParams.setInstallerUid(callingUid); 8928 8929 final File originFile = new File(originPath); 8930 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8931 8932 final Message msg = mHandler.obtainMessage(INIT_COPY); 8933 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8934 null, verificationParams, user, packageAbiOverride); 8935 mHandler.sendMessage(msg); 8936 } 8937 8938 void installStage(String packageName, File stagedDir, String stagedCid, 8939 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8940 String installerPackageName, int installerUid, UserHandle user) { 8941 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8942 params.referrerUri, installerUid, null); 8943 8944 final OriginInfo origin; 8945 if (stagedDir != null) { 8946 origin = OriginInfo.fromStagedFile(stagedDir); 8947 } else { 8948 origin = OriginInfo.fromStagedContainer(stagedCid); 8949 } 8950 8951 final Message msg = mHandler.obtainMessage(INIT_COPY); 8952 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8953 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8954 mHandler.sendMessage(msg); 8955 } 8956 8957 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8958 Bundle extras = new Bundle(1); 8959 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8960 8961 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8962 packageName, extras, null, null, new int[] {userId}); 8963 try { 8964 IActivityManager am = ActivityManagerNative.getDefault(); 8965 final boolean isSystem = 8966 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8967 if (isSystem && am.isUserRunning(userId, false)) { 8968 // The just-installed/enabled app is bundled on the system, so presumed 8969 // to be able to run automatically without needing an explicit launch. 8970 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8971 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8972 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8973 .setPackage(packageName); 8974 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8975 android.app.AppOpsManager.OP_NONE, false, false, userId); 8976 } 8977 } catch (RemoteException e) { 8978 // shouldn't happen 8979 Slog.w(TAG, "Unable to bootstrap installed package", e); 8980 } 8981 } 8982 8983 @Override 8984 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8985 int userId) { 8986 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8987 PackageSetting pkgSetting; 8988 final int uid = Binder.getCallingUid(); 8989 enforceCrossUserPermission(uid, userId, true, true, 8990 "setApplicationHiddenSetting for user " + userId); 8991 8992 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8993 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8994 return false; 8995 } 8996 8997 long callingId = Binder.clearCallingIdentity(); 8998 try { 8999 boolean sendAdded = false; 9000 boolean sendRemoved = false; 9001 // writer 9002 synchronized (mPackages) { 9003 pkgSetting = mSettings.mPackages.get(packageName); 9004 if (pkgSetting == null) { 9005 return false; 9006 } 9007 if (pkgSetting.getHidden(userId) != hidden) { 9008 pkgSetting.setHidden(hidden, userId); 9009 mSettings.writePackageRestrictionsLPr(userId); 9010 if (hidden) { 9011 sendRemoved = true; 9012 } else { 9013 sendAdded = true; 9014 } 9015 } 9016 } 9017 if (sendAdded) { 9018 sendPackageAddedForUser(packageName, pkgSetting, userId); 9019 return true; 9020 } 9021 if (sendRemoved) { 9022 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9023 "hiding pkg"); 9024 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9025 } 9026 } finally { 9027 Binder.restoreCallingIdentity(callingId); 9028 } 9029 return false; 9030 } 9031 9032 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9033 int userId) { 9034 final PackageRemovedInfo info = new PackageRemovedInfo(); 9035 info.removedPackage = packageName; 9036 info.removedUsers = new int[] {userId}; 9037 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9038 info.sendBroadcast(false, false, false); 9039 } 9040 9041 /** 9042 * Returns true if application is not found or there was an error. Otherwise it returns 9043 * the hidden state of the package for the given user. 9044 */ 9045 @Override 9046 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9047 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9048 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9049 false, "getApplicationHidden for user " + userId); 9050 PackageSetting pkgSetting; 9051 long callingId = Binder.clearCallingIdentity(); 9052 try { 9053 // writer 9054 synchronized (mPackages) { 9055 pkgSetting = mSettings.mPackages.get(packageName); 9056 if (pkgSetting == null) { 9057 return true; 9058 } 9059 return pkgSetting.getHidden(userId); 9060 } 9061 } finally { 9062 Binder.restoreCallingIdentity(callingId); 9063 } 9064 } 9065 9066 /** 9067 * @hide 9068 */ 9069 @Override 9070 public int installExistingPackageAsUser(String packageName, int userId) { 9071 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9072 null); 9073 PackageSetting pkgSetting; 9074 final int uid = Binder.getCallingUid(); 9075 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9076 + userId); 9077 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9078 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9079 } 9080 9081 long callingId = Binder.clearCallingIdentity(); 9082 try { 9083 boolean sendAdded = false; 9084 9085 // writer 9086 synchronized (mPackages) { 9087 pkgSetting = mSettings.mPackages.get(packageName); 9088 if (pkgSetting == null) { 9089 return PackageManager.INSTALL_FAILED_INVALID_URI; 9090 } 9091 if (!pkgSetting.getInstalled(userId)) { 9092 pkgSetting.setInstalled(true, userId); 9093 pkgSetting.setHidden(false, userId); 9094 mSettings.writePackageRestrictionsLPr(userId); 9095 sendAdded = true; 9096 } 9097 } 9098 9099 if (sendAdded) { 9100 sendPackageAddedForUser(packageName, pkgSetting, userId); 9101 } 9102 } finally { 9103 Binder.restoreCallingIdentity(callingId); 9104 } 9105 9106 return PackageManager.INSTALL_SUCCEEDED; 9107 } 9108 9109 boolean isUserRestricted(int userId, String restrictionKey) { 9110 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9111 if (restrictions.getBoolean(restrictionKey, false)) { 9112 Log.w(TAG, "User is restricted: " + restrictionKey); 9113 return true; 9114 } 9115 return false; 9116 } 9117 9118 @Override 9119 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9120 mContext.enforceCallingOrSelfPermission( 9121 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9122 "Only package verification agents can verify applications"); 9123 9124 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9125 final PackageVerificationResponse response = new PackageVerificationResponse( 9126 verificationCode, Binder.getCallingUid()); 9127 msg.arg1 = id; 9128 msg.obj = response; 9129 mHandler.sendMessage(msg); 9130 } 9131 9132 @Override 9133 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9134 long millisecondsToDelay) { 9135 mContext.enforceCallingOrSelfPermission( 9136 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9137 "Only package verification agents can extend verification timeouts"); 9138 9139 final PackageVerificationState state = mPendingVerification.get(id); 9140 final PackageVerificationResponse response = new PackageVerificationResponse( 9141 verificationCodeAtTimeout, Binder.getCallingUid()); 9142 9143 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9144 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9145 } 9146 if (millisecondsToDelay < 0) { 9147 millisecondsToDelay = 0; 9148 } 9149 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9150 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9151 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9152 } 9153 9154 if ((state != null) && !state.timeoutExtended()) { 9155 state.extendTimeout(); 9156 9157 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9158 msg.arg1 = id; 9159 msg.obj = response; 9160 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9161 } 9162 } 9163 9164 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9165 int verificationCode, UserHandle user) { 9166 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9167 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9168 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9169 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9170 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9171 9172 mContext.sendBroadcastAsUser(intent, user, 9173 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9174 } 9175 9176 private ComponentName matchComponentForVerifier(String packageName, 9177 List<ResolveInfo> receivers) { 9178 ActivityInfo targetReceiver = null; 9179 9180 final int NR = receivers.size(); 9181 for (int i = 0; i < NR; i++) { 9182 final ResolveInfo info = receivers.get(i); 9183 if (info.activityInfo == null) { 9184 continue; 9185 } 9186 9187 if (packageName.equals(info.activityInfo.packageName)) { 9188 targetReceiver = info.activityInfo; 9189 break; 9190 } 9191 } 9192 9193 if (targetReceiver == null) { 9194 return null; 9195 } 9196 9197 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9198 } 9199 9200 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9201 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9202 if (pkgInfo.verifiers.length == 0) { 9203 return null; 9204 } 9205 9206 final int N = pkgInfo.verifiers.length; 9207 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9208 for (int i = 0; i < N; i++) { 9209 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9210 9211 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9212 receivers); 9213 if (comp == null) { 9214 continue; 9215 } 9216 9217 final int verifierUid = getUidForVerifier(verifierInfo); 9218 if (verifierUid == -1) { 9219 continue; 9220 } 9221 9222 if (DEBUG_VERIFY) { 9223 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9224 + " with the correct signature"); 9225 } 9226 sufficientVerifiers.add(comp); 9227 verificationState.addSufficientVerifier(verifierUid); 9228 } 9229 9230 return sufficientVerifiers; 9231 } 9232 9233 private int getUidForVerifier(VerifierInfo verifierInfo) { 9234 synchronized (mPackages) { 9235 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9236 if (pkg == null) { 9237 return -1; 9238 } else if (pkg.mSignatures.length != 1) { 9239 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9240 + " has more than one signature; ignoring"); 9241 return -1; 9242 } 9243 9244 /* 9245 * If the public key of the package's signature does not match 9246 * our expected public key, then this is a different package and 9247 * we should skip. 9248 */ 9249 9250 final byte[] expectedPublicKey; 9251 try { 9252 final Signature verifierSig = pkg.mSignatures[0]; 9253 final PublicKey publicKey = verifierSig.getPublicKey(); 9254 expectedPublicKey = publicKey.getEncoded(); 9255 } catch (CertificateException e) { 9256 return -1; 9257 } 9258 9259 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9260 9261 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9262 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9263 + " does not have the expected public key; ignoring"); 9264 return -1; 9265 } 9266 9267 return pkg.applicationInfo.uid; 9268 } 9269 } 9270 9271 @Override 9272 public void finishPackageInstall(int token) { 9273 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9274 9275 if (DEBUG_INSTALL) { 9276 Slog.v(TAG, "BM finishing package install for " + token); 9277 } 9278 9279 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9280 mHandler.sendMessage(msg); 9281 } 9282 9283 /** 9284 * Get the verification agent timeout. 9285 * 9286 * @return verification timeout in milliseconds 9287 */ 9288 private long getVerificationTimeout() { 9289 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9290 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9291 DEFAULT_VERIFICATION_TIMEOUT); 9292 } 9293 9294 /** 9295 * Get the default verification agent response code. 9296 * 9297 * @return default verification response code 9298 */ 9299 private int getDefaultVerificationResponse() { 9300 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9301 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9302 DEFAULT_VERIFICATION_RESPONSE); 9303 } 9304 9305 /** 9306 * Check whether or not package verification has been enabled. 9307 * 9308 * @return true if verification should be performed 9309 */ 9310 private boolean isVerificationEnabled(int userId, int installFlags) { 9311 if (!DEFAULT_VERIFY_ENABLE) { 9312 return false; 9313 } 9314 9315 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9316 9317 // Check if installing from ADB 9318 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9319 // Do not run verification in a test harness environment 9320 if (ActivityManager.isRunningInTestHarness()) { 9321 return false; 9322 } 9323 if (ensureVerifyAppsEnabled) { 9324 return true; 9325 } 9326 // Check if the developer does not want package verification for ADB installs 9327 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9328 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9329 return false; 9330 } 9331 } 9332 9333 if (ensureVerifyAppsEnabled) { 9334 return true; 9335 } 9336 9337 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9338 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9339 } 9340 9341 @Override 9342 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9343 throws RemoteException { 9344 mContext.enforceCallingOrSelfPermission( 9345 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9346 "Only intentfilter verification agents can verify applications"); 9347 9348 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9349 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9350 Binder.getCallingUid(), verificationCode, failedDomains); 9351 msg.arg1 = id; 9352 msg.obj = response; 9353 mHandler.sendMessage(msg); 9354 } 9355 9356 @Override 9357 public int getIntentVerificationStatus(String packageName, int userId) { 9358 synchronized (mPackages) { 9359 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9360 } 9361 } 9362 9363 @Override 9364 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9365 boolean result = false; 9366 synchronized (mPackages) { 9367 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9368 } 9369 if (result) { 9370 scheduleWritePackageRestrictionsLocked(userId); 9371 } 9372 return result; 9373 } 9374 9375 @Override 9376 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9377 synchronized (mPackages) { 9378 return mSettings.getIntentFilterVerificationsLPr(packageName); 9379 } 9380 } 9381 9382 @Override 9383 public List<IntentFilter> getAllIntentFilters(String packageName) { 9384 if (TextUtils.isEmpty(packageName)) { 9385 return Collections.<IntentFilter>emptyList(); 9386 } 9387 synchronized (mPackages) { 9388 PackageParser.Package pkg = mPackages.get(packageName); 9389 if (pkg == null || pkg.activities == null) { 9390 return Collections.<IntentFilter>emptyList(); 9391 } 9392 final int count = pkg.activities.size(); 9393 ArrayList<IntentFilter> result = new ArrayList<>(); 9394 for (int n=0; n<count; n++) { 9395 PackageParser.Activity activity = pkg.activities.get(n); 9396 if (activity.intents != null || activity.intents.size() > 0) { 9397 result.addAll(activity.intents); 9398 } 9399 } 9400 return result; 9401 } 9402 } 9403 9404 @Override 9405 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9406 synchronized (mPackages) { 9407 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9408 if (packageName != null) { 9409 result |= updateIntentVerificationStatus(packageName, 9410 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9411 UserHandle.myUserId()); 9412 } 9413 return result; 9414 } 9415 } 9416 9417 @Override 9418 public String getDefaultBrowserPackageName(int userId) { 9419 synchronized (mPackages) { 9420 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9421 } 9422 } 9423 9424 /** 9425 * Get the "allow unknown sources" setting. 9426 * 9427 * @return the current "allow unknown sources" setting 9428 */ 9429 private int getUnknownSourcesSettings() { 9430 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9431 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9432 -1); 9433 } 9434 9435 @Override 9436 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9437 final int uid = Binder.getCallingUid(); 9438 // writer 9439 synchronized (mPackages) { 9440 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9441 if (targetPackageSetting == null) { 9442 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9443 } 9444 9445 PackageSetting installerPackageSetting; 9446 if (installerPackageName != null) { 9447 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9448 if (installerPackageSetting == null) { 9449 throw new IllegalArgumentException("Unknown installer package: " 9450 + installerPackageName); 9451 } 9452 } else { 9453 installerPackageSetting = null; 9454 } 9455 9456 Signature[] callerSignature; 9457 Object obj = mSettings.getUserIdLPr(uid); 9458 if (obj != null) { 9459 if (obj instanceof SharedUserSetting) { 9460 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9461 } else if (obj instanceof PackageSetting) { 9462 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9463 } else { 9464 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9465 } 9466 } else { 9467 throw new SecurityException("Unknown calling uid " + uid); 9468 } 9469 9470 // Verify: can't set installerPackageName to a package that is 9471 // not signed with the same cert as the caller. 9472 if (installerPackageSetting != null) { 9473 if (compareSignatures(callerSignature, 9474 installerPackageSetting.signatures.mSignatures) 9475 != PackageManager.SIGNATURE_MATCH) { 9476 throw new SecurityException( 9477 "Caller does not have same cert as new installer package " 9478 + installerPackageName); 9479 } 9480 } 9481 9482 // Verify: if target already has an installer package, it must 9483 // be signed with the same cert as the caller. 9484 if (targetPackageSetting.installerPackageName != null) { 9485 PackageSetting setting = mSettings.mPackages.get( 9486 targetPackageSetting.installerPackageName); 9487 // If the currently set package isn't valid, then it's always 9488 // okay to change it. 9489 if (setting != null) { 9490 if (compareSignatures(callerSignature, 9491 setting.signatures.mSignatures) 9492 != PackageManager.SIGNATURE_MATCH) { 9493 throw new SecurityException( 9494 "Caller does not have same cert as old installer package " 9495 + targetPackageSetting.installerPackageName); 9496 } 9497 } 9498 } 9499 9500 // Okay! 9501 targetPackageSetting.installerPackageName = installerPackageName; 9502 scheduleWriteSettingsLocked(); 9503 } 9504 } 9505 9506 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9507 // Queue up an async operation since the package installation may take a little while. 9508 mHandler.post(new Runnable() { 9509 public void run() { 9510 mHandler.removeCallbacks(this); 9511 // Result object to be returned 9512 PackageInstalledInfo res = new PackageInstalledInfo(); 9513 res.returnCode = currentStatus; 9514 res.uid = -1; 9515 res.pkg = null; 9516 res.removedInfo = new PackageRemovedInfo(); 9517 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9518 args.doPreInstall(res.returnCode); 9519 synchronized (mInstallLock) { 9520 installPackageLI(args, res); 9521 } 9522 args.doPostInstall(res.returnCode, res.uid); 9523 } 9524 9525 // A restore should be performed at this point if (a) the install 9526 // succeeded, (b) the operation is not an update, and (c) the new 9527 // package has not opted out of backup participation. 9528 final boolean update = res.removedInfo.removedPackage != null; 9529 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9530 boolean doRestore = !update 9531 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9532 9533 // Set up the post-install work request bookkeeping. This will be used 9534 // and cleaned up by the post-install event handling regardless of whether 9535 // there's a restore pass performed. Token values are >= 1. 9536 int token; 9537 if (mNextInstallToken < 0) mNextInstallToken = 1; 9538 token = mNextInstallToken++; 9539 9540 PostInstallData data = new PostInstallData(args, res); 9541 mRunningInstalls.put(token, data); 9542 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9543 9544 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9545 // Pass responsibility to the Backup Manager. It will perform a 9546 // restore if appropriate, then pass responsibility back to the 9547 // Package Manager to run the post-install observer callbacks 9548 // and broadcasts. 9549 IBackupManager bm = IBackupManager.Stub.asInterface( 9550 ServiceManager.getService(Context.BACKUP_SERVICE)); 9551 if (bm != null) { 9552 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9553 + " to BM for possible restore"); 9554 try { 9555 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9556 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9557 } else { 9558 doRestore = false; 9559 } 9560 } catch (RemoteException e) { 9561 // can't happen; the backup manager is local 9562 } catch (Exception e) { 9563 Slog.e(TAG, "Exception trying to enqueue restore", e); 9564 doRestore = false; 9565 } 9566 } else { 9567 Slog.e(TAG, "Backup Manager not found!"); 9568 doRestore = false; 9569 } 9570 } 9571 9572 if (!doRestore) { 9573 // No restore possible, or the Backup Manager was mysteriously not 9574 // available -- just fire the post-install work request directly. 9575 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9576 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9577 mHandler.sendMessage(msg); 9578 } 9579 } 9580 }); 9581 } 9582 9583 private abstract class HandlerParams { 9584 private static final int MAX_RETRIES = 4; 9585 9586 /** 9587 * Number of times startCopy() has been attempted and had a non-fatal 9588 * error. 9589 */ 9590 private int mRetries = 0; 9591 9592 /** User handle for the user requesting the information or installation. */ 9593 private final UserHandle mUser; 9594 9595 HandlerParams(UserHandle user) { 9596 mUser = user; 9597 } 9598 9599 UserHandle getUser() { 9600 return mUser; 9601 } 9602 9603 final boolean startCopy() { 9604 boolean res; 9605 try { 9606 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9607 9608 if (++mRetries > MAX_RETRIES) { 9609 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9610 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9611 handleServiceError(); 9612 return false; 9613 } else { 9614 handleStartCopy(); 9615 res = true; 9616 } 9617 } catch (RemoteException e) { 9618 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9619 mHandler.sendEmptyMessage(MCS_RECONNECT); 9620 res = false; 9621 } 9622 handleReturnCode(); 9623 return res; 9624 } 9625 9626 final void serviceError() { 9627 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9628 handleServiceError(); 9629 handleReturnCode(); 9630 } 9631 9632 abstract void handleStartCopy() throws RemoteException; 9633 abstract void handleServiceError(); 9634 abstract void handleReturnCode(); 9635 } 9636 9637 class MeasureParams extends HandlerParams { 9638 private final PackageStats mStats; 9639 private boolean mSuccess; 9640 9641 private final IPackageStatsObserver mObserver; 9642 9643 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9644 super(new UserHandle(stats.userHandle)); 9645 mObserver = observer; 9646 mStats = stats; 9647 } 9648 9649 @Override 9650 public String toString() { 9651 return "MeasureParams{" 9652 + Integer.toHexString(System.identityHashCode(this)) 9653 + " " + mStats.packageName + "}"; 9654 } 9655 9656 @Override 9657 void handleStartCopy() throws RemoteException { 9658 synchronized (mInstallLock) { 9659 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9660 } 9661 9662 if (mSuccess) { 9663 final boolean mounted; 9664 if (Environment.isExternalStorageEmulated()) { 9665 mounted = true; 9666 } else { 9667 final String status = Environment.getExternalStorageState(); 9668 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9669 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9670 } 9671 9672 if (mounted) { 9673 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9674 9675 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9676 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9677 9678 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9679 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9680 9681 // Always subtract cache size, since it's a subdirectory 9682 mStats.externalDataSize -= mStats.externalCacheSize; 9683 9684 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9685 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9686 9687 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9688 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9689 } 9690 } 9691 } 9692 9693 @Override 9694 void handleReturnCode() { 9695 if (mObserver != null) { 9696 try { 9697 mObserver.onGetStatsCompleted(mStats, mSuccess); 9698 } catch (RemoteException e) { 9699 Slog.i(TAG, "Observer no longer exists."); 9700 } 9701 } 9702 } 9703 9704 @Override 9705 void handleServiceError() { 9706 Slog.e(TAG, "Could not measure application " + mStats.packageName 9707 + " external storage"); 9708 } 9709 } 9710 9711 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9712 throws RemoteException { 9713 long result = 0; 9714 for (File path : paths) { 9715 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9716 } 9717 return result; 9718 } 9719 9720 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9721 for (File path : paths) { 9722 try { 9723 mcs.clearDirectory(path.getAbsolutePath()); 9724 } catch (RemoteException e) { 9725 } 9726 } 9727 } 9728 9729 static class OriginInfo { 9730 /** 9731 * Location where install is coming from, before it has been 9732 * copied/renamed into place. This could be a single monolithic APK 9733 * file, or a cluster directory. This location may be untrusted. 9734 */ 9735 final File file; 9736 final String cid; 9737 9738 /** 9739 * Flag indicating that {@link #file} or {@link #cid} has already been 9740 * staged, meaning downstream users don't need to defensively copy the 9741 * contents. 9742 */ 9743 final boolean staged; 9744 9745 /** 9746 * Flag indicating that {@link #file} or {@link #cid} is an already 9747 * installed app that is being moved. 9748 */ 9749 final boolean existing; 9750 9751 final String resolvedPath; 9752 final File resolvedFile; 9753 9754 static OriginInfo fromNothing() { 9755 return new OriginInfo(null, null, false, false); 9756 } 9757 9758 static OriginInfo fromUntrustedFile(File file) { 9759 return new OriginInfo(file, null, false, false); 9760 } 9761 9762 static OriginInfo fromExistingFile(File file) { 9763 return new OriginInfo(file, null, false, true); 9764 } 9765 9766 static OriginInfo fromStagedFile(File file) { 9767 return new OriginInfo(file, null, true, false); 9768 } 9769 9770 static OriginInfo fromStagedContainer(String cid) { 9771 return new OriginInfo(null, cid, true, false); 9772 } 9773 9774 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9775 this.file = file; 9776 this.cid = cid; 9777 this.staged = staged; 9778 this.existing = existing; 9779 9780 if (cid != null) { 9781 resolvedPath = PackageHelper.getSdDir(cid); 9782 resolvedFile = new File(resolvedPath); 9783 } else if (file != null) { 9784 resolvedPath = file.getAbsolutePath(); 9785 resolvedFile = file; 9786 } else { 9787 resolvedPath = null; 9788 resolvedFile = null; 9789 } 9790 } 9791 } 9792 9793 class MoveInfo { 9794 final int moveId; 9795 final String fromUuid; 9796 final String toUuid; 9797 final String packageName; 9798 final String dataAppName; 9799 final int appId; 9800 final String seinfo; 9801 9802 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9803 String dataAppName, int appId, String seinfo) { 9804 this.moveId = moveId; 9805 this.fromUuid = fromUuid; 9806 this.toUuid = toUuid; 9807 this.packageName = packageName; 9808 this.dataAppName = dataAppName; 9809 this.appId = appId; 9810 this.seinfo = seinfo; 9811 } 9812 } 9813 9814 class InstallParams extends HandlerParams { 9815 final OriginInfo origin; 9816 final MoveInfo move; 9817 final IPackageInstallObserver2 observer; 9818 int installFlags; 9819 final String installerPackageName; 9820 final String volumeUuid; 9821 final VerificationParams verificationParams; 9822 private InstallArgs mArgs; 9823 private int mRet; 9824 final String packageAbiOverride; 9825 9826 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9827 int installFlags, String installerPackageName, String volumeUuid, 9828 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9829 super(user); 9830 this.origin = origin; 9831 this.move = move; 9832 this.observer = observer; 9833 this.installFlags = installFlags; 9834 this.installerPackageName = installerPackageName; 9835 this.volumeUuid = volumeUuid; 9836 this.verificationParams = verificationParams; 9837 this.packageAbiOverride = packageAbiOverride; 9838 } 9839 9840 @Override 9841 public String toString() { 9842 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9843 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9844 } 9845 9846 public ManifestDigest getManifestDigest() { 9847 if (verificationParams == null) { 9848 return null; 9849 } 9850 return verificationParams.getManifestDigest(); 9851 } 9852 9853 private int installLocationPolicy(PackageInfoLite pkgLite) { 9854 String packageName = pkgLite.packageName; 9855 int installLocation = pkgLite.installLocation; 9856 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9857 // reader 9858 synchronized (mPackages) { 9859 PackageParser.Package pkg = mPackages.get(packageName); 9860 if (pkg != null) { 9861 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9862 // Check for downgrading. 9863 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9864 try { 9865 checkDowngrade(pkg, pkgLite); 9866 } catch (PackageManagerException e) { 9867 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9868 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9869 } 9870 } 9871 // Check for updated system application. 9872 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9873 if (onSd) { 9874 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9875 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9876 } 9877 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9878 } else { 9879 if (onSd) { 9880 // Install flag overrides everything. 9881 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9882 } 9883 // If current upgrade specifies particular preference 9884 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9885 // Application explicitly specified internal. 9886 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9887 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9888 // App explictly prefers external. Let policy decide 9889 } else { 9890 // Prefer previous location 9891 if (isExternal(pkg)) { 9892 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9893 } 9894 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9895 } 9896 } 9897 } else { 9898 // Invalid install. Return error code 9899 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9900 } 9901 } 9902 } 9903 // All the special cases have been taken care of. 9904 // Return result based on recommended install location. 9905 if (onSd) { 9906 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9907 } 9908 return pkgLite.recommendedInstallLocation; 9909 } 9910 9911 /* 9912 * Invoke remote method to get package information and install 9913 * location values. Override install location based on default 9914 * policy if needed and then create install arguments based 9915 * on the install location. 9916 */ 9917 public void handleStartCopy() throws RemoteException { 9918 int ret = PackageManager.INSTALL_SUCCEEDED; 9919 9920 // If we're already staged, we've firmly committed to an install location 9921 if (origin.staged) { 9922 if (origin.file != null) { 9923 installFlags |= PackageManager.INSTALL_INTERNAL; 9924 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9925 } else if (origin.cid != null) { 9926 installFlags |= PackageManager.INSTALL_EXTERNAL; 9927 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9928 } else { 9929 throw new IllegalStateException("Invalid stage location"); 9930 } 9931 } 9932 9933 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9934 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9935 9936 PackageInfoLite pkgLite = null; 9937 9938 if (onInt && onSd) { 9939 // Check if both bits are set. 9940 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9941 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9942 } else { 9943 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9944 packageAbiOverride); 9945 9946 /* 9947 * If we have too little free space, try to free cache 9948 * before giving up. 9949 */ 9950 if (!origin.staged && pkgLite.recommendedInstallLocation 9951 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9952 // TODO: focus freeing disk space on the target device 9953 final StorageManager storage = StorageManager.from(mContext); 9954 final long lowThreshold = storage.getStorageLowBytes( 9955 Environment.getDataDirectory()); 9956 9957 final long sizeBytes = mContainerService.calculateInstalledSize( 9958 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9959 9960 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9961 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9962 installFlags, packageAbiOverride); 9963 } 9964 9965 /* 9966 * The cache free must have deleted the file we 9967 * downloaded to install. 9968 * 9969 * TODO: fix the "freeCache" call to not delete 9970 * the file we care about. 9971 */ 9972 if (pkgLite.recommendedInstallLocation 9973 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9974 pkgLite.recommendedInstallLocation 9975 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9976 } 9977 } 9978 } 9979 9980 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9981 int loc = pkgLite.recommendedInstallLocation; 9982 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9983 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9984 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9985 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9986 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9987 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9988 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9989 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9990 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9991 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9992 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9993 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9994 } else { 9995 // Override with defaults if needed. 9996 loc = installLocationPolicy(pkgLite); 9997 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9998 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9999 } else if (!onSd && !onInt) { 10000 // Override install location with flags 10001 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10002 // Set the flag to install on external media. 10003 installFlags |= PackageManager.INSTALL_EXTERNAL; 10004 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10005 } else { 10006 // Make sure the flag for installing on external 10007 // media is unset 10008 installFlags |= PackageManager.INSTALL_INTERNAL; 10009 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10010 } 10011 } 10012 } 10013 } 10014 10015 final InstallArgs args = createInstallArgs(this); 10016 mArgs = args; 10017 10018 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10019 /* 10020 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10021 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10022 */ 10023 int userIdentifier = getUser().getIdentifier(); 10024 if (userIdentifier == UserHandle.USER_ALL 10025 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10026 userIdentifier = UserHandle.USER_OWNER; 10027 } 10028 10029 /* 10030 * Determine if we have any installed package verifiers. If we 10031 * do, then we'll defer to them to verify the packages. 10032 */ 10033 final int requiredUid = mRequiredVerifierPackage == null ? -1 10034 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10035 if (!origin.existing && requiredUid != -1 10036 && isVerificationEnabled(userIdentifier, installFlags)) { 10037 final Intent verification = new Intent( 10038 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10039 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10040 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10041 PACKAGE_MIME_TYPE); 10042 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10043 10044 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10045 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10046 0 /* TODO: Which userId? */); 10047 10048 if (DEBUG_VERIFY) { 10049 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10050 + verification.toString() + " with " + pkgLite.verifiers.length 10051 + " optional verifiers"); 10052 } 10053 10054 final int verificationId = mPendingVerificationToken++; 10055 10056 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10057 10058 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10059 installerPackageName); 10060 10061 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10062 installFlags); 10063 10064 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10065 pkgLite.packageName); 10066 10067 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10068 pkgLite.versionCode); 10069 10070 if (verificationParams != null) { 10071 if (verificationParams.getVerificationURI() != null) { 10072 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10073 verificationParams.getVerificationURI()); 10074 } 10075 if (verificationParams.getOriginatingURI() != null) { 10076 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10077 verificationParams.getOriginatingURI()); 10078 } 10079 if (verificationParams.getReferrer() != null) { 10080 verification.putExtra(Intent.EXTRA_REFERRER, 10081 verificationParams.getReferrer()); 10082 } 10083 if (verificationParams.getOriginatingUid() >= 0) { 10084 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10085 verificationParams.getOriginatingUid()); 10086 } 10087 if (verificationParams.getInstallerUid() >= 0) { 10088 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10089 verificationParams.getInstallerUid()); 10090 } 10091 } 10092 10093 final PackageVerificationState verificationState = new PackageVerificationState( 10094 requiredUid, args); 10095 10096 mPendingVerification.append(verificationId, verificationState); 10097 10098 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10099 receivers, verificationState); 10100 10101 /* 10102 * If any sufficient verifiers were listed in the package 10103 * manifest, attempt to ask them. 10104 */ 10105 if (sufficientVerifiers != null) { 10106 final int N = sufficientVerifiers.size(); 10107 if (N == 0) { 10108 Slog.i(TAG, "Additional verifiers required, but none installed."); 10109 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10110 } else { 10111 for (int i = 0; i < N; i++) { 10112 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10113 10114 final Intent sufficientIntent = new Intent(verification); 10115 sufficientIntent.setComponent(verifierComponent); 10116 10117 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10118 } 10119 } 10120 } 10121 10122 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10123 mRequiredVerifierPackage, receivers); 10124 if (ret == PackageManager.INSTALL_SUCCEEDED 10125 && mRequiredVerifierPackage != null) { 10126 /* 10127 * Send the intent to the required verification agent, 10128 * but only start the verification timeout after the 10129 * target BroadcastReceivers have run. 10130 */ 10131 verification.setComponent(requiredVerifierComponent); 10132 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10133 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10134 new BroadcastReceiver() { 10135 @Override 10136 public void onReceive(Context context, Intent intent) { 10137 final Message msg = mHandler 10138 .obtainMessage(CHECK_PENDING_VERIFICATION); 10139 msg.arg1 = verificationId; 10140 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10141 } 10142 }, null, 0, null, null); 10143 10144 /* 10145 * We don't want the copy to proceed until verification 10146 * succeeds, so null out this field. 10147 */ 10148 mArgs = null; 10149 } 10150 } else { 10151 /* 10152 * No package verification is enabled, so immediately start 10153 * the remote call to initiate copy using temporary file. 10154 */ 10155 ret = args.copyApk(mContainerService, true); 10156 } 10157 } 10158 10159 mRet = ret; 10160 } 10161 10162 @Override 10163 void handleReturnCode() { 10164 // If mArgs is null, then MCS couldn't be reached. When it 10165 // reconnects, it will try again to install. At that point, this 10166 // will succeed. 10167 if (mArgs != null) { 10168 processPendingInstall(mArgs, mRet); 10169 } 10170 } 10171 10172 @Override 10173 void handleServiceError() { 10174 mArgs = createInstallArgs(this); 10175 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10176 } 10177 10178 public boolean isForwardLocked() { 10179 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10180 } 10181 } 10182 10183 /** 10184 * Used during creation of InstallArgs 10185 * 10186 * @param installFlags package installation flags 10187 * @return true if should be installed on external storage 10188 */ 10189 private static boolean installOnExternalAsec(int installFlags) { 10190 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10191 return false; 10192 } 10193 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10194 return true; 10195 } 10196 return false; 10197 } 10198 10199 /** 10200 * Used during creation of InstallArgs 10201 * 10202 * @param installFlags package installation flags 10203 * @return true if should be installed as forward locked 10204 */ 10205 private static boolean installForwardLocked(int installFlags) { 10206 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10207 } 10208 10209 private InstallArgs createInstallArgs(InstallParams params) { 10210 if (params.move != null) { 10211 return new MoveInstallArgs(params); 10212 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10213 return new AsecInstallArgs(params); 10214 } else { 10215 return new FileInstallArgs(params); 10216 } 10217 } 10218 10219 /** 10220 * Create args that describe an existing installed package. Typically used 10221 * when cleaning up old installs, or used as a move source. 10222 */ 10223 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10224 String resourcePath, String[] instructionSets) { 10225 final boolean isInAsec; 10226 if (installOnExternalAsec(installFlags)) { 10227 /* Apps on SD card are always in ASEC containers. */ 10228 isInAsec = true; 10229 } else if (installForwardLocked(installFlags) 10230 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10231 /* 10232 * Forward-locked apps are only in ASEC containers if they're the 10233 * new style 10234 */ 10235 isInAsec = true; 10236 } else { 10237 isInAsec = false; 10238 } 10239 10240 if (isInAsec) { 10241 return new AsecInstallArgs(codePath, instructionSets, 10242 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10243 } else { 10244 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10245 } 10246 } 10247 10248 static abstract class InstallArgs { 10249 /** @see InstallParams#origin */ 10250 final OriginInfo origin; 10251 /** @see InstallParams#move */ 10252 final MoveInfo move; 10253 10254 final IPackageInstallObserver2 observer; 10255 // Always refers to PackageManager flags only 10256 final int installFlags; 10257 final String installerPackageName; 10258 final String volumeUuid; 10259 final ManifestDigest manifestDigest; 10260 final UserHandle user; 10261 final String abiOverride; 10262 10263 // The list of instruction sets supported by this app. This is currently 10264 // only used during the rmdex() phase to clean up resources. We can get rid of this 10265 // if we move dex files under the common app path. 10266 /* nullable */ String[] instructionSets; 10267 10268 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10269 int installFlags, String installerPackageName, String volumeUuid, 10270 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10271 String abiOverride) { 10272 this.origin = origin; 10273 this.move = move; 10274 this.installFlags = installFlags; 10275 this.observer = observer; 10276 this.installerPackageName = installerPackageName; 10277 this.volumeUuid = volumeUuid; 10278 this.manifestDigest = manifestDigest; 10279 this.user = user; 10280 this.instructionSets = instructionSets; 10281 this.abiOverride = abiOverride; 10282 } 10283 10284 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10285 abstract int doPreInstall(int status); 10286 10287 /** 10288 * Rename package into final resting place. All paths on the given 10289 * scanned package should be updated to reflect the rename. 10290 */ 10291 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10292 abstract int doPostInstall(int status, int uid); 10293 10294 /** @see PackageSettingBase#codePathString */ 10295 abstract String getCodePath(); 10296 /** @see PackageSettingBase#resourcePathString */ 10297 abstract String getResourcePath(); 10298 10299 // Need installer lock especially for dex file removal. 10300 abstract void cleanUpResourcesLI(); 10301 abstract boolean doPostDeleteLI(boolean delete); 10302 10303 /** 10304 * Called before the source arguments are copied. This is used mostly 10305 * for MoveParams when it needs to read the source file to put it in the 10306 * destination. 10307 */ 10308 int doPreCopy() { 10309 return PackageManager.INSTALL_SUCCEEDED; 10310 } 10311 10312 /** 10313 * Called after the source arguments are copied. This is used mostly for 10314 * MoveParams when it needs to read the source file to put it in the 10315 * destination. 10316 * 10317 * @return 10318 */ 10319 int doPostCopy(int uid) { 10320 return PackageManager.INSTALL_SUCCEEDED; 10321 } 10322 10323 protected boolean isFwdLocked() { 10324 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10325 } 10326 10327 protected boolean isExternalAsec() { 10328 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10329 } 10330 10331 UserHandle getUser() { 10332 return user; 10333 } 10334 } 10335 10336 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10337 if (!allCodePaths.isEmpty()) { 10338 if (instructionSets == null) { 10339 throw new IllegalStateException("instructionSet == null"); 10340 } 10341 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10342 for (String codePath : allCodePaths) { 10343 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10344 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10345 if (retCode < 0) { 10346 Slog.w(TAG, "Couldn't remove dex file for package: " 10347 + " at location " + codePath + ", retcode=" + retCode); 10348 // we don't consider this to be a failure of the core package deletion 10349 } 10350 } 10351 } 10352 } 10353 } 10354 10355 /** 10356 * Logic to handle installation of non-ASEC applications, including copying 10357 * and renaming logic. 10358 */ 10359 class FileInstallArgs extends InstallArgs { 10360 private File codeFile; 10361 private File resourceFile; 10362 10363 // Example topology: 10364 // /data/app/com.example/base.apk 10365 // /data/app/com.example/split_foo.apk 10366 // /data/app/com.example/lib/arm/libfoo.so 10367 // /data/app/com.example/lib/arm64/libfoo.so 10368 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10369 10370 /** New install */ 10371 FileInstallArgs(InstallParams params) { 10372 super(params.origin, params.move, params.observer, params.installFlags, 10373 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10374 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10375 if (isFwdLocked()) { 10376 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10377 } 10378 } 10379 10380 /** Existing install */ 10381 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10382 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10383 null); 10384 this.codeFile = (codePath != null) ? new File(codePath) : null; 10385 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10386 } 10387 10388 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10389 if (origin.staged) { 10390 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10391 codeFile = origin.file; 10392 resourceFile = origin.file; 10393 return PackageManager.INSTALL_SUCCEEDED; 10394 } 10395 10396 try { 10397 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10398 codeFile = tempDir; 10399 resourceFile = tempDir; 10400 } catch (IOException e) { 10401 Slog.w(TAG, "Failed to create copy file: " + e); 10402 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10403 } 10404 10405 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10406 @Override 10407 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10408 if (!FileUtils.isValidExtFilename(name)) { 10409 throw new IllegalArgumentException("Invalid filename: " + name); 10410 } 10411 try { 10412 final File file = new File(codeFile, name); 10413 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10414 O_RDWR | O_CREAT, 0644); 10415 Os.chmod(file.getAbsolutePath(), 0644); 10416 return new ParcelFileDescriptor(fd); 10417 } catch (ErrnoException e) { 10418 throw new RemoteException("Failed to open: " + e.getMessage()); 10419 } 10420 } 10421 }; 10422 10423 int ret = PackageManager.INSTALL_SUCCEEDED; 10424 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10425 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10426 Slog.e(TAG, "Failed to copy package"); 10427 return ret; 10428 } 10429 10430 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10431 NativeLibraryHelper.Handle handle = null; 10432 try { 10433 handle = NativeLibraryHelper.Handle.create(codeFile); 10434 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10435 abiOverride); 10436 } catch (IOException e) { 10437 Slog.e(TAG, "Copying native libraries failed", e); 10438 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10439 } finally { 10440 IoUtils.closeQuietly(handle); 10441 } 10442 10443 return ret; 10444 } 10445 10446 int doPreInstall(int status) { 10447 if (status != PackageManager.INSTALL_SUCCEEDED) { 10448 cleanUp(); 10449 } 10450 return status; 10451 } 10452 10453 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10454 if (status != PackageManager.INSTALL_SUCCEEDED) { 10455 cleanUp(); 10456 return false; 10457 } 10458 10459 final File targetDir = codeFile.getParentFile(); 10460 final File beforeCodeFile = codeFile; 10461 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10462 10463 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10464 try { 10465 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10466 } catch (ErrnoException e) { 10467 Slog.w(TAG, "Failed to rename", e); 10468 return false; 10469 } 10470 10471 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10472 Slog.w(TAG, "Failed to restorecon"); 10473 return false; 10474 } 10475 10476 // Reflect the rename internally 10477 codeFile = afterCodeFile; 10478 resourceFile = afterCodeFile; 10479 10480 // Reflect the rename in scanned details 10481 pkg.codePath = afterCodeFile.getAbsolutePath(); 10482 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10483 pkg.baseCodePath); 10484 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10485 pkg.splitCodePaths); 10486 10487 // Reflect the rename in app info 10488 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10489 pkg.applicationInfo.setCodePath(pkg.codePath); 10490 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10491 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10492 pkg.applicationInfo.setResourcePath(pkg.codePath); 10493 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10494 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10495 10496 return true; 10497 } 10498 10499 int doPostInstall(int status, int uid) { 10500 if (status != PackageManager.INSTALL_SUCCEEDED) { 10501 cleanUp(); 10502 } 10503 return status; 10504 } 10505 10506 @Override 10507 String getCodePath() { 10508 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10509 } 10510 10511 @Override 10512 String getResourcePath() { 10513 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10514 } 10515 10516 private boolean cleanUp() { 10517 if (codeFile == null || !codeFile.exists()) { 10518 return false; 10519 } 10520 10521 if (codeFile.isDirectory()) { 10522 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10523 } else { 10524 codeFile.delete(); 10525 } 10526 10527 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10528 resourceFile.delete(); 10529 } 10530 10531 return true; 10532 } 10533 10534 void cleanUpResourcesLI() { 10535 // Try enumerating all code paths before deleting 10536 List<String> allCodePaths = Collections.EMPTY_LIST; 10537 if (codeFile != null && codeFile.exists()) { 10538 try { 10539 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10540 allCodePaths = pkg.getAllCodePaths(); 10541 } catch (PackageParserException e) { 10542 // Ignored; we tried our best 10543 } 10544 } 10545 10546 cleanUp(); 10547 removeDexFiles(allCodePaths, instructionSets); 10548 } 10549 10550 boolean doPostDeleteLI(boolean delete) { 10551 // XXX err, shouldn't we respect the delete flag? 10552 cleanUpResourcesLI(); 10553 return true; 10554 } 10555 } 10556 10557 private boolean isAsecExternal(String cid) { 10558 final String asecPath = PackageHelper.getSdFilesystem(cid); 10559 return !asecPath.startsWith(mAsecInternalPath); 10560 } 10561 10562 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10563 PackageManagerException { 10564 if (copyRet < 0) { 10565 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10566 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10567 throw new PackageManagerException(copyRet, message); 10568 } 10569 } 10570 } 10571 10572 /** 10573 * Extract the MountService "container ID" from the full code path of an 10574 * .apk. 10575 */ 10576 static String cidFromCodePath(String fullCodePath) { 10577 int eidx = fullCodePath.lastIndexOf("/"); 10578 String subStr1 = fullCodePath.substring(0, eidx); 10579 int sidx = subStr1.lastIndexOf("/"); 10580 return subStr1.substring(sidx+1, eidx); 10581 } 10582 10583 /** 10584 * Logic to handle installation of ASEC applications, including copying and 10585 * renaming logic. 10586 */ 10587 class AsecInstallArgs extends InstallArgs { 10588 static final String RES_FILE_NAME = "pkg.apk"; 10589 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10590 10591 String cid; 10592 String packagePath; 10593 String resourcePath; 10594 10595 /** New install */ 10596 AsecInstallArgs(InstallParams params) { 10597 super(params.origin, params.move, params.observer, params.installFlags, 10598 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10599 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10600 } 10601 10602 /** Existing install */ 10603 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10604 boolean isExternal, boolean isForwardLocked) { 10605 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10606 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10607 instructionSets, null); 10608 // Hackily pretend we're still looking at a full code path 10609 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10610 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10611 } 10612 10613 // Extract cid from fullCodePath 10614 int eidx = fullCodePath.lastIndexOf("/"); 10615 String subStr1 = fullCodePath.substring(0, eidx); 10616 int sidx = subStr1.lastIndexOf("/"); 10617 cid = subStr1.substring(sidx+1, eidx); 10618 setMountPath(subStr1); 10619 } 10620 10621 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10622 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10623 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10624 instructionSets, null); 10625 this.cid = cid; 10626 setMountPath(PackageHelper.getSdDir(cid)); 10627 } 10628 10629 void createCopyFile() { 10630 cid = mInstallerService.allocateExternalStageCidLegacy(); 10631 } 10632 10633 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10634 if (origin.staged) { 10635 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10636 cid = origin.cid; 10637 setMountPath(PackageHelper.getSdDir(cid)); 10638 return PackageManager.INSTALL_SUCCEEDED; 10639 } 10640 10641 if (temp) { 10642 createCopyFile(); 10643 } else { 10644 /* 10645 * Pre-emptively destroy the container since it's destroyed if 10646 * copying fails due to it existing anyway. 10647 */ 10648 PackageHelper.destroySdDir(cid); 10649 } 10650 10651 final String newMountPath = imcs.copyPackageToContainer( 10652 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10653 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10654 10655 if (newMountPath != null) { 10656 setMountPath(newMountPath); 10657 return PackageManager.INSTALL_SUCCEEDED; 10658 } else { 10659 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10660 } 10661 } 10662 10663 @Override 10664 String getCodePath() { 10665 return packagePath; 10666 } 10667 10668 @Override 10669 String getResourcePath() { 10670 return resourcePath; 10671 } 10672 10673 int doPreInstall(int status) { 10674 if (status != PackageManager.INSTALL_SUCCEEDED) { 10675 // Destroy container 10676 PackageHelper.destroySdDir(cid); 10677 } else { 10678 boolean mounted = PackageHelper.isContainerMounted(cid); 10679 if (!mounted) { 10680 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10681 Process.SYSTEM_UID); 10682 if (newMountPath != null) { 10683 setMountPath(newMountPath); 10684 } else { 10685 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10686 } 10687 } 10688 } 10689 return status; 10690 } 10691 10692 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10693 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10694 String newMountPath = null; 10695 if (PackageHelper.isContainerMounted(cid)) { 10696 // Unmount the container 10697 if (!PackageHelper.unMountSdDir(cid)) { 10698 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10699 return false; 10700 } 10701 } 10702 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10703 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10704 " which might be stale. Will try to clean up."); 10705 // Clean up the stale container and proceed to recreate. 10706 if (!PackageHelper.destroySdDir(newCacheId)) { 10707 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10708 return false; 10709 } 10710 // Successfully cleaned up stale container. Try to rename again. 10711 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10712 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10713 + " inspite of cleaning it up."); 10714 return false; 10715 } 10716 } 10717 if (!PackageHelper.isContainerMounted(newCacheId)) { 10718 Slog.w(TAG, "Mounting container " + newCacheId); 10719 newMountPath = PackageHelper.mountSdDir(newCacheId, 10720 getEncryptKey(), Process.SYSTEM_UID); 10721 } else { 10722 newMountPath = PackageHelper.getSdDir(newCacheId); 10723 } 10724 if (newMountPath == null) { 10725 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10726 return false; 10727 } 10728 Log.i(TAG, "Succesfully renamed " + cid + 10729 " to " + newCacheId + 10730 " at new path: " + newMountPath); 10731 cid = newCacheId; 10732 10733 final File beforeCodeFile = new File(packagePath); 10734 setMountPath(newMountPath); 10735 final File afterCodeFile = new File(packagePath); 10736 10737 // Reflect the rename in scanned details 10738 pkg.codePath = afterCodeFile.getAbsolutePath(); 10739 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10740 pkg.baseCodePath); 10741 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10742 pkg.splitCodePaths); 10743 10744 // Reflect the rename in app info 10745 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10746 pkg.applicationInfo.setCodePath(pkg.codePath); 10747 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10748 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10749 pkg.applicationInfo.setResourcePath(pkg.codePath); 10750 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10751 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10752 10753 return true; 10754 } 10755 10756 private void setMountPath(String mountPath) { 10757 final File mountFile = new File(mountPath); 10758 10759 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10760 if (monolithicFile.exists()) { 10761 packagePath = monolithicFile.getAbsolutePath(); 10762 if (isFwdLocked()) { 10763 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10764 } else { 10765 resourcePath = packagePath; 10766 } 10767 } else { 10768 packagePath = mountFile.getAbsolutePath(); 10769 resourcePath = packagePath; 10770 } 10771 } 10772 10773 int doPostInstall(int status, int uid) { 10774 if (status != PackageManager.INSTALL_SUCCEEDED) { 10775 cleanUp(); 10776 } else { 10777 final int groupOwner; 10778 final String protectedFile; 10779 if (isFwdLocked()) { 10780 groupOwner = UserHandle.getSharedAppGid(uid); 10781 protectedFile = RES_FILE_NAME; 10782 } else { 10783 groupOwner = -1; 10784 protectedFile = null; 10785 } 10786 10787 if (uid < Process.FIRST_APPLICATION_UID 10788 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10789 Slog.e(TAG, "Failed to finalize " + cid); 10790 PackageHelper.destroySdDir(cid); 10791 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10792 } 10793 10794 boolean mounted = PackageHelper.isContainerMounted(cid); 10795 if (!mounted) { 10796 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10797 } 10798 } 10799 return status; 10800 } 10801 10802 private void cleanUp() { 10803 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10804 10805 // Destroy secure container 10806 PackageHelper.destroySdDir(cid); 10807 } 10808 10809 private List<String> getAllCodePaths() { 10810 final File codeFile = new File(getCodePath()); 10811 if (codeFile != null && codeFile.exists()) { 10812 try { 10813 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10814 return pkg.getAllCodePaths(); 10815 } catch (PackageParserException e) { 10816 // Ignored; we tried our best 10817 } 10818 } 10819 return Collections.EMPTY_LIST; 10820 } 10821 10822 void cleanUpResourcesLI() { 10823 // Enumerate all code paths before deleting 10824 cleanUpResourcesLI(getAllCodePaths()); 10825 } 10826 10827 private void cleanUpResourcesLI(List<String> allCodePaths) { 10828 cleanUp(); 10829 removeDexFiles(allCodePaths, instructionSets); 10830 } 10831 10832 String getPackageName() { 10833 return getAsecPackageName(cid); 10834 } 10835 10836 boolean doPostDeleteLI(boolean delete) { 10837 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10838 final List<String> allCodePaths = getAllCodePaths(); 10839 boolean mounted = PackageHelper.isContainerMounted(cid); 10840 if (mounted) { 10841 // Unmount first 10842 if (PackageHelper.unMountSdDir(cid)) { 10843 mounted = false; 10844 } 10845 } 10846 if (!mounted && delete) { 10847 cleanUpResourcesLI(allCodePaths); 10848 } 10849 return !mounted; 10850 } 10851 10852 @Override 10853 int doPreCopy() { 10854 if (isFwdLocked()) { 10855 if (!PackageHelper.fixSdPermissions(cid, 10856 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10857 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10858 } 10859 } 10860 10861 return PackageManager.INSTALL_SUCCEEDED; 10862 } 10863 10864 @Override 10865 int doPostCopy(int uid) { 10866 if (isFwdLocked()) { 10867 if (uid < Process.FIRST_APPLICATION_UID 10868 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10869 RES_FILE_NAME)) { 10870 Slog.e(TAG, "Failed to finalize " + cid); 10871 PackageHelper.destroySdDir(cid); 10872 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10873 } 10874 } 10875 10876 return PackageManager.INSTALL_SUCCEEDED; 10877 } 10878 } 10879 10880 /** 10881 * Logic to handle movement of existing installed applications. 10882 */ 10883 class MoveInstallArgs extends InstallArgs { 10884 private File codeFile; 10885 private File resourceFile; 10886 10887 /** New install */ 10888 MoveInstallArgs(InstallParams params) { 10889 super(params.origin, params.move, params.observer, params.installFlags, 10890 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10891 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10892 } 10893 10894 int copyApk(IMediaContainerService imcs, boolean temp) { 10895 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10896 + move.fromUuid + " to " + move.toUuid); 10897 synchronized (mInstaller) { 10898 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10899 move.dataAppName, move.appId, move.seinfo) != 0) { 10900 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10901 } 10902 } 10903 10904 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10905 resourceFile = codeFile; 10906 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10907 10908 return PackageManager.INSTALL_SUCCEEDED; 10909 } 10910 10911 int doPreInstall(int status) { 10912 if (status != PackageManager.INSTALL_SUCCEEDED) { 10913 cleanUp(); 10914 } 10915 return status; 10916 } 10917 10918 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10919 if (status != PackageManager.INSTALL_SUCCEEDED) { 10920 cleanUp(); 10921 return false; 10922 } 10923 10924 // Reflect the move in app info 10925 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10926 pkg.applicationInfo.setCodePath(pkg.codePath); 10927 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10928 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10929 pkg.applicationInfo.setResourcePath(pkg.codePath); 10930 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10931 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10932 10933 return true; 10934 } 10935 10936 int doPostInstall(int status, int uid) { 10937 if (status != PackageManager.INSTALL_SUCCEEDED) { 10938 cleanUp(); 10939 } 10940 return status; 10941 } 10942 10943 @Override 10944 String getCodePath() { 10945 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10946 } 10947 10948 @Override 10949 String getResourcePath() { 10950 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10951 } 10952 10953 private boolean cleanUp() { 10954 if (codeFile == null || !codeFile.exists()) { 10955 return false; 10956 } 10957 10958 if (codeFile.isDirectory()) { 10959 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10960 } else { 10961 codeFile.delete(); 10962 } 10963 10964 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10965 resourceFile.delete(); 10966 } 10967 10968 return true; 10969 } 10970 10971 void cleanUpResourcesLI() { 10972 cleanUp(); 10973 } 10974 10975 boolean doPostDeleteLI(boolean delete) { 10976 // XXX err, shouldn't we respect the delete flag? 10977 cleanUpResourcesLI(); 10978 return true; 10979 } 10980 } 10981 10982 static String getAsecPackageName(String packageCid) { 10983 int idx = packageCid.lastIndexOf("-"); 10984 if (idx == -1) { 10985 return packageCid; 10986 } 10987 return packageCid.substring(0, idx); 10988 } 10989 10990 // Utility method used to create code paths based on package name and available index. 10991 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10992 String idxStr = ""; 10993 int idx = 1; 10994 // Fall back to default value of idx=1 if prefix is not 10995 // part of oldCodePath 10996 if (oldCodePath != null) { 10997 String subStr = oldCodePath; 10998 // Drop the suffix right away 10999 if (suffix != null && subStr.endsWith(suffix)) { 11000 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11001 } 11002 // If oldCodePath already contains prefix find out the 11003 // ending index to either increment or decrement. 11004 int sidx = subStr.lastIndexOf(prefix); 11005 if (sidx != -1) { 11006 subStr = subStr.substring(sidx + prefix.length()); 11007 if (subStr != null) { 11008 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11009 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11010 } 11011 try { 11012 idx = Integer.parseInt(subStr); 11013 if (idx <= 1) { 11014 idx++; 11015 } else { 11016 idx--; 11017 } 11018 } catch(NumberFormatException e) { 11019 } 11020 } 11021 } 11022 } 11023 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11024 return prefix + idxStr; 11025 } 11026 11027 private File getNextCodePath(File targetDir, String packageName) { 11028 int suffix = 1; 11029 File result; 11030 do { 11031 result = new File(targetDir, packageName + "-" + suffix); 11032 suffix++; 11033 } while (result.exists()); 11034 return result; 11035 } 11036 11037 // Utility method that returns the relative package path with respect 11038 // to the installation directory. Like say for /data/data/com.test-1.apk 11039 // string com.test-1 is returned. 11040 static String deriveCodePathName(String codePath) { 11041 if (codePath == null) { 11042 return null; 11043 } 11044 final File codeFile = new File(codePath); 11045 final String name = codeFile.getName(); 11046 if (codeFile.isDirectory()) { 11047 return name; 11048 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11049 final int lastDot = name.lastIndexOf('.'); 11050 return name.substring(0, lastDot); 11051 } else { 11052 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11053 return null; 11054 } 11055 } 11056 11057 class PackageInstalledInfo { 11058 String name; 11059 int uid; 11060 // The set of users that originally had this package installed. 11061 int[] origUsers; 11062 // The set of users that now have this package installed. 11063 int[] newUsers; 11064 PackageParser.Package pkg; 11065 int returnCode; 11066 String returnMsg; 11067 PackageRemovedInfo removedInfo; 11068 11069 public void setError(int code, String msg) { 11070 returnCode = code; 11071 returnMsg = msg; 11072 Slog.w(TAG, msg); 11073 } 11074 11075 public void setError(String msg, PackageParserException e) { 11076 returnCode = e.error; 11077 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11078 Slog.w(TAG, msg, e); 11079 } 11080 11081 public void setError(String msg, PackageManagerException e) { 11082 returnCode = e.error; 11083 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11084 Slog.w(TAG, msg, e); 11085 } 11086 11087 // In some error cases we want to convey more info back to the observer 11088 String origPackage; 11089 String origPermission; 11090 } 11091 11092 /* 11093 * Install a non-existing package. 11094 */ 11095 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11096 UserHandle user, String installerPackageName, String volumeUuid, 11097 PackageInstalledInfo res) { 11098 // Remember this for later, in case we need to rollback this install 11099 String pkgName = pkg.packageName; 11100 11101 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11102 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11103 UserHandle.USER_OWNER).exists(); 11104 synchronized(mPackages) { 11105 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11106 // A package with the same name is already installed, though 11107 // it has been renamed to an older name. The package we 11108 // are trying to install should be installed as an update to 11109 // the existing one, but that has not been requested, so bail. 11110 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11111 + " without first uninstalling package running as " 11112 + mSettings.mRenamedPackages.get(pkgName)); 11113 return; 11114 } 11115 if (mPackages.containsKey(pkgName)) { 11116 // Don't allow installation over an existing package with the same name. 11117 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11118 + " without first uninstalling."); 11119 return; 11120 } 11121 } 11122 11123 try { 11124 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11125 System.currentTimeMillis(), user); 11126 11127 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11128 // delete the partially installed application. the data directory will have to be 11129 // restored if it was already existing 11130 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11131 // remove package from internal structures. Note that we want deletePackageX to 11132 // delete the package data and cache directories that it created in 11133 // scanPackageLocked, unless those directories existed before we even tried to 11134 // install. 11135 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11136 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11137 res.removedInfo, true); 11138 } 11139 11140 } catch (PackageManagerException e) { 11141 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11142 } 11143 } 11144 11145 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11146 // Can't rotate keys during boot or if sharedUser. 11147 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11148 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11149 return false; 11150 } 11151 // app is using upgradeKeySets; make sure all are valid 11152 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11153 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11154 for (int i = 0; i < upgradeKeySets.length; i++) { 11155 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11156 Slog.wtf(TAG, "Package " 11157 + (oldPs.name != null ? oldPs.name : "<null>") 11158 + " contains upgrade-key-set reference to unknown key-set: " 11159 + upgradeKeySets[i] 11160 + " reverting to signatures check."); 11161 return false; 11162 } 11163 } 11164 return true; 11165 } 11166 11167 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11168 // Upgrade keysets are being used. Determine if new package has a superset of the 11169 // required keys. 11170 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11171 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11172 for (int i = 0; i < upgradeKeySets.length; i++) { 11173 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11174 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11175 return true; 11176 } 11177 } 11178 return false; 11179 } 11180 11181 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11182 UserHandle user, String installerPackageName, String volumeUuid, 11183 PackageInstalledInfo res) { 11184 final PackageParser.Package oldPackage; 11185 final String pkgName = pkg.packageName; 11186 final int[] allUsers; 11187 final boolean[] perUserInstalled; 11188 final boolean weFroze; 11189 11190 // First find the old package info and check signatures 11191 synchronized(mPackages) { 11192 oldPackage = mPackages.get(pkgName); 11193 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11194 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11195 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11196 if(!checkUpgradeKeySetLP(ps, pkg)) { 11197 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11198 "New package not signed by keys specified by upgrade-keysets: " 11199 + pkgName); 11200 return; 11201 } 11202 } else { 11203 // default to original signature matching 11204 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11205 != PackageManager.SIGNATURE_MATCH) { 11206 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11207 "New package has a different signature: " + pkgName); 11208 return; 11209 } 11210 } 11211 11212 // In case of rollback, remember per-user/profile install state 11213 allUsers = sUserManager.getUserIds(); 11214 perUserInstalled = new boolean[allUsers.length]; 11215 for (int i = 0; i < allUsers.length; i++) { 11216 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11217 } 11218 11219 // Mark the app as frozen to prevent launching during the upgrade 11220 // process, and then kill all running instances 11221 if (!ps.frozen) { 11222 ps.frozen = true; 11223 weFroze = true; 11224 } else { 11225 weFroze = false; 11226 } 11227 } 11228 11229 // Now that we're guarded by frozen state, kill app during upgrade 11230 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11231 11232 try { 11233 boolean sysPkg = (isSystemApp(oldPackage)); 11234 if (sysPkg) { 11235 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11236 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11237 } else { 11238 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11239 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11240 } 11241 } finally { 11242 // Regardless of success or failure of upgrade steps above, always 11243 // unfreeze the package if we froze it 11244 if (weFroze) { 11245 unfreezePackage(pkgName); 11246 } 11247 } 11248 } 11249 11250 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11251 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11252 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11253 String volumeUuid, PackageInstalledInfo res) { 11254 String pkgName = deletedPackage.packageName; 11255 boolean deletedPkg = true; 11256 boolean updatedSettings = false; 11257 11258 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11259 + deletedPackage); 11260 long origUpdateTime; 11261 if (pkg.mExtras != null) { 11262 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11263 } else { 11264 origUpdateTime = 0; 11265 } 11266 11267 // First delete the existing package while retaining the data directory 11268 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11269 res.removedInfo, true)) { 11270 // If the existing package wasn't successfully deleted 11271 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11272 deletedPkg = false; 11273 } else { 11274 // Successfully deleted the old package; proceed with replace. 11275 11276 // If deleted package lived in a container, give users a chance to 11277 // relinquish resources before killing. 11278 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11279 if (DEBUG_INSTALL) { 11280 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11281 } 11282 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11283 final ArrayList<String> pkgList = new ArrayList<String>(1); 11284 pkgList.add(deletedPackage.applicationInfo.packageName); 11285 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11286 } 11287 11288 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11289 try { 11290 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11291 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11292 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11293 perUserInstalled, res, user); 11294 updatedSettings = true; 11295 } catch (PackageManagerException e) { 11296 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11297 } 11298 } 11299 11300 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11301 // remove package from internal structures. Note that we want deletePackageX to 11302 // delete the package data and cache directories that it created in 11303 // scanPackageLocked, unless those directories existed before we even tried to 11304 // install. 11305 if(updatedSettings) { 11306 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11307 deletePackageLI( 11308 pkgName, null, true, allUsers, perUserInstalled, 11309 PackageManager.DELETE_KEEP_DATA, 11310 res.removedInfo, true); 11311 } 11312 // Since we failed to install the new package we need to restore the old 11313 // package that we deleted. 11314 if (deletedPkg) { 11315 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11316 File restoreFile = new File(deletedPackage.codePath); 11317 // Parse old package 11318 boolean oldExternal = isExternal(deletedPackage); 11319 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11320 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11321 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11322 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11323 try { 11324 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11325 } catch (PackageManagerException e) { 11326 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11327 + e.getMessage()); 11328 return; 11329 } 11330 // Restore of old package succeeded. Update permissions. 11331 // writer 11332 synchronized (mPackages) { 11333 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11334 UPDATE_PERMISSIONS_ALL); 11335 // can downgrade to reader 11336 mSettings.writeLPr(); 11337 } 11338 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11339 } 11340 } 11341 } 11342 11343 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11344 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11345 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11346 String volumeUuid, PackageInstalledInfo res) { 11347 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11348 + ", old=" + deletedPackage); 11349 boolean disabledSystem = false; 11350 boolean updatedSettings = false; 11351 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11352 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11353 != 0) { 11354 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11355 } 11356 String packageName = deletedPackage.packageName; 11357 if (packageName == null) { 11358 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11359 "Attempt to delete null packageName."); 11360 return; 11361 } 11362 PackageParser.Package oldPkg; 11363 PackageSetting oldPkgSetting; 11364 // reader 11365 synchronized (mPackages) { 11366 oldPkg = mPackages.get(packageName); 11367 oldPkgSetting = mSettings.mPackages.get(packageName); 11368 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11369 (oldPkgSetting == null)) { 11370 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11371 "Couldn't find package:" + packageName + " information"); 11372 return; 11373 } 11374 } 11375 11376 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11377 res.removedInfo.removedPackage = packageName; 11378 // Remove existing system package 11379 removePackageLI(oldPkgSetting, true); 11380 // writer 11381 synchronized (mPackages) { 11382 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11383 if (!disabledSystem && deletedPackage != null) { 11384 // We didn't need to disable the .apk as a current system package, 11385 // which means we are replacing another update that is already 11386 // installed. We need to make sure to delete the older one's .apk. 11387 res.removedInfo.args = createInstallArgsForExisting(0, 11388 deletedPackage.applicationInfo.getCodePath(), 11389 deletedPackage.applicationInfo.getResourcePath(), 11390 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11391 } else { 11392 res.removedInfo.args = null; 11393 } 11394 } 11395 11396 // Successfully disabled the old package. Now proceed with re-installation 11397 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11398 11399 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11400 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11401 11402 PackageParser.Package newPackage = null; 11403 try { 11404 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11405 if (newPackage.mExtras != null) { 11406 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11407 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11408 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11409 11410 // is the update attempting to change shared user? that isn't going to work... 11411 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11412 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11413 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11414 + " to " + newPkgSetting.sharedUser); 11415 updatedSettings = true; 11416 } 11417 } 11418 11419 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11420 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11421 perUserInstalled, res, user); 11422 updatedSettings = true; 11423 } 11424 11425 } catch (PackageManagerException e) { 11426 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11427 } 11428 11429 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11430 // Re installation failed. Restore old information 11431 // Remove new pkg information 11432 if (newPackage != null) { 11433 removeInstalledPackageLI(newPackage, true); 11434 } 11435 // Add back the old system package 11436 try { 11437 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11438 } catch (PackageManagerException e) { 11439 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11440 } 11441 // Restore the old system information in Settings 11442 synchronized (mPackages) { 11443 if (disabledSystem) { 11444 mSettings.enableSystemPackageLPw(packageName); 11445 } 11446 if (updatedSettings) { 11447 mSettings.setInstallerPackageName(packageName, 11448 oldPkgSetting.installerPackageName); 11449 } 11450 mSettings.writeLPr(); 11451 } 11452 } 11453 } 11454 11455 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11456 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11457 UserHandle user) { 11458 String pkgName = newPackage.packageName; 11459 synchronized (mPackages) { 11460 //write settings. the installStatus will be incomplete at this stage. 11461 //note that the new package setting would have already been 11462 //added to mPackages. It hasn't been persisted yet. 11463 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11464 mSettings.writeLPr(); 11465 } 11466 11467 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11468 11469 synchronized (mPackages) { 11470 updatePermissionsLPw(newPackage.packageName, newPackage, 11471 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11472 ? UPDATE_PERMISSIONS_ALL : 0)); 11473 // For system-bundled packages, we assume that installing an upgraded version 11474 // of the package implies that the user actually wants to run that new code, 11475 // so we enable the package. 11476 PackageSetting ps = mSettings.mPackages.get(pkgName); 11477 if (ps != null) { 11478 if (isSystemApp(newPackage)) { 11479 // NB: implicit assumption that system package upgrades apply to all users 11480 if (DEBUG_INSTALL) { 11481 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11482 } 11483 if (res.origUsers != null) { 11484 for (int userHandle : res.origUsers) { 11485 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11486 userHandle, installerPackageName); 11487 } 11488 } 11489 // Also convey the prior install/uninstall state 11490 if (allUsers != null && perUserInstalled != null) { 11491 for (int i = 0; i < allUsers.length; i++) { 11492 if (DEBUG_INSTALL) { 11493 Slog.d(TAG, " user " + allUsers[i] 11494 + " => " + perUserInstalled[i]); 11495 } 11496 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11497 } 11498 // these install state changes will be persisted in the 11499 // upcoming call to mSettings.writeLPr(). 11500 } 11501 } 11502 // It's implied that when a user requests installation, they want the app to be 11503 // installed and enabled. 11504 int userId = user.getIdentifier(); 11505 if (userId != UserHandle.USER_ALL) { 11506 ps.setInstalled(true, userId); 11507 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11508 } 11509 } 11510 res.name = pkgName; 11511 res.uid = newPackage.applicationInfo.uid; 11512 res.pkg = newPackage; 11513 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11514 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11515 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11516 //to update install status 11517 mSettings.writeLPr(); 11518 } 11519 } 11520 11521 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11522 final int installFlags = args.installFlags; 11523 final String installerPackageName = args.installerPackageName; 11524 final String volumeUuid = args.volumeUuid; 11525 final File tmpPackageFile = new File(args.getCodePath()); 11526 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11527 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11528 || (args.volumeUuid != null)); 11529 boolean replace = false; 11530 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11531 // Result object to be returned 11532 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11533 11534 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11535 // Retrieve PackageSettings and parse package 11536 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11537 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11538 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11539 PackageParser pp = new PackageParser(); 11540 pp.setSeparateProcesses(mSeparateProcesses); 11541 pp.setDisplayMetrics(mMetrics); 11542 11543 final PackageParser.Package pkg; 11544 try { 11545 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11546 } catch (PackageParserException e) { 11547 res.setError("Failed parse during installPackageLI", e); 11548 return; 11549 } 11550 11551 // Mark that we have an install time CPU ABI override. 11552 pkg.cpuAbiOverride = args.abiOverride; 11553 11554 String pkgName = res.name = pkg.packageName; 11555 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11556 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11557 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11558 return; 11559 } 11560 } 11561 11562 try { 11563 pp.collectCertificates(pkg, parseFlags); 11564 pp.collectManifestDigest(pkg); 11565 } catch (PackageParserException e) { 11566 res.setError("Failed collect during installPackageLI", e); 11567 return; 11568 } 11569 11570 /* If the installer passed in a manifest digest, compare it now. */ 11571 if (args.manifestDigest != null) { 11572 if (DEBUG_INSTALL) { 11573 final String parsedManifest = pkg.manifestDigest == null ? "null" 11574 : pkg.manifestDigest.toString(); 11575 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11576 + parsedManifest); 11577 } 11578 11579 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11580 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11581 return; 11582 } 11583 } else if (DEBUG_INSTALL) { 11584 final String parsedManifest = pkg.manifestDigest == null 11585 ? "null" : pkg.manifestDigest.toString(); 11586 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11587 } 11588 11589 // Get rid of all references to package scan path via parser. 11590 pp = null; 11591 String oldCodePath = null; 11592 boolean systemApp = false; 11593 synchronized (mPackages) { 11594 // Check if installing already existing package 11595 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11596 String oldName = mSettings.mRenamedPackages.get(pkgName); 11597 if (pkg.mOriginalPackages != null 11598 && pkg.mOriginalPackages.contains(oldName) 11599 && mPackages.containsKey(oldName)) { 11600 // This package is derived from an original package, 11601 // and this device has been updating from that original 11602 // name. We must continue using the original name, so 11603 // rename the new package here. 11604 pkg.setPackageName(oldName); 11605 pkgName = pkg.packageName; 11606 replace = true; 11607 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11608 + oldName + " pkgName=" + pkgName); 11609 } else if (mPackages.containsKey(pkgName)) { 11610 // This package, under its official name, already exists 11611 // on the device; we should replace it. 11612 replace = true; 11613 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11614 } 11615 11616 // Prevent apps opting out from runtime permissions 11617 if (replace) { 11618 PackageParser.Package oldPackage = mPackages.get(pkgName); 11619 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11620 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11621 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11622 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11623 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11624 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11625 + " doesn't support runtime permissions but the old" 11626 + " target SDK " + oldTargetSdk + " does."); 11627 return; 11628 } 11629 } 11630 } 11631 11632 PackageSetting ps = mSettings.mPackages.get(pkgName); 11633 if (ps != null) { 11634 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11635 11636 // Quick sanity check that we're signed correctly if updating; 11637 // we'll check this again later when scanning, but we want to 11638 // bail early here before tripping over redefined permissions. 11639 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11640 if (!checkUpgradeKeySetLP(ps, pkg)) { 11641 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11642 + pkg.packageName + " upgrade keys do not match the " 11643 + "previously installed version"); 11644 return; 11645 } 11646 } else { 11647 try { 11648 verifySignaturesLP(ps, pkg); 11649 } catch (PackageManagerException e) { 11650 res.setError(e.error, e.getMessage()); 11651 return; 11652 } 11653 } 11654 11655 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11656 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11657 systemApp = (ps.pkg.applicationInfo.flags & 11658 ApplicationInfo.FLAG_SYSTEM) != 0; 11659 } 11660 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11661 } 11662 11663 // Check whether the newly-scanned package wants to define an already-defined perm 11664 int N = pkg.permissions.size(); 11665 for (int i = N-1; i >= 0; i--) { 11666 PackageParser.Permission perm = pkg.permissions.get(i); 11667 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11668 if (bp != null) { 11669 // If the defining package is signed with our cert, it's okay. This 11670 // also includes the "updating the same package" case, of course. 11671 // "updating same package" could also involve key-rotation. 11672 final boolean sigsOk; 11673 if (bp.sourcePackage.equals(pkg.packageName) 11674 && (bp.packageSetting instanceof PackageSetting) 11675 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11676 scanFlags))) { 11677 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11678 } else { 11679 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11680 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11681 } 11682 if (!sigsOk) { 11683 // If the owning package is the system itself, we log but allow 11684 // install to proceed; we fail the install on all other permission 11685 // redefinitions. 11686 if (!bp.sourcePackage.equals("android")) { 11687 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11688 + pkg.packageName + " attempting to redeclare permission " 11689 + perm.info.name + " already owned by " + bp.sourcePackage); 11690 res.origPermission = perm.info.name; 11691 res.origPackage = bp.sourcePackage; 11692 return; 11693 } else { 11694 Slog.w(TAG, "Package " + pkg.packageName 11695 + " attempting to redeclare system permission " 11696 + perm.info.name + "; ignoring new declaration"); 11697 pkg.permissions.remove(i); 11698 } 11699 } 11700 } 11701 } 11702 11703 } 11704 11705 if (systemApp && onExternal) { 11706 // Disable updates to system apps on sdcard 11707 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11708 "Cannot install updates to system apps on sdcard"); 11709 return; 11710 } 11711 11712 if (args.move != null) { 11713 // We did an in-place move, so dex is ready to roll 11714 scanFlags |= SCAN_NO_DEX; 11715 scanFlags |= SCAN_MOVE; 11716 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11717 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11718 scanFlags |= SCAN_NO_DEX; 11719 11720 try { 11721 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11722 true /* extract libs */); 11723 } catch (PackageManagerException pme) { 11724 Slog.e(TAG, "Error deriving application ABI", pme); 11725 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11726 return; 11727 } 11728 11729 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11730 int result = mPackageDexOptimizer 11731 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11732 false /* defer */, false /* inclDependencies */); 11733 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11734 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11735 return; 11736 } 11737 } 11738 11739 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11740 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11741 return; 11742 } 11743 11744 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11745 11746 if (replace) { 11747 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11748 installerPackageName, volumeUuid, res); 11749 } else { 11750 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11751 args.user, installerPackageName, volumeUuid, res); 11752 } 11753 synchronized (mPackages) { 11754 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11755 if (ps != null) { 11756 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11757 } 11758 } 11759 } 11760 11761 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11762 if (mIntentFilterVerifierComponent == null) { 11763 Slog.w(TAG, "No IntentFilter verification will not be done as " 11764 + "there is no IntentFilterVerifier available!"); 11765 return; 11766 } 11767 11768 final int verifierUid = getPackageUid( 11769 mIntentFilterVerifierComponent.getPackageName(), 11770 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11771 11772 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11773 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11774 msg.obj = pkg; 11775 msg.arg1 = userId; 11776 msg.arg2 = verifierUid; 11777 11778 mHandler.sendMessage(msg); 11779 } 11780 11781 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11782 PackageParser.Package pkg) { 11783 int size = pkg.activities.size(); 11784 if (size == 0) { 11785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11786 "No activity, so no need to verify any IntentFilter!"); 11787 return; 11788 } 11789 11790 final boolean hasDomainURLs = hasDomainURLs(pkg); 11791 if (!hasDomainURLs) { 11792 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11793 "No domain URLs, so no need to verify any IntentFilter!"); 11794 return; 11795 } 11796 11797 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11798 + " if any IntentFilter from the " + size 11799 + " Activities needs verification ..."); 11800 11801 final int verificationId = mIntentFilterVerificationToken++; 11802 int count = 0; 11803 final String packageName = pkg.packageName; 11804 boolean needToVerify = false; 11805 11806 synchronized (mPackages) { 11807 // If any filters need to be verified, then all need to be. 11808 for (PackageParser.Activity a : pkg.activities) { 11809 for (ActivityIntentInfo filter : a.intents) { 11810 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 11811 if (DEBUG_DOMAIN_VERIFICATION) { 11812 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 11813 } 11814 needToVerify = true; 11815 break; 11816 } 11817 } 11818 } 11819 if (needToVerify) { 11820 for (PackageParser.Activity a : pkg.activities) { 11821 for (ActivityIntentInfo filter : a.intents) { 11822 boolean needsFilterVerification = filter.hasWebDataURI(); 11823 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11824 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11825 "Verification needed for IntentFilter:" + filter.toString()); 11826 mIntentFilterVerifier.addOneIntentFilterVerification( 11827 verifierUid, userId, verificationId, filter, packageName); 11828 count++; 11829 } 11830 } 11831 } 11832 } 11833 } 11834 11835 if (count > 0) { 11836 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 11837 + " IntentFilter verification" + (count > 1 ? "s" : "") 11838 + " for userId:" + userId); 11839 mIntentFilterVerifier.startVerifications(userId); 11840 } else { 11841 if (DEBUG_DOMAIN_VERIFICATION) { 11842 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 11843 } 11844 } 11845 } 11846 11847 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11848 final ComponentName cn = filter.activity.getComponentName(); 11849 final String packageName = cn.getPackageName(); 11850 11851 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11852 packageName); 11853 if (ivi == null) { 11854 return true; 11855 } 11856 int status = ivi.getStatus(); 11857 switch (status) { 11858 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11859 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11860 return true; 11861 11862 default: 11863 // Nothing to do 11864 return false; 11865 } 11866 } 11867 11868 private static boolean isMultiArch(PackageSetting ps) { 11869 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11870 } 11871 11872 private static boolean isMultiArch(ApplicationInfo info) { 11873 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11874 } 11875 11876 private static boolean isExternal(PackageParser.Package pkg) { 11877 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11878 } 11879 11880 private static boolean isExternal(PackageSetting ps) { 11881 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11882 } 11883 11884 private static boolean isExternal(ApplicationInfo info) { 11885 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11886 } 11887 11888 private static boolean isSystemApp(PackageParser.Package pkg) { 11889 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11890 } 11891 11892 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11893 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11894 } 11895 11896 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11897 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11898 } 11899 11900 private static boolean isSystemApp(PackageSetting ps) { 11901 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11902 } 11903 11904 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11905 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11906 } 11907 11908 private int packageFlagsToInstallFlags(PackageSetting ps) { 11909 int installFlags = 0; 11910 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11911 // This existing package was an external ASEC install when we have 11912 // the external flag without a UUID 11913 installFlags |= PackageManager.INSTALL_EXTERNAL; 11914 } 11915 if (ps.isForwardLocked()) { 11916 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11917 } 11918 return installFlags; 11919 } 11920 11921 private void deleteTempPackageFiles() { 11922 final FilenameFilter filter = new FilenameFilter() { 11923 public boolean accept(File dir, String name) { 11924 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11925 } 11926 }; 11927 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11928 file.delete(); 11929 } 11930 } 11931 11932 @Override 11933 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11934 int flags) { 11935 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11936 flags); 11937 } 11938 11939 @Override 11940 public void deletePackage(final String packageName, 11941 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11942 mContext.enforceCallingOrSelfPermission( 11943 android.Manifest.permission.DELETE_PACKAGES, null); 11944 final int uid = Binder.getCallingUid(); 11945 if (UserHandle.getUserId(uid) != userId) { 11946 mContext.enforceCallingPermission( 11947 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11948 "deletePackage for user " + userId); 11949 } 11950 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11951 try { 11952 observer.onPackageDeleted(packageName, 11953 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11954 } catch (RemoteException re) { 11955 } 11956 return; 11957 } 11958 11959 boolean uninstallBlocked = false; 11960 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11961 int[] users = sUserManager.getUserIds(); 11962 for (int i = 0; i < users.length; ++i) { 11963 if (getBlockUninstallForUser(packageName, users[i])) { 11964 uninstallBlocked = true; 11965 break; 11966 } 11967 } 11968 } else { 11969 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11970 } 11971 if (uninstallBlocked) { 11972 try { 11973 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11974 null); 11975 } catch (RemoteException re) { 11976 } 11977 return; 11978 } 11979 11980 if (DEBUG_REMOVE) { 11981 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11982 } 11983 // Queue up an async operation since the package deletion may take a little while. 11984 mHandler.post(new Runnable() { 11985 public void run() { 11986 mHandler.removeCallbacks(this); 11987 final int returnCode = deletePackageX(packageName, userId, flags); 11988 if (observer != null) { 11989 try { 11990 observer.onPackageDeleted(packageName, returnCode, null); 11991 } catch (RemoteException e) { 11992 Log.i(TAG, "Observer no longer exists."); 11993 } //end catch 11994 } //end if 11995 } //end run 11996 }); 11997 } 11998 11999 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12000 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12001 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12002 try { 12003 if (dpm != null) { 12004 if (dpm.isDeviceOwner(packageName)) { 12005 return true; 12006 } 12007 int[] users; 12008 if (userId == UserHandle.USER_ALL) { 12009 users = sUserManager.getUserIds(); 12010 } else { 12011 users = new int[]{userId}; 12012 } 12013 for (int i = 0; i < users.length; ++i) { 12014 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12015 return true; 12016 } 12017 } 12018 } 12019 } catch (RemoteException e) { 12020 } 12021 return false; 12022 } 12023 12024 /** 12025 * This method is an internal method that could be get invoked either 12026 * to delete an installed package or to clean up a failed installation. 12027 * After deleting an installed package, a broadcast is sent to notify any 12028 * listeners that the package has been installed. For cleaning up a failed 12029 * installation, the broadcast is not necessary since the package's 12030 * installation wouldn't have sent the initial broadcast either 12031 * The key steps in deleting a package are 12032 * deleting the package information in internal structures like mPackages, 12033 * deleting the packages base directories through installd 12034 * updating mSettings to reflect current status 12035 * persisting settings for later use 12036 * sending a broadcast if necessary 12037 */ 12038 private int deletePackageX(String packageName, int userId, int flags) { 12039 final PackageRemovedInfo info = new PackageRemovedInfo(); 12040 final boolean res; 12041 12042 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12043 ? UserHandle.ALL : new UserHandle(userId); 12044 12045 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12046 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12047 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12048 } 12049 12050 boolean removedForAllUsers = false; 12051 boolean systemUpdate = false; 12052 12053 // for the uninstall-updates case and restricted profiles, remember the per- 12054 // userhandle installed state 12055 int[] allUsers; 12056 boolean[] perUserInstalled; 12057 synchronized (mPackages) { 12058 PackageSetting ps = mSettings.mPackages.get(packageName); 12059 allUsers = sUserManager.getUserIds(); 12060 perUserInstalled = new boolean[allUsers.length]; 12061 for (int i = 0; i < allUsers.length; i++) { 12062 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12063 } 12064 } 12065 12066 synchronized (mInstallLock) { 12067 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12068 res = deletePackageLI(packageName, removeForUser, 12069 true, allUsers, perUserInstalled, 12070 flags | REMOVE_CHATTY, info, true); 12071 systemUpdate = info.isRemovedPackageSystemUpdate; 12072 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12073 removedForAllUsers = true; 12074 } 12075 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12076 + " removedForAllUsers=" + removedForAllUsers); 12077 } 12078 12079 if (res) { 12080 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12081 12082 // If the removed package was a system update, the old system package 12083 // was re-enabled; we need to broadcast this information 12084 if (systemUpdate) { 12085 Bundle extras = new Bundle(1); 12086 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12087 ? info.removedAppId : info.uid); 12088 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12089 12090 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12091 extras, null, null, null); 12092 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12093 extras, null, null, null); 12094 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12095 null, packageName, null, null); 12096 } 12097 } 12098 // Force a gc here. 12099 Runtime.getRuntime().gc(); 12100 // Delete the resources here after sending the broadcast to let 12101 // other processes clean up before deleting resources. 12102 if (info.args != null) { 12103 synchronized (mInstallLock) { 12104 info.args.doPostDeleteLI(true); 12105 } 12106 } 12107 12108 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12109 } 12110 12111 class PackageRemovedInfo { 12112 String removedPackage; 12113 int uid = -1; 12114 int removedAppId = -1; 12115 int[] removedUsers = null; 12116 boolean isRemovedPackageSystemUpdate = false; 12117 // Clean up resources deleted packages. 12118 InstallArgs args = null; 12119 12120 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12121 Bundle extras = new Bundle(1); 12122 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12123 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12124 if (replacing) { 12125 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12126 } 12127 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12128 if (removedPackage != null) { 12129 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12130 extras, null, null, removedUsers); 12131 if (fullRemove && !replacing) { 12132 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12133 extras, null, null, removedUsers); 12134 } 12135 } 12136 if (removedAppId >= 0) { 12137 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12138 removedUsers); 12139 } 12140 } 12141 } 12142 12143 /* 12144 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12145 * flag is not set, the data directory is removed as well. 12146 * make sure this flag is set for partially installed apps. If not its meaningless to 12147 * delete a partially installed application. 12148 */ 12149 private void removePackageDataLI(PackageSetting ps, 12150 int[] allUserHandles, boolean[] perUserInstalled, 12151 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12152 String packageName = ps.name; 12153 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12154 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12155 // Retrieve object to delete permissions for shared user later on 12156 final PackageSetting deletedPs; 12157 // reader 12158 synchronized (mPackages) { 12159 deletedPs = mSettings.mPackages.get(packageName); 12160 if (outInfo != null) { 12161 outInfo.removedPackage = packageName; 12162 outInfo.removedUsers = deletedPs != null 12163 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12164 : null; 12165 } 12166 } 12167 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12168 removeDataDirsLI(ps.volumeUuid, packageName); 12169 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12170 } 12171 // writer 12172 synchronized (mPackages) { 12173 if (deletedPs != null) { 12174 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12175 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12176 clearDefaultBrowserIfNeeded(packageName); 12177 if (outInfo != null) { 12178 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12179 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12180 } 12181 updatePermissionsLPw(deletedPs.name, null, 0); 12182 if (deletedPs.sharedUser != null) { 12183 // Remove permissions associated with package. Since runtime 12184 // permissions are per user we have to kill the removed package 12185 // or packages running under the shared user of the removed 12186 // package if revoking the permissions requested only by the removed 12187 // package is successful and this causes a change in gids. 12188 for (int userId : UserManagerService.getInstance().getUserIds()) { 12189 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12190 userId); 12191 if (userIdToKill == UserHandle.USER_ALL 12192 || userIdToKill >= UserHandle.USER_OWNER) { 12193 // If gids changed for this user, kill all affected packages. 12194 mHandler.post(new Runnable() { 12195 @Override 12196 public void run() { 12197 // This has to happen with no lock held. 12198 killSettingPackagesForUser(deletedPs, userIdToKill, 12199 KILL_APP_REASON_GIDS_CHANGED); 12200 } 12201 }); 12202 break; 12203 } 12204 } 12205 } 12206 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12207 } 12208 // make sure to preserve per-user disabled state if this removal was just 12209 // a downgrade of a system app to the factory package 12210 if (allUserHandles != null && perUserInstalled != null) { 12211 if (DEBUG_REMOVE) { 12212 Slog.d(TAG, "Propagating install state across downgrade"); 12213 } 12214 for (int i = 0; i < allUserHandles.length; i++) { 12215 if (DEBUG_REMOVE) { 12216 Slog.d(TAG, " user " + allUserHandles[i] 12217 + " => " + perUserInstalled[i]); 12218 } 12219 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12220 } 12221 } 12222 } 12223 // can downgrade to reader 12224 if (writeSettings) { 12225 // Save settings now 12226 mSettings.writeLPr(); 12227 } 12228 } 12229 if (outInfo != null) { 12230 // A user ID was deleted here. Go through all users and remove it 12231 // from KeyStore. 12232 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12233 } 12234 } 12235 12236 static boolean locationIsPrivileged(File path) { 12237 try { 12238 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12239 .getCanonicalPath(); 12240 return path.getCanonicalPath().startsWith(privilegedAppDir); 12241 } catch (IOException e) { 12242 Slog.e(TAG, "Unable to access code path " + path); 12243 } 12244 return false; 12245 } 12246 12247 /* 12248 * Tries to delete system package. 12249 */ 12250 private boolean deleteSystemPackageLI(PackageSetting newPs, 12251 int[] allUserHandles, boolean[] perUserInstalled, 12252 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12253 final boolean applyUserRestrictions 12254 = (allUserHandles != null) && (perUserInstalled != null); 12255 PackageSetting disabledPs = null; 12256 // Confirm if the system package has been updated 12257 // An updated system app can be deleted. This will also have to restore 12258 // the system pkg from system partition 12259 // reader 12260 synchronized (mPackages) { 12261 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12262 } 12263 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12264 + " disabledPs=" + disabledPs); 12265 if (disabledPs == null) { 12266 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12267 return false; 12268 } else if (DEBUG_REMOVE) { 12269 Slog.d(TAG, "Deleting system pkg from data partition"); 12270 } 12271 if (DEBUG_REMOVE) { 12272 if (applyUserRestrictions) { 12273 Slog.d(TAG, "Remembering install states:"); 12274 for (int i = 0; i < allUserHandles.length; i++) { 12275 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12276 } 12277 } 12278 } 12279 // Delete the updated package 12280 outInfo.isRemovedPackageSystemUpdate = true; 12281 if (disabledPs.versionCode < newPs.versionCode) { 12282 // Delete data for downgrades 12283 flags &= ~PackageManager.DELETE_KEEP_DATA; 12284 } else { 12285 // Preserve data by setting flag 12286 flags |= PackageManager.DELETE_KEEP_DATA; 12287 } 12288 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12289 allUserHandles, perUserInstalled, outInfo, writeSettings); 12290 if (!ret) { 12291 return false; 12292 } 12293 // writer 12294 synchronized (mPackages) { 12295 // Reinstate the old system package 12296 mSettings.enableSystemPackageLPw(newPs.name); 12297 // Remove any native libraries from the upgraded package. 12298 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12299 } 12300 // Install the system package 12301 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12302 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12303 if (locationIsPrivileged(disabledPs.codePath)) { 12304 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12305 } 12306 12307 final PackageParser.Package newPkg; 12308 try { 12309 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12310 } catch (PackageManagerException e) { 12311 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12312 return false; 12313 } 12314 12315 // writer 12316 synchronized (mPackages) { 12317 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12318 updatePermissionsLPw(newPkg.packageName, newPkg, 12319 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12320 if (applyUserRestrictions) { 12321 if (DEBUG_REMOVE) { 12322 Slog.d(TAG, "Propagating install state across reinstall"); 12323 } 12324 for (int i = 0; i < allUserHandles.length; i++) { 12325 if (DEBUG_REMOVE) { 12326 Slog.d(TAG, " user " + allUserHandles[i] 12327 + " => " + perUserInstalled[i]); 12328 } 12329 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12330 } 12331 // Regardless of writeSettings we need to ensure that this restriction 12332 // state propagation is persisted 12333 mSettings.writeAllUsersPackageRestrictionsLPr(); 12334 } 12335 // can downgrade to reader here 12336 if (writeSettings) { 12337 mSettings.writeLPr(); 12338 } 12339 } 12340 return true; 12341 } 12342 12343 private boolean deleteInstalledPackageLI(PackageSetting ps, 12344 boolean deleteCodeAndResources, int flags, 12345 int[] allUserHandles, boolean[] perUserInstalled, 12346 PackageRemovedInfo outInfo, boolean writeSettings) { 12347 if (outInfo != null) { 12348 outInfo.uid = ps.appId; 12349 } 12350 12351 // Delete package data from internal structures and also remove data if flag is set 12352 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12353 12354 // Delete application code and resources 12355 if (deleteCodeAndResources && (outInfo != null)) { 12356 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12357 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12358 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12359 } 12360 return true; 12361 } 12362 12363 @Override 12364 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12365 int userId) { 12366 mContext.enforceCallingOrSelfPermission( 12367 android.Manifest.permission.DELETE_PACKAGES, null); 12368 synchronized (mPackages) { 12369 PackageSetting ps = mSettings.mPackages.get(packageName); 12370 if (ps == null) { 12371 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12372 return false; 12373 } 12374 if (!ps.getInstalled(userId)) { 12375 // Can't block uninstall for an app that is not installed or enabled. 12376 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12377 return false; 12378 } 12379 ps.setBlockUninstall(blockUninstall, userId); 12380 mSettings.writePackageRestrictionsLPr(userId); 12381 } 12382 return true; 12383 } 12384 12385 @Override 12386 public boolean getBlockUninstallForUser(String packageName, int userId) { 12387 synchronized (mPackages) { 12388 PackageSetting ps = mSettings.mPackages.get(packageName); 12389 if (ps == null) { 12390 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12391 return false; 12392 } 12393 return ps.getBlockUninstall(userId); 12394 } 12395 } 12396 12397 /* 12398 * This method handles package deletion in general 12399 */ 12400 private boolean deletePackageLI(String packageName, UserHandle user, 12401 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12402 int flags, PackageRemovedInfo outInfo, 12403 boolean writeSettings) { 12404 if (packageName == null) { 12405 Slog.w(TAG, "Attempt to delete null packageName."); 12406 return false; 12407 } 12408 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12409 PackageSetting ps; 12410 boolean dataOnly = false; 12411 int removeUser = -1; 12412 int appId = -1; 12413 synchronized (mPackages) { 12414 ps = mSettings.mPackages.get(packageName); 12415 if (ps == null) { 12416 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12417 return false; 12418 } 12419 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12420 && user.getIdentifier() != UserHandle.USER_ALL) { 12421 // The caller is asking that the package only be deleted for a single 12422 // user. To do this, we just mark its uninstalled state and delete 12423 // its data. If this is a system app, we only allow this to happen if 12424 // they have set the special DELETE_SYSTEM_APP which requests different 12425 // semantics than normal for uninstalling system apps. 12426 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12427 ps.setUserState(user.getIdentifier(), 12428 COMPONENT_ENABLED_STATE_DEFAULT, 12429 false, //installed 12430 true, //stopped 12431 true, //notLaunched 12432 false, //hidden 12433 null, null, null, 12434 false, // blockUninstall 12435 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12436 if (!isSystemApp(ps)) { 12437 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12438 // Other user still have this package installed, so all 12439 // we need to do is clear this user's data and save that 12440 // it is uninstalled. 12441 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12442 removeUser = user.getIdentifier(); 12443 appId = ps.appId; 12444 scheduleWritePackageRestrictionsLocked(removeUser); 12445 } else { 12446 // We need to set it back to 'installed' so the uninstall 12447 // broadcasts will be sent correctly. 12448 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12449 ps.setInstalled(true, user.getIdentifier()); 12450 } 12451 } else { 12452 // This is a system app, so we assume that the 12453 // other users still have this package installed, so all 12454 // we need to do is clear this user's data and save that 12455 // it is uninstalled. 12456 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12457 removeUser = user.getIdentifier(); 12458 appId = ps.appId; 12459 scheduleWritePackageRestrictionsLocked(removeUser); 12460 } 12461 } 12462 } 12463 12464 if (removeUser >= 0) { 12465 // From above, we determined that we are deleting this only 12466 // for a single user. Continue the work here. 12467 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12468 if (outInfo != null) { 12469 outInfo.removedPackage = packageName; 12470 outInfo.removedAppId = appId; 12471 outInfo.removedUsers = new int[] {removeUser}; 12472 } 12473 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12474 removeKeystoreDataIfNeeded(removeUser, appId); 12475 schedulePackageCleaning(packageName, removeUser, false); 12476 synchronized (mPackages) { 12477 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12478 scheduleWritePackageRestrictionsLocked(removeUser); 12479 } 12480 } 12481 return true; 12482 } 12483 12484 if (dataOnly) { 12485 // Delete application data first 12486 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12487 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12488 return true; 12489 } 12490 12491 boolean ret = false; 12492 if (isSystemApp(ps)) { 12493 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12494 // When an updated system application is deleted we delete the existing resources as well and 12495 // fall back to existing code in system partition 12496 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12497 flags, outInfo, writeSettings); 12498 } else { 12499 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12500 // Kill application pre-emptively especially for apps on sd. 12501 killApplication(packageName, ps.appId, "uninstall pkg"); 12502 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12503 allUserHandles, perUserInstalled, 12504 outInfo, writeSettings); 12505 } 12506 12507 return ret; 12508 } 12509 12510 private final class ClearStorageConnection implements ServiceConnection { 12511 IMediaContainerService mContainerService; 12512 12513 @Override 12514 public void onServiceConnected(ComponentName name, IBinder service) { 12515 synchronized (this) { 12516 mContainerService = IMediaContainerService.Stub.asInterface(service); 12517 notifyAll(); 12518 } 12519 } 12520 12521 @Override 12522 public void onServiceDisconnected(ComponentName name) { 12523 } 12524 } 12525 12526 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12527 final boolean mounted; 12528 if (Environment.isExternalStorageEmulated()) { 12529 mounted = true; 12530 } else { 12531 final String status = Environment.getExternalStorageState(); 12532 12533 mounted = status.equals(Environment.MEDIA_MOUNTED) 12534 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12535 } 12536 12537 if (!mounted) { 12538 return; 12539 } 12540 12541 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12542 int[] users; 12543 if (userId == UserHandle.USER_ALL) { 12544 users = sUserManager.getUserIds(); 12545 } else { 12546 users = new int[] { userId }; 12547 } 12548 final ClearStorageConnection conn = new ClearStorageConnection(); 12549 if (mContext.bindServiceAsUser( 12550 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12551 try { 12552 for (int curUser : users) { 12553 long timeout = SystemClock.uptimeMillis() + 5000; 12554 synchronized (conn) { 12555 long now = SystemClock.uptimeMillis(); 12556 while (conn.mContainerService == null && now < timeout) { 12557 try { 12558 conn.wait(timeout - now); 12559 } catch (InterruptedException e) { 12560 } 12561 } 12562 } 12563 if (conn.mContainerService == null) { 12564 return; 12565 } 12566 12567 final UserEnvironment userEnv = new UserEnvironment(curUser); 12568 clearDirectory(conn.mContainerService, 12569 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12570 if (allData) { 12571 clearDirectory(conn.mContainerService, 12572 userEnv.buildExternalStorageAppDataDirs(packageName)); 12573 clearDirectory(conn.mContainerService, 12574 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12575 } 12576 } 12577 } finally { 12578 mContext.unbindService(conn); 12579 } 12580 } 12581 } 12582 12583 @Override 12584 public void clearApplicationUserData(final String packageName, 12585 final IPackageDataObserver observer, final int userId) { 12586 mContext.enforceCallingOrSelfPermission( 12587 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12588 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12589 // Queue up an async operation since the package deletion may take a little while. 12590 mHandler.post(new Runnable() { 12591 public void run() { 12592 mHandler.removeCallbacks(this); 12593 final boolean succeeded; 12594 synchronized (mInstallLock) { 12595 succeeded = clearApplicationUserDataLI(packageName, userId); 12596 } 12597 clearExternalStorageDataSync(packageName, userId, true); 12598 if (succeeded) { 12599 // invoke DeviceStorageMonitor's update method to clear any notifications 12600 DeviceStorageMonitorInternal 12601 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12602 if (dsm != null) { 12603 dsm.checkMemory(); 12604 } 12605 } 12606 if(observer != null) { 12607 try { 12608 observer.onRemoveCompleted(packageName, succeeded); 12609 } catch (RemoteException e) { 12610 Log.i(TAG, "Observer no longer exists."); 12611 } 12612 } //end if observer 12613 } //end run 12614 }); 12615 } 12616 12617 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12618 if (packageName == null) { 12619 Slog.w(TAG, "Attempt to delete null packageName."); 12620 return false; 12621 } 12622 12623 // Try finding details about the requested package 12624 PackageParser.Package pkg; 12625 synchronized (mPackages) { 12626 pkg = mPackages.get(packageName); 12627 if (pkg == null) { 12628 final PackageSetting ps = mSettings.mPackages.get(packageName); 12629 if (ps != null) { 12630 pkg = ps.pkg; 12631 } 12632 } 12633 12634 if (pkg == null) { 12635 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12636 return false; 12637 } 12638 12639 PackageSetting ps = (PackageSetting) pkg.mExtras; 12640 PermissionsState permissionsState = ps.getPermissionsState(); 12641 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12642 } 12643 12644 // Always delete data directories for package, even if we found no other 12645 // record of app. This helps users recover from UID mismatches without 12646 // resorting to a full data wipe. 12647 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12648 if (retCode < 0) { 12649 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12650 return false; 12651 } 12652 12653 final int appId = pkg.applicationInfo.uid; 12654 removeKeystoreDataIfNeeded(userId, appId); 12655 12656 // Create a native library symlink only if we have native libraries 12657 // and if the native libraries are 32 bit libraries. We do not provide 12658 // this symlink for 64 bit libraries. 12659 if (pkg.applicationInfo.primaryCpuAbi != null && 12660 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12661 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12662 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12663 nativeLibPath, userId) < 0) { 12664 Slog.w(TAG, "Failed linking native library dir"); 12665 return false; 12666 } 12667 } 12668 12669 return true; 12670 } 12671 12672 12673 /** 12674 * Revokes granted runtime permissions and clears resettable flags 12675 * which are flags that can be set by a user interaction. 12676 * 12677 * @param permissionsState The permission state to reset. 12678 * @param userId The device user for which to do a reset. 12679 */ 12680 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12681 PermissionsState permissionsState, int userId) { 12682 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12683 | PackageManager.FLAG_PERMISSION_USER_FIXED 12684 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12685 12686 boolean needsWrite = false; 12687 12688 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12689 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12690 if (bp != null) { 12691 permissionsState.revokeRuntimePermission(bp, userId); 12692 permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0); 12693 needsWrite = true; 12694 } 12695 } 12696 12697 if (needsWrite) { 12698 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12699 } 12700 } 12701 12702 /** 12703 * Remove entries from the keystore daemon. Will only remove it if the 12704 * {@code appId} is valid. 12705 */ 12706 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12707 if (appId < 0) { 12708 return; 12709 } 12710 12711 final KeyStore keyStore = KeyStore.getInstance(); 12712 if (keyStore != null) { 12713 if (userId == UserHandle.USER_ALL) { 12714 for (final int individual : sUserManager.getUserIds()) { 12715 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12716 } 12717 } else { 12718 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12719 } 12720 } else { 12721 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12722 } 12723 } 12724 12725 @Override 12726 public void deleteApplicationCacheFiles(final String packageName, 12727 final IPackageDataObserver observer) { 12728 mContext.enforceCallingOrSelfPermission( 12729 android.Manifest.permission.DELETE_CACHE_FILES, null); 12730 // Queue up an async operation since the package deletion may take a little while. 12731 final int userId = UserHandle.getCallingUserId(); 12732 mHandler.post(new Runnable() { 12733 public void run() { 12734 mHandler.removeCallbacks(this); 12735 final boolean succeded; 12736 synchronized (mInstallLock) { 12737 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12738 } 12739 clearExternalStorageDataSync(packageName, userId, false); 12740 if (observer != null) { 12741 try { 12742 observer.onRemoveCompleted(packageName, succeded); 12743 } catch (RemoteException e) { 12744 Log.i(TAG, "Observer no longer exists."); 12745 } 12746 } //end if observer 12747 } //end run 12748 }); 12749 } 12750 12751 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12752 if (packageName == null) { 12753 Slog.w(TAG, "Attempt to delete null packageName."); 12754 return false; 12755 } 12756 PackageParser.Package p; 12757 synchronized (mPackages) { 12758 p = mPackages.get(packageName); 12759 } 12760 if (p == null) { 12761 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12762 return false; 12763 } 12764 final ApplicationInfo applicationInfo = p.applicationInfo; 12765 if (applicationInfo == null) { 12766 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12767 return false; 12768 } 12769 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12770 if (retCode < 0) { 12771 Slog.w(TAG, "Couldn't remove cache files for package: " 12772 + packageName + " u" + userId); 12773 return false; 12774 } 12775 return true; 12776 } 12777 12778 @Override 12779 public void getPackageSizeInfo(final String packageName, int userHandle, 12780 final IPackageStatsObserver observer) { 12781 mContext.enforceCallingOrSelfPermission( 12782 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12783 if (packageName == null) { 12784 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12785 } 12786 12787 PackageStats stats = new PackageStats(packageName, userHandle); 12788 12789 /* 12790 * Queue up an async operation since the package measurement may take a 12791 * little while. 12792 */ 12793 Message msg = mHandler.obtainMessage(INIT_COPY); 12794 msg.obj = new MeasureParams(stats, observer); 12795 mHandler.sendMessage(msg); 12796 } 12797 12798 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12799 PackageStats pStats) { 12800 if (packageName == null) { 12801 Slog.w(TAG, "Attempt to get size of null packageName."); 12802 return false; 12803 } 12804 PackageParser.Package p; 12805 boolean dataOnly = false; 12806 String libDirRoot = null; 12807 String asecPath = null; 12808 PackageSetting ps = null; 12809 synchronized (mPackages) { 12810 p = mPackages.get(packageName); 12811 ps = mSettings.mPackages.get(packageName); 12812 if(p == null) { 12813 dataOnly = true; 12814 if((ps == null) || (ps.pkg == null)) { 12815 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12816 return false; 12817 } 12818 p = ps.pkg; 12819 } 12820 if (ps != null) { 12821 libDirRoot = ps.legacyNativeLibraryPathString; 12822 } 12823 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12824 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12825 if (secureContainerId != null) { 12826 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12827 } 12828 } 12829 } 12830 String publicSrcDir = null; 12831 if(!dataOnly) { 12832 final ApplicationInfo applicationInfo = p.applicationInfo; 12833 if (applicationInfo == null) { 12834 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12835 return false; 12836 } 12837 if (p.isForwardLocked()) { 12838 publicSrcDir = applicationInfo.getBaseResourcePath(); 12839 } 12840 } 12841 // TODO: extend to measure size of split APKs 12842 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12843 // not just the first level. 12844 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12845 // just the primary. 12846 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12847 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12848 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12849 if (res < 0) { 12850 return false; 12851 } 12852 12853 // Fix-up for forward-locked applications in ASEC containers. 12854 if (!isExternal(p)) { 12855 pStats.codeSize += pStats.externalCodeSize; 12856 pStats.externalCodeSize = 0L; 12857 } 12858 12859 return true; 12860 } 12861 12862 12863 @Override 12864 public void addPackageToPreferred(String packageName) { 12865 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12866 } 12867 12868 @Override 12869 public void removePackageFromPreferred(String packageName) { 12870 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12871 } 12872 12873 @Override 12874 public List<PackageInfo> getPreferredPackages(int flags) { 12875 return new ArrayList<PackageInfo>(); 12876 } 12877 12878 private int getUidTargetSdkVersionLockedLPr(int uid) { 12879 Object obj = mSettings.getUserIdLPr(uid); 12880 if (obj instanceof SharedUserSetting) { 12881 final SharedUserSetting sus = (SharedUserSetting) obj; 12882 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12883 final Iterator<PackageSetting> it = sus.packages.iterator(); 12884 while (it.hasNext()) { 12885 final PackageSetting ps = it.next(); 12886 if (ps.pkg != null) { 12887 int v = ps.pkg.applicationInfo.targetSdkVersion; 12888 if (v < vers) vers = v; 12889 } 12890 } 12891 return vers; 12892 } else if (obj instanceof PackageSetting) { 12893 final PackageSetting ps = (PackageSetting) obj; 12894 if (ps.pkg != null) { 12895 return ps.pkg.applicationInfo.targetSdkVersion; 12896 } 12897 } 12898 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12899 } 12900 12901 @Override 12902 public void addPreferredActivity(IntentFilter filter, int match, 12903 ComponentName[] set, ComponentName activity, int userId) { 12904 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12905 "Adding preferred"); 12906 } 12907 12908 private void addPreferredActivityInternal(IntentFilter filter, int match, 12909 ComponentName[] set, ComponentName activity, boolean always, int userId, 12910 String opname) { 12911 // writer 12912 int callingUid = Binder.getCallingUid(); 12913 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12914 if (filter.countActions() == 0) { 12915 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12916 return; 12917 } 12918 synchronized (mPackages) { 12919 if (mContext.checkCallingOrSelfPermission( 12920 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12921 != PackageManager.PERMISSION_GRANTED) { 12922 if (getUidTargetSdkVersionLockedLPr(callingUid) 12923 < Build.VERSION_CODES.FROYO) { 12924 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12925 + callingUid); 12926 return; 12927 } 12928 mContext.enforceCallingOrSelfPermission( 12929 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12930 } 12931 12932 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12933 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12934 + userId + ":"); 12935 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12936 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12937 scheduleWritePackageRestrictionsLocked(userId); 12938 } 12939 } 12940 12941 @Override 12942 public void replacePreferredActivity(IntentFilter filter, int match, 12943 ComponentName[] set, ComponentName activity, int userId) { 12944 if (filter.countActions() != 1) { 12945 throw new IllegalArgumentException( 12946 "replacePreferredActivity expects filter to have only 1 action."); 12947 } 12948 if (filter.countDataAuthorities() != 0 12949 || filter.countDataPaths() != 0 12950 || filter.countDataSchemes() > 1 12951 || filter.countDataTypes() != 0) { 12952 throw new IllegalArgumentException( 12953 "replacePreferredActivity expects filter to have no data authorities, " + 12954 "paths, or types; and at most one scheme."); 12955 } 12956 12957 final int callingUid = Binder.getCallingUid(); 12958 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12959 synchronized (mPackages) { 12960 if (mContext.checkCallingOrSelfPermission( 12961 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12962 != PackageManager.PERMISSION_GRANTED) { 12963 if (getUidTargetSdkVersionLockedLPr(callingUid) 12964 < Build.VERSION_CODES.FROYO) { 12965 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12966 + Binder.getCallingUid()); 12967 return; 12968 } 12969 mContext.enforceCallingOrSelfPermission( 12970 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12971 } 12972 12973 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12974 if (pir != null) { 12975 // Get all of the existing entries that exactly match this filter. 12976 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12977 if (existing != null && existing.size() == 1) { 12978 PreferredActivity cur = existing.get(0); 12979 if (DEBUG_PREFERRED) { 12980 Slog.i(TAG, "Checking replace of preferred:"); 12981 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12982 if (!cur.mPref.mAlways) { 12983 Slog.i(TAG, " -- CUR; not mAlways!"); 12984 } else { 12985 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12986 Slog.i(TAG, " -- CUR: mSet=" 12987 + Arrays.toString(cur.mPref.mSetComponents)); 12988 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12989 Slog.i(TAG, " -- NEW: mMatch=" 12990 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12991 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12992 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12993 } 12994 } 12995 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12996 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12997 && cur.mPref.sameSet(set)) { 12998 // Setting the preferred activity to what it happens to be already 12999 if (DEBUG_PREFERRED) { 13000 Slog.i(TAG, "Replacing with same preferred activity " 13001 + cur.mPref.mShortComponent + " for user " 13002 + userId + ":"); 13003 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13004 } 13005 return; 13006 } 13007 } 13008 13009 if (existing != null) { 13010 if (DEBUG_PREFERRED) { 13011 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13012 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13013 } 13014 for (int i = 0; i < existing.size(); i++) { 13015 PreferredActivity pa = existing.get(i); 13016 if (DEBUG_PREFERRED) { 13017 Slog.i(TAG, "Removing existing preferred activity " 13018 + pa.mPref.mComponent + ":"); 13019 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13020 } 13021 pir.removeFilter(pa); 13022 } 13023 } 13024 } 13025 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13026 "Replacing preferred"); 13027 } 13028 } 13029 13030 @Override 13031 public void clearPackagePreferredActivities(String packageName) { 13032 final int uid = Binder.getCallingUid(); 13033 // writer 13034 synchronized (mPackages) { 13035 PackageParser.Package pkg = mPackages.get(packageName); 13036 if (pkg == null || pkg.applicationInfo.uid != uid) { 13037 if (mContext.checkCallingOrSelfPermission( 13038 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13039 != PackageManager.PERMISSION_GRANTED) { 13040 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13041 < Build.VERSION_CODES.FROYO) { 13042 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13043 + Binder.getCallingUid()); 13044 return; 13045 } 13046 mContext.enforceCallingOrSelfPermission( 13047 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13048 } 13049 } 13050 13051 int user = UserHandle.getCallingUserId(); 13052 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13053 scheduleWritePackageRestrictionsLocked(user); 13054 } 13055 } 13056 } 13057 13058 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13059 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13060 ArrayList<PreferredActivity> removed = null; 13061 boolean changed = false; 13062 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13063 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13064 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13065 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13066 continue; 13067 } 13068 Iterator<PreferredActivity> it = pir.filterIterator(); 13069 while (it.hasNext()) { 13070 PreferredActivity pa = it.next(); 13071 // Mark entry for removal only if it matches the package name 13072 // and the entry is of type "always". 13073 if (packageName == null || 13074 (pa.mPref.mComponent.getPackageName().equals(packageName) 13075 && pa.mPref.mAlways)) { 13076 if (removed == null) { 13077 removed = new ArrayList<PreferredActivity>(); 13078 } 13079 removed.add(pa); 13080 } 13081 } 13082 if (removed != null) { 13083 for (int j=0; j<removed.size(); j++) { 13084 PreferredActivity pa = removed.get(j); 13085 pir.removeFilter(pa); 13086 } 13087 changed = true; 13088 } 13089 } 13090 return changed; 13091 } 13092 13093 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13094 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13095 if (userId == UserHandle.USER_ALL) { 13096 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13097 sUserManager.getUserIds())) { 13098 for (int oneUserId : sUserManager.getUserIds()) { 13099 scheduleWritePackageRestrictionsLocked(oneUserId); 13100 } 13101 } 13102 } else { 13103 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13104 scheduleWritePackageRestrictionsLocked(userId); 13105 } 13106 } 13107 } 13108 13109 13110 void clearDefaultBrowserIfNeeded(String packageName) { 13111 for (int oneUserId : sUserManager.getUserIds()) { 13112 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13113 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13114 if (packageName.equals(defaultBrowserPackageName)) { 13115 setDefaultBrowserPackageName(null, oneUserId); 13116 } 13117 } 13118 } 13119 13120 @Override 13121 public void resetPreferredActivities(int userId) { 13122 /* TODO: Actually use userId. Why is it being passed in? */ 13123 mContext.enforceCallingOrSelfPermission( 13124 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13125 // writer 13126 synchronized (mPackages) { 13127 int user = UserHandle.getCallingUserId(); 13128 clearPackagePreferredActivitiesLPw(null, user); 13129 mSettings.readDefaultPreferredAppsLPw(this, user); 13130 scheduleWritePackageRestrictionsLocked(user); 13131 } 13132 } 13133 13134 @Override 13135 public int getPreferredActivities(List<IntentFilter> outFilters, 13136 List<ComponentName> outActivities, String packageName) { 13137 13138 int num = 0; 13139 final int userId = UserHandle.getCallingUserId(); 13140 // reader 13141 synchronized (mPackages) { 13142 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13143 if (pir != null) { 13144 final Iterator<PreferredActivity> it = pir.filterIterator(); 13145 while (it.hasNext()) { 13146 final PreferredActivity pa = it.next(); 13147 if (packageName == null 13148 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13149 && pa.mPref.mAlways)) { 13150 if (outFilters != null) { 13151 outFilters.add(new IntentFilter(pa)); 13152 } 13153 if (outActivities != null) { 13154 outActivities.add(pa.mPref.mComponent); 13155 } 13156 } 13157 } 13158 } 13159 } 13160 13161 return num; 13162 } 13163 13164 @Override 13165 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13166 int userId) { 13167 int callingUid = Binder.getCallingUid(); 13168 if (callingUid != Process.SYSTEM_UID) { 13169 throw new SecurityException( 13170 "addPersistentPreferredActivity can only be run by the system"); 13171 } 13172 if (filter.countActions() == 0) { 13173 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13174 return; 13175 } 13176 synchronized (mPackages) { 13177 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13178 " :"); 13179 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13180 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13181 new PersistentPreferredActivity(filter, activity)); 13182 scheduleWritePackageRestrictionsLocked(userId); 13183 } 13184 } 13185 13186 @Override 13187 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13188 int callingUid = Binder.getCallingUid(); 13189 if (callingUid != Process.SYSTEM_UID) { 13190 throw new SecurityException( 13191 "clearPackagePersistentPreferredActivities can only be run by the system"); 13192 } 13193 ArrayList<PersistentPreferredActivity> removed = null; 13194 boolean changed = false; 13195 synchronized (mPackages) { 13196 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13197 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13198 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13199 .valueAt(i); 13200 if (userId != thisUserId) { 13201 continue; 13202 } 13203 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13204 while (it.hasNext()) { 13205 PersistentPreferredActivity ppa = it.next(); 13206 // Mark entry for removal only if it matches the package name. 13207 if (ppa.mComponent.getPackageName().equals(packageName)) { 13208 if (removed == null) { 13209 removed = new ArrayList<PersistentPreferredActivity>(); 13210 } 13211 removed.add(ppa); 13212 } 13213 } 13214 if (removed != null) { 13215 for (int j=0; j<removed.size(); j++) { 13216 PersistentPreferredActivity ppa = removed.get(j); 13217 ppir.removeFilter(ppa); 13218 } 13219 changed = true; 13220 } 13221 } 13222 13223 if (changed) { 13224 scheduleWritePackageRestrictionsLocked(userId); 13225 } 13226 } 13227 } 13228 13229 /** 13230 * Non-Binder method, support for the backup/restore mechanism: write the 13231 * full set of preferred activities in its canonical XML format. Returns true 13232 * on success; false otherwise. 13233 */ 13234 @Override 13235 public byte[] getPreferredActivityBackup(int userId) { 13236 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13237 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13238 } 13239 13240 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13241 try { 13242 final XmlSerializer serializer = new FastXmlSerializer(); 13243 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13244 serializer.startDocument(null, true); 13245 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13246 13247 synchronized (mPackages) { 13248 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13249 } 13250 13251 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13252 serializer.endDocument(); 13253 serializer.flush(); 13254 } catch (Exception e) { 13255 if (DEBUG_BACKUP) { 13256 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13257 } 13258 return null; 13259 } 13260 13261 return dataStream.toByteArray(); 13262 } 13263 13264 @Override 13265 public void restorePreferredActivities(byte[] backup, int userId) { 13266 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13267 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13268 } 13269 13270 try { 13271 final XmlPullParser parser = Xml.newPullParser(); 13272 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13273 13274 int type; 13275 while ((type = parser.next()) != XmlPullParser.START_TAG 13276 && type != XmlPullParser.END_DOCUMENT) { 13277 } 13278 if (type != XmlPullParser.START_TAG) { 13279 // oops didn't find a start tag?! 13280 if (DEBUG_BACKUP) { 13281 Slog.e(TAG, "Didn't find start tag during restore"); 13282 } 13283 return; 13284 } 13285 13286 // this is supposed to be TAG_PREFERRED_BACKUP 13287 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13288 if (DEBUG_BACKUP) { 13289 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13290 } 13291 return; 13292 } 13293 13294 // skip interfering stuff, then we're aligned with the backing implementation 13295 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13296 synchronized (mPackages) { 13297 mSettings.readPreferredActivitiesLPw(parser, userId); 13298 } 13299 } catch (Exception e) { 13300 if (DEBUG_BACKUP) { 13301 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13302 } 13303 } 13304 } 13305 13306 @Override 13307 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13308 int sourceUserId, int targetUserId, int flags) { 13309 mContext.enforceCallingOrSelfPermission( 13310 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13311 int callingUid = Binder.getCallingUid(); 13312 enforceOwnerRights(ownerPackage, callingUid); 13313 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13314 if (intentFilter.countActions() == 0) { 13315 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13316 return; 13317 } 13318 synchronized (mPackages) { 13319 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13320 ownerPackage, targetUserId, flags); 13321 CrossProfileIntentResolver resolver = 13322 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13323 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13324 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13325 if (existing != null) { 13326 int size = existing.size(); 13327 for (int i = 0; i < size; i++) { 13328 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13329 return; 13330 } 13331 } 13332 } 13333 resolver.addFilter(newFilter); 13334 scheduleWritePackageRestrictionsLocked(sourceUserId); 13335 } 13336 } 13337 13338 @Override 13339 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13340 mContext.enforceCallingOrSelfPermission( 13341 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13342 int callingUid = Binder.getCallingUid(); 13343 enforceOwnerRights(ownerPackage, callingUid); 13344 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13345 synchronized (mPackages) { 13346 CrossProfileIntentResolver resolver = 13347 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13348 ArraySet<CrossProfileIntentFilter> set = 13349 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13350 for (CrossProfileIntentFilter filter : set) { 13351 if (filter.getOwnerPackage().equals(ownerPackage)) { 13352 resolver.removeFilter(filter); 13353 } 13354 } 13355 scheduleWritePackageRestrictionsLocked(sourceUserId); 13356 } 13357 } 13358 13359 // Enforcing that callingUid is owning pkg on userId 13360 private void enforceOwnerRights(String pkg, int callingUid) { 13361 // The system owns everything. 13362 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13363 return; 13364 } 13365 int callingUserId = UserHandle.getUserId(callingUid); 13366 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13367 if (pi == null) { 13368 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13369 + callingUserId); 13370 } 13371 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13372 throw new SecurityException("Calling uid " + callingUid 13373 + " does not own package " + pkg); 13374 } 13375 } 13376 13377 @Override 13378 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13379 Intent intent = new Intent(Intent.ACTION_MAIN); 13380 intent.addCategory(Intent.CATEGORY_HOME); 13381 13382 final int callingUserId = UserHandle.getCallingUserId(); 13383 List<ResolveInfo> list = queryIntentActivities(intent, null, 13384 PackageManager.GET_META_DATA, callingUserId); 13385 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13386 true, false, false, callingUserId); 13387 13388 allHomeCandidates.clear(); 13389 if (list != null) { 13390 for (ResolveInfo ri : list) { 13391 allHomeCandidates.add(ri); 13392 } 13393 } 13394 return (preferred == null || preferred.activityInfo == null) 13395 ? null 13396 : new ComponentName(preferred.activityInfo.packageName, 13397 preferred.activityInfo.name); 13398 } 13399 13400 @Override 13401 public void setApplicationEnabledSetting(String appPackageName, 13402 int newState, int flags, int userId, String callingPackage) { 13403 if (!sUserManager.exists(userId)) return; 13404 if (callingPackage == null) { 13405 callingPackage = Integer.toString(Binder.getCallingUid()); 13406 } 13407 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13408 } 13409 13410 @Override 13411 public void setComponentEnabledSetting(ComponentName componentName, 13412 int newState, int flags, int userId) { 13413 if (!sUserManager.exists(userId)) return; 13414 setEnabledSetting(componentName.getPackageName(), 13415 componentName.getClassName(), newState, flags, userId, null); 13416 } 13417 13418 private void setEnabledSetting(final String packageName, String className, int newState, 13419 final int flags, int userId, String callingPackage) { 13420 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13421 || newState == COMPONENT_ENABLED_STATE_ENABLED 13422 || newState == COMPONENT_ENABLED_STATE_DISABLED 13423 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13424 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13425 throw new IllegalArgumentException("Invalid new component state: " 13426 + newState); 13427 } 13428 PackageSetting pkgSetting; 13429 final int uid = Binder.getCallingUid(); 13430 final int permission = mContext.checkCallingOrSelfPermission( 13431 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13432 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13433 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13434 boolean sendNow = false; 13435 boolean isApp = (className == null); 13436 String componentName = isApp ? packageName : className; 13437 int packageUid = -1; 13438 ArrayList<String> components; 13439 13440 // writer 13441 synchronized (mPackages) { 13442 pkgSetting = mSettings.mPackages.get(packageName); 13443 if (pkgSetting == null) { 13444 if (className == null) { 13445 throw new IllegalArgumentException( 13446 "Unknown package: " + packageName); 13447 } 13448 throw new IllegalArgumentException( 13449 "Unknown component: " + packageName 13450 + "/" + className); 13451 } 13452 // Allow root and verify that userId is not being specified by a different user 13453 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13454 throw new SecurityException( 13455 "Permission Denial: attempt to change component state from pid=" 13456 + Binder.getCallingPid() 13457 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13458 } 13459 if (className == null) { 13460 // We're dealing with an application/package level state change 13461 if (pkgSetting.getEnabled(userId) == newState) { 13462 // Nothing to do 13463 return; 13464 } 13465 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13466 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13467 // Don't care about who enables an app. 13468 callingPackage = null; 13469 } 13470 pkgSetting.setEnabled(newState, userId, callingPackage); 13471 // pkgSetting.pkg.mSetEnabled = newState; 13472 } else { 13473 // We're dealing with a component level state change 13474 // First, verify that this is a valid class name. 13475 PackageParser.Package pkg = pkgSetting.pkg; 13476 if (pkg == null || !pkg.hasComponentClassName(className)) { 13477 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13478 throw new IllegalArgumentException("Component class " + className 13479 + " does not exist in " + packageName); 13480 } else { 13481 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13482 + className + " does not exist in " + packageName); 13483 } 13484 } 13485 switch (newState) { 13486 case COMPONENT_ENABLED_STATE_ENABLED: 13487 if (!pkgSetting.enableComponentLPw(className, userId)) { 13488 return; 13489 } 13490 break; 13491 case COMPONENT_ENABLED_STATE_DISABLED: 13492 if (!pkgSetting.disableComponentLPw(className, userId)) { 13493 return; 13494 } 13495 break; 13496 case COMPONENT_ENABLED_STATE_DEFAULT: 13497 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13498 return; 13499 } 13500 break; 13501 default: 13502 Slog.e(TAG, "Invalid new component state: " + newState); 13503 return; 13504 } 13505 } 13506 scheduleWritePackageRestrictionsLocked(userId); 13507 components = mPendingBroadcasts.get(userId, packageName); 13508 final boolean newPackage = components == null; 13509 if (newPackage) { 13510 components = new ArrayList<String>(); 13511 } 13512 if (!components.contains(componentName)) { 13513 components.add(componentName); 13514 } 13515 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13516 sendNow = true; 13517 // Purge entry from pending broadcast list if another one exists already 13518 // since we are sending one right away. 13519 mPendingBroadcasts.remove(userId, packageName); 13520 } else { 13521 if (newPackage) { 13522 mPendingBroadcasts.put(userId, packageName, components); 13523 } 13524 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13525 // Schedule a message 13526 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13527 } 13528 } 13529 } 13530 13531 long callingId = Binder.clearCallingIdentity(); 13532 try { 13533 if (sendNow) { 13534 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13535 sendPackageChangedBroadcast(packageName, 13536 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13537 } 13538 } finally { 13539 Binder.restoreCallingIdentity(callingId); 13540 } 13541 } 13542 13543 private void sendPackageChangedBroadcast(String packageName, 13544 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13545 if (DEBUG_INSTALL) 13546 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13547 + componentNames); 13548 Bundle extras = new Bundle(4); 13549 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13550 String nameList[] = new String[componentNames.size()]; 13551 componentNames.toArray(nameList); 13552 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13553 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13554 extras.putInt(Intent.EXTRA_UID, packageUid); 13555 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13556 new int[] {UserHandle.getUserId(packageUid)}); 13557 } 13558 13559 @Override 13560 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13561 if (!sUserManager.exists(userId)) return; 13562 final int uid = Binder.getCallingUid(); 13563 final int permission = mContext.checkCallingOrSelfPermission( 13564 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13565 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13566 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13567 // writer 13568 synchronized (mPackages) { 13569 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13570 allowedByPermission, uid, userId)) { 13571 scheduleWritePackageRestrictionsLocked(userId); 13572 } 13573 } 13574 } 13575 13576 @Override 13577 public String getInstallerPackageName(String packageName) { 13578 // reader 13579 synchronized (mPackages) { 13580 return mSettings.getInstallerPackageNameLPr(packageName); 13581 } 13582 } 13583 13584 @Override 13585 public int getApplicationEnabledSetting(String packageName, int userId) { 13586 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13587 int uid = Binder.getCallingUid(); 13588 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13589 // reader 13590 synchronized (mPackages) { 13591 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13592 } 13593 } 13594 13595 @Override 13596 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13597 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13598 int uid = Binder.getCallingUid(); 13599 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13600 // reader 13601 synchronized (mPackages) { 13602 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13603 } 13604 } 13605 13606 @Override 13607 public void enterSafeMode() { 13608 enforceSystemOrRoot("Only the system can request entering safe mode"); 13609 13610 if (!mSystemReady) { 13611 mSafeMode = true; 13612 } 13613 } 13614 13615 @Override 13616 public void systemReady() { 13617 mSystemReady = true; 13618 13619 // Read the compatibilty setting when the system is ready. 13620 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13621 mContext.getContentResolver(), 13622 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13623 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13624 if (DEBUG_SETTINGS) { 13625 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13626 } 13627 13628 synchronized (mPackages) { 13629 // Verify that all of the preferred activity components actually 13630 // exist. It is possible for applications to be updated and at 13631 // that point remove a previously declared activity component that 13632 // had been set as a preferred activity. We try to clean this up 13633 // the next time we encounter that preferred activity, but it is 13634 // possible for the user flow to never be able to return to that 13635 // situation so here we do a sanity check to make sure we haven't 13636 // left any junk around. 13637 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13638 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13639 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13640 removed.clear(); 13641 for (PreferredActivity pa : pir.filterSet()) { 13642 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13643 removed.add(pa); 13644 } 13645 } 13646 if (removed.size() > 0) { 13647 for (int r=0; r<removed.size(); r++) { 13648 PreferredActivity pa = removed.get(r); 13649 Slog.w(TAG, "Removing dangling preferred activity: " 13650 + pa.mPref.mComponent); 13651 pir.removeFilter(pa); 13652 } 13653 mSettings.writePackageRestrictionsLPr( 13654 mSettings.mPreferredActivities.keyAt(i)); 13655 } 13656 } 13657 } 13658 sUserManager.systemReady(); 13659 13660 // If we upgraded grant all default permissions before kicking off. 13661 if (isFirstBoot()) { 13662 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 13663 for (int userId : UserManagerService.getInstance().getUserIds()) { 13664 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13665 } 13666 } 13667 13668 // Kick off any messages waiting for system ready 13669 if (mPostSystemReadyMessages != null) { 13670 for (Message msg : mPostSystemReadyMessages) { 13671 msg.sendToTarget(); 13672 } 13673 mPostSystemReadyMessages = null; 13674 } 13675 13676 // Watch for external volumes that come and go over time 13677 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13678 storage.registerListener(mStorageListener); 13679 13680 mInstallerService.systemReady(); 13681 mPackageDexOptimizer.systemReady(); 13682 } 13683 13684 @Override 13685 public boolean isSafeMode() { 13686 return mSafeMode; 13687 } 13688 13689 @Override 13690 public boolean hasSystemUidErrors() { 13691 return mHasSystemUidErrors; 13692 } 13693 13694 static String arrayToString(int[] array) { 13695 StringBuffer buf = new StringBuffer(128); 13696 buf.append('['); 13697 if (array != null) { 13698 for (int i=0; i<array.length; i++) { 13699 if (i > 0) buf.append(", "); 13700 buf.append(array[i]); 13701 } 13702 } 13703 buf.append(']'); 13704 return buf.toString(); 13705 } 13706 13707 static class DumpState { 13708 public static final int DUMP_LIBS = 1 << 0; 13709 public static final int DUMP_FEATURES = 1 << 1; 13710 public static final int DUMP_RESOLVERS = 1 << 2; 13711 public static final int DUMP_PERMISSIONS = 1 << 3; 13712 public static final int DUMP_PACKAGES = 1 << 4; 13713 public static final int DUMP_SHARED_USERS = 1 << 5; 13714 public static final int DUMP_MESSAGES = 1 << 6; 13715 public static final int DUMP_PROVIDERS = 1 << 7; 13716 public static final int DUMP_VERIFIERS = 1 << 8; 13717 public static final int DUMP_PREFERRED = 1 << 9; 13718 public static final int DUMP_PREFERRED_XML = 1 << 10; 13719 public static final int DUMP_KEYSETS = 1 << 11; 13720 public static final int DUMP_VERSION = 1 << 12; 13721 public static final int DUMP_INSTALLS = 1 << 13; 13722 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13723 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13724 13725 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13726 13727 private int mTypes; 13728 13729 private int mOptions; 13730 13731 private boolean mTitlePrinted; 13732 13733 private SharedUserSetting mSharedUser; 13734 13735 public boolean isDumping(int type) { 13736 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13737 return true; 13738 } 13739 13740 return (mTypes & type) != 0; 13741 } 13742 13743 public void setDump(int type) { 13744 mTypes |= type; 13745 } 13746 13747 public boolean isOptionEnabled(int option) { 13748 return (mOptions & option) != 0; 13749 } 13750 13751 public void setOptionEnabled(int option) { 13752 mOptions |= option; 13753 } 13754 13755 public boolean onTitlePrinted() { 13756 final boolean printed = mTitlePrinted; 13757 mTitlePrinted = true; 13758 return printed; 13759 } 13760 13761 public boolean getTitlePrinted() { 13762 return mTitlePrinted; 13763 } 13764 13765 public void setTitlePrinted(boolean enabled) { 13766 mTitlePrinted = enabled; 13767 } 13768 13769 public SharedUserSetting getSharedUser() { 13770 return mSharedUser; 13771 } 13772 13773 public void setSharedUser(SharedUserSetting user) { 13774 mSharedUser = user; 13775 } 13776 } 13777 13778 @Override 13779 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13780 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13781 != PackageManager.PERMISSION_GRANTED) { 13782 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13783 + Binder.getCallingPid() 13784 + ", uid=" + Binder.getCallingUid() 13785 + " without permission " 13786 + android.Manifest.permission.DUMP); 13787 return; 13788 } 13789 13790 DumpState dumpState = new DumpState(); 13791 boolean fullPreferred = false; 13792 boolean checkin = false; 13793 13794 String packageName = null; 13795 13796 int opti = 0; 13797 while (opti < args.length) { 13798 String opt = args[opti]; 13799 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13800 break; 13801 } 13802 opti++; 13803 13804 if ("-a".equals(opt)) { 13805 // Right now we only know how to print all. 13806 } else if ("-h".equals(opt)) { 13807 pw.println("Package manager dump options:"); 13808 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13809 pw.println(" --checkin: dump for a checkin"); 13810 pw.println(" -f: print details of intent filters"); 13811 pw.println(" -h: print this help"); 13812 pw.println(" cmd may be one of:"); 13813 pw.println(" l[ibraries]: list known shared libraries"); 13814 pw.println(" f[ibraries]: list device features"); 13815 pw.println(" k[eysets]: print known keysets"); 13816 pw.println(" r[esolvers]: dump intent resolvers"); 13817 pw.println(" perm[issions]: dump permissions"); 13818 pw.println(" pref[erred]: print preferred package settings"); 13819 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13820 pw.println(" prov[iders]: dump content providers"); 13821 pw.println(" p[ackages]: dump installed packages"); 13822 pw.println(" s[hared-users]: dump shared user IDs"); 13823 pw.println(" m[essages]: print collected runtime messages"); 13824 pw.println(" v[erifiers]: print package verifier info"); 13825 pw.println(" version: print database version info"); 13826 pw.println(" write: write current settings now"); 13827 pw.println(" <package.name>: info about given package"); 13828 pw.println(" installs: details about install sessions"); 13829 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13830 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13831 return; 13832 } else if ("--checkin".equals(opt)) { 13833 checkin = true; 13834 } else if ("-f".equals(opt)) { 13835 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13836 } else { 13837 pw.println("Unknown argument: " + opt + "; use -h for help"); 13838 } 13839 } 13840 13841 // Is the caller requesting to dump a particular piece of data? 13842 if (opti < args.length) { 13843 String cmd = args[opti]; 13844 opti++; 13845 // Is this a package name? 13846 if ("android".equals(cmd) || cmd.contains(".")) { 13847 packageName = cmd; 13848 // When dumping a single package, we always dump all of its 13849 // filter information since the amount of data will be reasonable. 13850 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13851 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13852 dumpState.setDump(DumpState.DUMP_LIBS); 13853 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13854 dumpState.setDump(DumpState.DUMP_FEATURES); 13855 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13856 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13857 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13858 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13859 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13860 dumpState.setDump(DumpState.DUMP_PREFERRED); 13861 } else if ("preferred-xml".equals(cmd)) { 13862 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13863 if (opti < args.length && "--full".equals(args[opti])) { 13864 fullPreferred = true; 13865 opti++; 13866 } 13867 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13868 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13869 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13870 dumpState.setDump(DumpState.DUMP_PACKAGES); 13871 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13872 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13873 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13874 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13875 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13876 dumpState.setDump(DumpState.DUMP_MESSAGES); 13877 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13878 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13879 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13880 || "intent-filter-verifiers".equals(cmd)) { 13881 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13882 } else if ("version".equals(cmd)) { 13883 dumpState.setDump(DumpState.DUMP_VERSION); 13884 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13885 dumpState.setDump(DumpState.DUMP_KEYSETS); 13886 } else if ("installs".equals(cmd)) { 13887 dumpState.setDump(DumpState.DUMP_INSTALLS); 13888 } else if ("write".equals(cmd)) { 13889 synchronized (mPackages) { 13890 mSettings.writeLPr(); 13891 pw.println("Settings written."); 13892 return; 13893 } 13894 } 13895 } 13896 13897 if (checkin) { 13898 pw.println("vers,1"); 13899 } 13900 13901 // reader 13902 synchronized (mPackages) { 13903 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13904 if (!checkin) { 13905 if (dumpState.onTitlePrinted()) 13906 pw.println(); 13907 pw.println("Database versions:"); 13908 pw.print(" SDK Version:"); 13909 pw.print(" internal="); 13910 pw.print(mSettings.mInternalSdkPlatform); 13911 pw.print(" external="); 13912 pw.println(mSettings.mExternalSdkPlatform); 13913 pw.print(" DB Version:"); 13914 pw.print(" internal="); 13915 pw.print(mSettings.mInternalDatabaseVersion); 13916 pw.print(" external="); 13917 pw.println(mSettings.mExternalDatabaseVersion); 13918 } 13919 } 13920 13921 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13922 if (!checkin) { 13923 if (dumpState.onTitlePrinted()) 13924 pw.println(); 13925 pw.println("Verifiers:"); 13926 pw.print(" Required: "); 13927 pw.print(mRequiredVerifierPackage); 13928 pw.print(" (uid="); 13929 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13930 pw.println(")"); 13931 } else if (mRequiredVerifierPackage != null) { 13932 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13933 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13934 } 13935 } 13936 13937 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13938 packageName == null) { 13939 if (mIntentFilterVerifierComponent != null) { 13940 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13941 if (!checkin) { 13942 if (dumpState.onTitlePrinted()) 13943 pw.println(); 13944 pw.println("Intent Filter Verifier:"); 13945 pw.print(" Using: "); 13946 pw.print(verifierPackageName); 13947 pw.print(" (uid="); 13948 pw.print(getPackageUid(verifierPackageName, 0)); 13949 pw.println(")"); 13950 } else if (verifierPackageName != null) { 13951 pw.print("ifv,"); pw.print(verifierPackageName); 13952 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13953 } 13954 } else { 13955 pw.println(); 13956 pw.println("No Intent Filter Verifier available!"); 13957 } 13958 } 13959 13960 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13961 boolean printedHeader = false; 13962 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13963 while (it.hasNext()) { 13964 String name = it.next(); 13965 SharedLibraryEntry ent = mSharedLibraries.get(name); 13966 if (!checkin) { 13967 if (!printedHeader) { 13968 if (dumpState.onTitlePrinted()) 13969 pw.println(); 13970 pw.println("Libraries:"); 13971 printedHeader = true; 13972 } 13973 pw.print(" "); 13974 } else { 13975 pw.print("lib,"); 13976 } 13977 pw.print(name); 13978 if (!checkin) { 13979 pw.print(" -> "); 13980 } 13981 if (ent.path != null) { 13982 if (!checkin) { 13983 pw.print("(jar) "); 13984 pw.print(ent.path); 13985 } else { 13986 pw.print(",jar,"); 13987 pw.print(ent.path); 13988 } 13989 } else { 13990 if (!checkin) { 13991 pw.print("(apk) "); 13992 pw.print(ent.apk); 13993 } else { 13994 pw.print(",apk,"); 13995 pw.print(ent.apk); 13996 } 13997 } 13998 pw.println(); 13999 } 14000 } 14001 14002 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14003 if (dumpState.onTitlePrinted()) 14004 pw.println(); 14005 if (!checkin) { 14006 pw.println("Features:"); 14007 } 14008 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14009 while (it.hasNext()) { 14010 String name = it.next(); 14011 if (!checkin) { 14012 pw.print(" "); 14013 } else { 14014 pw.print("feat,"); 14015 } 14016 pw.println(name); 14017 } 14018 } 14019 14020 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14021 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14022 : "Activity Resolver Table:", " ", packageName, 14023 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14024 dumpState.setTitlePrinted(true); 14025 } 14026 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14027 : "Receiver Resolver Table:", " ", packageName, 14028 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14029 dumpState.setTitlePrinted(true); 14030 } 14031 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14032 : "Service Resolver Table:", " ", packageName, 14033 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14034 dumpState.setTitlePrinted(true); 14035 } 14036 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14037 : "Provider Resolver Table:", " ", packageName, 14038 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14039 dumpState.setTitlePrinted(true); 14040 } 14041 } 14042 14043 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14044 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14045 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14046 int user = mSettings.mPreferredActivities.keyAt(i); 14047 if (pir.dump(pw, 14048 dumpState.getTitlePrinted() 14049 ? "\nPreferred Activities User " + user + ":" 14050 : "Preferred Activities User " + user + ":", " ", 14051 packageName, true, false)) { 14052 dumpState.setTitlePrinted(true); 14053 } 14054 } 14055 } 14056 14057 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14058 pw.flush(); 14059 FileOutputStream fout = new FileOutputStream(fd); 14060 BufferedOutputStream str = new BufferedOutputStream(fout); 14061 XmlSerializer serializer = new FastXmlSerializer(); 14062 try { 14063 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14064 serializer.startDocument(null, true); 14065 serializer.setFeature( 14066 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14067 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14068 serializer.endDocument(); 14069 serializer.flush(); 14070 } catch (IllegalArgumentException e) { 14071 pw.println("Failed writing: " + e); 14072 } catch (IllegalStateException e) { 14073 pw.println("Failed writing: " + e); 14074 } catch (IOException e) { 14075 pw.println("Failed writing: " + e); 14076 } 14077 } 14078 14079 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 14080 pw.println(); 14081 int count = mSettings.mPackages.size(); 14082 if (count == 0) { 14083 pw.println("No domain preferred apps!"); 14084 pw.println(); 14085 } else { 14086 final String prefix = " "; 14087 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14088 if (allPackageSettings.size() == 0) { 14089 pw.println("No domain preferred apps!"); 14090 pw.println(); 14091 } else { 14092 pw.println("Domain preferred apps status:"); 14093 pw.println(); 14094 count = 0; 14095 for (PackageSetting ps : allPackageSettings) { 14096 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14097 if (ivi == null || ivi.getPackageName() == null) continue; 14098 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14099 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14100 pw.println(prefix + "Status: " + ivi.getStatusString()); 14101 pw.println(); 14102 count++; 14103 } 14104 if (count == 0) { 14105 pw.println(prefix + "No domain preferred app status!"); 14106 pw.println(); 14107 } 14108 for (int userId : sUserManager.getUserIds()) { 14109 pw.println("Domain preferred apps for User " + userId + ":"); 14110 pw.println(); 14111 count = 0; 14112 for (PackageSetting ps : allPackageSettings) { 14113 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14114 if (ivi == null || ivi.getPackageName() == null) { 14115 continue; 14116 } 14117 final int status = ps.getDomainVerificationStatusForUser(userId); 14118 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14119 continue; 14120 } 14121 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14122 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14123 String statusStr = IntentFilterVerificationInfo. 14124 getStatusStringFromValue(status); 14125 pw.println(prefix + "Status: " + statusStr); 14126 pw.println(); 14127 count++; 14128 } 14129 if (count == 0) { 14130 pw.println(prefix + "No domain preferred apps!"); 14131 pw.println(); 14132 } 14133 } 14134 } 14135 } 14136 } 14137 14138 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14139 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14140 if (packageName == null) { 14141 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14142 if (iperm == 0) { 14143 if (dumpState.onTitlePrinted()) 14144 pw.println(); 14145 pw.println("AppOp Permissions:"); 14146 } 14147 pw.print(" AppOp Permission "); 14148 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14149 pw.println(":"); 14150 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14151 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14152 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14153 } 14154 } 14155 } 14156 } 14157 14158 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14159 boolean printedSomething = false; 14160 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14161 if (packageName != null && !packageName.equals(p.info.packageName)) { 14162 continue; 14163 } 14164 if (!printedSomething) { 14165 if (dumpState.onTitlePrinted()) 14166 pw.println(); 14167 pw.println("Registered ContentProviders:"); 14168 printedSomething = true; 14169 } 14170 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14171 pw.print(" "); pw.println(p.toString()); 14172 } 14173 printedSomething = false; 14174 for (Map.Entry<String, PackageParser.Provider> entry : 14175 mProvidersByAuthority.entrySet()) { 14176 PackageParser.Provider p = entry.getValue(); 14177 if (packageName != null && !packageName.equals(p.info.packageName)) { 14178 continue; 14179 } 14180 if (!printedSomething) { 14181 if (dumpState.onTitlePrinted()) 14182 pw.println(); 14183 pw.println("ContentProvider Authorities:"); 14184 printedSomething = true; 14185 } 14186 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14187 pw.print(" "); pw.println(p.toString()); 14188 if (p.info != null && p.info.applicationInfo != null) { 14189 final String appInfo = p.info.applicationInfo.toString(); 14190 pw.print(" applicationInfo="); pw.println(appInfo); 14191 } 14192 } 14193 } 14194 14195 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14196 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14197 } 14198 14199 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14200 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14201 } 14202 14203 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14204 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14205 } 14206 14207 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14208 // XXX should handle packageName != null by dumping only install data that 14209 // the given package is involved with. 14210 if (dumpState.onTitlePrinted()) pw.println(); 14211 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14212 } 14213 14214 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14215 if (dumpState.onTitlePrinted()) pw.println(); 14216 mSettings.dumpReadMessagesLPr(pw, dumpState); 14217 14218 pw.println(); 14219 pw.println("Package warning messages:"); 14220 BufferedReader in = null; 14221 String line = null; 14222 try { 14223 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14224 while ((line = in.readLine()) != null) { 14225 if (line.contains("ignored: updated version")) continue; 14226 pw.println(line); 14227 } 14228 } catch (IOException ignored) { 14229 } finally { 14230 IoUtils.closeQuietly(in); 14231 } 14232 } 14233 14234 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14235 BufferedReader in = null; 14236 String line = null; 14237 try { 14238 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14239 while ((line = in.readLine()) != null) { 14240 if (line.contains("ignored: updated version")) continue; 14241 pw.print("msg,"); 14242 pw.println(line); 14243 } 14244 } catch (IOException ignored) { 14245 } finally { 14246 IoUtils.closeQuietly(in); 14247 } 14248 } 14249 } 14250 } 14251 14252 // ------- apps on sdcard specific code ------- 14253 static final boolean DEBUG_SD_INSTALL = false; 14254 14255 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14256 14257 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14258 14259 private boolean mMediaMounted = false; 14260 14261 static String getEncryptKey() { 14262 try { 14263 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14264 SD_ENCRYPTION_KEYSTORE_NAME); 14265 if (sdEncKey == null) { 14266 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14267 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14268 if (sdEncKey == null) { 14269 Slog.e(TAG, "Failed to create encryption keys"); 14270 return null; 14271 } 14272 } 14273 return sdEncKey; 14274 } catch (NoSuchAlgorithmException nsae) { 14275 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14276 return null; 14277 } catch (IOException ioe) { 14278 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14279 return null; 14280 } 14281 } 14282 14283 /* 14284 * Update media status on PackageManager. 14285 */ 14286 @Override 14287 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14288 int callingUid = Binder.getCallingUid(); 14289 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14290 throw new SecurityException("Media status can only be updated by the system"); 14291 } 14292 // reader; this apparently protects mMediaMounted, but should probably 14293 // be a different lock in that case. 14294 synchronized (mPackages) { 14295 Log.i(TAG, "Updating external media status from " 14296 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14297 + (mediaStatus ? "mounted" : "unmounted")); 14298 if (DEBUG_SD_INSTALL) 14299 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14300 + ", mMediaMounted=" + mMediaMounted); 14301 if (mediaStatus == mMediaMounted) { 14302 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14303 : 0, -1); 14304 mHandler.sendMessage(msg); 14305 return; 14306 } 14307 mMediaMounted = mediaStatus; 14308 } 14309 // Queue up an async operation since the package installation may take a 14310 // little while. 14311 mHandler.post(new Runnable() { 14312 public void run() { 14313 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14314 } 14315 }); 14316 } 14317 14318 /** 14319 * Called by MountService when the initial ASECs to scan are available. 14320 * Should block until all the ASEC containers are finished being scanned. 14321 */ 14322 public void scanAvailableAsecs() { 14323 updateExternalMediaStatusInner(true, false, false); 14324 if (mShouldRestoreconData) { 14325 SELinuxMMAC.setRestoreconDone(); 14326 mShouldRestoreconData = false; 14327 } 14328 } 14329 14330 /* 14331 * Collect information of applications on external media, map them against 14332 * existing containers and update information based on current mount status. 14333 * Please note that we always have to report status if reportStatus has been 14334 * set to true especially when unloading packages. 14335 */ 14336 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14337 boolean externalStorage) { 14338 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14339 int[] uidArr = EmptyArray.INT; 14340 14341 final String[] list = PackageHelper.getSecureContainerList(); 14342 if (ArrayUtils.isEmpty(list)) { 14343 Log.i(TAG, "No secure containers found"); 14344 } else { 14345 // Process list of secure containers and categorize them 14346 // as active or stale based on their package internal state. 14347 14348 // reader 14349 synchronized (mPackages) { 14350 for (String cid : list) { 14351 // Leave stages untouched for now; installer service owns them 14352 if (PackageInstallerService.isStageName(cid)) continue; 14353 14354 if (DEBUG_SD_INSTALL) 14355 Log.i(TAG, "Processing container " + cid); 14356 String pkgName = getAsecPackageName(cid); 14357 if (pkgName == null) { 14358 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14359 continue; 14360 } 14361 if (DEBUG_SD_INSTALL) 14362 Log.i(TAG, "Looking for pkg : " + pkgName); 14363 14364 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14365 if (ps == null) { 14366 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14367 continue; 14368 } 14369 14370 /* 14371 * Skip packages that are not external if we're unmounting 14372 * external storage. 14373 */ 14374 if (externalStorage && !isMounted && !isExternal(ps)) { 14375 continue; 14376 } 14377 14378 final AsecInstallArgs args = new AsecInstallArgs(cid, 14379 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14380 // The package status is changed only if the code path 14381 // matches between settings and the container id. 14382 if (ps.codePathString != null 14383 && ps.codePathString.startsWith(args.getCodePath())) { 14384 if (DEBUG_SD_INSTALL) { 14385 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14386 + " at code path: " + ps.codePathString); 14387 } 14388 14389 // We do have a valid package installed on sdcard 14390 processCids.put(args, ps.codePathString); 14391 final int uid = ps.appId; 14392 if (uid != -1) { 14393 uidArr = ArrayUtils.appendInt(uidArr, uid); 14394 } 14395 } else { 14396 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14397 + ps.codePathString); 14398 } 14399 } 14400 } 14401 14402 Arrays.sort(uidArr); 14403 } 14404 14405 // Process packages with valid entries. 14406 if (isMounted) { 14407 if (DEBUG_SD_INSTALL) 14408 Log.i(TAG, "Loading packages"); 14409 loadMediaPackages(processCids, uidArr); 14410 startCleaningPackages(); 14411 mInstallerService.onSecureContainersAvailable(); 14412 } else { 14413 if (DEBUG_SD_INSTALL) 14414 Log.i(TAG, "Unloading packages"); 14415 unloadMediaPackages(processCids, uidArr, reportStatus); 14416 } 14417 } 14418 14419 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14420 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14421 final int size = infos.size(); 14422 final String[] packageNames = new String[size]; 14423 final int[] packageUids = new int[size]; 14424 for (int i = 0; i < size; i++) { 14425 final ApplicationInfo info = infos.get(i); 14426 packageNames[i] = info.packageName; 14427 packageUids[i] = info.uid; 14428 } 14429 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14430 finishedReceiver); 14431 } 14432 14433 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14434 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14435 sendResourcesChangedBroadcast(mediaStatus, replacing, 14436 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14437 } 14438 14439 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14440 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14441 int size = pkgList.length; 14442 if (size > 0) { 14443 // Send broadcasts here 14444 Bundle extras = new Bundle(); 14445 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14446 if (uidArr != null) { 14447 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14448 } 14449 if (replacing) { 14450 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14451 } 14452 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14453 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14454 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14455 } 14456 } 14457 14458 /* 14459 * Look at potentially valid container ids from processCids If package 14460 * information doesn't match the one on record or package scanning fails, 14461 * the cid is added to list of removeCids. We currently don't delete stale 14462 * containers. 14463 */ 14464 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14465 ArrayList<String> pkgList = new ArrayList<String>(); 14466 Set<AsecInstallArgs> keys = processCids.keySet(); 14467 14468 for (AsecInstallArgs args : keys) { 14469 String codePath = processCids.get(args); 14470 if (DEBUG_SD_INSTALL) 14471 Log.i(TAG, "Loading container : " + args.cid); 14472 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14473 try { 14474 // Make sure there are no container errors first. 14475 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14476 Slog.e(TAG, "Failed to mount cid : " + args.cid 14477 + " when installing from sdcard"); 14478 continue; 14479 } 14480 // Check code path here. 14481 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14482 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14483 + " does not match one in settings " + codePath); 14484 continue; 14485 } 14486 // Parse package 14487 int parseFlags = mDefParseFlags; 14488 if (args.isExternalAsec()) { 14489 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14490 } 14491 if (args.isFwdLocked()) { 14492 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14493 } 14494 14495 synchronized (mInstallLock) { 14496 PackageParser.Package pkg = null; 14497 try { 14498 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14499 } catch (PackageManagerException e) { 14500 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14501 } 14502 // Scan the package 14503 if (pkg != null) { 14504 /* 14505 * TODO why is the lock being held? doPostInstall is 14506 * called in other places without the lock. This needs 14507 * to be straightened out. 14508 */ 14509 // writer 14510 synchronized (mPackages) { 14511 retCode = PackageManager.INSTALL_SUCCEEDED; 14512 pkgList.add(pkg.packageName); 14513 // Post process args 14514 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14515 pkg.applicationInfo.uid); 14516 } 14517 } else { 14518 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14519 } 14520 } 14521 14522 } finally { 14523 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14524 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14525 } 14526 } 14527 } 14528 // writer 14529 synchronized (mPackages) { 14530 // If the platform SDK has changed since the last time we booted, 14531 // we need to re-grant app permission to catch any new ones that 14532 // appear. This is really a hack, and means that apps can in some 14533 // cases get permissions that the user didn't initially explicitly 14534 // allow... it would be nice to have some better way to handle 14535 // this situation. 14536 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14537 if (regrantPermissions) 14538 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14539 + mSdkVersion + "; regranting permissions for external storage"); 14540 mSettings.mExternalSdkPlatform = mSdkVersion; 14541 14542 // Make sure group IDs have been assigned, and any permission 14543 // changes in other apps are accounted for 14544 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14545 | (regrantPermissions 14546 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14547 : 0)); 14548 14549 mSettings.updateExternalDatabaseVersion(); 14550 14551 // can downgrade to reader 14552 // Persist settings 14553 mSettings.writeLPr(); 14554 } 14555 // Send a broadcast to let everyone know we are done processing 14556 if (pkgList.size() > 0) { 14557 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14558 } 14559 } 14560 14561 /* 14562 * Utility method to unload a list of specified containers 14563 */ 14564 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14565 // Just unmount all valid containers. 14566 for (AsecInstallArgs arg : cidArgs) { 14567 synchronized (mInstallLock) { 14568 arg.doPostDeleteLI(false); 14569 } 14570 } 14571 } 14572 14573 /* 14574 * Unload packages mounted on external media. This involves deleting package 14575 * data from internal structures, sending broadcasts about diabled packages, 14576 * gc'ing to free up references, unmounting all secure containers 14577 * corresponding to packages on external media, and posting a 14578 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14579 * that we always have to post this message if status has been requested no 14580 * matter what. 14581 */ 14582 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14583 final boolean reportStatus) { 14584 if (DEBUG_SD_INSTALL) 14585 Log.i(TAG, "unloading media packages"); 14586 ArrayList<String> pkgList = new ArrayList<String>(); 14587 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14588 final Set<AsecInstallArgs> keys = processCids.keySet(); 14589 for (AsecInstallArgs args : keys) { 14590 String pkgName = args.getPackageName(); 14591 if (DEBUG_SD_INSTALL) 14592 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14593 // Delete package internally 14594 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14595 synchronized (mInstallLock) { 14596 boolean res = deletePackageLI(pkgName, null, false, null, null, 14597 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14598 if (res) { 14599 pkgList.add(pkgName); 14600 } else { 14601 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14602 failedList.add(args); 14603 } 14604 } 14605 } 14606 14607 // reader 14608 synchronized (mPackages) { 14609 // We didn't update the settings after removing each package; 14610 // write them now for all packages. 14611 mSettings.writeLPr(); 14612 } 14613 14614 // We have to absolutely send UPDATED_MEDIA_STATUS only 14615 // after confirming that all the receivers processed the ordered 14616 // broadcast when packages get disabled, force a gc to clean things up. 14617 // and unload all the containers. 14618 if (pkgList.size() > 0) { 14619 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14620 new IIntentReceiver.Stub() { 14621 public void performReceive(Intent intent, int resultCode, String data, 14622 Bundle extras, boolean ordered, boolean sticky, 14623 int sendingUser) throws RemoteException { 14624 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14625 reportStatus ? 1 : 0, 1, keys); 14626 mHandler.sendMessage(msg); 14627 } 14628 }); 14629 } else { 14630 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14631 keys); 14632 mHandler.sendMessage(msg); 14633 } 14634 } 14635 14636 private void loadPrivatePackages(VolumeInfo vol) { 14637 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14638 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14639 synchronized (mInstallLock) { 14640 synchronized (mPackages) { 14641 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14642 for (PackageSetting ps : packages) { 14643 final PackageParser.Package pkg; 14644 try { 14645 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14646 loaded.add(pkg.applicationInfo); 14647 } catch (PackageManagerException e) { 14648 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14649 } 14650 } 14651 14652 // TODO: regrant any permissions that changed based since original install 14653 14654 mSettings.writeLPr(); 14655 } 14656 } 14657 14658 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14659 sendResourcesChangedBroadcast(true, false, loaded, null); 14660 } 14661 14662 private void unloadPrivatePackages(VolumeInfo vol) { 14663 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14664 synchronized (mInstallLock) { 14665 synchronized (mPackages) { 14666 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14667 for (PackageSetting ps : packages) { 14668 if (ps.pkg == null) continue; 14669 14670 final ApplicationInfo info = ps.pkg.applicationInfo; 14671 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14672 if (deletePackageLI(ps.name, null, false, null, null, 14673 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14674 unloaded.add(info); 14675 } else { 14676 Slog.w(TAG, "Failed to unload " + ps.codePath); 14677 } 14678 } 14679 14680 mSettings.writeLPr(); 14681 } 14682 } 14683 14684 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14685 sendResourcesChangedBroadcast(false, false, unloaded, null); 14686 } 14687 14688 private void unfreezePackage(String packageName) { 14689 synchronized (mPackages) { 14690 final PackageSetting ps = mSettings.mPackages.get(packageName); 14691 if (ps != null) { 14692 ps.frozen = false; 14693 } 14694 } 14695 } 14696 14697 @Override 14698 public int movePackage(final String packageName, final String volumeUuid) { 14699 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14700 14701 final int moveId = mNextMoveId.getAndIncrement(); 14702 try { 14703 movePackageInternal(packageName, volumeUuid, moveId); 14704 } catch (PackageManagerException e) { 14705 Slog.w(TAG, "Failed to move " + packageName, e); 14706 mMoveCallbacks.notifyStatusChanged(moveId, 14707 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14708 } 14709 return moveId; 14710 } 14711 14712 private void movePackageInternal(final String packageName, final String volumeUuid, 14713 final int moveId) throws PackageManagerException { 14714 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14715 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14716 final PackageManager pm = mContext.getPackageManager(); 14717 14718 final boolean currentAsec; 14719 final String currentVolumeUuid; 14720 final File codeFile; 14721 final String installerPackageName; 14722 final String packageAbiOverride; 14723 final int appId; 14724 final String seinfo; 14725 final String label; 14726 14727 // reader 14728 synchronized (mPackages) { 14729 final PackageParser.Package pkg = mPackages.get(packageName); 14730 final PackageSetting ps = mSettings.mPackages.get(packageName); 14731 if (pkg == null || ps == null) { 14732 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14733 } 14734 14735 if (pkg.applicationInfo.isSystemApp()) { 14736 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14737 "Cannot move system application"); 14738 } 14739 14740 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14741 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14742 "Package already moved to " + volumeUuid); 14743 } 14744 14745 final File probe = new File(pkg.codePath); 14746 final File probeOat = new File(probe, "oat"); 14747 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14748 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14749 "Move only supported for modern cluster style installs"); 14750 } 14751 14752 if (ps.frozen) { 14753 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14754 "Failed to move already frozen package"); 14755 } 14756 ps.frozen = true; 14757 14758 currentAsec = pkg.applicationInfo.isForwardLocked() 14759 || pkg.applicationInfo.isExternalAsec(); 14760 currentVolumeUuid = ps.volumeUuid; 14761 codeFile = new File(pkg.codePath); 14762 installerPackageName = ps.installerPackageName; 14763 packageAbiOverride = ps.cpuAbiOverrideString; 14764 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14765 seinfo = pkg.applicationInfo.seinfo; 14766 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14767 } 14768 14769 // Now that we're guarded by frozen state, kill app during move 14770 killApplication(packageName, appId, "move pkg"); 14771 14772 final Bundle extras = new Bundle(); 14773 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14774 extras.putString(Intent.EXTRA_TITLE, label); 14775 mMoveCallbacks.notifyCreated(moveId, extras); 14776 14777 int installFlags; 14778 final boolean moveCompleteApp; 14779 final File measurePath; 14780 14781 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14782 installFlags = INSTALL_INTERNAL; 14783 moveCompleteApp = !currentAsec; 14784 measurePath = Environment.getDataAppDirectory(volumeUuid); 14785 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14786 installFlags = INSTALL_EXTERNAL; 14787 moveCompleteApp = false; 14788 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14789 } else { 14790 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14791 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14792 || !volume.isMountedWritable()) { 14793 unfreezePackage(packageName); 14794 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14795 "Move location not mounted private volume"); 14796 } 14797 14798 Preconditions.checkState(!currentAsec); 14799 14800 installFlags = INSTALL_INTERNAL; 14801 moveCompleteApp = true; 14802 measurePath = Environment.getDataAppDirectory(volumeUuid); 14803 } 14804 14805 final PackageStats stats = new PackageStats(null, -1); 14806 synchronized (mInstaller) { 14807 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14808 unfreezePackage(packageName); 14809 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14810 "Failed to measure package size"); 14811 } 14812 } 14813 14814 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14815 + stats.dataSize); 14816 14817 final long startFreeBytes = measurePath.getFreeSpace(); 14818 final long sizeBytes; 14819 if (moveCompleteApp) { 14820 sizeBytes = stats.codeSize + stats.dataSize; 14821 } else { 14822 sizeBytes = stats.codeSize; 14823 } 14824 14825 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14826 unfreezePackage(packageName); 14827 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14828 "Not enough free space to move"); 14829 } 14830 14831 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14832 14833 final CountDownLatch installedLatch = new CountDownLatch(1); 14834 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14835 @Override 14836 public void onUserActionRequired(Intent intent) throws RemoteException { 14837 throw new IllegalStateException(); 14838 } 14839 14840 @Override 14841 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14842 Bundle extras) throws RemoteException { 14843 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14844 + PackageManager.installStatusToString(returnCode, msg)); 14845 14846 installedLatch.countDown(); 14847 14848 // Regardless of success or failure of the move operation, 14849 // always unfreeze the package 14850 unfreezePackage(packageName); 14851 14852 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14853 switch (status) { 14854 case PackageInstaller.STATUS_SUCCESS: 14855 mMoveCallbacks.notifyStatusChanged(moveId, 14856 PackageManager.MOVE_SUCCEEDED); 14857 break; 14858 case PackageInstaller.STATUS_FAILURE_STORAGE: 14859 mMoveCallbacks.notifyStatusChanged(moveId, 14860 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14861 break; 14862 default: 14863 mMoveCallbacks.notifyStatusChanged(moveId, 14864 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14865 break; 14866 } 14867 } 14868 }; 14869 14870 final MoveInfo move; 14871 if (moveCompleteApp) { 14872 // Kick off a thread to report progress estimates 14873 new Thread() { 14874 @Override 14875 public void run() { 14876 while (true) { 14877 try { 14878 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14879 break; 14880 } 14881 } catch (InterruptedException ignored) { 14882 } 14883 14884 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14885 final int progress = 10 + (int) MathUtils.constrain( 14886 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14887 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14888 } 14889 } 14890 }.start(); 14891 14892 final String dataAppName = codeFile.getName(); 14893 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14894 dataAppName, appId, seinfo); 14895 } else { 14896 move = null; 14897 } 14898 14899 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14900 14901 final Message msg = mHandler.obtainMessage(INIT_COPY); 14902 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14903 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14904 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14905 mHandler.sendMessage(msg); 14906 } 14907 14908 @Override 14909 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14910 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14911 14912 final int realMoveId = mNextMoveId.getAndIncrement(); 14913 final Bundle extras = new Bundle(); 14914 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14915 mMoveCallbacks.notifyCreated(realMoveId, extras); 14916 14917 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14918 @Override 14919 public void onCreated(int moveId, Bundle extras) { 14920 // Ignored 14921 } 14922 14923 @Override 14924 public void onStatusChanged(int moveId, int status, long estMillis) { 14925 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14926 } 14927 }; 14928 14929 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14930 storage.setPrimaryStorageUuid(volumeUuid, callback); 14931 return realMoveId; 14932 } 14933 14934 @Override 14935 public int getMoveStatus(int moveId) { 14936 mContext.enforceCallingOrSelfPermission( 14937 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14938 return mMoveCallbacks.mLastStatus.get(moveId); 14939 } 14940 14941 @Override 14942 public void registerMoveCallback(IPackageMoveObserver callback) { 14943 mContext.enforceCallingOrSelfPermission( 14944 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14945 mMoveCallbacks.register(callback); 14946 } 14947 14948 @Override 14949 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14950 mContext.enforceCallingOrSelfPermission( 14951 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14952 mMoveCallbacks.unregister(callback); 14953 } 14954 14955 @Override 14956 public boolean setInstallLocation(int loc) { 14957 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14958 null); 14959 if (getInstallLocation() == loc) { 14960 return true; 14961 } 14962 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14963 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14964 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14965 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14966 return true; 14967 } 14968 return false; 14969 } 14970 14971 @Override 14972 public int getInstallLocation() { 14973 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14974 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14975 PackageHelper.APP_INSTALL_AUTO); 14976 } 14977 14978 /** Called by UserManagerService */ 14979 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14980 mDirtyUsers.remove(userHandle); 14981 mSettings.removeUserLPw(userHandle); 14982 mPendingBroadcasts.remove(userHandle); 14983 if (mInstaller != null) { 14984 // Technically, we shouldn't be doing this with the package lock 14985 // held. However, this is very rare, and there is already so much 14986 // other disk I/O going on, that we'll let it slide for now. 14987 final StorageManager storage = StorageManager.from(mContext); 14988 final List<VolumeInfo> vols = storage.getVolumes(); 14989 for (VolumeInfo vol : vols) { 14990 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14991 final String volumeUuid = vol.getFsUuid(); 14992 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14993 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14994 } 14995 } 14996 } 14997 mUserNeedsBadging.delete(userHandle); 14998 removeUnusedPackagesLILPw(userManager, userHandle); 14999 } 15000 15001 /** 15002 * We're removing userHandle and would like to remove any downloaded packages 15003 * that are no longer in use by any other user. 15004 * @param userHandle the user being removed 15005 */ 15006 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15007 final boolean DEBUG_CLEAN_APKS = false; 15008 int [] users = userManager.getUserIdsLPr(); 15009 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15010 while (psit.hasNext()) { 15011 PackageSetting ps = psit.next(); 15012 if (ps.pkg == null) { 15013 continue; 15014 } 15015 final String packageName = ps.pkg.packageName; 15016 // Skip over if system app 15017 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15018 continue; 15019 } 15020 if (DEBUG_CLEAN_APKS) { 15021 Slog.i(TAG, "Checking package " + packageName); 15022 } 15023 boolean keep = false; 15024 for (int i = 0; i < users.length; i++) { 15025 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15026 keep = true; 15027 if (DEBUG_CLEAN_APKS) { 15028 Slog.i(TAG, " Keeping package " + packageName + " for user " 15029 + users[i]); 15030 } 15031 break; 15032 } 15033 } 15034 if (!keep) { 15035 if (DEBUG_CLEAN_APKS) { 15036 Slog.i(TAG, " Removing package " + packageName); 15037 } 15038 mHandler.post(new Runnable() { 15039 public void run() { 15040 deletePackageX(packageName, userHandle, 0); 15041 } //end run 15042 }); 15043 } 15044 } 15045 } 15046 15047 /** Called by UserManagerService */ 15048 void createNewUserLILPw(int userHandle, File path) { 15049 if (mInstaller != null) { 15050 mInstaller.createUserConfig(userHandle); 15051 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15052 } 15053 } 15054 15055 void newUserCreatedLILPw(final int userHandle) { 15056 // We cannot grant the default permissions with a lock held as 15057 // we query providers from other components for default handlers 15058 // such as enabled IMEs, etc. 15059 mHandler.post(new Runnable() { 15060 @Override 15061 public void run() { 15062 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15063 } 15064 }); 15065 } 15066 15067 @Override 15068 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15069 mContext.enforceCallingOrSelfPermission( 15070 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15071 "Only package verification agents can read the verifier device identity"); 15072 15073 synchronized (mPackages) { 15074 return mSettings.getVerifierDeviceIdentityLPw(); 15075 } 15076 } 15077 15078 @Override 15079 public void setPermissionEnforced(String permission, boolean enforced) { 15080 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15081 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15082 synchronized (mPackages) { 15083 if (mSettings.mReadExternalStorageEnforced == null 15084 || mSettings.mReadExternalStorageEnforced != enforced) { 15085 mSettings.mReadExternalStorageEnforced = enforced; 15086 mSettings.writeLPr(); 15087 } 15088 } 15089 // kill any non-foreground processes so we restart them and 15090 // grant/revoke the GID. 15091 final IActivityManager am = ActivityManagerNative.getDefault(); 15092 if (am != null) { 15093 final long token = Binder.clearCallingIdentity(); 15094 try { 15095 am.killProcessesBelowForeground("setPermissionEnforcement"); 15096 } catch (RemoteException e) { 15097 } finally { 15098 Binder.restoreCallingIdentity(token); 15099 } 15100 } 15101 } else { 15102 throw new IllegalArgumentException("No selective enforcement for " + permission); 15103 } 15104 } 15105 15106 @Override 15107 @Deprecated 15108 public boolean isPermissionEnforced(String permission) { 15109 return true; 15110 } 15111 15112 @Override 15113 public boolean isStorageLow() { 15114 final long token = Binder.clearCallingIdentity(); 15115 try { 15116 final DeviceStorageMonitorInternal 15117 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15118 if (dsm != null) { 15119 return dsm.isMemoryLow(); 15120 } else { 15121 return false; 15122 } 15123 } finally { 15124 Binder.restoreCallingIdentity(token); 15125 } 15126 } 15127 15128 @Override 15129 public IPackageInstaller getPackageInstaller() { 15130 return mInstallerService; 15131 } 15132 15133 private boolean userNeedsBadging(int userId) { 15134 int index = mUserNeedsBadging.indexOfKey(userId); 15135 if (index < 0) { 15136 final UserInfo userInfo; 15137 final long token = Binder.clearCallingIdentity(); 15138 try { 15139 userInfo = sUserManager.getUserInfo(userId); 15140 } finally { 15141 Binder.restoreCallingIdentity(token); 15142 } 15143 final boolean b; 15144 if (userInfo != null && userInfo.isManagedProfile()) { 15145 b = true; 15146 } else { 15147 b = false; 15148 } 15149 mUserNeedsBadging.put(userId, b); 15150 return b; 15151 } 15152 return mUserNeedsBadging.valueAt(index); 15153 } 15154 15155 @Override 15156 public KeySet getKeySetByAlias(String packageName, String alias) { 15157 if (packageName == null || alias == null) { 15158 return null; 15159 } 15160 synchronized(mPackages) { 15161 final PackageParser.Package pkg = mPackages.get(packageName); 15162 if (pkg == null) { 15163 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15164 throw new IllegalArgumentException("Unknown package: " + packageName); 15165 } 15166 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15167 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15168 } 15169 } 15170 15171 @Override 15172 public KeySet getSigningKeySet(String packageName) { 15173 if (packageName == null) { 15174 return null; 15175 } 15176 synchronized(mPackages) { 15177 final PackageParser.Package pkg = mPackages.get(packageName); 15178 if (pkg == null) { 15179 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15180 throw new IllegalArgumentException("Unknown package: " + packageName); 15181 } 15182 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15183 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15184 throw new SecurityException("May not access signing KeySet of other apps."); 15185 } 15186 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15187 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15188 } 15189 } 15190 15191 @Override 15192 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15193 if (packageName == null || ks == null) { 15194 return false; 15195 } 15196 synchronized(mPackages) { 15197 final PackageParser.Package pkg = mPackages.get(packageName); 15198 if (pkg == null) { 15199 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15200 throw new IllegalArgumentException("Unknown package: " + packageName); 15201 } 15202 IBinder ksh = ks.getToken(); 15203 if (ksh instanceof KeySetHandle) { 15204 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15205 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15206 } 15207 return false; 15208 } 15209 } 15210 15211 @Override 15212 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15213 if (packageName == null || ks == null) { 15214 return false; 15215 } 15216 synchronized(mPackages) { 15217 final PackageParser.Package pkg = mPackages.get(packageName); 15218 if (pkg == null) { 15219 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15220 throw new IllegalArgumentException("Unknown package: " + packageName); 15221 } 15222 IBinder ksh = ks.getToken(); 15223 if (ksh instanceof KeySetHandle) { 15224 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15225 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15226 } 15227 return false; 15228 } 15229 } 15230 15231 public void getUsageStatsIfNoPackageUsageInfo() { 15232 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15233 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15234 if (usm == null) { 15235 throw new IllegalStateException("UsageStatsManager must be initialized"); 15236 } 15237 long now = System.currentTimeMillis(); 15238 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15239 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15240 String packageName = entry.getKey(); 15241 PackageParser.Package pkg = mPackages.get(packageName); 15242 if (pkg == null) { 15243 continue; 15244 } 15245 UsageStats usage = entry.getValue(); 15246 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15247 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15248 } 15249 } 15250 } 15251 15252 /** 15253 * Check and throw if the given before/after packages would be considered a 15254 * downgrade. 15255 */ 15256 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15257 throws PackageManagerException { 15258 if (after.versionCode < before.mVersionCode) { 15259 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15260 "Update version code " + after.versionCode + " is older than current " 15261 + before.mVersionCode); 15262 } else if (after.versionCode == before.mVersionCode) { 15263 if (after.baseRevisionCode < before.baseRevisionCode) { 15264 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15265 "Update base revision code " + after.baseRevisionCode 15266 + " is older than current " + before.baseRevisionCode); 15267 } 15268 15269 if (!ArrayUtils.isEmpty(after.splitNames)) { 15270 for (int i = 0; i < after.splitNames.length; i++) { 15271 final String splitName = after.splitNames[i]; 15272 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15273 if (j != -1) { 15274 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15275 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15276 "Update split " + splitName + " revision code " 15277 + after.splitRevisionCodes[i] + " is older than current " 15278 + before.splitRevisionCodes[j]); 15279 } 15280 } 15281 } 15282 } 15283 } 15284 } 15285 15286 private static class MoveCallbacks extends Handler { 15287 private static final int MSG_CREATED = 1; 15288 private static final int MSG_STATUS_CHANGED = 2; 15289 15290 private final RemoteCallbackList<IPackageMoveObserver> 15291 mCallbacks = new RemoteCallbackList<>(); 15292 15293 private final SparseIntArray mLastStatus = new SparseIntArray(); 15294 15295 public MoveCallbacks(Looper looper) { 15296 super(looper); 15297 } 15298 15299 public void register(IPackageMoveObserver callback) { 15300 mCallbacks.register(callback); 15301 } 15302 15303 public void unregister(IPackageMoveObserver callback) { 15304 mCallbacks.unregister(callback); 15305 } 15306 15307 @Override 15308 public void handleMessage(Message msg) { 15309 final SomeArgs args = (SomeArgs) msg.obj; 15310 final int n = mCallbacks.beginBroadcast(); 15311 for (int i = 0; i < n; i++) { 15312 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15313 try { 15314 invokeCallback(callback, msg.what, args); 15315 } catch (RemoteException ignored) { 15316 } 15317 } 15318 mCallbacks.finishBroadcast(); 15319 args.recycle(); 15320 } 15321 15322 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15323 throws RemoteException { 15324 switch (what) { 15325 case MSG_CREATED: { 15326 callback.onCreated(args.argi1, (Bundle) args.arg2); 15327 break; 15328 } 15329 case MSG_STATUS_CHANGED: { 15330 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15331 break; 15332 } 15333 } 15334 } 15335 15336 private void notifyCreated(int moveId, Bundle extras) { 15337 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15338 15339 final SomeArgs args = SomeArgs.obtain(); 15340 args.argi1 = moveId; 15341 args.arg2 = extras; 15342 obtainMessage(MSG_CREATED, args).sendToTarget(); 15343 } 15344 15345 private void notifyStatusChanged(int moveId, int status) { 15346 notifyStatusChanged(moveId, status, -1); 15347 } 15348 15349 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15350 Slog.v(TAG, "Move " + moveId + " status " + status); 15351 15352 final SomeArgs args = SomeArgs.obtain(); 15353 args.argi1 = moveId; 15354 args.argi2 = status; 15355 args.arg3 = estMillis; 15356 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15357 15358 synchronized (mLastStatus) { 15359 mLastStatus.put(moveId, status); 15360 } 15361 } 15362 } 15363 15364 private final class OnPermissionChangeListeners extends Handler { 15365 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15366 15367 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15368 new RemoteCallbackList<>(); 15369 15370 public OnPermissionChangeListeners(Looper looper) { 15371 super(looper); 15372 } 15373 15374 @Override 15375 public void handleMessage(Message msg) { 15376 switch (msg.what) { 15377 case MSG_ON_PERMISSIONS_CHANGED: { 15378 final int uid = msg.arg1; 15379 handleOnPermissionsChanged(uid); 15380 } break; 15381 } 15382 } 15383 15384 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15385 mPermissionListeners.register(listener); 15386 15387 } 15388 15389 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15390 mPermissionListeners.unregister(listener); 15391 } 15392 15393 public void onPermissionsChanged(int uid) { 15394 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15395 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15396 } 15397 } 15398 15399 private void handleOnPermissionsChanged(int uid) { 15400 final int count = mPermissionListeners.beginBroadcast(); 15401 try { 15402 for (int i = 0; i < count; i++) { 15403 IOnPermissionsChangeListener callback = mPermissionListeners 15404 .getBroadcastItem(i); 15405 try { 15406 callback.onPermissionsChanged(uid); 15407 } catch (RemoteException e) { 15408 Log.e(TAG, "Permission listener is dead", e); 15409 } 15410 } 15411 } finally { 15412 mPermissionListeners.finishBroadcast(); 15413 } 15414 } 15415 } 15416 15417 private class PackageManagerInternalImpl extends PackageManagerInternal { 15418 @Override 15419 public void setLocationPackagesProvider(PackagesProvider provider) { 15420 synchronized (mPackages) { 15421 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15422 } 15423 } 15424 15425 @Override 15426 public void setImePackagesProvider(PackagesProvider provider) { 15427 synchronized (mPackages) { 15428 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15429 } 15430 } 15431 15432 @Override 15433 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15434 synchronized (mPackages) { 15435 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15436 } 15437 } 15438 } 15439} 15440